Compare commits

...
Author SHA1 Message Date
Gina Häußge 67047c006c 🚨 Start to flesh out connection parameters 2019-06-06 16:43:06 +02:00
Gina Häußge 2d872baaec 🚧 connection profiles now load properly 2019-06-06 15:50:48 +02:00
Gina Häußge a412ff42cb 🚧 WIP: More work on the connection profiles 2019-05-31 17:53:45 +02:00
Gina Häußge 06cd4ead8d 🚧 Support adding & updating connection profiles 2019-05-24 17:18:35 +02:00
Gina Häußge 13995e30b7 🚧 Introduce connection profiles 2019-05-24 16:30:22 +02:00
Gina Häußge 0d6d0f7256 🐛 Fix protocol/transport selection 2019-05-22 16:12:23 +02:00
Gina Häußge 1e8cb55be9 🐛 Fix script processing 2019-05-17 12:04:45 +02:00
Gina Häußge e63161ae17 ✨ Reset line numbers before all jobs 2019-05-16 17:40:12 +02:00
Gina Häußge f41dc58d97 ✨ Port part_of_job tracking & fix some bugs 2019-05-16 17:04:01 +02:00
Gina Häußge 522abbddbe ✨ Port various bits from old comm layer 2019-05-16 15:24:53 +02:00
Gina Häußge fecc162b5d ✨ Add "starting" state 2019-05-16 11:31:00 +02:00
Gina Häußge accb222a92 ✨ Support autodetection of klipper 2019-05-16 11:30:32 +02:00
Gina Häußge 0768e3e72b Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/standard.py
2019-05-16 11:30:11 +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 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 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 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 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 ce9315850f 🔖 maintenance is now 1.3.12.dev 2019-03-28 12:25:22 +01:00
Gina Häußge 961b41f0fe 🐛 Fix action commands & various other things 2019-03-08 20:02:51 +01:00
Gina Häußge 4f59e0fd48 🐛 Fix resumed script 2019-03-08 16:32:21 +01:00
Gina Häußge e441976682 🐛 Fix sending of cancel, pause, resume scripts 2019-03-08 14:32:20 +01:00
Gina Häußge 864ac12097 🐛 Fix time reporting & user logging 2019-03-08 10:59:58 +01:00
Gina Häußge ee854f44cc ♻ Make some protocol flags dynamic
Less risk of forgetting to adjust them on some randomg state change.

Fixes issues with pausing/resuming/finishing.
2019-03-07 12:48:06 +01:00
Gina Häußge cc5c19dde9 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/filemanager/storage/local.py
2019-03-06 15:12:27 +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 f36a6a0409 🐛 Fix missing error field on protocol 2019-03-01 18:09:28 +01:00
Gina Häußge de8be65be7 🚧 WIP: user action logging, continued 2019-03-01 18:09:13 +01:00
Gina Häußge 780948fe7d 🐛 Fix ok_timeout detection under Py2 as well
d291734 only fixed it for Py3 🤦‍♀️
2019-03-01 16:24:32 +01:00
Gina Häußge c27936a9db 🐛 Fix print logging 2019-03-01 15:31:36 +01:00
Gina Häußge caad7a3f60 🐛 tracking: Use correct payload roperty for elapsed time 2019-03-01 13:16:11 +01:00
Gina Häußge 7c75c882d3 ♻ Put time into job event payload 2019-03-01 13:15:45 +01:00
Gina Häußge 9594b75b78 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/plugins/tracking/__init__.py
2019-03-01 11:29:14 +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 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 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 9eafe9979a 🚧 WIP: user action logging 2019-02-22 19:25:02 +01:00
Gina Häußge 086a2c9f82 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/plugins/virtual_printer/virtual.py
2019-02-22 18:48:10 +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 0c58566789 🐛 Fix on_protocol_job_resumed call 2019-02-22 17:51:34 +01:00
Gina Häußge d2917346f5 🐛 Fix ok_timeout detection 2019-02-22 17:50:43 +01:00
Gina Häußge e7f1302f3c 🐛 Fix pausing -> paused
Was not waiting for scripts and such to complete before the state
change.
2019-02-22 15:23:28 +01:00
Gina Häußge eca74233eb 🐛 Fix resume 2019-02-22 14:47:31 +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 36fb7805e5 🐛 Fix type error in case of a resend 2019-02-22 11:33:45 +01:00
Gina Häußge c7afd7951c 💚 Fix tests (final pass) 2019-02-21 16:58:44 +01:00
Gina Häußge f489f4ffd1 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	.travis.yml
#	src/octoprint/util/__init__.py
2019-02-21 15:44:27 +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 ba96ba8fe8 🚧 WIP: Fixing tests, part 3 2019-02-21 15:29:41 +01:00
Gina Häußge 02566ae9d0 👷 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:29:20 +01:00
Gina Häußge 8080e65366 Merge branch 'devel' into dev/commRefactoringNG 2019-02-21 11:52:11 +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 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 4c76225c41 🚧 WIP: Fixing tests, part 2 2019-02-15 18:54:07 +01:00
Gina Häußge 1f4bfa854b 👷 Switching from nose to pytest 2019-02-15 18:52:44 +01:00
Gina Häußge 4be18c2668 🚧 WIP: Fixing tests 2019-02-15 12:56:57 +01:00
Gina Häußge 225cca34e1 🔥 Remove old test code 2019-02-14 17:29:42 +01:00
Gina Häußge 9a4149164b ♻ Some porting from maintenance/devel 2019-02-14 17:29:02 +01:00
Gina Häußge cf9243c2e7 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/filemanager/storage/local.py
#	src/octoprint/logging/handlers.py
#	src/octoprint/plugin/__init__.py
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/connection.py
#	src/octoprint/server/api/files.py
#	src/octoprint/settings.py
#	src/octoprint/static/js/app/viewmodels/connection.js
#	src/octoprint/util/__init__.py
#	tests/plugin/test_settings.py
2019-02-14 17:27:00 +01: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 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 3c5aa60d2b 🐛 Some more unicode vs bytes fixes 2019-02-07 18:35:35 +01: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 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
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
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
Matthias Urlichs a301fc6da9 Merge remote-tracking branch 'origin/devel' into py23 2019-02-04 18:44:23 +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
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 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
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 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 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
Matthias Urlichs 5794a347f1 Added myself to AUTHORS ;-) 2019-01-28 15:08:40 +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
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
MirceaDan d987cb23c1 Merge branch 'devel' into dev/py23_metaclass 2019-01-07 21:41:14 -08: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 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
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
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
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 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 54677f96f4 Merge branch 'maintenance' into devel 2018-11-06 12:32:25 +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 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
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
Gina Häußge 8eba3fef0a Add disconnect handling
Had to refactor quite some bits to be able to implement this.
2018-07-05 17:36:43 +02:00
Gina Häußge e93d2104fd Add last temperature to script context & event on M112 2018-07-05 12:22:53 +02:00
Gina Häußge a7aa58e524 Add printer profile, use where needed 2018-07-05 12:17:10 +02:00
Gina Häußge c442906379 Resolve a dwelling TODO 2018-07-05 11:25:38 +02:00
Gina Häußge bb0b01aa01 Add resend_ok_timer to work around broken resends 2018-07-04 17:52:25 +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 3173783620 Join connection dialog with new comm layer 2018-06-29 20:55:54 +02:00
Gina Häußge 5d0cb14f71 Fix Print Time/Printed tracking for successfully completed jobs
We want this data to stick around after the print job ended, just like
it does now
2018-06-28 15:31:04 +02:00
Gina Häußge 60d84b7d06 Make SD prints work again
#mswa
2018-06-27 17:37:56 +02:00
Gina Häußge 93d77e6b25 Fix missing event field 2018-06-26 16:30:48 +02:00
Gina Häußge fd13b18ef7 Remove parsing limitation on sd file streaming 2018-06-26 13:28:05 +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 acd05cdcc5 Limit parsing to comm when streaming to SD 2018-06-14 19:16:25 +02:00
Gina Häußge 1a67b5b3fc Upload to SD is now working 2018-06-14 18:54:40 +02:00
Gina Häußge 473d4a752a Fix message parsing again 2018-06-14 12:58:10 +02:00
Gina Häußge 33a5e389fd Fix line pushing 2018-06-13 17:35:16 +02:00
Gina Häußge 287a13b944 Reset handling 2018-06-12 16:28:22 +02:00
Gina Häußge 5282db6871 Implement job_on_hold functionality 2018-06-12 15:57:46 +02:00
Gina Häußge b79618d752 Disable heatup detection when auto reporting 2018-06-12 13:54:35 +02:00
Gina Häußge 391930e2cb Fix reported state id 2018-06-12 13:48:12 +02:00
Gina Häußge 4630cc8ee0 Fix restart button 2018-06-12 13:47:52 +02:00
Gina Häußge 4e83466af3 Fix temperature polling 2018-06-12 13:29:29 +02:00
Gina Häußge b7e08c7ddc Fix pausing 2018-06-12 13:29:19 +02:00
Gina Häußge 701208484a WIP first throw at scripts
Currently broken:
  * temperature and position logging in context
  * pausing and cancelling
2018-06-07 17:49:35 +02:00
Gina Häußge 02252d1254 finishing state 2018-06-07 14:29:42 +02:00
Gina Häußge 8347f182ef queue markers, pausing, cancelling 2018-06-07 14:16:47 +02:00
Gina Häußge 7e4faa20b7 Fix temperature access 2018-06-06 15:12:27 +02:00
Gina Häußge 717eef25da Fix wrong (1%) progress on print finish 2018-06-06 13:06:39 +02:00
Gina Häußge 31fbebdbb9 Basic action commands are working 2018-06-05 17:39:04 +02:00
Gina Häußge afe224ae08 Fix resend request handling
Resends didn't use up oks due to a missing to_command during enqueuing.
2018-06-05 16:54:52 +02:00
Gina Häußge d09f75a815 Add commdebug logger
To help with debugging ping pong communication
2018-06-05 16:54:01 +02:00
Gina Häußge 812ce40e35 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/logging/handlers.py
#	src/octoprint/printer/standard.py
2018-06-05 13:22:15 +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 66cad78c41 WIP: busy proto, dwelling, ok timeout 2018-05-31 17:42:52 +02:00
Gina Häußge 4e91f47e8b Add protocol state to handler calls 2018-05-31 15:15:32 +02:00
Gina Häußge 4b753d03dc internal_state => internal_flags 2018-05-31 10:59:17 +02:00
Gina Häußge 6f18749df1 time.time => monotonic_time 2018-05-31 10:44:30 +02:00
Gina Häußge eab0ce8aee Add firmware & capability reporting, temp autoreports
Also refactored flavors to make adding additional ones (e.g. from
plugins) even easier.
2018-05-31 10:19:15 +02:00
Gina Häußge ba00b4d675 Fix bug in GcodeCommand constructor 2018-05-30 19:12:30 +02:00
Gina Häußge 9bc8638d80 Fix resend handling 2018-05-30 14:32:46 +02:00
Gina Häußge d9c8351025 WIP: tags, print time estimation, gcode parsing 2018-05-24 18:52:19 +02:00
Gina Häußge 73a16f6075 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/printer/standard.py
2018-05-24 10:53:56 +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 4967d19b6a WIP: Add tags & atcommands 2018-05-23 18:45:00 +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 4b64fb7f47 Corrected some merge issues 2018-05-09 14:05:25 +02:00
Gina Häußge 7e11104b9c Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/__init__.py
#	src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/files.py
#	src/octoprint/util/__init__.py
2018-05-08 15:57:05 +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 81efd3251c Merge branch 'devel' into dev/commRefactoringNG 2017-06-14 11:27:22 +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
Gina Häußge f21a1093f3 Eval message integrity for checksumming 2017-05-02 09:21:53 +02:00
Gina Häußge 72318fa696 Fix comment stripping 2017-05-02 09:21:19 +02:00
Gina Häußge babc581c5d More migrations from stable comm layer to new layer
Also fixed:
  * comment stripping
  * resends (? maybe ?)
  * transport error detection
2017-04-21 23:05:58 +02:00
Gina Häußge c28fb4164b Transport registry, events and various fixes
Broken:

  * print time estimation
  * comment stripping (not stripping totally empty lines)
  * resend handling (837, 838, 833 - boom)
  * job pause/resume events?
  * possibly more
2017-04-20 17:18:36 +02:00
Gina Häußge a6db08992f Fixed some merge errors & temperature reporting 2017-04-20 15:17:07 +02:00
Gina Häußge 2dea5e0ffc Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	setup.py
#	src/octoprint/filemanager/__init__.py
#	src/octoprint/filemanager/storage.py
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
2017-04-20 12:25:08 +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
Gina Häußge a2323a7bb2 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	setup.py
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/util/__init__.py
2016-12-08 14:37:12 +01: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
Gina Häußge cfe8b1a764 Experimenting with a real printer 2016-02-15 09:43:50 +01:00
Gina Häußge aee1dff718 Trying to get disconnecting to work reliably 2016-02-12 08:51:14 +01:00
Gina Häußge 54bd41903b Merge branch 'devel' into dev/commRefactoringNG 2016-02-11 13:46:58 +01:00
Gina Häußge c813df9afe Do not hiccup if listener to remove isn't registered 2016-02-11 08:46:47 +01:00
Gina Häußge e312f66823 We depend on pyserial 3 in this branch... 2016-02-11 08:34:55 +01:00
Gina Häußge 648c10c91f Merge branch 'devel' into dev/commRefactoringNG
Conflicts:
	src/octoprint/printer/__init__.py
	src/octoprint/printer/standard.py
2016-02-10 16:54:15 +01:00
Gina Häußge 2cf902c6c3 Stupid typos are stupid 2016-02-08 11:28:20 +01:00
Gina Häußge 26934fae02 Printing more or less works against the virtual printer 2016-02-05 16:19:36 +01:00
Gina Häußge 74ba9364f4 First attempt at connecting with existing architecture 2016-02-04 18:39:50 +01:00
Gina Häußge 18222420ee Merge branch 'devel' into dev/commRefactoringNG 2016-02-04 14:11:35 +01:00
Gina Häußge 89a37766df Minimal job queue in test code, first local file print 2016-01-30 12:08:31 +01:00
Gina Häußge cf02471db7 More work on getting to the point where printing might work
Status reporting, timeout handling, parsing etc... lots of work
2016-01-29 21:16:13 +01:00
Gina Häußge ff9b7de615 Introduced jobs, more work on protocols and transports 2016-01-29 09:02:35 +01:00
Gina Häußge b7ad8faaee WIP 2016-01-27 14:34:00 +01:00
Gina Häußge 34facfe764 WIP 2016-01-22 12:05:17 +01:00
Gina Häußge c83b6288aa Started implementation of Protocol type hierarchy 2016-01-20 13:03:34 +01:00
Gina Häußge b66f86de71 Renamed url_scheme property to key 2016-01-19 11:59:29 +01:00
Gina Häußge 581cd19446 Starting work on a better version of the comm refactoring 2016-01-16 16:35:31 +01:00
349 changed files with 22177 additions and 12147 deletions

No files matched your search

+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
+7 -7
View File
@@ -18,16 +18,16 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.11
# maintenance is currently the branch for preparation of maintenance release 1.3.12
# so are any fix/... and improve/... branches
maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
maintenance 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
fix/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
improve/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.11rc2
# staging/maintenance is currently the branch for preparation of 1.3.11rc4
# so is regressionfix/...
staging/maintenance 1.3.11rc2 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
regressionfix/.* 1.3.11rc2 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
staging/maintenance 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
regressionfix/.* 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 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
+7 -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,14 +92,19 @@ 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)
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
+37 -49
View File
@@ -1,57 +1,13 @@
# OctoPrint Changelog
## 1.3.11rc2 (2019-04-04)
### Improvements
* More resilience against broken configurations.
* More resilience against platform startup issues during environment detection.
* Don't confuse users with pip's new "OMG PY2.7 IS EOL!!1!" message.
* Error Tracking: Severely restrict what gets tracked:
* we are only interested in handled core exceptions or unhandled exceptions
* we are not interested at all in `SerialException`
* in the frontend we are only interested in things originating in the `static` files
* in the frontend we are not interested in anything originating in `packed_plugins.js`
### Bug fixes
* [#3088](https://github.com/foosel/OctoPrint/issues/3088) (regression) - Fix 500 error on index rendering in case of plugins that use unicode in plugin vars.
* [#3089](https://github.com/foosel/OctoPrint/issues/3089) (regression) - Fix missing `_chamberTemp` definition
* [#3090](https://github.com/foosel/OctoPrint/issues/3090) (regression) - Fix missing method causing an exception on `/api/printer/tool` endpoint
* [#3091](https://github.com/foosel/OctoPrint/issues/3091) (regression) - Printer Safety Check: Fix unicode errors in certain communication scenarios.
* [#3092](https://github.com/foosel/OctoPrint/issues/3092) - Fix invalid tool parameter detection on `/api/printer/tool` endpoint.
* [#3098](https://github.com/foosel/OctoPrint/issues/3098) - Backup: Exclude temporary timelapse files as well if timelapses are excluded from backup.
* Fix missing default value for `self._errorValue` in comm layer.
* Don't read return code on async system commands, it won't work.
### Unreproduced issues
The following issues were reported in RC1 but so far have been unreproduced and further data to analyse them is still missing. If you encounter any of them please report back with a [fully filled out issue template](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#what-should-i-include-in-a-bug-report):
* ["Print completes but temp data appears to be 'stuck' at last known value for bed and hotend."](https://github.com/foosel/OctoPrint/issues/3087#issuecomment-478369220)
### Special thanks to all the contributors!
Special thanks to everyone who contributed to this release candidate and provided full, analysable bug reports.
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.11rc1...1.3.11rc1)
## 1.3.11rc1 (2019-03-28)
## 1.3.11 (2019-05-14)
### Heads-up: 1.3.11 unbundles the Cura plugin
If you rely on the Cura Plugin for your workflow that so far was bundled with OctoPrint, be sure to install the [Cura Legacy plugin](https://github.com/OctoPrint/OctoPrint-CuraLegacy) that's now also available on the plugin repository.
If you rely on the Cura Plugin for your workflow that so far was bundled with OctoPrint, be sure to install the [Cura Legacy plugin](https://github.com/OctoPrint/OctoPrint-CuraLegacy) that's now also [available on the plugin repository](https://plugins.octoprint.org/plugins/curalegacy/).
Once installed the Cura Legacy plugin will import the settings and profiles from the former bundled Cura plugin automatically on first start.
### Heads-up: 1.3.11 bundles a new Error Tracking plugin, please enable it on Release Candidates
The Error Tracking plugin is a completely separate plugin from the existing Anonymous Usage Tracking plugin. It's tracking is disabled by default. Its purpose is to collect error information from instances in order to allow better issue analysis especially during the Release Candidate phase, or when prompted after reporting a bug. Thus it will also ask you to enable it on start while subscribed to an RC release channel.
The plugin uses a [sentry.io](https://sentry.io) instance, kindly provided to OctoPrint by sentry.io.
### Improvements
* [#1938](https://github.com/foosel/OctoPrint/issues/1938) - Allow slicing parallel to printing on machines with more than one core.
@@ -107,12 +63,23 @@ The plugin uses a [sentry.io](https://sentry.io) instance, kindly provided to Oc
* Use `monotonic_time` for relative times everywhere.
* Support for heated chamber firmware capabilities.
* Remove `UI_API_KEY` and 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.
* More resilience against broken configurations.
* More resilience against platform startup issues during environment detection.
* Don't confuse users with current `pip`'s "Python 2.7 is EOL" messages
* Define empty `UI_API_KEY` for backwards compatibility with third party plugins
* Add config flag `server.ignoredIncompleteStartup` to override incomplete startup detection
* Hardening against errors triggered during print time estimation
* Introduce setting to disable exclusive claim on serial port. There might be issues with this out there in the field, so having the option to disable it is a good thing.
* Docs: Improve docs of connection API to avoid issues as encountered in [#3043](https://github.com/foosel/OctoPrint/issues/3043).
* Action Command Prompt plugin: Set `M876` as default command as discussed in [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
* Action Command Prompt plugin: Add `M876` to `EMERGENCY_PARSER` compliant commands, if configured accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
* Action Command Prompt plugin: Signal support for action command prompts to firmware via `M876 P1`, if configured accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
* Action Command Prompt plugin: Properly handle `PROMPT_SUPPORT` capability report from firmware and configure action command prompt support accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
* Error Tracking plugin: New plugin utilizing [sentry.io](https://sentry.io) to track any kind of errors thrown in either backend or the default UI. Will ship disabled by default, has to be enabled by the user. Release Candidates will prompt users to enable it in order to improve on error detection during RC phase.
* Error Tracking: Severely restrict what gets tracked:
* we are only interested in handled core exceptions or unhandled exceptions
* we are not interested at all in `SerialException`
* Error Tracking: Further restriction of what gets tracked
* Forcelogin plugin: Set sorting key to 0 to increase likelihood of coming before alternative UIs.
* Forcelogin plugin: Add favicon meta tags.
* Plugin Manager plugin, Softwareupdate plugin: Use scrollables instead of pagination.
@@ -142,10 +109,26 @@ The plugin uses a [sentry.io](https://sentry.io) instance, kindly provided to Oc
* [#3053](https://github.com/foosel/OctoPrint/pull/3053) - GCODE Viewer: Fix an issue with multi extruder files where only a higher extruder index is actually used and all prior ones are undefined.
* [#3080](https://github.com/foosel/OctoPrint/issues/3080) - Virtual Printer plugin: Fix tracking of negative movements and homing.
* [#3071](https://github.com/foosel/OctoPrint/issues/3071) - Application Keys plugin: Fix appkeys not working when access control is disabled.
* [#3088](https://github.com/foosel/OctoPrint/issues/3088) (regression) - Fix 500 error on index rendering in case of plugins that use unicode in plugin vars.
* [#3089](https://github.com/foosel/OctoPrint/issues/3089) (regression) - Fix missing `_chamberTemp` definition
* [#3090](https://github.com/foosel/OctoPrint/issues/3090) (regression) - Fix missing method causing an exception on `/api/printer/tool` endpoint
* [#3091](https://github.com/foosel/OctoPrint/issues/3091) (regression) - Printer Safety Check: Fix unicode errors in certain communication scenarios.
* [#3092](https://github.com/foosel/OctoPrint/issues/3092) - Fix invalid tool parameter detection on `/api/printer/tool` endpoint.
* [#3098](https://github.com/foosel/OctoPrint/issues/3098) - Backup: Exclude temporary timelapse files as well if timelapses are excluded from backup.
* [#3105](https://github.com/foosel/OctoPrint/issues/3105) (regression) - Virtual printer: Fix an encoding issue
* [#3108](https://github.com/foosel/OctoPrint/issues/3108) (regression) - Fix bug in port detection
* [#3111](https://github.com/foosel/OctoPrint/issues/3111) (regression) - Refresh port list after disconnect to detect vanishing ports
* [#3115](https://github.com/foosel/OctoPrint/issues/3115) (regression) - Fix extra newlines in `serial.log` and empty lines on terminal
* [#3116](https://github.com/foosel/OctoPrint/issues/3116) - Fix potential division by zero
* Fix a typo in an error message during startup.
* `paused` action command must not trigger *any* local processing. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
* Only use page size from local storage in `ItemListHelper` if configured.
* Fix caching headers on main view.
* Fix missing default value for `self._errorValue` in comm layer.
* Don't read return code on async system commands, it won't work.
* Fix wrong textual representation of `STARTING` state
* Fix some potential encoding errors in the comm layer
* Fix for the file list in the UI not getting refreshed after an SD list refresh from the printer.
* Docs: Fix documentation for firmware info & capability plugin hooks.
* Docs: Fix a formatting issue in the event docs, making it seem like events were deprecated when it was only payload entries that are deprecated.
* Forcelogin plugin: Never handle the UI if ACL is disabled.
@@ -154,11 +137,16 @@ The plugin uses a [sentry.io](https://sentry.io) instance, kindly provided to Oc
### Special thanks to all the contributors!
Special thanks to everyone who contributed to this release candidate, especially [@agrif](https://github.com/agrif), [@akraus53](https://github.com/akraus53), [@AndyQ](https://github.com/AndyQ), [@CapnBry](https://github.com/CapnBry), [@DanielJoyce](https://github.com/DanielJoyce), [@devildant](https://github.com/devildant), [@Fabi0San](https://github.com/Fabi0San), [@fake-name](https://github.com/fake-name), [@fieldOfView](https://github.com/fieldOfView), [@gloomyandy](https://github.com/gloomyandy), [@HarlemSquirrel](https://github.com/HarlemSquirrel), [@hgross](https://github.com/hgross), [@jubaleth](https://github.com/foosel/OctoPrint/commits?author=jubaleth), [@melgish](https://github.com/melgish), [@rgriebl](https://github.com/rgriebl) and [@tedder](https://github.com/tedder) for their PRs.
Special thanks to everyone who contributed to this release, especially [@agrif](https://github.com/agrif), [@akraus53](https://github.com/akraus53), [@AndyQ](https://github.com/AndyQ), [@CapnBry](https://github.com/CapnBry), [@DanielJoyce](https://github.com/DanielJoyce), [@devildant](https://github.com/devildant), [@Fabi0San](https://github.com/Fabi0San), [@fake-name](https://github.com/fake-name), [@fieldOfView](https://github.com/fieldOfView), [@gloomyandy](https://github.com/gloomyandy), [@HarlemSquirrel](https://github.com/HarlemSquirrel), [@hgross](https://github.com/hgross), [@jubaleth](https://github.com/foosel/OctoPrint/commits?author=jubaleth), [@melgish](https://github.com/melgish), [@rgriebl](https://github.com/rgriebl) and [@tedder](https://github.com/tedder) for their PRs.
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.10...1.3.11rc1)
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.10...1.3.11)
* Release Candidates:
* [1.3.11rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc1)
* [1.3.11rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc2)
* [1.3.11rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc3)
* A big **Thank you!** to everyone who reported back on these release candidates this time: [@arhi](https://github.com/arhi), [@b-morgan](https://github.com/b-morgan), [@CRCinAU](https://github.com/CRCinAU), [@devildant](https://github.com/devildant), [@evanquinnalaska](https://github.com/evanquinnalaska), [@FormerLurker](https://github.com/FormerLurker), [@gege2b](https://github.com/gege2b), [@isbric](https://github.com/isbric), [@JohnOCFII](https://github.com/JohnOCFII), [@kazibole](https://github.com/kazibole), [@nionio6915](https://github.com/nionio6915), [@reloxx13](https://github.com/reloxx13), [@schnello](https://github.com/schnello), [@trunzoc](https://github.com/trunzoc), [@vfrdirk](https://github.com/vfrdirk) & [@zeroflow](https://github.com/zeroflow)
## 1.3.10 (2018-12-10)
@@ -715,7 +703,7 @@ You can find out more about the change, how to know if a plugin is even affected
* Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937))
* Add `ToolChange` event and tool change GCODE scripts
* Support parsing GCODE subcodes.
* Add `octoprint.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses.
* Add `octoprint.access.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses.
* Corewizard: Disable view model and client code if it's not actually required.
* Corewizard: Disable injection of JS files into UI when it's not actually required.
* GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems.
+2 -2
View File
@@ -61,7 +61,7 @@ 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`
@@ -83,7 +83,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
+2 -2
View File
@@ -21,7 +21,7 @@ thanks to everyone who contributed!
* E3D BigBox
* Eric Betts
* Ernesto Martinez
* Frank Sander
* Franziska Kunsmann
* George Robles
* jean-claude migneault
* Jeff Renfer
@@ -54,4 +54,4 @@ thanks to everyone who contributed!
* Trent Shumay
* Ulrich Kempken
and 1509 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1544 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+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
-174
View File
@@ -1,174 +0,0 @@
.. _sec-api-apps:
****
Apps
****
.. contents::
.. _sec-api-apps-sessionkey:
Session Keys
============
.. deprecated:: 1.3.11
This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` instead.
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-----
+21 -10
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
+2
View File
@@ -514,6 +514,8 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
-
* - ``webcam.ffmpegThreads``
-
* - ``webcam.ffmpegVideoCodec``
-
* - ``webcam.watermark``
-
* - ``webcam.flipH``
+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
+2 -2
View File
@@ -385,8 +385,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(
+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'),
]
+28 -1
View File
@@ -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
@@ -673,6 +685,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
@@ -952,6 +969,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
@@ -1226,6 +1250,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
+37 -10
View File
@@ -14,18 +14,25 @@ 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 +40,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 +85,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 +100,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 +139,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 +181,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
+8
View File
@@ -38,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
@@ -53,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
+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::
+3 -3
View File
@@ -1,9 +1,9 @@
.. _sec-modules-users:
octoprint.users
---------------
octoprint.access.users
----------------------
.. automodule:: octoprint.users
.. automodule:: octoprint.access.users
: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
+46 -45
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,35 +200,6 @@ Available plugin hooks
.. contents::
:local:
.. _sec-plugins-hook-accesscontrol-appkey:
octoprint.accesscontrol.appkey
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: acl_appkey_hook(*args, **kwargs)
.. deprecated:: 1.3.11
This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` instead.
By handling this hook plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
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 ``id`` should be the (unique) identifier of the app. Using a domain prefix might make sense here, e.g.
``org.octoprint.example.MyApp``.
``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.
Finally, the public key is expected to be provided as a PKCS1 string without newlines.
:return: A list of 3-tuples as described above
:rtype: list
.. _sec-plugins-hook-accesscontrol-keyvalidator:
octoprint.accesscontrol.keyvalidator
@@ -241,7 +211,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.
@@ -259,7 +229,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:
@@ -766,9 +736,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
@@ -1061,9 +1032,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.
@@ -1557,12 +1527,12 @@ octoprint.ui.web.templatetypes
.. _sec-plugins-hook-users-factory:
octoprint.users.factory
~~~~~~~~~~~~~~~~~~~~~~~
octoprint.access.users.factory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will
be called only once during initial server startup.
The provided ``components`` is a dictionary containing the already initialized system components:
@@ -1573,7 +1543,6 @@ octoprint.users.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`
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
@@ -1581,7 +1550,7 @@ octoprint.users.factory
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
: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
@@ -1589,3 +1558,35 @@ octoprint.users.factory
:return: The ``userManager`` instance to use globally.
:rtype: UserManager subclass or None
.. _sec-plugins-hook-timelapse-capture-pre:
octoprint.timelapse.capture.pre
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: capture_pre_hook(filename)
Perform specific actions prior to capturing a timelapse frame.
``filename`` will be the future path of the frame to be saved.
:param str filename: The future path of the frame to be saved.
:return: None
:rtype: None
.. _sec-plugins-hook-timelapse-capture-post:
octoprint.timelapse.capture.post
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. 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`.
+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")
+2 -2
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>'
+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()
+3
View File
@@ -1,6 +1,9 @@
[metadata]
license_file = LICENSE.txt
[bdist_wheel]
universal = 1
[versioneer]
VCS = git
style = pep440-tag
+48 -16
View File
@@ -9,27 +9,29 @@ 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.9,<3"
# 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 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
"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
"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
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"Flask-Login>=0.4.1,<0.5",
"Flask-Principal>=0.4,<0.5",
"Flask-Babel>=0.12,<0.13",
"Flask-Assets>=0.12,<0.13",
@@ -51,21 +53,27 @@ INSTALL_REQUIRES = [
"Click>=7,<8",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3",
"chainmap>=1.0.3,<1.1",
"future>=0.17.1,<0.18",
"scandir>=1.10,<1.11",
"future>=0.17,<0.18",
"websocket-client>=0.56,<0.57",
"wrapt>=1.11.1,<1.12",
"futures>=3.2,<3.3",
"emoji>=0.5.1,<0.6",
"monotonic>=1.5,<1.6",
"frozendict>=1.2,<1.3",
"sentry-sdk==0.7.7",
"sentry-sdk==0.7.7"
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"futures>=3.2,<3.3",
"monotonic>=1.5,<1.6",
"scandir>=1.10,<1.11",
"chainmap>=1.0.3,<1.1",
"typing>=3.6.6,<4"
]
if sys.platform == "darwin":
INSTALL_REQUIRES.append("appdirs>=1.4.0")
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.0",
]
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
@@ -73,9 +81,13 @@ EXTRA_REQUIRES = dict(
develop=[
# Testing dependencies
"mock>=2.0.0,<3",
"nose>=1.3.7,<1.4",
"pytest>=4.2.1,<5.0",
"pytest-doctest-custom>=1.0.0,<1.1",
"ddt",
# linter
"flake8",
# Documentation dependencies
"sphinx>=1.6,<1.7",
"sphinxcontrib-httpdomain",
@@ -92,6 +104,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
@@ -183,6 +212,9 @@ 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 :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
+59 -20
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
@@ -104,7 +105,10 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
after_logging(**kwargs)
settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None
settings_incomplete_startup_safemode = "incomplete_startup" if settings.getBoolean(["server", "incompleteStartup"]) 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):
@@ -229,6 +233,12 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
},
"serial": {
"format": "%(asctime)s - %(message)s"
},
"communication": {
"format": "%(asctime)s - %(name)s - %(message)s"
},
"commdebug": {
"format": "%(asctime)s - %(threadName)s - %(message)s"
}
},
"handlers": {
@@ -246,19 +256,45 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
"backupCount": 6,
"filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log")
},
"serialFile": {
"class": "octoprint.logging.handlers.SerialLogHandler",
"protocolFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "serial",
"formatter": "communication",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
"filename": os.path.join(settings.getBaseFolder("logs"), "protocol.log"),
"delay": True
},
"transportFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "communication",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "transport.log"),
"delay": True
},
"commDebugFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "commdebug",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "commdebug.log"),
"delay": True
}
},
"loggers": {
"SERIAL": {
"level": "INFO",
"handlers": ["serialFile"],
"PROTOCOL": {
"level": "DEBUG",
"handlers": ["protocolFile"],
"propagate": False
},
"TRANSPORT": {
"level": "DEBUG",
"handlers": ["transportFile"],
"propagate": False
},
"COMMDEBUG": {
"level": "DEBUG",
"handlers": ["commDebugFile"],
"propagate": False
},
"octoprint": {
@@ -294,7 +330,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
@@ -367,13 +403,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()
@@ -486,7 +525,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):
@@ -500,12 +539,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:
@@ -532,7 +571,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.")
+6 -6
View File
@@ -1,10 +1,10 @@
#!/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 sys
if sys.version_info[0] >= 3:
raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
#import sys
#if sys.version_info[0] >= 3:
# raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
if __name__ == "__main__":
import octoprint
+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 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 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
+3 -2
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
+4 -3
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
@@ -71,7 +72,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
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
+3 -2
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
import sys
+7
View File
@@ -0,0 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
+215
View File
@@ -0,0 +1,215 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import io
try:
from os import scandir
except ImportError:
from scandir import scandir
from octoprint.settings import settings
from octoprint.util import is_hidden_path
class ConnectionProfile(object):
def __init__(self, id, name=None, printer_profile=None, protocol=None, protocol_parameters=None, transport=None, transport_parameters=None, **kwargs):
self.id = id
self.name = name if name is not None else id
self.printer_profile = printer_profile
self.protocol = protocol
self.protocol_parameters = protocol_parameters
self.transport = transport
self.transport_parameters = transport_parameters
@classmethod
def from_dict(cls, data):
identifier = data.pop("id")
return ConnectionProfile(identifier, **data)
def as_dict(self):
return dict(id=self.id,
name=self.name,
printer_profile=self.printer_profile,
protocol=self.protocol,
protocol_parameters=self.protocol_parameters,
transport=self.transport,
transport_parameters=self.transport_parameters)
class ConnectionProfileManager(object):
@classmethod
def to_profile(cls, data):
return ConnectionProfile.from_dict(data)
def __init__(self):
self._current = None
self._folder = settings().getBaseFolder("connectionProfiles")
self._logger = logging.getLogger(__name__)
def select(self, identifier):
self._current = self.get(identifier)
if self._current is None:
self._logger.error("Profile {} is invalid, cannot select".format(identifier))
return False
return True
def deselect(self):
self._current = None
@property
def current(self):
return self._current
def get_all(self):
return self._load_all()
def get(self, identifier):
try:
if self.exists(identifier):
return self._load_from_path(self._get_profile_path(identifier))
else:
return None
except InvalidProfileError:
return None
def remove(self, identifier):
return self._remove_from_path(self._get_profile_path(identifier))
def save(self, profile, allow_overwrite=False, make_default=False):
self._save_to_path(self._get_profile_path(profile.id),
profile,
allow_overwrite=allow_overwrite)
if make_default:
self.set_default(profile.id)
return self.get(profile.id)
@property
def profile_count(self):
return len(self._load_all_identifiers())
@property
def last_modified(self):
dates = [os.stat(self._folder).st_mtime]
dates += [entry.stat().st_mtime for entry in scandir(self._folder) if entry.name.endswith(".profile")]
return max(dates)
def get_default(self):
default = settings().get(["connectionProfiles", "default"])
if default is not None and self.exists(default):
profile = self.get(default)
if profile is not None:
return profile
else:
self._logger.warning("Default profile {} is invalid".format(default))
return None
def set_default(self, identifier):
all_identifiers = self._load_all_identifiers()
if identifier is not None and identifier not in all_identifiers:
return
settings().set(["connectionProfiles", "default"], identifier)
settings().save()
def get_current_or_default(self):
if self._current is not None:
return self._current
else:
return self.get_default()
def get_current(self):
return self._current
def exists(self, identifier):
if identifier is None:
return False
path = self._get_profile_path(identifier)
return os.path.exists(path) and os.path.isfile(path)
def _load_all(self):
all_identifiers = self._load_all_identifiers()
results = dict()
for identifier, path in all_identifiers.items():
try:
profile = self._load_from_path(path)
except InvalidProfileError:
self._logger.warning("Profile {} is invalid, skipping".format(identifier))
continue
if profile is None:
continue
results[identifier] = profile
return results
def _load_all_identifiers(self):
results = dict()
for entry in scandir(self._folder):
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
continue
if not entry.is_file():
continue
identifier = entry.name[:-len(".profile")]
results[identifier] = entry.path
return results
def _load_from_path(self, path):
if not os.path.exists(path) or not os.path.isfile(path):
return None
import yaml
with io.open(path, 'rt', encoding='utf-8') as f:
data = yaml.safe_load(f)
if data is None or not isinstance(data, dict):
raise InvalidProfileError("Profile is None or not a dict")
return ConnectionProfile.from_dict(data)
def _save_to_path(self, path, profile, allow_overwrite=False):
if os.path.exists(path) and not allow_overwrite:
raise SaveError("Profile {} already exists and overwriting is not allowed".format(profile["id"]))
from octoprint.util import atomic_write
import yaml
try:
with atomic_write(path, mode="wt", max_permissions=0o666) as f:
yaml.safe_dump(profile.as_dict(), f,
default_flow_style=False,
indent=2,
allow_unicode=True)
except Exception as e:
self._logger.exception("Error while trying to save profile {}".format(profile["id"]))
raise SaveError("Cannot save profile {}: {}".format(profile["id"], e))
def _remove_from_path(self, path):
try:
os.remove(path)
return True
except Exception:
return False
def _get_profile_path(self, identifier):
return os.path.join(self._folder, "{}.profile".format(identifier))
class InvalidProfileError(Exception):
pass
class SaveError(Exception):
pass
+573
View File
@@ -0,0 +1,573 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import copy
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, ProtocolState, FileManagementProtocolMixin
from octoprint.util.listener import ListenerAware
from abc import ABCMeta, abstractmethod, abstractproperty
from octoprint.util import monotonic_time
from future.utils import with_metaclass
class LastResult(object):
def __init__(self):
self.elapsed = None
self.clean_elapsed = None
self.progress = None
self.pos = None
self.success = None
self.available = False
class Printjob(with_metaclass(ABCMeta, ProtocolListener, ListenerAware)):
parallel = False
"""Job runs parallel to regular communication."""
exclusive = False
"""Job has exclusive claim to communication channel."""
def __init__(self, name=None, user=None, event_data=None):
if event_data is None:
event_data = dict()
super(Printjob, self).__init__()
self._logger = logging.getLogger(__name__)
self._start = None
self._protocol = None
self._printer_profile = None
self._name = name
self._user = user
self._event_data = event_data
self._lost_time = 0
self._last_result = LastResult()
@property
def name(self):
return self._name
@property
def user(self):
return self._user
@property
def size(self):
return None
@property
def pos(self):
return None
@property
def elapsed(self):
return monotonic_time() - self._start if self._start is not None else None
@property
def clean_elapsed(self):
elapsed = self.elapsed
if elapsed is None:
return None
return elapsed - self._lost_time
@property
def last_result(self):
return self._last_result
@property
def progress(self):
size = self.size
pos = self.pos
if pos is None or size is None or size == 0:
return None
return float(pos) / float(size)
@property
def active(self):
return self._start is not None
def add_to_lost_time(self, value):
self._lost_time += value
def can_process(self, protocol):
return False
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
self._last_result = LastResult()
self._start = monotonic_time()
self._user = user
self._protocol = protocol
self._protocol.register_listener(self)
def pause(self, user=None, tags=None, **kwargs):
self.process_job_paused(user=user, tags=tags, **kwargs)
def resume(self, user=None, tags=None, **kwargs):
self.process_job_resumed(user=user, tags=tags, **kwargs)
def cancel(self, error=False, user=None, tags=None, **kwargs):
if error:
self.process_job_failed(**kwargs)
else:
self.process_job_cancelled(user=user, tags=tags, **kwargs)
self._protocol.unregister_listener(self)
self._protocol = None
def get_next(self):
return None
def can_get_content(self):
return False
def get_content_generator(self):
return None
def event_payload(self, incl_last=False):
payload = copy.deepcopy(self._event_data)
payload["owner"] = self._user
elapsed = self.elapsed
if elapsed is None and incl_last and self.last_result.available:
elapsed = self.last_result.elapsed
if elapsed is not None:
payload["time"] = elapsed
return payload
def process_job_started(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_started", self, user=user, tags=tags, **kwargs)
def process_job_done(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_done", self, user=user, tags=tags, **kwargs)
self.report_stats()
self.reset_job()
def process_job_failed(self, **kwargs):
self.notify_listeners("on_job_failed", self, **kwargs)
self.report_stats()
self.reset_job(success=False)
def process_job_cancelled(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_cancelled", self, user=user, tags=tags, **kwargs)
self.report_stats()
self.reset_job(success=False)
def process_job_paused(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_paused", self, user=user, tags=tags, **kwargs)
def process_job_resumed(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_resumed", self, user=user, tags=tags, **kwargs)
def process_job_progress(self):
self.notify_listeners("on_job_progress", self)
def report_stats(self):
elapsed = self.elapsed
if elapsed:
self._logger.info("Job processed in {}s".format(elapsed))
def reset_job(self, success=True):
self._last_result.progress = 1.0 if success else self.progress
self._last_result.pos = self.size if success else self.pos
self._last_result.elapsed = self.elapsed
self._last_result.clean_elapsed = self.clean_elapsed
self._last_result.success = success
self._last_result.available = True
self._start = None
self._lost_time = 0
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
if new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) and self.active:
self.cancel(error=True)
class StoragePrintjob(Printjob):
def __init__(self, storage, path_in_storage, *args, **kwargs):
Printjob.__init__(self, *args, **kwargs)
self._storage = storage
self._path_in_storage = path_in_storage
@property
def storage(self):
return self._storage
@property
def path_in_storage(self):
return self._path_in_storage
def event_payload(self, incl_last=False):
payload = Printjob.event_payload(self, incl_last=incl_last)
payload["name"] = self.name
payload["path"] = self.path_in_storage
payload["origin"] = self.storage
return payload
class LocalFilePrintjob(StoragePrintjob):
def __init__(self, path, *args, **kwargs):
encoding = kwargs.pop("encoding", "utf-8")
StoragePrintjob.__init__(self, *args, **kwargs)
if path is None or not os.path.exists(path):
raise ValueError("path must be set to a local file path")
self._path = path
self._encoding = encoding
self._size = os.stat(path).st_size
self._pos = 0
self._read_lines = 0
self._actual_lines = 0
self._cancel_pos = None
self._handle = None
@property
def size(self):
return self._size
@property
def pos(self):
return self._pos
@property
def actual_lines(self):
return self._actual_lines
@property
def read_lines(self):
return self._read_lines
@property
def cancel_pos(self):
return self._cancel_pos
@property
def active(self):
return self._start is not None and self._handle is not None
@property
def path(self):
return self._path
def event_payload(self, incl_last=False):
event_data = StoragePrintjob.event_payload(self, incl_last=incl_last)
event_data["size"] = self.size
return event_data
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs)
from octoprint.util import bom_aware_open
self._handle = bom_aware_open(self._path, encoding=self._encoding, errors="replace")
if position > 0:
self._handle.seek(position)
self._pos = position
self.process_job_started(user=user, tags=tags)
def cancel(self, error=False, user=None, tags=None, **kwargs):
self._cancel_pos = self.pos
super(LocalFilePrintjob, self).cancel(error=error, user=user, tags=tags, **kwargs)
def get_next(self):
from octoprint.util import to_unicode
if self._handle is None:
raise ValueError("File {} is not open for reading" % self._path)
try:
processed = None
while processed is None:
if self._handle is None:
# file got closed just now
self.process_job_done()
return None
line = to_unicode(self._handle.readline())
# we need to manually keep track of our pos here since
# codecs' readline will make our handle's tell not
# return the actual number of bytes read, but also the
# already buffered bytes (for detecting the newlines)
self._pos += len(line)
self._actual_lines += 1
if not line:
self.process_job_done()
return None
processed = self.process_line(line)
self._read_lines += 1
self.process_job_progress()
return processed
except Exception as e:
self.cancel(error=True)
self._logger.exception("Exception while processing line")
raise e
def process_line(self, line):
return line
def close(self):
if self._handle is not None:
try:
self._handle.close()
except Exception:
pass
self._handle = None
def can_get_content(self):
return True
def get_content_generator(self):
from octoprint.util import bom_aware_open
with bom_aware_open(self._path, encoding=self._encoding, error="replace") as f:
for line in f.readline():
yield line
def reset_job(self, success=True):
super(LocalFilePrintjob, self).reset_job(success=success)
self.close()
self._pos = self._read_lines = 0
def report_stats(self):
elapsed = self.elapsed
lines = self._read_lines
if elapsed and lines:
self._logger.info("Job processed in {:.3f}s ({} lines)".format(elapsed, lines))
class LocalGcodeFilePrintjob(LocalFilePrintjob):
def can_process(self, protocol):
return LocalGcodeFilePrintjob in protocol.supported_jobs
def process_line(self, line):
# TODO no dependency on protocol module
from octoprint.comm.protocol.reprap.util import strip_comment
# strip line
processed = line.strip()
# strip comments
processed = strip_comment(processed)
if not len(processed):
return None
# TODO apply offsets
# return result
return processed
class CopyJobMixin(object):
pass
class LocalGcodeStreamjob(LocalGcodeFilePrintjob, CopyJobMixin):
exclusive = True
@classmethod
def from_job(cls, job, remote):
if not isinstance(job, LocalGcodeFilePrintjob):
raise ValueError("job must be a LocalGcodeFilePrintjob")
path = job._path
storage = job._storage
path_in_storage = job._path_in_storage
name = job._name
user = job._user
encoding = job._encoding
event_data = job._event_data
return cls(remote, path, storage, path_in_storage,
name=name, user=user, encoding=encoding, event_data=event_data)
def __init__(self, remote, *args, **kwargs):
super(LocalGcodeStreamjob, self).__init__(*args, **kwargs)
self._remote = remote
@property
def remote(self):
return self._remote
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
super(LocalGcodeStreamjob, self).process(protocol, position=position, user=user, tags=tags, **kwargs)
self._protocol.record_file(self._remote)
def process_job_done(self, user=None, tags=None, **kwargs):
self._protocol.stop_recording_file()
super(LocalGcodeStreamjob, self).process_job_done(user=user, tags=tags, **kwargs)
def process_job_failed(self, **kwargs):
self._protocol.stop_recording_file()
super(LocalGcodeStreamjob, self).process_job_failed(**kwargs)
def process_job_cancelled(self, user=None, tags=None, **kwargs):
self._protocol.stop_recording_file()
self._protocol.delete_file(self.remote)
super(LocalGcodeStreamjob, self).process_job_cancelled(user=user, tags=tags, **kwargs)
def can_process(self, protocol):
from octoprint.comm.protocol import FileStreamingProtocolMixin
return LocalGcodeStreamjob in protocol.supported_jobs and isinstance(protocol, FileStreamingProtocolMixin) and isinstance(protocol, FileManagementProtocolMixin)
def report_stats(self):
elapsed = self.elapsed
lines = self._read_lines
if elapsed and lines:
self._logger.info("Job processed in {:.3f}s ({} lines). Approx. {:.3f} lines/s, {:.3f} ms/line".format(elapsed,
lines,
float(lines) / float(elapsed),
float(elapsed) * 1000.0 / float(lines)))
class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener):
parallel = True
def __init__(self, path, status_interval=2.0, *args, **kwargs):
name = path
if name.startswith("/"):
name = name[1:]
StoragePrintjob.__init__(self,
"sdcard",
name,
name=name,
event_data=dict(name=name,
path=path,
origin="sdcard"))
self._filename = path
self._status_interval = status_interval
self._status_timer = None
self._active = False
self._size = None
self._last_pos = None
@property
def size(self):
return self._size
@property
def pos(self):
return self._last_pos
@property
def active(self):
return self._start is not None and self._active
@property
def status_interval(self):
return self._status_interval
def can_process(self, protocol):
from octoprint.comm.protocol import FileAwareProtocolMixin
return SDFilePrintjob in protocol.supported_jobs and isinstance(protocol, FileAwareProtocolMixin)
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs)
self._protocol.register_listener(self)
self._active = True
self._last_pos = position
self._protocol.start_file_print(self._filename,
position=position,
user=user,
tags=tags,
part_of_job=True,
**kwargs)
self._protocol.start_file_print_status_monitor()
def pause(self, user=None, tags=None, **kwargs):
super(SDFilePrintjob, self).pause(user=user, tags=tags, **kwargs)
self._protocol.pause_file_print(user=user,
tags=tags,
part_of_job=True,
**kwargs)
def resume(self, user=None, tags=None, **kwargs):
super(SDFilePrintjob, self).resume(user=user, tags=tags, **kwargs)
self._protocol.resume_file_print(user=user,
tags=tags,
part_of_job=True,
**kwargs)
def on_protocol_sd_status(self, protocol, pos, total):
self._last_pos = pos
self._size = total
self.process_job_progress()
def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs):
self._size = size
self.process_job_started(**kwargs)
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
self._protocol.stop_file_print_status_monitor(**kwargs)
self.process_job_done(**kwargs)
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
self._protocol.pause_file_print(**kwargs)
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
self._protocol.resume_file_print(**kwargs)
def reset_job(self, success=True):
super(SDFilePrintjob, self).reset_job(success=success)
self._active = False
self._last_pos = None
self._size = None
def event_payload(self, incl_last=False):
payload = Printjob.event_payload(self, incl_last=incl_last)
payload["size"] = self.size
return payload
class PrintjobListener(object):
def on_job_started(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_done(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_failed(self, job, *args, **kwargs):
pass
def on_job_cancelling(self, job, firmware_error=None, *args, **kwargs):
pass
def on_job_cancelled(self, job, cancel_position=None, suppress_script=False, *args, **kwargs):
pass
def on_job_paused(self, job, pause_position=None, suppress_script=False, *args, **kwargs):
pass
def on_job_resumed(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_progress(self, job, *args, **kwargs):
pass
+542
View File
@@ -0,0 +1,542 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.transport import TransportListener, TransportState
from octoprint.plugin import plugin_manager
from octoprint.util import to_unicode, CountedEvent
from octoprint.util.listener import ListenerAware
from octoprint.settings import SubSettings
import contextlib
import copy
import logging
_registry = dict()
def register_protocols():
from .reprap import ReprapGcodeProtocol
logger = logging.getLogger(__name__)
# stock protocols
register_protocol(ReprapGcodeProtocol)
# more protocols provided by plugins
hooks = plugin_manager().get_hooks("octoprint.comm.protocol.register")
for name, hook in hooks.items():
try:
protocols = hook()
for protocol in protocols:
try:
register_protocol(protocol)
except Exception:
logger.exception("Error while registering protocol class {} for plugin {}".format(protocol, name))
except Exception:
logger.exception("Error executing octoprint.comm.protocol.register hook for plugin {}".format(name))
def register_protocol(protocol_class):
if not hasattr(protocol_class, "key"):
raise ValueError("Protocol class {} is missing key".format(protocol_class))
_registry[protocol_class.key] = protocol_class
def lookup_protocol(key):
return _registry.get(key)
def all_protocols():
return _registry.values()
class Protocol(ListenerAware, TransportListener):
name = None
key = None
supported_jobs = []
@classmethod
def get_connection_options(cls):
return []
@classmethod
def get_settings_defaults(cls):
return dict()
def __init__(self, *args, **kwargs):
super(Protocol, self).__init__()
self._logger = logging.getLogger(__name__)
self._protocol_logger = logging.getLogger("PROTOCOL")
self._state = ProtocolState.DISCONNECTED
self._error = None
self._printer_profile = kwargs.get("printer_profile")
self._plugin_manager = kwargs.get("plugin_manager")
self._event_bus = kwargs.get("event_bus")
self._settings = kwargs.get("settings")
if not isinstance(self._settings, ProtocolSettings):
self._settings = ProtocolSettings(self._settings, self)
self._job = None
self._transport = None
self._job_on_hold = CountedEvent()
self._args = dict()
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@contextlib.contextmanager
def job_put_on_hold(self, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
raise RuntimeError("Could not acquire job_on_hold lock")
self._job_on_hold.set()
try:
yield
finally:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._job_on_hold_cleared()
self._job_on_hold.release()
@property
def job_on_hold(self):
return self._job_on_hold.counter > 0
def set_job_on_hold(self, value, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
return False
try:
if value:
self._job_on_hold.set()
else:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._job_on_hold_cleared()
finally:
self._job_on_hold.release()
return True
@property
def transport(self):
return self._transport
@property
def state(self):
return self._state
@state.setter
def state(self, new_state):
old_state = self._state
if old_state == new_state:
return
self._state = new_state
name = "_on_switching_state_{}".format(new_state)
method = getattr(self, name, None)
if method is not None:
method(old_state)
self.process_protocol_log("--- Protocol state changed from '{}' to '{}'".format(old_state, new_state))
self.notify_listeners("on_protocol_state", self, old_state, new_state)
name = "_on_switched_state_{}".format(new_state)
method = getattr(self, name, None)
if method is not None:
method(old_state)
@property
def error(self):
return self._error
@error.setter
def error(self, new_error):
self._error = new_error
def connect(self, transport, transport_args=None, transport_kwargs=None):
if self.state not in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR):
raise ProtocolAlreadyConnectedError("Already connected, disconnect first")
self.process_protocol_log("--- Protocol {} connecting via transport {}...".format(self,
transport))
if transport_args is None:
transport_args = []
if transport_kwargs is None:
transport_kwargs = dict()
self._transport = transport
self._transport.register_listener(self)
if self._transport.state == TransportState.DISCONNECTED:
self._transport.connect(*transport_args, **transport_kwargs)
self.state = ProtocolState.CONNECTING
def disconnect(self, error=False):
if self.state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR, ProtocolState.DISCONNECTING, ProtocolState.DISCONNECTING_WITH_ERROR):
raise ProtocolNotConnectedError("Already disconnecting or disconnected")
if error:
self.state = ProtocolState.DISCONNECTING_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTING
self.process_protocol_log("--- Protocol {} disconnecting from transport {}...".format(self,
self._transport))
self._transport.unregister_listener(self)
if self._transport.state == TransportState.CONNECTED:
try:
self._transport.disconnect()
except Exception:
self._logger.exception("Error while disconnecting from transport {}".format(self._transport))
error = True
if error:
self.state = ProtocolState.DISCONNECTED_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTED
def process(self, job, position=0, user=None, tags=None, **kwargs):
if not job.can_process(self):
raise ValueError("Job {} cannot be processed with protocol {}".format(job, self))
self._job = job
self._job.register_listener(self)
self.state = ProtocolState.STARTING
self.notify_listeners("on_protocol_job_starting", self, self._job, user=user, tags=tags, **kwargs)
self._job.process(self, position=position, user=user, tags=tags, **kwargs)
def pause_processing(self, user=None, tags=None, **kwargs):
if self._job is None or self.state not in ProtocolState.PROCESSING_STATES:
return
self.state = ProtocolState.PAUSING
self.notify_listeners("on_protocol_job_pausing", self, self._job, user=user, tags=tags, **kwargs)
self._job.pause(user=user, tags=tags)
def resume_processing(self, user=None, tags=None, **kwargs):
if self._job is None or self.state not in (ProtocolState.PAUSING, ProtocolState.PAUSED):
return
self.state = ProtocolState.RESUMING
self.notify_listeners("on_protocol_job_resuming", self, self._job, user=user, tags=tags, **kwargs)
self._job.resume(user=user, tags=tags, **kwargs)
def cancel_processing(self, error=False, user=None, tags=None, **kwargs):
if self._job is not None and self.state in ProtocolState.PROCESSING_STATES + (ProtocolState.PAUSED,):
self.state = ProtocolState.CANCELLING
self.notify_listeners("on_protocol_job_cancelling", self, self._job, user=user, tags=tags, **kwargs)
self._job.cancel(error=error, user=user, tags=tags, **kwargs)
def can_send(self):
return True
def send_commands(self, command_type=None, tags=None, *commands):
pass
def send_script(self, script, context=None, user=None, tags=None):
"""
Sends the specified script/the GCODE script with the specified name.
Args:
script (GcodeScript or unicode): Script or name of the script to send
context (dict): Additional render context
user (str): The user on whose behalf the script is being sent. May be None
tags (set): And tags to send with the script commands. May be None
"""
pass
def repair(self):
pass
def on_job_started(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs)
self.state = ProtocolState.PROCESSING
def on_job_paused(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_paused", self, job, *args, **kwargs)
self.state = ProtocolState.PAUSED
def on_job_resumed(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_resumed", self, job, *args, **kwargs)
self.state = ProtocolState.PROCESSING
def on_job_done(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs)
self._job_processed(job)
def on_job_cancelled(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_cancelled", self, job, *args, **kwargs)
self._job_processed(job)
def on_job_failed(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_failed", self, job, *args, **kwargs)
self._job_processed(job)
def _job_processed(self, job, *args, **kwargs):
self._job.unregister_listener(self)
self.state = ProtocolState.CONNECTED
def on_transport_disconnected(self, transport, error=None):
self.disconnect(error=error is not None)
def on_transport_log_received_data(self, transport, data):
message = "<<< {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def on_transport_log_sent_data(self, transport, data):
message = ">>> {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def on_transport_log_message(self, transport, data):
message = "--- {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def process_protocol_log(self, message):
self._protocol_logger.info(message)
self.notify_listeners("on_protocol_log", self, message)
def _job_on_hold_cleared(self):
pass
def __str__(self):
return self.__class__.__name__
class ProtocolState(object):
CONNECTING = "connecting"
CONNECTED = "connected"
DISCONNECTING = "disconnecting"
DISCONNECTED = "disconnected"
STARTING = "starting"
PROCESSING = "processing"
FINISHING = "finishing"
CANCELLING = "cancelling"
PAUSING = "pausing"
RESUMING = "resuming"
PAUSED = "paused"
ERROR = "error"
DISCONNECTING_WITH_ERROR = "disconnecting_with_error"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
PROCESSING_STATES = (STARTING, PROCESSING, CANCELLING, PAUSING, RESUMING, FINISHING)
OPERATIONAL_STATES = (CONNECTED, PAUSED) + PROCESSING_STATES
class ProtocolSettings(SubSettings):
def __init__(self, settings, protocol):
SubSettings.__init__(self, settings, ["comm", "protocol", protocol.key],
defaults=protocol.get_settings_defaults())
class ProtocolAlreadyConnectedError(Exception):
pass
class ProtocolNotConnectedError(Exception):
pass
class ThreeAxisProtocolMixin(object):
def move(self, x=None, y=None, z=None, feedrate=None, relative=False, *args, **kwargs):
pass
def home(self, x=False, y=False, z=False, *args, **kwargs):
pass
class MultiToolProtocolMixin(object):
def change_tool(self, tool, *args, **kwargs):
pass
class ThreeDPrinterProtocolMixin(ThreeAxisProtocolMixin, MultiToolProtocolMixin):
def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False, *args, **kwargs):
pass
def set_feedrate_multiplier(self, multiplier, *args, **kwargs):
pass
def set_extrusion_multiplier(self, multiplier, *args, **kwargs):
pass
def set_extruder_temperature(self, temperature, tool=None, wait=False, *args, **kwargs):
pass
def set_bed_temperature(self, temperature, wait=False, *args, **kwargs):
pass
def set_chamber_temperature(self, temperature, wait=False, *args, **kwargs):
pass
class FanControlProtocolMixin(object):
def set_fan_speed(self, speed, *args, **kwargs):
pass
def get_fan_speed(self, speed, *args, **kwargs):
pass
class MotorControlProtocolMixin(object):
def enable_motors(self, *args, **kwargs):
self.set_motor_state(True)
def disable_motors(self, *args, **kwargs):
self.set_motor_state(False)
def set_motor_state(self, enabled, *args, **kwargs):
pass
def get_motor_state(self, *args, **kwargs):
pass
class PowerControlProtocolMixin(object):
def enable_power(self, *args, **kwargs):
self.set_power_state(True)
def disable_power(self, *args, **kwargs):
self.set_power_state(False)
def set_power_state(self, enabled, *args, **kwargs):
pass
def get_power_state(self, *args, **kwargs):
return None
class FileAwareProtocolMixin(object):
def init_file_storage(self, *args, **kwargs):
pass
def eject_file_storage(self, *args, **kwargs):
pass
def list_files(self, *args, **kwargs):
pass
def start_file_print(self, name, position=0, tags=None, *args, **kwargs):
pass
def pause_file_print(self, *args, **kwargs):
pass
def resume_file_print(self, *args, **kwargs):
pass
def get_file_print_status(self, *args, **kwargs):
pass
def start_file_print_status_monitor(self, *args, **kwargs):
pass
def stop_file_print_status_monitor(self, *args, **kwargs):
pass
class FileManagementProtocolMixin(FileAwareProtocolMixin):
def delete_file(self, name, *args, **kwargs):
pass
class FileStreamingProtocolMixin(FileManagementProtocolMixin):
def record_file(self, name, *args, **kwargs):
pass
def stop_recording_file(self, *args, **kwargs):
pass
class ProtocolListener(object):
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
pass
def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs):
pass
def on_protocol_log(self, protocol, message, *args, **kwargs):
pass
def on_protocol_reset(self, protocol, idle, *args, **kwargs):
pass
def on_protocol_job_started(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_pausing(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_paused(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_resuming(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_resumed(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_finishing(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_done(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_failed(self, protocol, job, *args, **kwargs):
pass
class FileAwareProtocolListener(object):
def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs):
pass
def on_protocol_file_list(self, protocol, files, *args, **kwargs):
pass
def on_protocol_file_status(self, protocol, pos, total, *args, **kwargs):
pass
def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs):
pass
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
pass
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
pass
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
pass
class PositionAwareProtocolListener(object):
def on_protocol_position_all_update(self, protocol, position, *args, **kwargs):
pass
def on_protocol_position_z_update(self, protocol, z, *args, **kwargs):
pass
class FirmwareDataAwareProtocolListener(object):
def on_protocol_firmware_info(self, protocol, info, *args, **kwargs):
pass
def on_protocol_firmware_capability(self, protocol, capability, enabled, capabilities, *args, **kwargs):
pass
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,93 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import re
from future.utils import with_metaclass
from octoprint.util import pp
_compiled_regex_type = type(re.compile(r"a"))
def _is_compiled_regex(obj):
return isinstance(obj, _compiled_regex_type)
__registry = dict()
def _register_command_class(cls):
__registry[cls.__name__] = cls
def to_command(line, type=None, tags=None, **kwargs):
if isinstance(line, Command):
return line
for cls in __registry.values():
if cls.pattern:
# noinspection PyUnresolvedReferences,PyProtectedMember
if _is_compiled_regex(cls.pattern) and cls.pattern.match(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
elif callable(cls.pattern) and cls.pattern(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
return Command.from_line(line, type=type, tags=tags, **kwargs)
class CommandMetaClass(type):
def __new__(mcs, *args, **kwargs):
c = type.__new__(mcs, *args, **kwargs)
_register_command_class(c)
return c
class Command(with_metaclass(CommandMetaClass, object)):
pattern = None
@classmethod
def from_line(cls, line, type=None, tags=None, **kwargs):
return cls(line, type=type, tags=tags, **kwargs)
def __init__(self, line, type=None, tags=None, **kwargs):
if tags is None:
tags = set()
self.line = line
self.bytes = line.encode("ascii", errors="replace")
self.type = type
self.tags = tags
def __repr__(self):
return "{}({!r},type={!r},tags={})".format(self.__class__.__name__, self.line, self.type, pp(self.tags))
def __str__(self):
return self.line
def __bytes__(self):
return self.bytes
def __key(self):
return self.line, self.type
def __eq__(self, other):
return self.__key() == other.__key()
def __hash__(self):
return hash(self.__key())
def with_type(self, type):
c = copy.deepcopy(self)
c.type = type
return c
def with_tags(self, tags):
if tags is None:
return self
c = copy.deepcopy(self)
c.tags |= tags
return c
@@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.commands import Command
from octoprint.util import pp
class AtCommand(Command):
pattern = staticmethod(lambda x: x.startswith("@"))
@staticmethod
def from_line(line, **kwargs):
split = line.split(None, 1)
if len(split) == 2:
atcommand = split[0]
parameters = split[1]
else:
atcommand = split[0]
parameters = ""
atcommand = atcommand[1:]
return AtCommand(line, atcommand, parameters, **kwargs)
def __init__(self, line, atcommand, parameters, **kwargs):
self.atcommand = atcommand
self.parameters = parameters
super(AtCommand, self).__init__(line, **kwargs)
def __repr__(self):
return "AtCommand({!r},{!r},{!r},type={!r},tags={}".format(self.line,
self.atcommand,
self.parameters,
self.type,
pp(self.tags))
@@ -0,0 +1,134 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.commands import Command
import re
import string
from octoprint.util import pp
class GcodeCommand(Command):
pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x))
command_regex = re.compile(r"^\s*((?P<GM>[GM](?P<number>\d+))(\\.(?P<subcode>\d+))?|(?P<T>T(?P<tool>\d+))|(?P<F>F(?P<feedrate>\d+)))")
parameter_regex = re.compile(r"(?P<key>[A-Z])((?P<value>[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))")
possible_params = tuple(string.ascii_lowercase) + ("subcode", "param", "tool", "feedrate", "original")
@staticmethod
def from_line(line, **kwargs):
if isinstance(line, GcodeCommand):
return line
tags = kwargs.get("tags")
if tags is None:
tags = set()
command_type = kwargs.get("type")
line = line.strip()
code = ""
args = dict(original=line, type=command_type, tags=tags)
match = GcodeCommand.command_regex.match(line)
if match is None:
# not a gcode command
return Command.from_line(line, **kwargs)
if match.group("GM"):
code = match.group("GM")
if match.group("subcode"):
args["subcode"] = int(match.group("subcode"))
if match.group(0) != line:
rest = line[len(match.group(0)):]
while True:
matched_param = GcodeCommand.parameter_regex.search(rest)
if not matched_param:
break
key = matched_param.group("key").lower()
if matched_param.group("value"):
value = matched_param.group("value")
if "." in value:
value = float(value)
else:
value = int(value)
else:
value = True
args[key] = value
rest = rest[:matched_param.start()] + rest[matched_param.end():]
rest = rest.lstrip()
if rest:
args["param"] = rest
elif match.group("T"):
code = "T"
args["tool"] = int(match.group("tool"))
elif match.group("F"):
code = "F"
args["feedrate"] = int(match.group("feedrate"))
return GcodeCommand(code, **args)
def __init__(self, code, **kwargs):
self.code = code
self.subcode = kwargs.pop("subcode", None)
self.tool = kwargs.pop("tool", None)
self.feedrate = kwargs.pop("feedrate", None)
self.param = kwargs.pop("param", None)
self.original = kwargs.pop("original", None)
command_type = kwargs.pop("type", None)
tags = kwargs.pop("tags", None)
self.args = kwargs
if self.original is None:
line = self._to_line()
else:
line = self.original
super(GcodeCommand, self).__init__(line, type=command_type, tags=tags)
self._repr = self._to_repr()
def __getattr__(self, item):
if len(item) == 1:
return self.args.get(item, None)
raise AttributeError("'GcodeCommand' object has no attribute '{}'".format(item))
def __repr__(self):
return self._repr
def _to_line(self):
attr = []
for key in string.ascii_lowercase:
value = self.args.get(key, None)
if value is not None:
if value is True:
attr.append(key.upper())
else:
attr.append("{}{!r}".format(key.upper(), value))
attribute_str = " ".join(attr)
return "{}{}{}".format(self.code.upper(), " " + attribute_str if attribute_str else "",
" " + self.param if self.param else "")
def _to_repr(self):
args = [k + "=" + repr(getattr(self, k)) for k in self.possible_params if getattr(self, k, None) is not None]
return "GcodeCommand({!r}{},type={!r},tags={})".format(self.code,
"," + ",".join(args) if args else "",
self.type,
pp(self.tags))
@@ -0,0 +1,44 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from .generic import * # noqa: F403
from .klipper import * # noqa: F403
from .marlin import * # noqa: F403
from .repetier import * # noqa: F403
from .reprapfirmware import * # noqa: F403
from .smoothieware import * # noqa: F403
from .anet import * # noqa: F403
from .malyan import * # noqa: F403
class FlavorOverride(object):
def __init__(self, flavor, overrides):
self._flavor = flavor
self._overrides = overrides
@property
def flavor(self):
return self._flavor
@flavor.setter
def flavor(self, value):
self._flavor = value
@property
def overrides(self):
return self._overrides
@overrides.setter
def overrides(self, value):
self._overrides = value
def __getattr__(self, item):
try:
return self._overrides[item]
except KeyError:
return getattr(self._flavor, item)
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from .repetier import RepetierFlavor
class AnetA8RepetierFlavor(RepetierFlavor):
key = "aneta8repetier"
name = "Anet A8"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "anet_a8" in firmware_name.lower()
@@ -0,0 +1,706 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
import logging
import time
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.reprap.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
from octoprint.util import chunks, monotonic_time
from future.utils import with_metaclass
_flavor_registry = dict()
def _register_flavor(cls):
key = getattr(cls, "key", None)
if key and not key in _flavor_registry:
_flavor_registry[key] = cls
def all_flavors():
return _flavor_registry.values()
def lookup_flavor(key):
return _flavor_registry.get(key)
class FlavorMeta(type):
def __new__(mcs, name, bases, class_dict):
cls = type.__new__(mcs, name, bases, class_dict)
_register_flavor(cls)
return cls
class GenericFlavor(with_metaclass(FlavorMeta, object)):
key = "generic"
name = "Generic Flavor"
logger = logging.getLogger(__name__)
unknown_requires_ack = False
unknown_with_checksum = False
always_send_checksum = False
never_send_checksum = False
detect_external_heatups = True
block_while_dwelling = False
trigger_ok_after_resend = "detect"
sd_relative_path = False
checksum_requiring_commands = ["M110"]
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"]
asynchronous_commands = ["G0", "G1", "G2", "G3"]
blocked_commands = ["M0", "M1"]
pausing_commands = ["M0", "M1", "M25"]
emergency_commands = ["M112", "M108", "M410"]
heatup_abortable = False
regex_resend_linenumber = re.compile(r"(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
regex_temp = re.compile(r"(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*/?\s*(?P<target>%s))?" % (
regex_positive_float_pattern, regex_positive_float_pattern))
"""Regex matching temperature entries in line.
Groups will be as follows:
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
* ``toolnum``: tool number, if provided (int)
* ``actual``: actual temperature (float)
* ``target``: target temperature, if provided (float)
"""
regex_position = re.compile(r"(?P<axis>[XYZE]):(?P<pos>{float})\s*".format(float=regex_float_pattern))
"""Regex for matching position entries in line.
Groups will be as follows:
* ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str)
* ``pos``: axis position (float)
"""
regex_firmware_splitter = re.compile(r"\s*([A-Z0-9_]+):")
"""Regex to use for splitting M115 responses."""
regex_sd_file_opened = re.compile(r"file opened:\s*(?P<name>.*?)(\s+size:\s*(?P<size>[0-9]+)|$)")
regex_sd_printing_byte = re.compile(r"sd printing byte (?P<current>[0-9]*)/(?P<total>[0-9]*)")
"""Regex matching SD printing status reports.
Groups will be as follows:
* ``current``: current byte position in file being printed
* ``total``: total size of file being printed
"""
##~~ Overrides
_overrides = dict()
@classmethod
def with_overrides(cls, overrides):
return type(b"{}WithOverrides".format(cls.__name__), (cls,), overrides)
##~~ Identifier
@classmethod
def identifier(cls, firmware_name, firmware_info):
return False
##~~ Message matchers
@classmethod
def comm_timeout(cls, line, lower_line, state, flags):
now = monotonic_time()
matches = ((line == "" and now > flags["timeout"]) or (flags["expect_continous_comms"]
and not flags["job_on_hold"]
and not flags["long_running_command"]
and not flags["heating"]
and now > flags["ok_timeout"])) and \
(not cls.block_while_dwelling or not flags["dwelling_until"] or now > flags["dwelling_until"])
continue_further = line != ""
return matches, continue_further
@classmethod
def comm_ok(cls, line, lower_line, state, flags):
matches = lower_line.startswith("ok")
continue_further = not matches \
or cls.message_temperature(line, lower_line, state, flags) \
or cls.message_position(line, lower_line, state, flags) \
or cls.message_firmware_info(line, lower_line, state, flags)
return matches, continue_further
@classmethod
def comm_start(cls, line, lower_line, state, flags):
return lower_line == "start"
@classmethod
def comm_wait(cls, line, lower_line, state, flags):
return lower_line == "wait"
@classmethod
def comm_resend(cls, line, lower_line, state, flags):
return lower_line.startswith("resend") or lower_line.startswith("rs")
@classmethod
def comm_action_command(cls, line, lower_line, state, flags):
return line.startswith("//") and line[2:].strip().startswith("action:")
@classmethod
def comm_error(cls, line, lower_line, state, flags):
return line.startswith("Error:") or line.startswith("!!")
@classmethod
def comm_ignore_ok(cls, line, lower_line, state, flags):
return False
@classmethod
def comm_busy(cls, line, lower_line, state, flags):
return line.startswith("echo:busy:") or line.startswith("busy:")
@classmethod
def error_multiline(cls, line, lower_line, state, flags):
return False
@classmethod
def error_communication(cls, line, lower_line, state, flags):
return "line number" in lower_line or "checksum" in lower_line or "format error" in lower_line or "expected line" in lower_line
@classmethod
def message_temperature(cls, line, lower_line, state, flags):
return "T:" in line or "T0:" in line or "B:" in line
@classmethod
def message_position(cls, line, lower_line, state, flags):
return 'X:' in line and 'Y:' in line and 'Z:' in line
@classmethod
def message_firmware_info(cls, line, lower_line, state, flags):
return "NAME:" in line
@classmethod
def message_firmware_capability(cls, line, lower_line, state, flags):
return lower_line.startswith("cap:")
@classmethod
def message_sd_init_ok(cls, line, lower_line, state, flags):
return "sd card ok" in lower_line
@classmethod
def message_sd_init_fail(cls, line, lower_line, state, flags):
return "sd init fail" in lower_line or "volume.init failed" in lower_line or "openroot failed" in lower_line
@classmethod
def message_sd_file_opened(cls, line, lower_line, state, flags):
return lower_line.startswith("file opened")
@classmethod
def message_sd_file_selected(cls, line, lower_line, state, flags):
return lower_line.startswith("file selected")
@classmethod
def message_sd_begin_file_list(cls, line, lower_line, state, flags):
return lower_line.startswith("begin file list")
@classmethod
def message_sd_end_file_list(cls, line, lower_line, state, flags):
return lower_line.startswith("end file list")
@classmethod
def message_sd_printing_byte(cls, line, lower_line, state, flags):
return "sd printing byte" in lower_line
@classmethod
def message_sd_not_printing(cls, line, lower_line, state, flags):
return "not sd printing" in lower_line
@classmethod
def message_sd_done_printing(cls, line, lower_line, state, flags):
return "done printing file" in lower_line
@classmethod
def message_sd_begin_writing(cls, line, lower_line, state, flags):
return "writing to file" in lower_line
@classmethod
def message_sd_end_writing(cls, line, lower_line, state, flags):
return "done saving file" in lower_line
@classmethod
def message_sd_entry(cls, line, lower_line, state, flags):
return flags["sd_files_temp"] is not None
##~~ Message parsers
@classmethod
def parse_comm_error(cls, line, lower_line, state, flags):
return dict(line=line, lower_line=lower_line)
@classmethod
def parse_comm_timeout(cls, line, lower_line, state, flags):
return dict(line=line, lower_line=lower_line)
@classmethod
def parse_comm_action_command(cls, line, lower_line, state, flags):
action = line[2:].strip()[len("action:"):].strip()
return dict(line=line, lower_line=lower_line, action=action)
@classmethod
def parse_error_communication(cls, line, lower_line, state, flags):
if "line number" in lower_line or "expected line" in lower_line:
error_type = "linenumber"
elif "checksum" in lower_line:
error_type = "checksum"
else:
error_type = "other"
flags["last_communication_error"] = error_type
return dict(error_type=error_type)
@classmethod
def parse_comm_resend(cls, line, lower_line, state, flags):
line_to_resend = None
match = cls.regex_resend_linenumber.search(line)
if match is not None:
line_to_resend = int(match.group("n"))
return dict(linenumber=line_to_resend)
@classmethod
def parse_message_temperature(cls, line, lower_line, state, flags):
"""
Parses the provided temperature line.
The result will be a dictionary mapping from the extruder or bed key to
a tuple with current and target temperature. The result will be canonicalized
with :func:`canonicalize_temperatures` before returning.
Returns:
tuple: a 2-tuple with the maximum tool number and a dict mapping from
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
"""
current_tool = flags["current_tool"]
result = {}
max_tool_num = 0
for match in re.finditer(cls.regex_temp, line):
values = match.groupdict()
tool = values["tool"]
if tool == "T" and "toolnum" in values and values["toolnum"]:
tool_num = int(values["toolnum"])
if tool_num > max_tool_num:
max_tool_num = tool_num
try:
actual = float(values.get("actual", None)) if values.get("actual", None) is not None else None
target = float(values.get("target", None)) if values.get("target", None) is not None else None
result[tool] = actual, target
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
heatup_detected = not lower_line.startswith("ok") and not flags["heating"] and not flags["temperature_autoreporting"]
return dict(max_tool_num=max(max_tool_num, current_tool),
temperatures=cls._canonicalize_temperatures(result, current_tool),
heatup_detected=heatup_detected)
@classmethod
def parse_message_position(cls, line, lower_line, state, flags):
position = dict(x=None, y=None, z=None, e=None)
for match in re.finditer(cls.regex_position, line):
position[match.group("axis").lower()] = float(match.group("pos"))
return dict(position=position)
@classmethod
def parse_message_firmware_info(cls, line, lower_line, state, flags):
data = cls._parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
if firmware_name is None:
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
# report its firmware name properly in response to M115. Wonderful - why stick to established
# protocol when you can do your own thing, right?
#
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
#
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
name = data.get("NAME")
ver = data.get("VER")
if "malyan" in name.lower() and ver:
firmware_name = name.strip() + " " + ver.strip()
if firmware_name is not None:
firmware_name = firmware_name.strip()
return dict(firmware_name=firmware_name,
data=data)
@classmethod
def parse_message_firmware_capability(cls, line, lower_line, state, flags):
result = cls._parse_capability_line(line)
if not result:
return
cap, enabled = result
return dict(cap=cap, enabled=enabled)
@classmethod
def parse_message_sd_file_opened(cls, line, lower_line, state, flags):
match = cls.regex_sd_file_opened.match(lower_line)
if not match:
return
name = match.group("name")
size = int(match.group("size"))
return dict(name=name, long_name=name, size=size)
@classmethod
def parse_message_sd_entry(cls, line, lower_line, state, flags):
fileinfo = lower_line.rsplit(None, 1)
if len(fileinfo) > 1:
# we might have extended file information here, so let's split filename and size and try to make them a bit nicer
filename, size = fileinfo
try:
size = int(size)
except ValueError:
# whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None
filename = lower_line
size = None
else:
# no extended file information, so only the filename is there and we set size to None
filename = lower_line
size = None
from octoprint.util import filter_non_ascii
if filter_non_ascii(filename):
return None
else:
if not filename.startswith("/"):
# file from the root of the sd -- we'll prepend a /
filename = "/" + filename
return dict(name=filename, long_name=filename, size=int(size) if size is not None else None)
@classmethod
def parse_message_sd_printing_byte(cls, line, lower_line, state, flags):
match = cls.regex_sd_printing_byte.match(lower_line)
if not match:
return None
return dict(current=int(match.group("current")), total=int(match.group("total")))
##~~ Commands
@classmethod
def command_hello(cls):
return cls.command_set_line(0)
@classmethod
def command_get_firmware_info(cls):
return GcodeCommand("M115")
@classmethod
def command_finish_moving(cls):
return GcodeCommand("M400")
@classmethod
def command_get_position(cls):
return GcodeCommand("M114")
@classmethod
def command_get_temp(cls):
return GcodeCommand("M105")
@classmethod
def command_set_line(cls, n):
return GcodeCommand("M110", n=n)
@classmethod
def command_emergency_stop(cls):
return GcodeCommand("M112")
@classmethod
def command_abort_heatup(cls):
return GcodeCommand("M108")
@classmethod
def command_set_extruder_temp(cls, temperature, tool=None, wait=False):
command = "M109" if wait else "M104"
args = dict(s=temperature)
if tool is not None:
args["t"] = tool
return GcodeCommand(command, **args)
@classmethod
def command_set_bed_temp(cls, temperature, wait=False):
return GcodeCommand("M190" if wait else "M140", s=temperature)
@classmethod
def command_set_chamber_temp(cls, temperature, wait=False):
return GcodeCommand("M191" if wait else "M141", s=temperature)
@classmethod
def command_set_relative_positioning(cls):
return GcodeCommand("G91")
@classmethod
def command_set_absolute_positioning(cls):
return GcodeCommand("G90")
@classmethod
def command_move(cls, x=None, y=None, z=None, e=None, f=None):
return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f)
@classmethod
def command_extrude(cls, e=None, f=None):
return cls.command_move(e=e, f=f)
@classmethod
def command_home(cls, x=False, y=False, z=False):
return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None)
@classmethod
def command_set_tool(cls, tool):
return GcodeCommand("T{}".format(tool))
@classmethod
def command_set_feedrate_multiplier(cls, multiplier):
return GcodeCommand("M220", s=multiplier)
@classmethod
def command_set_extrusion_multiplier(cls, multiplier):
return GcodeCommand("M221", s=multiplier)
@classmethod
def command_set_fan_speed(cls, speed):
return GcodeCommand("M106", s=speed)
@classmethod
def command_set_motors(cls, enable):
return GcodeCommand("M17") if enable else GcodeCommand("M18")
@classmethod
def command_sd_refresh(cls):
return GcodeCommand("M20")
@classmethod
def command_sd_init(cls):
return GcodeCommand("M21")
@classmethod
def command_sd_release(cls):
return GcodeCommand("M22")
@classmethod
def command_sd_select_file(cls, name):
return GcodeCommand("M23", param=name)
@classmethod
def command_sd_start(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_pause(cls):
return GcodeCommand("M25")
@classmethod
def command_sd_resume(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_set_pos(cls, pos):
return GcodeCommand("M26", s=pos)
@classmethod
def command_sd_status(cls):
return GcodeCommand("M27")
@classmethod
def command_sd_begin_write(cls, name):
return GcodeCommand("M28", param=name)
@classmethod
def command_sd_end_write(cls):
return GcodeCommand("M29")
@classmethod
def command_sd_delete(cls, name):
return GcodeCommand("M30", param=name)
@classmethod
def command_autoreport_temperature(cls, interval):
return GcodeCommand("M155", s=interval)
@classmethod
def command_autoreport_sd_status(cls, interval):
return GcodeCommand("M27", s=interval)
@classmethod
def command_busy_protocol_interval(cls, interval):
return GcodeCommand("M113", s=interval)
##~~ Helpers
@classmethod
def _canonicalize_temperatures(cls, parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
``T`` from the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys()))
if not "T" in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, so T contains the current
# extruder's temperature, e.g. for current_tool == 1:
#
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
#
# Same goes if Tc is already present, it will be overwritten:
#
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result[current_tool_key] = result["T"]
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
#
# In both cases it is however safe to just move our T over
# to T<current> in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
result[current_tool_key] = result["T"]
del result["T"]
return result
@classmethod
def _parse_firmware_line(cls, line):
"""
Parses the provided firmware info line.
The result will be a dictionary mapping from the contained keys to the contained
values.
Arguments:
line (unicode): the line to parse
Returns:
dict: a dictionary with the parsed data
"""
result = dict()
split_line = cls.regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
for key, value in chunks(split_line, 2):
result[key] = value
return result
@classmethod
def _parse_capability_line(cls, line):
"""
Parses the provided firmware capability line.
Lines are expected to be of the format
Cap:<capability name in caps>:<0 or 1>
e.g.
Cap:AUTOREPORT_TEMP:1
Cap:TOGGLE_LIGHTS:0
Args:
line (unicode): the line to parse
Returns:
tuple: a 2-tuple of the parsed capability name and whether it's on (true) or off (false), or None if the line
could not be parsed
"""
line = line.lower()
if line.startswith("cap:"):
line = line[len("cap:"):]
parts = line.split(":")
if len(parts) != 2:
# wrong format, can't parse this
return None
capability, flag = parts
if not flag in ("0", "1"):
# wrong format, can't parse this
return None
return capability.upper(), flag == "1"
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "klipper"
name = "Klipper"
unknown_requires_ack = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "klipper" in firmware_name.lower()
@@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MalyanFlavor(GenericFlavor):
key = "malyan"
name = "Malyan"
always_send_checksum = False
block_while_dwelling = True
sd_always_available = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "malyan" in firmware_name.lower()
@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MarlinFlavor(GenericFlavor):
key = "marlin"
name = "Marlin"
emergency_commands = ["M112", "M108", "M410"]
heatup_abortable = True
class MarlinLegacyFlavor(GenericFlavor):
key = "marlinlegacy"
name = "Legacy Marlin"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "marlin v1" in firmware_name.lower()
class PrusaMarlinFlavor(MarlinFlavor):
key = "prusamarlin"
name = "Marlin: Prusa variant"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "prusa-firmware" in firmware_name.lower() and "marlin" in firmware_name.lower()
@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors import GenericFlavor
from octoprint.comm.protocol.reprap.util import regex_positive_float_pattern
import re
class RepetierFlavor(GenericFlavor):
key = "repetier"
name = "Repetier"
always_send_checksum = True
identical_resends_countdown = 5
block_while_dwelling = True
detect_external_heatups = False
regex_tempextr = re.compile("targetextr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier.
Groups will be as follows:
* ``toolnum``: number of the extruder to which the target temperature
report belongs (int)
* ``target``: new target temperature (float)
"""
regex_tempbed = re.compile("targetbed:(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows:
* ``target``: new target temperature (float)
"""
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "repetier" in firmware_name.lower()
@classmethod
def message_temperature(cls, line, lower_line, state, flags):
return GenericFlavor.message_temperature(line, lower_line, state, flags) or "targetextr" in lower_line or "targetbed" in lower_line
@classmethod
def parse_message_temperature(cls, line, lower_line, state, flags):
if "targetextr" in lower_line:
match = cls.regex_tempextr.match(lower_line)
if match is not None:
tool_num = int(match.group("toolnum"))
target = float(match.group("target"))
tool = "T{}".format(tool_num)
temperatures = dict()
temperatures[tool] = (None, target)
return dict(max_tool_num=max(tool_num, flags.get("current_tool", 0)),
temperatures=temperatures,
heatup_detected=False)
elif "targetbed" in lower_line:
match = cls.regex_tempbed.match(lower_line)
if match is not None:
target = float(match.group("target"))
temperatures = dict(bed=(None, target))
return dict(max_tool_num=flags.get("current_tool", 0),
temperatures=temperatures,
heatup_detected=False)
else:
# Repetier sends temperature output on it's own line, so we can't use the
# "no ok in temperature output" metric to detected external heatups
result = GenericFlavor.parse_message_temperature(line, lower_line, state, flags)
result[b"heatup_detected"] = False
return result
##~~ Preprocessors, returning True stops further processing by the protocol
@classmethod
def preprocess_comm_resend(cls, linenumber, state, flags):
if flags.get("resend_swallow_repetitions", False) \
and flags.get("resend_swallow_repetitions_counter", 0) \
and linenumber == flags["resend_requested"] \
and flags["resend_swallow_repetitions_counter"] > 0:
cls.logger.debug("Ignoring resend request for line {}, that is "
"probably a repetition sent by the firmware to "
"ensure it arrives, not a real request"
.format(linenumber))
flags["resend_swallow_repetitions_counter"] -= 1
return True
flags["resend_swallow_repetitions_counter"] = cls.identical_resends_countdown
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "reprapfirmware"
name = "RepRapFirmware"
sd_relative_path = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "reprapfirmware" in firmware_name.lower()
@@ -0,0 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "smoothieware"
name = "Smoothieware"
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.scripts import Script, UnknownScript
from octoprint.comm.protocol.reprap.util import process_gcode_line
class GcodeScript(Script):
def __init__(self, settings, name, context=None):
def renderer(ctx):
lines = settings.loadScript("gcode", name, context=ctx)
if lines is None:
raise UnknownScript(name)
return lines
super(GcodeScript, self).__init__(name, renderer, context=context)
def render(self, context=None):
script = super(GcodeScript, self).render(context)
return list(filter(lambda x: x is not None and x.strip() != "",
map(lambda x: process_gcode_line(x),
script)))
@@ -0,0 +1,398 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.commands import Command, to_command
from octoprint.util import PrependableQueue, TypeAlreadyInQueue, CountedEvent
# noinspection PyCompatibility
from past.builtins import basestring
import contextlib
import copy
import logging
import threading
try:
# noinspection PyCompatibility
import queue
except Exception:
# noinspection PyCompatibility
import Queue as queue
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = "\d+"
def strip_comment(line):
if not ";" in line:
# shortcut
return line
escaped = False
result = []
for c in line:
if c == ";" and not escaped:
break
result += c
escaped = (c == "\\") and not escaped
return "".join(result).strip()
def process_gcode_line(line, offsets=None, current_tool=None):
line = strip_comment(line).strip()
if not len(line):
return None
# if offsets is not None:
# line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
return line
def normalize_command_handler_result(command, handler_results, tags_to_add=None):
"""
Normalizes a command handler result.
Handler results can be either ``None``, a single result entry or a list of result
entries.
``None`` results are ignored, the provided ``command``, ``command_type``,
``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with
one 5-tuple as entry).
Single result entries are either:
* a single string defining a replacement ``command``
* a 1-tuple defining a replacement ``command``
* a 2-tuple defining a replacement ``command`` and ``command_type``
* a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set
A ``command`` that is ``None`` will lead to the entry being ignored for
the normalized result.
The method returns a list of normalized result entries. Normalized result
entries always are a 4-tuple consisting of ``command``, ``command_type``,
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
be empty in which case the command is to be suppressed.
Examples:
>>> from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
>>> normalize_command_handler_result(GcodeCommand("M105"), None) # doctest: +ALLOW_UNICODE
[GcodeCommand('M105',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), GcodeCommand("M110")) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type='lineno_reset',tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), []) # doctest: +ALLOW_UNICODE
[]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", None]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type='display_message',tags=set()), GcodeCommand('M110',original='M110',type='lineno_reset',tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2'})]
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2', 'tag3'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2', 'tag3'})]
Arguments:
command (Command): The command for which the handler result was
generated
handler_results: The handler result(s) to normalized. Can be either
a single result entry or a list of result entries.
tags_to_add (set of unicode or None): List of tags to add to expanded result
entries
Returns:
(list) - A list of normalized handler result entries, which are
``Command`` instances
"""
original = command
if handler_results is None:
# handler didn't return anything, we'll just continue
return [original]
if not isinstance(handler_results, list):
handler_results = [handler_results, ]
result = []
for handler_result in handler_results:
# we iterate over all handler result entries and process each one
# individually here
if handler_result is None:
# entry is None, we'll ignore that entry and continue
continue
def expand_tags(tags, tags_to_add):
tags = tags.copy()
if tags_to_add and isinstance(tags_to_add, set):
tags |= tags_to_add
return tags
if isinstance(handler_result, basestring):
# entry is just a string, replace command with it
if handler_result != original.line:
# command changed, swap it
command = to_command(handler_result,
type=original.type,
tags=expand_tags(original.tags, tags_to_add))
result.append(command)
elif isinstance(handler_result, Command):
if handler_result != original:
command = copy.copy(handler_result)
command.tags = expand_tags(original.tags, tags_to_add)
result.append(command)
elif isinstance(handler_result, tuple):
# entry is a tuple, extract command and command_type
hook_result_length = len(handler_result)
command_type = original.type
command_tags = original.tags
if hook_result_length == 1:
# handler returned just the command
command_line, = handler_result
elif hook_result_length == 2:
# handler returned command and command_type
command_line, command_type = handler_result
elif hook_result_length == 3:
# handler returned command, command type and additional tags
command_line, command_type, command_tags = handler_result
else:
# handler returned a tuple of an unexpected length, ignore
# and continue
continue
if command_line is None:
# command is None, ignore it and continue
continue
if command_line != original.line or command_type != original.type:
# command or command_type changed, tags need to be rewritten
command_tags = expand_tags(command_tags, tags_to_add)
result.append(to_command(command_line, type=command_type, tags=command_tags))
# reset to original
command = original
return result
class SendToken(CountedEvent):
def __init__(self, value=0, maximum=None, **kwargs):
super(SendToken, self).__init__(value=value, maximum=maximum, **kwargs)
self._ignored = 0
def set(self, ignore=False):
with self._mutex:
if ignore:
self._ignored += 1
self._internal_set(self._counter + 1)
def clear(self, completely=False):
with self._mutex:
if completely:
self._internal_set(0)
self._ignored = 0
else:
if self._ignored > 0:
self._ignored -= 1
self._internal_set(self._counter - 1)
self._internal_set(self._counter - 1)
class LineHistory(object):
def __init__(self, max=None):
self.max = max
self._lines = []
self._mutex = threading.RLock()
self._line_number_lookup = dict()
@property
def lines(self):
with self._mutex:
return [x[0] for x in self._lines]
def append(self, line, line_number=None):
with self._mutex:
self._lines.append((line, line_number))
if line_number is not None:
self._line_number_lookup[line_number] = line
self._cleanup()
def clear(self):
with self._mutex:
self._lines = []
self._line_number_lookup = dict()
def __len__(self):
with self._mutex:
return len(self._lines)
def __getitem__(self, line_number):
with self._mutex:
return self._line_number_lookup[line_number]
def __contains__(self, line_number):
with self._mutex:
return line_number in self._line_number_lookup
def __iter__(self):
return iter(self.lines)
def _cleanup(self):
if len(self._lines) <= self.max:
return
while len(self._lines) > self.max:
_, line_number = self._lines.pop(0)
if line_number is not None:
try:
del self._line_number_lookup[line_number]
except KeyError:
pass
class PositionRecord(object):
_standard_attrs = {"x", "y", "z", "e", "f", "t"}
@classmethod
def valid_e(cls, attr):
if not attr.startswith("e"):
return False
try:
int(attr[1:])
except Exception:
return False
return True
def __init__(self, *args, **kwargs):
attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)])
for attr in attrs:
setattr(self, attr, kwargs.get(attr))
def copy_from(self, other):
# make sure all standard attrs and attrs from other are set
attrs = self._standard_attrs | set([key for key in dir(other) if self.valid_e(key)])
for attr in attrs:
setattr(self, attr, getattr(other, attr))
# delete attrs other doesn't have
attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs
for attr in attrs:
delattr(self, attr)
def as_dict(self):
attrs = self._standard_attrs | set([key for key in dir(self) if self.valid_e(key)])
return dict((attr, getattr(self, attr)) for attr in attrs)
class TemperatureRecord(object):
def __init__(self):
self._tools = dict()
self._bed = (None, None)
self._chamber = (None, None)
def copy_from(self, other):
self._tools = other.tools
self._bed = other.bed
self._chamber = other.chamber
def set_tool(self, tool, actual=None, target=None):
current = self._tools.get(tool, (None, None))
self._tools[tool] = self._to_new_tuple(current, actual, target)
def set_bed(self, actual=None, target=None):
current = self._bed
self._bed = self._to_new_tuple(current, actual, target)
def set_chamber(self, actual=None, target=None):
current = self._chamber()
self._chamber = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@property
def bed(self):
return self._bed
@property
def chamber(self):
return self._chamber
def as_dict(self):
result = dict()
tools = self.tools
for tool, data in tools.items():
result["tool{}".format(tool)] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["bed"] = dict(actual=bed[0],
target=bed[1])
chamber = self.chamber
result["chamber"] = dict(actual=chamber[0],
target=chamber[1])
return result
def as_script_dict(self):
result = self.as_dict()
# backwards compatibility
tools = self.tools
for tool, data in tools.items():
result[tool] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["b"] = dict(actual=bed[0],
target=bed[1])
chamber = self.chamber
result["c"] = dict(actual=chamber[0],
target=chamber[1])
return result
@classmethod
def _to_new_tuple(cls, current, actual, target):
if current is None or not isinstance(current, tuple) or len(current) != 2:
current = (None, None)
if actual is None and target is None:
return current
old_actual, old_target = current
if actual is None:
return old_actual, target
elif target is None:
return actual, old_target
else:
return actual, target
@@ -0,0 +1,194 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.util import PrependableQueue, TypedQueue, TypeAlreadyInQueue
try:
import queue
except ImportError:
import Queue as queue
import contextlib
import logging
import threading
class ScriptQueue(PrependableQueue):
pass
class JobQueue(PrependableQueue):
pass
class CommandQueue(TypedQueue):
def __init__(self, *args, **kwargs):
TypedQueue.__init__(self, *args, **kwargs)
self._unblocked = threading.Event()
self._unblocked.set()
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def get(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.get(self, *args, **kwargs)
def put(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.put(self, *args, **kwargs)
def clear(self):
cleared = []
while True:
try:
cleared.append(TypedQueue.get(self, False))
TypedQueue.task_done(self)
except queue.Empty:
break
return cleared
class SendQueue(PrependableQueue):
def __init__(self, maxsize=0):
PrependableQueue.__init__(self, maxsize=maxsize)
self._unblocked = threading.Event()
self._unblocked.set()
self._resend_queue = PrependableQueue()
self._send_queue = PrependableQueue()
self._lookup = set()
self._resend_active = False
@property
def resend_active(self):
return self._resend_active
@resend_active.setter
def resend_active(self, resend_active):
with self.mutex:
self._resend_active = resend_active
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout)
def put(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout)
def get(self, block=True, timeout=None):
self._unblocked.wait()
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
return item
def clear(self):
cleared = []
while True:
try:
cleared.append(PrependableQueue.get(self, False))
PrependableQueue.task_done(self)
except queue.Empty:
break
return cleared
def _put(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.put(item)
else:
self._send_queue.put(item)
def _prepend(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.prepend(item)
else:
self._send_queue.prepend(item)
def _get(self):
if self.resend_active:
item = self._resend_queue.get(block=False)
else:
try:
item = self._resend_queue.get(block=False)
except queue.Empty:
item = self._send_queue.get(block=False)
_, item_type, _ = item
if item_type is not None:
if item_type in self._lookup:
self._lookup.remove(item_type)
return item
def _qsize(self, len=len):
if self.resend_active:
return self._resend_queue.qsize()
else:
return self._resend_queue.qsize() + self._send_queue.qsize()
class QueueMarker(object):
def __init__(self, callback):
self.callback = callback
def run(self):
if callable(self.callback):
try:
self.callback()
except Exception:
logging.getLogger(__name__).exception("Error while running callback of QueueMarker")
class SendQueueMarker(QueueMarker):
pass
+37
View File
@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
class Script(object):
def __init__(self, name, renderer, context=None):
if context is None:
context = dict()
self.name = name
self.renderer = renderer
self.context = context
def render(self, context=None):
if context is None:
context = dict()
render_context = dict(self.context)
render_context.update(context)
content = self.renderer(render_context)
if content is None:
return None
return content.split("\n")
class UnknownScript(Exception):
def __init__(self, name, *args, **kwargs):
self.name = name
class InvalidScript(Exception):
pass
+350
View File
@@ -0,0 +1,350 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.util.parameters import get_param_dict
import copy
import logging
import time
from octoprint.util import monotonic_time
from octoprint.util.listener import ListenerAware
from octoprint.plugin import plugin_manager
from octoprint.settings import SubSettings
_registry = dict()
def register_transports():
from .serialtransport import SerialTransport
from .sockettransport import TcpTransport, SerialOverTcpTransport
logger = logging.getLogger(__name__)
# stock transports
register_transport(SerialTransport)
register_transport(TcpTransport)
register_transport(SerialOverTcpTransport)
# more transports provided by plugins
hooks = plugin_manager().get_hooks("octoprint.comm.transport.register")
for name, hook in hooks.items():
try:
transports = hook()
for transport in transports:
try:
register_transport(transport)
except Exception:
logger.exception("Error while registering transport class {} for plugin {}".format(transport, name))
except Exception:
logger.exception("Error executing octoprint.comm.transport.register hook for plugin {}".format(name))
def register_transport(transport_class):
if not hasattr(transport_class, "key"):
raise ValueError("Transport class {} is missing key".format(transport_class))
_registry[transport_class.key] = transport_class
def lookup_transport(key):
return _registry.get(key)
def all_transports():
return _registry.values()
class Transport(ListenerAware):
name = None
key = None
message_integrity = False
@classmethod
def get_connection_options(cls):
return []
@classmethod
def get_settings_defaults(cls):
return dict()
def __init__(self, *args, **kwargs):
super(Transport, self).__init__()
self._logger = logging.getLogger(__name__)
self._state = TransportState.DISCONNECTED
self._args = dict()
self._printer_profile = kwargs.get("printer_profile")
self._plugin_manager = kwargs.get("plugin_manager")
self._event_bus = kwargs.get("event_bus")
self._settings = kwargs.get("settings")
if not isinstance(self._settings, TransportSettings):
self._settings = TransportSettings(self._settings, self)
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@property
def state(self):
return self._state
@state.setter
def state(self, value):
old_state = self.state
self._state = value
self.notify_listeners("on_transport_log_message", self, "Transport state changed from '{}' to '{}'".format(old_state, value))
def connect(self, **params):
if self.state == TransportState.CONNECTED:
raise TransportAlreadyConnectedError("Already connected, disconnect first")
options = self.get_connection_options()
param_dict = get_param_dict(params, options)
self.create_connection(**param_dict)
self.state = TransportState.CONNECTED
self.notify_listeners("on_transport_connected", self)
def disconnect(self, error=None):
if self.state == TransportState.DISCONNECTED:
raise TransportNotConnectedError("Already disconnected")
success = self.drop_connection()
if not success and not error:
error = "Error disconnecting transport"
if error:
self.state = TransportState.DISCONNECTED_WITH_ERROR
self.notify_listeners("on_transport_log_message", self, error)
else:
self.state = TransportState.DISCONNECTED
self.notify_listeners("on_transport_disconnected", self, error=error)
def create_connection(self, *args, **kwargs):
return True
def drop_connection(self):
return True
def read(self, size=None, timeout=None):
data = self.do_read(size=size, timeout=timeout)
self.notify_listeners("on_transport_log_received_data", self, data)
return data
def write(self, data):
self.do_write(data)
self.notify_listeners("on_transport_log_sent_data", self, data)
@property
def in_waiting(self):
return 0
def do_read(self, size=None, timeout=None):
return b""
def do_write(self, data):
pass
def __str__(self):
return self.__class__.__name__
class TransportState(object):
CONNECTED = "connected"
DISCONNECTED = "disconnected"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
class TransportSettings(SubSettings):
def __init__(self, settings, transport):
self.transport = transport.key
SubSettings.__init__(self, settings, ["comm", "transport", transport.key],
defaults=transport.get_settings_defaults())
class TransportNotConnectedError(Exception):
pass
class TransportAlreadyConnectedError(Exception):
pass
class TransportWrapper(ListenerAware):
unforwarded_handlers = []
"""Allows to explicitly disable certain transport listener handlers on sub classes."""
def __init__(self, transport):
ListenerAware.__init__(self)
self.transport = transport
self.transport.register_listener(self)
# make sure we forward any transport listener calls to our own registered listeners
def forward_handler(name):
def f(*args, **kwargs):
# replace references to self.transport with self
args = [self if arg == self.transport else arg for arg in args]
kwargs = dict((key, self if value == self.transport else value) for key, value in kwargs.items())
# forward
self.notify_listeners(name, *args, **kwargs)
return f
for handler in filter(lambda x: x.startswith("on_transport_"), dir(TransportListener)):
if handler not in self.__class__.unforwarded_handlers:
setattr(self, handler, forward_handler(handler))
def __getattr__(self, item):
return getattr(self.transport, item)
class SeparatorAwareTransportWrapper(TransportWrapper):
unforwarded_handlers = ["on_transport_log_received_data"]
"""We have read overwritten and hence send our own received_data notification."""
def __init__(self, transport, terminator):
TransportWrapper.__init__(self, transport)
self.terminator = terminator
self._buffered = bytearray()
def read(self, size=None, timeout=None):
start = monotonic_time()
termlen = len(self.terminator)
data = self._buffered
while True:
# make sure we always read everything that is waiting
data += bytearray(self.transport.read(self.transport.in_waiting))
# check for terminator, if it's there we have found our line
termpos = data.find(self.terminator)
if termpos >= 0:
# line: everything up to and incl. the terminator
line = data[:termpos + termlen]
# buffered: everything after the terminator
self._buffered = data[termpos + termlen:]
received = bytes(line)
self.notify_listeners("on_transport_log_received_data", self, received)
return received
# check if timeout expired
if timeout and monotonic_time() > start + timeout:
break
# if we arrive here we so far couldn't read a full line, wait for more data
c = self.transport.read(1)
if not c:
# EOF
break
# add to data and loop
data += c
self._buffered = data
raise TimeoutTransportException()
def __str__(self):
return "SeparatorAwareTransportWrapper({}, separator={})".format(self.transport, self.terminator)
class LineAwareTransportWrapper(SeparatorAwareTransportWrapper):
def __init__(self, transport):
SeparatorAwareTransportWrapper.__init__(self, transport, b"\n")
def __str__(self):
return "LineAwareTransportWrapper({})".format(self.transport)
class PushingTransportWrapper(TransportWrapper):
def __init__(self, transport, name=b"PushingTransportWrapper.receiver_loop", timeout=None):
super(PushingTransportWrapper, self).__init__(transport)
self.name = name
self.timeout = timeout
self._receiver_active = False
self._receiver_thread = None
@property
def active(self):
return self._receiver_active
def connect(self, **kwargs):
self.transport.connect(**kwargs)
import threading
self._receiver_active = True
self._receiver_thread = threading.Thread(target=self._receiver_loop, name=self.name)
self._receiver_thread.daemon = True
self._receiver_thread.start()
def disconnect(self):
self._receiver_active = False
self.transport.disconnect()
def wait(self):
self._receiver_thread.join()
def _receiver_loop(self):
while self._receiver_active:
try:
data = self.transport.read(timeout=self.timeout)
self.notify_listeners("on_transport_data_pushed", self, data)
except TimeoutTransportException as ex:
self.notify_listeners("on_transport_data_exception", self, ex)
except Exception:
if self._receiver_active:
raise
def __str__(self):
return "PushingTransportWrapper({})".format(self.transport)
class TransportListener(object):
def on_transport_connected(self, transport):
pass
def on_transport_disconnected(self, transport, error=None):
pass
def on_transport_log_sent_data(self, transport, data):
pass
def on_transport_log_received_data(self, transport, data):
pass
def on_transport_log_message(self, transport, data):
pass
class PushingTransportWrapperListener(object):
def on_transport_data_pushed(self, transport, data):
pass
def on_transport_data_exception(self, transport, exception):
pass
class TransportException(Exception):
pass
class TimeoutTransportException(TransportException):
pass
class EofTransportException(TransportException):
pass
@@ -0,0 +1,206 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, PushingTransportWrapper
from octoprint.comm.util.parameters import TextType, IntegerType, ChoiceType, SuggestionType, BooleanType, Value
import serial
import logging
class SerialTransport(Transport):
name = "Serial Connection"
key = "serial"
message_integrity = False
suggested_baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
unix_port_patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/tty.usb*",
"/dev/cu.*", "/dev/cuaU*", "/dev/rfcomm*"]
max_write_passes = 5
@classmethod
def for_additional_ports_and_baudrates(cls, additional_ports, additional_baudrates):
patterns = SerialTransport.unix_port_patterns
if additional_ports:
patterns += additional_ports
baudrates = SerialTransport.suggested_baudrates
if additional_baudrates:
baudrates += additional_baudrates
return type(cls.__name__ + b"WithAdditionalPorts",
(cls,),
{b"unix_port_patterns": patterns,
b"suggested_baudrates": baudrates})
@classmethod
def get_connection_options(cls):
return [
SuggestionType("port", "Port", cls.get_available_serial_ports(), lambda value: Value(value)),
SuggestionType("baudrate", "Baudrate", cls.get_available_baudrates(), lambda value: Value(value), default=0),
IntegerType("write_timeout", "Write Timeout (sec)", min=1, default=10, advanced=True),
BooleanType("exclusive", "Exclusive access", default=True, advanced=True),
ChoiceType("parity", "Parity",
[Value(serial.PARITY_NONE, "none"),
Value(serial.PARITY_ODD, "odd"),
Value(serial.PARITY_EVEN, "even")],
default=serial.PARITY_NONE, advanced=True)
]
@classmethod
def get_available_serial_ports(cls):
import sys
if sys.platform == "win32":
# windows
from serial.tools.list_ports import comports
ports = comports()
else:
# posix
import glob
devices = [device
for pattern in cls.unix_port_patterns
for device in glob.glob(pattern)]
plat = sys.platform.lower()
if plat[:5] == "linux":
# linux
from serial.tools.list_ports_linux import SysFS
ports = [info
for info in [SysFS(d) for d in devices]
if info.subsystem != "platform"]
else:
# other posix systems
from serial.tools import list_ports_common
ports = [list_ports_common.ListPortInfo(d) for d in devices]
port_values = [Value(None, title="Auto detect")] + sorted([Value(port.device, title=port.description) for port in ports], key=lambda x: x.title)
return port_values
@classmethod
def get_available_baudrates(cls):
return [Value(0, title="Auto detect")] + \
sorted([Value(baudrate) for baudrate in cls.suggested_baudrates], key=lambda x: x.title, reverse=True)
def __init__(self, *args, **kwargs):
super(SerialTransport, self).__init__()
self.serial_factory = kwargs.get("serial_factory", None)
self._logger = logging.getLogger(__name__)
self._serial = None
self._closing = False
def create_connection(self, **kwargs):
factory = self.serial_factory
if self.serial_factory is None:
factory = self._default_serial_factory
self._closing = False
self._serial = factory(**kwargs)
self.set_current_args(**kwargs)
return True
def drop_connection(self):
error = False
if self._serial is not None:
self._closing = True
try:
if callable(getattr(self._serial, "cancel_read", None)):
self._serial.cancel_read()
except Exception:
self._logger.exception("Error while cancelling pending reads from the serial port")
try:
if callable(getattr(self._serial, "cancel_write", None)):
self._serial.cancel_write()
except Exception:
self._logger.exception("Error while cancelling pending writes to the serial port")
try:
self._serial.close()
except Exception:
self._logger.exception("Error while closing the serial port")
error = True
self._serial = None
return not error
def do_read(self, size=None, timeout=None):
return self._serial.read(size=size)
def do_write(self, data):
written = 0
passes = 0
def try_to_write(d):
result = self._serial.write(d)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
return len(data)
else:
return result
while written < len(data):
to_send = data[written:]
old_written = written
try:
written += try_to_write(to_send)
except serial.SerialTimeoutException:
self._logger.warn("Serial timeout while writing to serial port, trying again.")
try:
# second try
written += try_to_write(to_send)
except Exception:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
except Exception:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
if old_written == written:
passes += 1
if passes > self.max_write_passes:
message = "Could not write anything to the serial port in {} tries, something appears to be " \
"wrong with the printer communication".format(self.max_write_passes)
self._logger.error(message)
self.disconnect(error=message)
break
@property
def in_waiting(self):
return getattr(self._serial, "in_waiting", 0)
def _default_serial_factory(self, **kwargs):
return serial.Serial(port=kwargs.get("port"),
baudrate=kwargs.get("baudrate"),
exclusive=kwargs.get("exclusive"),
parity=kwargs.get("parity"),
write_timeout=kwargs.get("write_timeout", 10) * 1000)
def __str__(self):
return "SerialTransport"
if __name__ == "__main__":
# list ports
ports = SerialTransport.get_available_serial_ports()
for port in ports:
print(port.title + ": " + port.value)
@@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.transport import Transport, LineAwareTransportWrapper
from octoprint.comm.util.parameters import TextType, IntegerType
import socket
class TcpTransport(Transport):
name = "TCP Connection"
key = "tcpsocket"
message_integrity = True
@classmethod
def get_connection_options(cls):
return [
TextType("host", "Host"),
IntegerType("port", "Port", min=1, max=65535)
]
def __init__(self):
super(TcpTransport, self).__init__()
self._socket = None
def create_connection(self, host=None, port=None):
if host is None:
raise ValueError("host must not be None")
if port is None:
raise ValueError("port must not be None")
self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
self._socket.connect((host, port))
self.set_current_args(host=host, port=port)
return True
def drop_connection(self):
try:
self._socket.close()
return True
except Exception:
self._logger.exception("Error closing socket")
return False
def do_read(self, size=None, timeout=None):
if size is None:
size = 16
return self._socket.recv(size)
def do_write(self, data):
self._socket.sendall(data)
def __str__(self):
return "TcpTransport"
class SerialOverTcpTransport(TcpTransport):
name = "Serial Connection over TCP"
key = "serialovertcpsocket"
message_integrity = False
View File
Whitespace-only changes.
+194
View File
@@ -0,0 +1,194 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from past.builtins import unicode
def get_param_dict(data, options):
options_by_name = dict((option.name, option) for option in options)
result = dict()
for key, value in data.items():
if not key in options_by_name:
continue
option = options_by_name[key]
result[key] = option.convert(value)
return result
class ParamType(object):
type = "generic"
def __init__(self, name, title, default=None, advanced=False, help=None):
self.name = name
self.title = title
self.default = default
self.advanced = advanced
self.help = help
def as_dict(self):
return dict(name=self.name,
title=self.title,
default=self.default,
advanced=self.advanced,
help=self.help,
type=self.type)
def convert(self, value):
return value
def __repr__(self):
return "{}(".format(self.__class__.__name__) \
+ ", ".join(["{}={!r}".format(key, value) for key, value in self.__dict__.items() if not key.startswith("_")]) + ")"
class TextType(ParamType):
type = "text"
def convert(self, value):
if isinstance(value, bytes):
value = value.decode("utf-8", "replace")
return value
class IntegerType(ParamType):
type = "integer"
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
self.min = min
self.max = max
self.unit = unit
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(min=self.min,
max=self.max,
unit=self.unit))
return result
def convert(self, value):
try:
value = int(value)
except ValueError:
raise ValueError("value {!r} is not a valid integer".format(value))
if self.min is not None and value < self.min:
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
if self.max is not None and value > self.max:
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
return value
class FloatType(ParamType):
type = "float"
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
self.min = min
self.max = max
self.unit = unit
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(min=self.min,
max=self.max,
unit=self.unit))
return result
def convert(self, value):
try:
value = float(value)
except ValueError:
raise ValueError("value {!r} is not a valid float".format(value))
if self.min is not None and value < self.min:
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
if self.max is not None and value > self.max:
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
return value
class BooleanType(ParamType):
type = "boolean"
def convert(self, value):
try:
value = bool(value)
except ValueError:
raise ValueError("value {!r} is not a valid boolean".format(value))
return value
class ChoiceType(ParamType):
type = "choice"
def __init__(self, name, title, choices, **kwargs):
self.choices = choices
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(choices=list(map(lambda x: x.as_dict(), self.choices))))
return result
class SmallChoiceType(ChoiceType):
type = "smallchoice"
class SuggestionType(ParamType):
type = "suggestion"
def __init__(self, name, title, suggestions, factory, **kwargs):
self.suggestions = suggestions
self.factory = factory
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(suggestions=list(map(lambda x: x.as_dict(), self.suggestions))))
return result
class ListType(ParamType):
type = "list"
def __init__(self, name, title, factory, **kwargs):
self.factory = factory
ParamType.__init__(self, name, title, **kwargs)
def convert(self, value):
if isinstance(value, unicode):
items = map(unicode.strip, value.split(","))
elif isinstance(value, list):
items = value
else:
raise ValueError("value {!r} must be either a comma-separated string or a list".format(value))
return list(map(self.factory, items))
class ParamGroup(ParamType):
type = "group"
def __init__(self, name, title, params, help=None, advanced=False):
ParamType.__init__(self, name, title, help=help, advanced=advanced)
self.params = params
def as_dict(self):
result = ParamType.as_dict(self)
result["params"] = [x.as_dict() for x in self.params]
return result
def convert(self, value):
if not isinstance(value, dict):
raise ValueError("value {!r} must be a dict".format(value))
return dict((k, v.convert()) for k, v in value.items())
class Value(object):
def __init__(self, value, title=None, help=None):
self.value = value
self.title = title if title else value
self.help = help
def as_dict(self):
return dict(value=self.value,
title=self.title,
help=self.help)
+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):
+14 -13
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"
@@ -59,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()
@@ -76,21 +76,21 @@ class EnvironmentDetector(object):
# determine python version
try:
result["version"] = get_python_version_string()
except:
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
@@ -110,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
@@ -123,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
@@ -139,7 +140,7 @@ class EnvironmentDetector(object):
try:
_log(self._format())
except:
except Exception:
self._logger.exception("Error logging detected environment")
def _format(self):
@@ -150,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)
@@ -167,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))
+39 -31
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'
@@ -181,15 +181,14 @@ class EventManager(object):
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except:
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):
@@ -253,12 +252,11 @@ class EventManager(object):
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 {}".format(callback, event))
try:
self._registeredListeners[event].remove(callback)
except ValueError:
# not registered
pass
def join(self, timeout=None):
self._worker.join(timeout)
@@ -301,7 +299,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):
@@ -335,26 +333,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)
@@ -374,12 +379,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":
@@ -407,10 +412,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)
@@ -425,13 +430,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
@@ -448,11 +454,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",
+43 -29
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
@@ -15,11 +16,11 @@ from octoprint.events import eventManager, Events
from .destinations import FileDestinations
from .analysis import QueueEntry, AnalysisQueue
from .storage import LocalFileStorage
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
from collections import namedtuple
# noinspection PyCompatibility
from past.builtins import basestring
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
@@ -77,8 +78,10 @@ def full_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:
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from SlicerPlugin {name}".format(name=plugin.key))
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():
@@ -87,8 +90,10 @@ 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
@@ -337,14 +342,14 @@ class FileManager(object):
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,
@@ -420,16 +425,19 @@ 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")
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))
@@ -451,8 +459,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()
@@ -464,11 +472,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:
@@ -594,6 +602,9 @@ class FileManager(object):
name=dst_name))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def create_print_job(self, destination, path, user=None):
return self._storage(destination).create_print_job(path, user=user)
def has_analysis(self, destination, path):
return self._storage(destination).has_analysis(path)
@@ -608,10 +619,13 @@ class FileManager(object):
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
try:
if success:
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
else:
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
try:
if success:
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
else:
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
except NotImplementedError:
pass
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
except NoSuchStorage:
# if there's no storage configured where to log the print, we'll just not log it
@@ -627,9 +641,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):
@@ -638,7 +652,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):
@@ -647,10 +661,10 @@ 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)
return data
except:
except Exception:
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
self.delete_recovery_data()
+9 -9
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'
@@ -96,16 +96,16 @@ 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:
@@ -383,7 +383,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):
@@ -0,0 +1,457 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
class Storage(object):
"""
Interface of storage adapters for OctoPrint.
"""
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
# noinspection PyUnreachableCode
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
# noinspection PyUnreachableCode
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
Args:
path (str or None): Path for which to determine the subtree's last modification date. If left out or
set to None, defatuls to storage root.
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
the whole ``path``'s subtree (True).
Returns: (float) The last modification date of the indicated subtree
"""
raise NotImplementedError()
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"name": "some_folder",
"path": "some_folder",
"type": "folder",
"children": {
"some_sub_folder": {
"name": "some_sub_folder",
"path": "some_folder/some_sub_folder",
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"name": "some_file.gcode",
"path": "some_folder/some_file.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"name": "test.gcode",
"path": "test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"name": "test.stl",
"path": "test.stl",
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
do one step down into sub folders to be able to populate the ``children``.
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
def remove_file(self, path):
"""
Removes the file at ``path``
Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param string path: path of the file to remove
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
def create_print_job(self, path, user=None):
"""
Retrieves the :class:`~octoprint.job.PrintJob` instance
to use for printing ``path``.
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
raise NotImplementedError()
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
referring to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
raise NotImplementedError()
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
raise NotImplementedError()
def add_history(self, path, data):
"""
Adds a history entry for the given ``path``.
:param path: path of the file for which to add the history entry
:param data: history entry
"""
raise NotImplementedError()
def update_history(self, path, index, data):
"""
Updates the history entry for ``path`` at ``index``.
:param path: path of the file for which to update the history entry
:param index: index
:param data: history entry
"""
raise NotImplementedError()
def remove_history(self, path, index):
"""
Removes the history entry for ``path`` at ``index``.
:param path: path of the file for which to remove the history entry
:param index: index
"""
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
raise NotImplementedError()
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
@@ -1,11 +1,10 @@
# 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 shutil
@@ -21,6 +20,7 @@ except ImportError:
from octoprint.util import atomic_write
from contextlib import contextmanager
# noinspection PyCompatibility
from past.builtins import basestring
from emoji import demojize
@@ -28,419 +28,12 @@ from slugify import Slugify
import octoprint.filemanager
from octoprint.util import is_hidden_path, to_unicode, timing
from octoprint.util import is_hidden_path, to_unicode, to_bytes
class StorageInterface(object):
"""
Interface of storage adapters for OctoPrint.
"""
from . import Storage, StorageError
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
Args:
path (str or None): Path for which to determine the subtree's last modification date. If left out or
set to None, defatuls to storage root.
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
the whole ``path``'s subtree (True).
Returns: (float) The last modification date of the indicated subtree
"""
raise NotImplementedError()
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"name": "some_folder",
"path": "some_folder",
"type": "folder",
"children": {
"some_sub_folder": {
"name": "some_sub_folder",
"path": "some_folder/some_sub_folder",
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"name": "some_file.gcode",
"path": "some_folder/some_file.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"name": "test.gcode",
"path": "test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"name": "test.stl",
"path": "test.stl",
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
do one step down into sub folders to be able to populate the ``children``.
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
def remove_file(self, path):
"""
Removes the file at ``path``
Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param string path: path of the file to remove
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
raise NotImplementedError()
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
referring to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
raise NotImplementedError()
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
raise NotImplementedError()
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
class LocalFileStorage(StorageInterface):
class LocalFileStorage(Storage):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
@@ -450,11 +43,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,10 +56,10 @@ 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):
def __init__(self, basefolder, create=False, key="local"):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
@@ -502,10 +95,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
@@ -516,7 +109,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:
@@ -599,10 +192,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):
@@ -849,6 +442,17 @@ class LocalFileStorage(StorageInterface):
metadata = self.get_metadata(path)
return "analysis" in metadata
def create_print_job(self, path, user=None):
from octoprint.comm.job import LocalGcodeFilePrintjob
return LocalGcodeFilePrintjob(self.path_on_disk(path),
"local",
self.path_in_storage(path),
name=self.path_in_storage(path),
user=user,
event_data=dict(path=path,
name=self.split_path(path)[1],
origin="local"))
def get_metadata(self, path):
path, name = self.sanitize(path)
return self._get_metadata_entry(path, name)
@@ -917,14 +521,14 @@ class LocalFileStorage(StorageInterface):
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):
"""
@@ -953,23 +557,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.
"""
@@ -978,11 +582,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
@@ -996,12 +600,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))
@@ -1021,16 +625,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
@@ -1038,12 +642,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
@@ -1120,8 +724,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:
@@ -1300,7 +904,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
@@ -1312,7 +916,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
@@ -1417,7 +1021,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
@@ -1473,7 +1077,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)
@@ -1541,19 +1145,27 @@ class LocalFileStorage(StorageInterface):
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:
metadata = json.load(f)
except:
except Exception:
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
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 entries from metadata for path {}".format(old_size - new_size,
path))
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):
@@ -1571,9 +1183,9 @@ class LocalFileStorage(StorageInterface):
with self._get_persisted_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.json")
try:
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()))
def _delete_metadata(self, path):
@@ -1588,7 +1200,7 @@ class LocalFileStorage(StorageInterface):
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()))
@staticmethod
@@ -1614,14 +1226,14 @@ class LocalFileStorage(StorageInterface):
# already migrated
try:
os.remove(metadata_path_yaml)
except:
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
@@ -1629,12 +1241,12 @@ 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=(",", ": "))))
try:
os.remove(metadata_path_yaml)
except:
except Exception:
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
@contextmanager
@@ -0,0 +1,14 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import Storage, StorageError
class PrinterSDStorage(Storage):
def create_print_job(self, path, user=None):
from octoprint.comm.job import SDFilePrintjob
return SDFilePrintjob("/" + path, user=user)
+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:]))
+17 -11
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))
@@ -56,22 +62,23 @@ class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
pass
class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
do_rollover = False
do_rollover = dict()
suffix_template = "%Y-%m-%d_%H-%M-%S"
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
@classmethod
def on_open_connection(cls):
cls.do_rollover = True
def on_open_connection(cls, logger):
cls.do_rollover[logger] = True
def __init__(self, *args, **kwargs):
super(SerialLogHandler, self).__init__(*args, **kwargs)
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(CommunicationLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
def shouldRollover(self, record):
return self.do_rollover
return self.do_rollover.pop(record.name, False)
def getFilesToDelete(self):
"""
@@ -100,8 +107,6 @@ class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandle
os.remove(path)
def doRollover(self):
self.do_rollover = False
if self.stream:
self.stream.close()
self.stream = None
@@ -118,6 +123,7 @@ class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandle
if not self.delay:
self.stream = self._open()
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
+24 -168
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,8 +15,6 @@ 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"
@@ -23,11 +23,12 @@ import os
import logging
import threading
from octoprint.settings import settings as s
from octoprint.settings import settings as s, SubSettings
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
@@ -37,7 +38,7 @@ def _validate_plugin(phase, plugin_info):
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.
@@ -63,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
@@ -86,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:
@@ -104,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
@@ -152,7 +157,7 @@ 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
@@ -196,8 +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)):
@@ -211,7 +215,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
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):
@@ -221,12 +225,12 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
if callback:
callback(plugin._identifier, plugin, result)
except Exception as exc:
logger.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)
class PluginSettings(object):
class PluginSettings(SubSettings):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
@@ -311,78 +315,15 @@ class PluginSettings(object):
"""
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
self.settings = settings
self.plugin_key = plugin_key
if defaults is not None:
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
SubSettings.__init__(self, settings, ["plugins", plugin_key],
defaults=defaults,
get_preprocessors=get_preprocessors,
set_preprocessors=set_preprocessors)
if self.defaults is not None:
self.defaults["plugins"][plugin_key]["_config_version"] = None
else:
self.defaults = None
if get_preprocessors is None:
get_preprocessors = dict()
self.get_preprocessors = dict(plugins=dict())
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
if set_preprocessors is None:
set_preprocessors = dict()
self.set_preprocessors = dict(plugins=dict())
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
def prefix_path_in_args(args, index=0):
result = []
if index == 0:
result.append(self._prefix_path(args[0]))
result.extend(args[1:])
else:
args_before = args[:index - 1]
args_after = args[index + 1:]
result.extend(args_before)
result.append(self._prefix_path(args[index]))
result.extend(args_after)
return result
def add_getter_kwargs(kwargs):
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
return kwargs
def add_setter_kwargs(kwargs):
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
return kwargs
self.access_methods = dict(
has =("has", prefix_path_in_args, add_getter_kwargs),
get =("get", prefix_path_in_args, add_getter_kwargs),
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
get_boolean=("getBoolean", prefix_path_in_args, add_getter_kwargs),
set =("set", prefix_path_in_args, add_setter_kwargs),
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
remove =("remove", prefix_path_in_args, lambda x: x)
)
self.deprecated_access_methods = dict(
getInt ="get_int",
getFloat ="get_float",
getBoolean="get_boolean",
setInt ="set_int",
setFloat ="set_float",
setBoolean="set_boolean"
)
def _prefix_path(self, path=None):
if path is None:
path = list()
return ['plugins', self.plugin_key] + path
def global_has(self, path, **kwargs):
return self.settings.has(path, **kwargs)
@@ -474,88 +415,3 @@ class PluginSettings(object):
filename += ".log"
return os.path.join(self.settings.getBaseFolder("logs"), filename)
@deprecated("PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder",
includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`",
since="1.2.0")
def get_plugin_data_folder(self):
path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key)
if not os.path.isdir(path):
os.makedirs(path)
return path
def get_all_data(self, **kwargs):
merged = kwargs.get("merged", True)
asdict = kwargs.get("asdict", True)
defaults = kwargs.get("defaults", self.defaults)
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
kwargs.update(dict(
merged=merged,
asdict=asdict,
defaults=defaults,
preprocessors=preprocessors
))
return self.settings.get(self._prefix_path(), **kwargs)
def clean_all_data(self):
self.settings.remove(self._prefix_path())
def __getattr__(self, item):
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
if item in all_access_methods:
decorator = None
if item in self.deprecated_access_methods:
new = self.deprecated_access_methods[item]
decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2)
item = new
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)):
orig_func = getattr(self.settings, settings_name)
if decorator is not None:
orig_func = decorator(orig_func)
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = 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)
+207 -112
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,19 +22,17 @@ 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
@@ -40,12 +40,37 @@ import pkginfo
from past.builtins import unicode
from octoprint.util import to_unicode
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")
@@ -93,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. """
@@ -148,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
@@ -163,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__
@@ -210,13 +251,13 @@ class PluginInfo(object):
def __str__(self):
if self.version:
return u"{name} ({version})".format(name=self.name, version=self.version)
return "{name} ({version})".format(name=self.name, version=self.version)
else:
return to_unicode(self.name)
def long_str(self, show_bundled=False, bundled_strs=(u" [B]", u""),
show_location=False, location_str=u" - {location}",
show_enabled=False, enabled_strs=(u"* ", u" ", u"X ")):
def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""),
show_location=False, location_str=" - {location}",
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>``.
@@ -224,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.
@@ -245,11 +287,16 @@ class PluginInfo(object):
str: The long string representation of the plugin as described above
"""
if show_enabled:
ret = to_unicode(enabled_strs[2]) if self.blacklisted \
else (to_unicode(enabled_strs[0]) if self.enabled
else to_unicode(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 = u""
ret = ""
ret += unicode(self)
@@ -384,6 +431,19 @@ 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):
"""
@@ -491,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):
@@ -517,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:
@@ -541,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
@@ -557,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:
@@ -572,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
@@ -582,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()
@@ -633,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)
@@ -656,8 +721,8 @@ class PluginManager(object):
ignored_uninstalled=ignore_uninstalled)
result_added.update(added)
result_found += found
except:
self.logger.exception(u"Error fetching plugins from folders")
except Exception:
self.logger.exception("Error fetching plugins from folders")
if self.plugin_entry_points:
existing.update(result_added)
@@ -667,8 +732,8 @@ class PluginManager(object):
ignore_uninstalled=ignore_uninstalled)
result_added.update(added)
result_found += found
except:
self.logger.exception(u"Error fetching plugins from entry points")
except Exception:
self.logger.exception("Error fetching plugins from entry points")
return result_added, result_found
@@ -690,7 +755,7 @@ class PluginManager(object):
actual_readonly = not os.access(folder, os.W_OK)
if not os.path.exists(folder):
self.logger.warn(u"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):
@@ -735,10 +800,10 @@ class PluginManager(object):
plugin.managable = not flagged_readonly and not actual_readonly
plugin.enabled = False
added[key] = plugin
except:
self.logger.exception(u"Error processing folder entry {!r} from folder {}".format(entry, folder))
except:
self.logger.exception(u"Error processing folder {}".format(folder))
except Exception:
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
except Exception:
self.logger.exception("Error processing folder {}".format(folder))
return added, found
@@ -767,9 +832,9 @@ class PluginManager(object):
for entry in gen:
try:
yield entry
except:
self.logger.exception(u"Something went wrong while processing the entry points of a package in the "
u"Python environment - broken entry_points.txt in some package?")
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?")
for group in groups:
for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)):
@@ -787,8 +852,8 @@ class PluginManager(object):
package_name = entry_point.dist.project_name
try:
entry_point_metadata = EntryPointMetadata(entry_point)
except:
self.logger.exception(u"Something went wrong while retrieving metadata for module {}".format(module_name))
except Exception:
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
else:
kwargs.update(dict(
name=entry_point_metadata.name,
@@ -817,8 +882,8 @@ class PluginManager(object):
plugin.location))
added[key] = plugin
except:
self.logger.exception(u"Error processing entry point {!r} for group {}".format(entry_point, group))
except Exception:
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
return added, found
@@ -827,43 +892,53 @@ 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(u"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
if self._is_plugin_disabled(key):
self.logger.info(u"Plugin {} is disabled.".format(plugin))
self.logger.info("Plugin {} is disabled.".format(plugin))
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(u"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,
module_name=module_name, 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, module_name=None, 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:
if module_name:
instance = imp.load_module(module_name, f, filename, description)
module = _load_module(module_name, spec)
else:
instance = imp.load_module(key, f, filename, description)
plugin = PluginInfo(key, filename, instance,
module = _load_module(key, spec)
plugin = PluginInfo(key, location, module,
name=name,
version=version,
description=summary,
@@ -871,15 +946,16 @@ class PluginManager(object):
url=url,
license=license,
parsed_metadata=parsed_metadata)
plugin.bundled = bundled
except:
self.logger.exception(u"Error loading plugin {key}".format(key=key))
except Exception:
self.logger.exception("Error loading plugin {key}".format(key=key))
return None
if plugin.check():
return plugin
else:
self.logger.info(u"Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
return None
def _is_plugin_disabled(self, key):
@@ -888,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:
@@ -899,7 +980,7 @@ class PluginManager(object):
self.plugin_blacklist))
def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None):
self.logger.info(u"Loading plugins from {folders} and installed plugin packages...".format(
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(
folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders))
))
@@ -910,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]
@@ -943,7 +1024,7 @@ class PluginManager(object):
try:
if plugin.loaded and not plugin.forced_disabled:
if plugin.blacklisted:
self.logger.warn(u"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:
@@ -956,9 +1037,9 @@ class PluginManager(object):
force_reload=force_reload)
if len(self.enabled_plugins) <= 0:
self.logger.info(u"No plugins found")
self.logger.info("No plugins found")
else:
self.logger.info(u"Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
count=len(self.enabled_plugins) + len(self.disabled_plugins),
implementations=len(self.plugin_implementations),
hooks=sum(map(lambda x: len(x), self.plugin_hooks.values()))
@@ -966,7 +1047,7 @@ class PluginManager(object):
def mark_plugin(self, name, **kwargs):
if not name in self.plugins:
self.logger.debug(u"Trying to mark an unknown plugin {name}".format(**locals()))
self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals()))
for key, value in kwargs.items():
if value is None:
@@ -985,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(u"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:
@@ -1000,15 +1081,15 @@ class PluginManager(object):
self.on_plugin_loaded(name, plugin)
plugin.loaded = True
self.logger.debug(u"Loaded plugin {name}: {plugin}".format(**locals()))
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
except PluginLifecycleException as e:
raise e
except:
self.logger.exception(u"There was an error loading plugin %s" % name)
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(u"Trying to unload unknown plugin {name}".format(**locals()))
self.logger.warning("Trying to unload unknown plugin {name}".format(**locals()))
return
plugin = self.plugins[name]
@@ -1028,11 +1109,11 @@ class PluginManager(object):
plugin.loaded = False
self.logger.debug(u"Unloaded plugin {name}: {plugin}".format(**locals()))
self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals()))
except PluginLifecycleException as e:
raise e
except:
self.logger.exception(u"There was an error unloading plugin {name}".format(**locals()))
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
if name in self.enabled_plugins:
@@ -1042,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(u"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:
@@ -1062,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:
@@ -1078,13 +1159,13 @@ class PluginManager(object):
plugin.implementation.on_plugin_enabled()
self.on_plugin_enabled(name, plugin)
self.logger.debug(u"Enabled plugin {name}: {plugin}".format(**locals()))
self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals()))
return True
def disable_plugin(self, name, plugin=None):
if not name in self.enabled_plugins:
self.logger.warn(u"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:
@@ -1098,8 +1179,8 @@ class PluginManager(object):
self._deactivate_plugin(name, plugin)
except PluginLifecycleException as e:
raise e
except:
self.logger.exception(u"There was an error while disabling plugin {name}".format(**locals()))
except Exception:
self.logger.exception("There was an error while disabling plugin {name}".format(**locals()))
return False
else:
if name in self.enabled_plugins:
@@ -1111,7 +1192,7 @@ class PluginManager(object):
plugin.implementation.on_plugin_disabled()
self.on_plugin_disabled(name, plugin)
self.logger.debug(u"Disabled plugin {name}: {plugin}".format(**locals()))
self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals()))
return True
@@ -1123,7 +1204,7 @@ class PluginManager(object):
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warn(u"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))
@@ -1142,7 +1223,7 @@ class PluginManager(object):
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warn(u"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:
@@ -1201,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:
@@ -1235,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:
@@ -1273,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:
@@ -1289,7 +1370,7 @@ class PluginManager(object):
additional_pre_inits=additional_pre_inits,
additional_post_inits=additional_post_inits)
self.logger.info(u"Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
if plugin.implementation is None:
@@ -1343,8 +1424,8 @@ class PluginManager(object):
for factory in inject_factories:
try:
return_value = factory(name, implementation)
except:
self.logger.exception(u"Exception while executing injection factory %r" % factory)
except Exception:
self.logger.exception("Exception while executing injection factory %r" % factory)
else:
if return_value is not None:
if isinstance(return_value, dict):
@@ -1368,19 +1449,19 @@ class PluginManager(object):
if isinstance(e, PluginLifecycleException):
raise e
else:
self.logger.exception(u"Exception while initializing plugin {name}, disabling it".format(**locals()))
self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals()))
return False
else:
self.on_plugin_implementations_initialized(name, plugin)
self.logger.debug(u"Initialized plugin mixin implementation for plugin {name}".format(**locals()))
self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals()))
return True
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:
@@ -1390,7 +1471,7 @@ class PluginManager(object):
self.logger.log(level, message)
if len(all_plugins) <= 0:
_log(u"No plugins available")
_log("No plugins available")
else:
formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
bundled_strs=bundled_str,
@@ -1399,8 +1480,10 @@ class PluginManager(object):
show_enabled=show_enabled,
enabled_strs=enabled_str),
sorted(self.plugins.values(), key=lambda x: unicode(x).lower())))
_log(u"{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
plugins=formatted_plugins))
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):
"""
@@ -1491,14 +1574,14 @@ 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:
self.logger.exception(u"Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
except Exception:
self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
if sorting_value is not None:
try:
sorting_value = int(sorting_value)
except ValueError:
self.logger.warn(u"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
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
@@ -1520,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):
"""
@@ -1551,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:
@@ -1563,21 +1647,28 @@ 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(u"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],
@@ -1632,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
@@ -1658,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):
+11 -9
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"
@@ -66,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
@@ -76,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
@@ -1497,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]
@@ -1540,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():
@@ -1617,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``
@@ -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,8 @@ __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
@@ -53,10 +55,21 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
self._cap_prompt_support = False
def initialize(self):
self._enable = self._settings.get([b"enable"])
self._command = self._settings.get([b"command"])
self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"])
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
@@ -80,10 +93,10 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._enable = self._settings.get([b"enable"])
self._command = self._settings.get([b"command"])
self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"])
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
@@ -92,7 +105,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:
@@ -105,7 +118,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()
@@ -120,39 +133,39 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
#~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not action.startswith(b"prompt_"):
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()
@@ -172,7 +185,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
return
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode)
return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode)
#~ capability reporting
@@ -217,7 +230,8 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin your printer wil
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
b"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
b"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_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,12 @@ $(function() {
var self = this;
self.loginState = parameters[0];
self.access = parameters[1];
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);
@@ -52,7 +53,7 @@ $(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;
}
@@ -73,6 +74,6 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: ActionCommandPromptViewModel,
dependencies: ["loginStateViewModel"]
dependencies: ["loginStateViewModel", "accessViewModel"]
});
});
+88 -54
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, monotonic_time
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
@@ -354,15 +380,15 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
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"], monotonic_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"]
});
});
+45 -26
View File
@@ -1,11 +1,11 @@
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import flask
import threading
import os
import yaml
import codecs
import io
import time
from binascii import hexlify
from collections import defaultdict
@@ -15,9 +15,11 @@ import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, admin_permission
from octoprint.users import DummyUser
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
@@ -96,6 +98,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
# Additional permissions hook
def get_additional_permissions(self):
return [
dict(key="ADMIN",
name="Admin access",
description=gettext("Allows administrating all application keys"),
roles=["admin"],
dangerous=True,
default_groups=[ADMIN_GROUP])
]
##~~ TemplatePlugin
def get_template_configs(self):
@@ -193,12 +207,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
if not user_id:
return flask.abort(403)
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can():
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
return flask.jsonify(keys=map(lambda x: x.external(), keys),
return flask.jsonify(keys=list(map(lambda x: x.external(), keys)),
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
def on_api_command(self, command, data):
@@ -267,7 +281,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
def _expire_pending(self, user_token):
with self._pending_lock:
len_before = len(self._pending_decisions)
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
self._pending_decisions = list(filter(lambda x: x.user_token != user_token,
self._pending_decisions))
len_after = len(self._pending_decisions)
if len_after < len_before:
@@ -280,8 +295,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = filter(lambda x: x.created >= cutoff,
self._pending_decisions)
self._pending_decisions = list(filter(lambda x: x.created >= cutoff,
self._pending_decisions))
len_after = len(self._pending_decisions)
if len_after < len_before:
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
@@ -301,7 +316,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
with self._pending_lock:
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
self._pending_decisions = list(filter(lambda x: x.user_token != user_token,
self._pending_decisions))
return True
@@ -319,7 +335,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
api_key = self._add_api_key(decision.user_id, decision.app_id)
with self._ready_lock:
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
self._ready_decisions = list(filter(lambda x: x.app_token != app_token,
self._ready_decisions))
return api_key
@@ -337,17 +354,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
def _delete_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
self._keys[user_id] = filter(lambda x: x.api_key != api_key, data)
self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data))
self._save_keys()
def _user_for_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
if filter(lambda x: x.api_key == api_key, data):
if any(filter(lambda x: x.api_key == api_key, data)):
if self._user_manager.enabled:
return self._user_manager.findUser(userid=user_id)
elif user_id == "dummy":
return DummyUser()
elif user_id == "_admin" or user_id == "dummy":
# dummy = backwards compatible
return self._user_manager.anonymous_user_factory()
return None
def _api_keys_for_user(self, user_id):
@@ -370,9 +388,9 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
return
try:
with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f:
persisted = yaml.safe_load(f)
except:
except Exception:
self._logger.exception("Could not load application keys from {}".format(self._key_path))
return
@@ -391,17 +409,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
to_persist[user_id] = [x.internal() for x in keys]
try:
with atomic_write(self._key_path) as f:
yaml.safe_dump(to_persist, f)
except:
with atomic_write(self._key_path, mode='wt') as f:
yaml.safe_dump(to_persist, f, allow_unicode=True)
except Exception:
self._logger.exception("Could not write application keys to {}".format(self._key_path))
__plugin_name__ = u"Application Keys Plugin"
__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys"
__plugin_author__ = u"Gina Häußge, Aldo Hoeben"
__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to "
u"obtain an API key without you manually copy-pasting it.")
__plugin_name__ = "Application Keys Plugin"
__plugin_description__ = "Implements a workflow for third party clients to obtain API keys"
__plugin_author__ = "Gina Häußge, Aldo Hoeben"
__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to "
"obtain an API key without you manually copy-pasting it.")
__plugin_implementation__ = AppKeysPlugin()
__plugin_hooks__ = {
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
+119 -103
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
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -9,11 +9,13 @@ import octoprint.plugin
from octoprint.settings import default_settings
from octoprint.plugin.core import FolderOrigin
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.util import is_hidden_path
from octoprint.server.util.flask import no_firstrun_access
from octoprint.util import is_hidden_path, to_bytes
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
from octoprint.util.platform import is_os_compatible
from octoprint.util.pip import LocalPipCaller
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
try:
from os import scandir
@@ -28,7 +30,7 @@ except ImportError:
from flask_babel import gettext
import codecs
import io
import flask
import logging
import os
@@ -68,6 +70,18 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
self._in_progress = []
self._in_progress_lock = threading.RLock()
# Additional permissions hook
def get_additional_permissions(self):
return [
dict(key="ACCESS",
name="Backup access",
description=gettext("Allows access to backups and restores"),
roles=["access"],
dangerous=True,
default_groups=[ADMIN_GROUP])
]
##~~ StartupPlugin
def on_after_startup(self):
@@ -85,13 +99,13 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
##~~ TemplatePlugin
def get_template_configs(self):
return [dict(type="settings", name=gettext(u"Backup & Restore"))]
return [dict(type="settings", name=gettext("Backup & Restore"))]
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@admin_permission.require(403)
@restricted_access
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
def get_state(self):
backups = self._get_backups()
unknown_plugins = self._get_unknown_plugins()
@@ -101,34 +115,34 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
restore_supported=is_os_compatible(["!windows"]))
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
@admin_permission.require(403)
@restricted_access
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
def get_unknown_plugins(self):
# TODO add caching
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(unknown_plugins=unknown_plugins)
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
@admin_permission.require(403)
@restricted_access
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
def delete_unknown_plugins(self):
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
try:
os.remove(data_file)
except:
except Exception:
pass
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
@admin_permission.require(403)
@restricted_access
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
def get_backups(self):
backups = self._get_backups()
return flask.jsonify(backups=backups)
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
@admin_permission.require(403)
@restricted_access
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
def create_backup(self):
backup_file = build_backup_filename()
@@ -136,8 +150,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
exclude = data.get("exclude", [])
def on_backup_start(name, temporary_path, exclude):
self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path,
u",".join(exclude) if len(exclude) else "-"))
self._logger.info("Creating backup zip at {} (excluded: {})...".format(temporary_path,
",".join(exclude) if len(exclude) else "-"))
with self._in_progress_lock:
self._in_progress.append(name)
@@ -148,7 +162,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
self._in_progress.remove(name)
self._send_client_message("backup_done", payload=dict(name=name))
self._logger.info(u"... done creating backup zip.")
self._logger.info("... done creating backup zip.")
def on_backup_error(name, exc_info):
with self._in_progress_lock:
@@ -159,8 +173,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
pass
self._send_client_message("backup_error", payload=dict(name=name,
error=u"{}".format(exc_info[1])))
self._logger.error(u"Error while creating backup zip", exc_info=exc_info)
error="{}".format(exc_info[1])))
self._logger.error("Error while creating backup zip", exc_info=exc_info)
thread = threading.Thread(target=self._create_backup,
args=(backup_file,),
@@ -180,8 +194,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
return response
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
@admin_permission.require(403)
@restricted_access
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
def delete_backup(self, filename):
backup_folder = self.get_plugin_data_folder()
full_path = os.path.realpath(os.path.join(backup_folder, filename))
@@ -190,17 +204,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
and not is_hidden_path(full_path):
try:
os.remove(full_path)
except:
self._logger.exception(u"Could not delete {}".format(filename))
except Exception:
self._logger.exception("Could not delete {}".format(filename))
raise
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
@admin_permission.require(403)
@restricted_access
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
def perform_restore(self):
if not is_os_compatible(["!windows"]):
return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400)
return flask.make_response("Invalid request, the restores are not supported on the underlying operating system", 400)
input_name = "file"
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
@@ -219,7 +233,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
return flask.abort(404)
else:
return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400)
return flask.make_response("Invalid request, neither a file nor a path of a file to restore provided", 400)
def on_install_plugins(plugins):
force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
@@ -235,20 +249,20 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
u"of OctoPrint and the underlying operating system".format(plugin["id"]))
self._logger.warn("Cannot install plugin {}, it is incompatible to this version "
"of OctoPrint and the underlying operating system".format(plugin["id"]))
elif not octoprint_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
u"of OctoPrint".format(plugin["id"]))
self._logger.warn("Cannot install plugin {}, it is incompatible to this version "
"of OctoPrint".format(plugin["id"]))
elif not os_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying "
u"operating system".format(plugin["id"]))
self._logger.warn("Cannot install plugin {}, it is incompatible to the underlying "
"operating system".format(plugin["id"]))
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
octoprint_compatible=octoprint_compatible,
os_compatible=os_compatible))
continue
self._logger.info(u"Installing plugin {}".format(plugin["id"]))
self._logger.info("Installing plugin {}".format(plugin["id"]))
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
self.__class__._install_plugin(plugin,
force_user=force_user,
@@ -387,7 +401,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
path = os.path.join(datafolder, path)
if not os.path.exists(path):
click.echo(u"Backup {} does not exist".format(path), err=True)
click.echo("Backup {} does not exist".format(path), err=True)
sys.exit(-1)
archive = tempfile.NamedTemporaryFile(delete=False)
@@ -403,7 +417,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
def log(line):
click.echo(u"\t{}".format(line))
click.echo("\t{}".format(line))
for plugin in plugins:
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
@@ -411,17 +425,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
u"OctoPrint and the underlying operating system".format(plugin["id"]))
click.echo("Cannot install plugin {}, it is incompatible to this version of "
"OctoPrint and the underlying operating system".format(plugin["id"]))
elif not octoprint_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
u"OctoPrint".format(plugin["id"]))
click.echo("Cannot install plugin {}, it is incompatible to this version of "
"OctoPrint".format(plugin["id"]))
elif not os_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to the underlying "
u"operating system".format(plugin["id"]))
click.echo("Cannot install plugin {}, it is incompatible to the underlying "
"operating system".format(plugin["id"]))
continue
click.echo(u"Installing plugin {}".format(plugin["id"]))
click.echo("Installing plugin {}".format(plugin["id"]))
self.__class__._install_plugin(plugin,
force_user=force_user,
pip_args=pip_args,
@@ -431,9 +445,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if not plugins:
return
click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.")
click.echo("The following plugins were not found in the plugin repository. You'll need to install them manually.")
for plugin in plugins:
click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
click.echo("\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
def on_log_progress(line):
click.echo(line)
@@ -456,9 +470,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
on_log_progress=on_log_progress,
on_log_error=on_log_error,
on_invalid_backup=on_log_error):
click.echo(u"Restored from {}".format(path))
click.echo("Restored from {}".format(path))
else:
click.echo(u"Restoring from {} failed".format(path), err=True)
click.echo("Restoring from {} failed".format(path), err=True)
return [backup_command, restore_command]
@@ -484,28 +498,28 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
if os.path.exists(data_file):
try:
with codecs.open(data_file, mode="r", encoding="utf-8") as f:
with io.open(data_file, mode='rb', encoding="utf-8") as f:
unknown_plugins = json.load(f)
assert isinstance(unknown_plugins, list)
assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins))
installed_plugins = self._plugin_manager.plugins
unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
unknown_plugins = list(filter(lambda x: x["key"] not in installed_plugins, unknown_plugins))
if not unknown_plugins:
# no plugins left uninstalled, delete data file
try:
os.remove(data_file)
except:
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
except Exception:
self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file))
return unknown_plugins
except:
self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file))
except Exception:
self._logger.exception("Error while reading list of unknown plugins from {}".format(data_file))
try:
os.remove(data_file)
except:
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
except Exception:
self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file))
return []
@@ -517,10 +531,10 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if os.path.exists(basedir_backup):
def remove_bck():
if callable(on_log_progress):
on_log_progress(u"Found config folder backup from prior restore, deleting it...")
on_log_progress("Found config folder backup from prior restore, deleting it...")
shutil.rmtree(basedir_backup)
if callable(on_log_progress):
on_log_progress(u"... deleted.")
on_log_progress("... deleted.")
thread = threading.Thread(target=remove_bck)
thread.daemon = True
@@ -555,8 +569,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
except:
logger.exception(u"Error while fetching the plugin repository data from {}".format(url))
except Exception:
logger.exception("Error while fetching the plugin repository data from {}".format(url))
return dict()
from octoprint.plugins.pluginmanager import map_repository_entry
@@ -573,16 +587,16 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
# prepare pip caller
def log(prefix, *lines):
for line in lines:
on_log(u"{} {}".format(prefix, line.rstrip()))
on_log("{} {}".format(prefix, line.rstrip()))
def log_call(*lines):
log(u">", *lines)
log(">", *lines)
def log_stdout(*lines):
log(u"<", *lines)
log("<", *lines)
def log_stderr(*lines):
log(u"!", *lines)
log("!", *lines)
if cls._pip_caller is None:
cls._pip_caller = LocalPipCaller(force_user=force_user)
@@ -704,7 +718,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
except:
except Exception as exc: ## noqa: F841
# TODO py3: use the exception, not sys.exc_info()
if callable(on_backup_error):
exc_info = sys.exc_info()
try:
@@ -728,7 +743,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
on_restore_failed=None):
if not is_os_compatible(["!windows"]):
if callable(on_log_error):
on_log_error(u"Restore is not supported on this operating system")
on_log_error("Restore is not supported on this operating system")
if callable(on_restore_failed):
on_restore_failed(path)
return False
@@ -755,7 +770,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
metadata_zipinfo = zip.getinfo("metadata.json")
except KeyError:
if callable(on_invalid_backup):
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
on_invalid_backup("Not an OctoPrint backup, lacks metadata.json")
if callable(on_restore_failed):
on_restore_failed(path)
return False
@@ -766,7 +781,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
backup_version = get_comparable_version(metadata["version"], base=True)
if backup_version > get_octoprint_version(base=True):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
on_invalid_backup("Backup is from a newer version of OctoPrint and cannot be applied")
if callable(on_restore_failed):
on_restore_failed(path)
return False
@@ -775,7 +790,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
temp = tempfile.mkdtemp()
try:
if callable(on_log_progress):
on_log_progress(u"Unpacking backup to {}...".format(temp))
on_log_progress("Unpacking backup to {}...".format(temp))
abstemp = os.path.abspath(temp)
for member in zip.infolist():
abspath = os.path.abspath(os.path.join(temp, member.filename))
@@ -786,33 +801,33 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
configfile = os.path.join(temp, "basedir", "config.yaml")
if not os.path.exists(configfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks config.yaml")
on_invalid_backup("Backup lacks config.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
import yaml
with codecs.open(configfile) as f:
with io.open(configfile, "rt", encoding="utf-8") as f:
configdata = yaml.safe_load(f)
if configdata.get("accessControl", dict()).get("enabled", True):
userfile = os.path.join(temp, "basedir", "users.yaml")
if not os.path.exists(userfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks users.yaml")
on_invalid_backup("Backup lacks users.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
if callable(on_log_progress):
on_log_progress(u"Unpacked")
on_log_progress("Unpacked")
# install available plugins
plugins = []
plugin_list_file = os.path.join(temp, "plugin_list.json")
if os.path.exists(plugin_list_file):
with codecs.open(plugin_list_file, "r") as f:
with io.open(os.path.join(temp, "plugin_list.json"), 'rb') as f:
plugins = json.load(f)
known_plugins = []
@@ -837,9 +852,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if callable(on_log_progress):
if known_plugins:
on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins))))
on_log_progress("Known and installable plugins: {}".format(", ".join(map(lambda x: x["id"], known_plugins))))
if unknown_plugins:
on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins))))
on_log_progress("Unknown plugins: {}".format(", ".join(map(lambda x: x["key"], unknown_plugins))))
if callable(on_install_plugins):
on_install_plugins(known_plugins)
@@ -852,17 +867,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
basedir_extracted = os.path.join(temp, "basedir")
if callable(on_log_progress):
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
on_log_progress("Renaming {} to {}...".format(basedir, basedir_backup))
shutil.move(basedir, basedir_backup)
try:
if callable(on_log_progress):
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
on_log_progress("Moving {} to {}...".format(basedir_extracted, basedir))
shutil.move(basedir_extracted, basedir)
except:
except Exception:
if callable(on_log_error):
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
on_log_error(u"Rolling back old config data")
on_log_error("Error while restoring config data", exc_info=sys.exc_info())
on_log_error("Rolling back old config data")
shutil.move(basedir_backup, basedir)
@@ -872,30 +887,30 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if unknown_plugins:
if callable(on_log_progress):
on_log_progress(u"Writing info file about unknown plugins")
on_log_progress("Writing info file about unknown plugins")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE)
try:
with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f:
json.dump(unknown_plugins, f)
except:
with io.open(unknown_plugins_path, mode='wb') as f:
f.write(to_bytes(json.dumps(unknown_plugins)))
except Exception:
if callable(on_log_error):
on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
on_log_error("Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
exc_info = sys.exc_info())
finally:
if callable(on_log_progress):
on_log_progress(u"Removing temporary unpacked folder")
on_log_progress("Removing temporary unpacked folder")
shutil.rmtree(temp)
except:
except Exception:
exc_info = sys.exc_info()
try:
if callable(on_log_error):
on_log_error(u"Error while running restore", exc_info=exc_info)
on_log_error("Error while running restore", exc_info=exc_info)
if callable(on_restore_failed):
on_restore_failed(path)
finally:
@@ -905,7 +920,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
finally:
# remove zip
if callable(on_log_progress):
on_log_progress(u"Removing temporary zip")
on_log_progress("Removing temporary zip")
os.remove(path)
# restart server
@@ -913,17 +928,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
import sarge
if callable(on_log_progress):
on_log_progress(u"Restarting...")
on_log_progress("Restarting...")
if callable(on_restore_done):
on_restore_done(path)
try:
sarge.run(restart_command, async_=True)
except:
except Exception:
if callable(on_log_error):
on_log_error(u"Error while restarting via command {}".format(restart_command),
on_log_error("Error while restarting via command {}".format(restart_command),
exc_info=sys.exc_info())
on_log_error(u"Please restart OctoPrint manually")
on_log_error("Please restart OctoPrint manually")
return False
else:
@@ -944,15 +959,16 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
class InsufficientSpace(Exception):
pass
__plugin_name__ = u"Backup & Restore"
__plugin_author__ = u"Gina Häußge"
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
u"& restore your OctoPrint settings and data.")
__plugin_license__ = u"AGPLv3"
__plugin_name__ = "Backup & Restore"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Backup & restore your OctoPrint settings and data"
__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to backup "
"& restore your OctoPrint settings and data.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = BackupPlugin()
__plugin_hooks__ = {
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
+2 -2
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
__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"
+15 -17
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
__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"
@@ -9,7 +9,8 @@ import octoprint.plugin
import sys
import inspect
from flask_babel import gettext
from octoprint.access import ADMIN_GROUP, USER_GROUP
from octoprint.util import to_native_str
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class ServerCommandsSubwizard(object):
@@ -55,7 +56,7 @@ class AclSubwizard(object):
return True
def _is_acl_wizard_required(self):
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
return self._user_manager.enabled and not self._user_manager.has_been_customized()
def _get_acl_wizard_details(self):
return dict(required=self._is_acl_wizard_required())
@@ -71,27 +72,24 @@ class AclSubwizard(object):
from flask import request, abort
from octoprint.server.api import valid_boolean_trues, NO_CONTENT
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.hasBeenCustomized():
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized():
abort(404)
data = request.values
if hasattr(request, "json") and request.json:
data = request.json
data = request.get_json()
if data is None:
data = request.values
if "ac" in data and data["ac"] in valid_boolean_trues and \
"user" in data.keys() and "pass1" in data.keys() and \
"pass2" in data.keys() and data["pass1"] == data["pass2"]:
"user" in data and "pass1" in data and \
"pass2" in data and data["pass1"] == data["pass2"]:
# configure access control
self._settings.global_set_boolean(["accessControl", "enabled"], True)
self._user_manager.enable()
self._user_manager.addUser(data["user"], data["pass1"], True, ["user", "admin"], overwrite=True)
elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues:
self._user_manager.add_user(data["user"], data["pass1"], True, [], [USER_GROUP, ADMIN_GROUP], overwrite=True)
elif "ac" in data and not data["ac"] in valid_boolean_trues:
# disable access control
self._settings.global_set_boolean(["accessControl", "enabled"], False)
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
self._user_manager.disable()
self._settings.save()
return NO_CONTENT
@@ -148,7 +146,7 @@ class PrinterProfileSubwizard(object):
return gettext("Default Printer Profile")
Subwizards = type("Subwizwards",
Subwizards = type(to_native_str("Subwizards"),
tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if clsname.endswith("Subwizard")),
dict())
+30 -22
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'
@@ -20,8 +20,9 @@ import octoprint.plugin
import octoprint.util
try:
# TODO: looks like pybonjour is py2 only - find alternatives or port?
import pybonjour
except:
except ImportError:
pybonjour = False
@@ -199,13 +200,13 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
while True:
try:
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
self._logger.info(u"Registered '{name}' for {regtype}".format(**params))
self._logger.info("Registered '{name}' for {regtype}".format(**params))
return True
except pybonjour.BonjourError as be:
if be.errorCode == pybonjour.kDNSServiceErr_NameConflict:
# Name already registered by different service, let's try a counter postfix. See #2852
counter += 1
params["name"] = u"{} ({})".format(name, counter)
params["name"] = "{} ({})".format(name, counter)
else:
raise
@@ -232,7 +233,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
try:
sd_ref.close()
self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
except:
except Exception:
self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5):
@@ -378,7 +379,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
def browse_callback(results):
for result in results:
print "Location: {}".format(result)
print("Location: {}".format(result))
:param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices
:param block: whether to block, defaults to True
@@ -390,10 +391,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
"""
import threading
import httplib
import io
class Response(httplib.HTTPResponse):
try:
# noinspection PyCompatibility
from http.client import HTTPResponse # py3
except ImportError:
# noinspection PyCompatibility
from httplib import HTTPResponse # py2
class Response(HTTPResponse):
def __init__(self, response_text):
self.fp = io.BytesIO(response_text)
self.debuglevel = 0
@@ -431,7 +438,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
mcast_addr=self.__class__.ssdp_multicast_addr,
mcast_port=self.__class__.ssdp_multicast_port)
for _ in range(2):
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
try:
data = sock.recv(1024)
@@ -441,7 +448,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
response = Response(data)
result.append(response.getheader("Location"))
except:
except Exception:
pass
if callback:
@@ -598,8 +605,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
mcast_port=self.__class__.ssdp_multicast_port)
for _ in range(2):
# send twice, stuff might get lost, it's only UDP
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
except:
sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
except Exception:
pass
self._ssdp_last_notify = octoprint.util.monotonic_time()
@@ -652,22 +659,23 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0'))
self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name()))
self._logger.info("Registered {} for SSDP".format(self.get_instance_name()))
self._ssdp_notify(alive=True)
try:
while (self._ssdp_monitor_active):
while self._ssdp_monitor_active:
try:
data, address = sock.recvfrom(4096)
request = Request(data)
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
interface_address = octoprint.util.address_for_client(*address)
if not interface_address:
self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
self._logger.warning("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
continue
message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
sock.sendto(message, address)
message = location_message.format(uuid=self.get_uuid(),
location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
sock.sendto(message.encode("utf-8"), address)
self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
except socket.timeout:
pass
@@ -676,7 +684,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
finally:
try:
sock.close()
except:
except Exception:
pass
##~~ helpers
@@ -693,10 +701,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
def get_instance_name(self):
name = self._settings.global_get(["appearance", "name"])
if name:
return u"OctoPrint instance \"{}\"".format(name)
return "OctoPrint instance \"{}\"".format(name)
else:
import socket
return u"OctoPrint instance on {}".format(socket.gethostname())
return "OctoPrint instance on {}".format(socket.gethostname())
__plugin_name__ = "Discovery"
@@ -12,10 +12,8 @@ from octoprint.util.version import get_octoprint_version_string, is_released_oct
from flask import jsonify
from flask_babel import gettext
from serial import SerialException
SENTRY_URL_SERVER = "https://4273b441bb654c4398de42ba86350963@sentry.io/1373987"
SENTRY_URL_COREUI = "https://f9bcd7185f73430bbe7c09ff69586b0f@sentry.io/1374096"
SENTRY_URL_SERVER = "https://4069187705ab4e76921eb19db2e9ccbb@sentry.io/1373987"
SENTRY_URL_COREUI = "https://a4ab48f27daf4c129392b78be15412b8@sentry.io/1374096"
SETTINGS_DEFAULTS = dict(enabled=False,
enabled_unreleased=False,
@@ -23,10 +21,40 @@ SETTINGS_DEFAULTS = dict(enabled=False,
url_server=SENTRY_URL_SERVER,
url_coreui=SENTRY_URL_COREUI)
import serial
import requests.exceptions
import errno
import octoprint.util.avr_isp.ispBase
import tornado.websocket
IGNORED_EXCEPTIONS = [
(SerialException, "octoprint.util.comm"),
# serial exceptions in octoprint.util.comm
(serial.SerialException, lambda exc, logger, plugin: logger == "octoprint.util.comm"),
# isp errors during port auto detection in octoprint.util.comm
(octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin: logger == "octoprint.util.comm"),
# IOErrors of any kind due to a full file system
(IOError, lambda exc, logger, plugin: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
# RequestExceptions of any kind
requests.exceptions.RequestException,
# Tornado WebSocketErrors of any kind
tornado.websocket.WebSocketError
]
try:
# noinspection PyUnresolvedReferences
from octoprint.plugins.backup import InsufficientSpace
# if the backup plugin is enabled, ignore InsufficientSpace errors from it as well
IGNORED_EXCEPTIONS.append(InsufficientSpace)
del InsufficientSpace
except ImportError:
pass
class ErrorTrackingPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
@@ -109,13 +137,19 @@ def _enable_errortracking():
handled = True
logger = event.get("logger", "")
plugin = event.get("extra", dict()).get("plugin", None)
for ignore in IGNORED_EXCEPTIONS:
if isinstance(ignore, tuple):
ignored_exc, ignored_logger = ignore
if isinstance(hint["exc_info"][1], ignored_exc) and logger.startswith(ignored_logger):
# exception ignored for logger
return None
ignored_exc, matcher = ignore
else:
ignored_exc = ignore
matcher = lambda *args: True
exc = hint["exc_info"][1]
if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin):
# exception ignored for logger
return None
elif isinstance(ignore, type):
if isinstance(hint["exc_info"][1], ignore):
@@ -139,6 +173,12 @@ def _enable_errortracking():
# we only want our active bundled plugins
return None
if plugin is not None:
plugin_info = plugin_manager().get_plugin_info(plugin)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
return event
sentry_sdk.init(url_server,
@@ -1,3 +1,2 @@
/*! @sentry/browser 4.5.1 (6a390acf) | https://github.com/getsentry/sentry-javascript */
var Sentry=function(t){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,n)};function n(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r,o,i=function(){return(i=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)};function s(t,e,n,r){return new(n||(n=Promise))(function(o,i){function s(t){try{u(r.next(t))}catch(t){i(t)}}function a(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){t.done?o(t.value):new n(function(e){e(t.value)}).then(s,a)}u((r=r.apply(t,e||[])).next())})}function a(t,e){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=e.call(t,s)}catch(t){i=[6,t],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function u(t){var e="function"==typeof Symbol&&t[Symbol.iterator],n=0;return e?e.call(t):{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}}}function c(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function l(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(c(arguments[e]));return t}function p(t){switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return t instanceof Error}}function f(t){return"[object ErrorEvent]"===Object.prototype.toString.call(t)}function h(t){return"[object DOMError]"===Object.prototype.toString.call(t)}function d(t){return void 0===t}function v(t){return"function"==typeof t}function g(t){return"[object String]"===Object.prototype.toString.call(t)}function y(t){return"[object Object]"===Object.prototype.toString.call(t)}function m(t){return t!=t}function b(){return"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}}function E(){var t=b(),e=t.crypto||t.msCrypto;if(void 0!==e&&e.getRandomValues){var n=new Uint16Array(8);e.getRandomValues(n),n[3]=4095&n[3]|16384,n[4]=16383&n[4]|32768;var r=function(t){for(var e=t.toString(16);e.length<4;)e="0"+e;return e};return r(n[0])+r(n[1])+r(n[2])+r(n[3])+r(n[4])+r(n[5])+r(n[6])+r(n[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function x(t){var e,n,r,o,i,s=[];if(!t||!t.tagName)return"";if(s.push(t.tagName.toLowerCase()),t.id&&s.push("#"+t.id),(e=t.className)&&g(e))for(n=e.split(/\s+/),i=0;i<n.length;i++)s.push("."+n[i]);var a=["type","name","title","alt"];for(i=0;i<a.length;i++)r=a[i],(o=t.getAttribute(r))&&s.push("["+r+'="'+o+'"]');return s.join("")}function _(t){if(!t)return{};var e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],relative:e[5]+n+r}}function S(t){if(t.message)return t.message;if(t.exception&&t.exception.values&&t.exception.values[0]){var e=t.exception.values[0];return e.type&&e.value?e.type+": "+e.value:e.type||e.value||t.event_id||"<unknown>"}return t.event_id||"<unknown>"}function w(t){var e=b();if(!("console"in e))return t();var n=e.console,r={};["debug","info","warn","error","log"].forEach(function(t){t in e.console&&n[t].__sentry__&&(r[t]=n[t].__sentry_wrapped__,n[t]=n[t].__sentry_original__)});var o=t();return Object.keys(r).forEach(function(t){n[t]=r[t]}),o}function k(t,e){return void 0===e&&(e=0),0!==e&&g(t)?t.length<=e?t:t.substr(0,e)+"...":t}function O(t,e){if(!Array.isArray(t))return"";for(var n=[],r=0;r<t.length;r++){var o=t[r];try{n.push(String(o))}catch(t){n.push("[value cannot be serialized]")}}return n.join(e)}function j(t,e){return!(Line truncated
//# sourceMappingURL=bundle.min.js.map
/*! @sentry/browser 5.0.5 (913eafc4) | https://github.com/getsentry/sentry-javascript */
var Sentry=function(n){"use strict";var t=function(n,r){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r])})(n,r)};function r(n,r){function i(){this.constructor=n}t(n,r),n.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var i,e,o,u=function(){return(u=Object.assign||function(n){for(var t,r=1,i=arguments.length;r<i;r++)for(var e in t=arguments[r])Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e]);return n}).apply(this,arguments)};function c(n,t,r,i){return new(r||(r=Promise))(function(e,o){function u(n){try{s(i.next(n))}catch(n){o(n)}}function c(n){try{s(i.throw(n))}catch(n){o(n)}}function s(n){n.done?e(n.value):new r(function(t){t(n.value)}).then(u,c)}s((i=i.apply(n,t||[])).next())})}function s(n,t){var r,i,e,o,u={label:0,sent:function(){if(1&e[0])throw e[1];return e[1]},trys:[],ops:[]};return o={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function c(o){return function(c){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;u;)try{if(r=1,i&&(e=2&o[0]?i.return:o[0]?i.throw||((e=i.return)&&e.call(i),0):i.next)&&!(e=e.call(i,o[1])).done)return e;switch(i=0,e&&(o=[2&o[0],e.value]),o[0]){case 0:case 1:e=o;break;case 4:return u.label++,{value:o[1],done:!1};case 5:u.label++,i=o[1],o=[0];continue;case 7:o=u.ops.pop(),u.trys.pop();continue;default:if(!(e=(e=u.trys).length>0&&e[e.length-1])&&(6===o[0]||2===o[0])){u=0;continue}if(3===o[0]&&(!e||o[1]>e[0]&&o[1]<e[3])){u.label=o[1];break}if(6===o[0]&&u.label<e[1]){u.label=e[1],e=o;break}if(e&&u.label<e[2]){u.label=e[2],u.ops.push(o);break}e[2]&&u.ops.pop(),u.trys.pop();continue}o=t.call(n,u)}catch(n){o=[6,n],i=0}finally{r=e=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}function f(n,t){var r="function"==typeof Symbol&&n[Symbol.iterator];if(!r)return n;var i,e,o=r.call(n),u=[];try{for(;(void 0===t||t-- >0)&&!(i=o.next()).done;)u.push(i.value)}catch(n){e={error:n}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return u}function a(){for(var n=[],t=0;t<arguments.length;t++)n=n.concat(f(arguments[t]));return n}function h(n){switch(Object.prototype.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return n instanceof Error}}function v(n){return"[object ErrorEvent]"===Object.prototype.toString.call(n)}function l(n){return"[object DOMError]"===Object.prototype.toString.call(n)}function d(n){return"[object String]"===Object.prototype.toString.call(n)}function p(n){return null===n||"object"!=typeof n&&"function"!=typeof n}function m(n){return"[object Object]"===Object.prototype.toString.call(n)}function y(n){return Boolean(n&&n.then&&"function"==typeof n.then)}!function(n){n[n.None=0]="None",n[n.Error=1]="Error",n[n.Debug=2]="Debug",n[n.Verbose=3]="Verbose"}(i||(i={})),(e=n.Severity||(n.Severity={})).Fatal="fatal",e.Error="error",e.Warning="warning",e.Log="log",e.Info="info",e.Debug="debug",e.Critical="critical",function(n){n.fromString=function(t){switch(t){case"debug":return n.Debug;case"info":return n.Info;case"warn":case"warning":return n.Warning;case"error":return n.Error;case"fatal":return n.Fatal;case"critical":return n.Critical;case"log":default:return n.Log}}}(n.Severity||(n.Severity={})),(o=n.Status||(n.Status={})).Unknown="unknown",o.Skipped="skipped",o.Success="success",o.RateLimit="rate_limit",o.Invalid="invalid",o.Failed="failed",function(n){n.fromHttpCode=function(t){return t>=200&&t<300?n.Success:429===t?n.RateLimit:t>=400&&t<500?n.Invalid:t>=500?n.Failed:n.Unknown}}(n.Status||(n.Status={}));var b={};function w(){return"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:b}function g(){var n=w(),t=n.crypto||n.msCrypto;if(void 0!==t&&t.getRandomValues){var r=new Uint16Array(8);t.getRandomValues(r),r[3]=4095&r[3]|16384,r[4]=16383&r[4]|32768;var i=function(n){for(var t=n.toString(16);t.length<4;)t="0"+t;return t};return i(r[0])+i(r[1])+i(r[2])+i(r[3])+i(r[4])+i(r[5])+i(r[6])+i(r[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(n){var t=16*Math.random()|0;return("x"===n?t:3&t|8).toString(16)})}function E(n){var t,r,i,e,o,u=[];if(!n||!n.tagName)return"";if(u.push(n.tagName.toLowerCase()),n.id&&u.push("#"+n.id),(t=n.className)&&d(t))for(r=t.split(/\s+/),o=0;o<r.length;o++)u.push("."+r[o]);var c=["type","name","title","alt"];for(o=0;o<c.length;o++)i=c[o],(e=n.getAttribute(i))&&u.push("["+i+'="'+e+'"]');return u.join("")}function x(n){if(!n)return{};var t=n.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!t)return{};var r=t[6]||"",i=t[8]||"";return{host:t[4],path:t[5],protocol:t[2],relative:t[5]+r+i}}function j(n){if(n.message)return n.message;if(n.exception&&n.exception.values&&n.excepLine truncated
@@ -7,7 +7,15 @@
Sentry.init({
dsn: errortracking_url_coreui,
release: VERSION
release: VERSION,
whitelistUrls: [
// only include static assets
"/static/"
],
blacklistUrls: [
// exclude third party plugins
"/static/webassets/packed_plugins.js"
]
});
Sentry.configureScope(function (scope) {
scope.setUser({"id": errortracking_unique_id});
@@ -1,201 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import flask
import flask_login
from flask_babel import gettext
from collections import defaultdict
import threading
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin):
MAX_BACKLOG_LEN = 100
# noinspection PyMissingConstructor
def __init__(self):
self._message_backlog = defaultdict(list)
self._message_backlog_mutex = threading.RLock()
@property
def active(self):
# we are only active if ACL is enabled AND configured
return self._user_manager.enabled and self._user_manager.hasBeenCustomized()
def get_assets(self):
return dict(
js=["js/viewmodel.js"]
)
def will_handle_ui(self, request):
if not self.active:
# not active, not responsible
return False
from octoprint.server.util import loginUserFromApiKey, loginUserFromAuthorizationHeader, InvalidApiKeyException
from octoprint.server.util.flask import passive_login
# first try to login via api key & authorization header, just in case that's set
try:
if loginUserFromApiKey():
# successful? No need for handling the UI
return False
except InvalidApiKeyException:
pass # ignored
if loginUserFromAuthorizationHeader():
# successful? No need for handling the UI
return False
# then try a passive login
result = passive_login()
if hasattr(result, "status_code") and result.status_code == 200:
# successful? No need for handling the UI
return False
else:
return True
def on_ui_render(self, now, request, render_kwargs):
from flask import render_template, make_response
"""
Support theming of the login dialog, just in case the core UI is themed as well.
Example usage by a plugin:
def forcelogin_theming():
from flask import url_for
return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
__plugin_hooks__ = {
"octoprint.plugin.forcelogin.theming": forcelogin_theming
}
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
url_for like in the example above to be prepared for any configured prefix URLs.
"""
additional_assets = []
for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
try:
assets = hook()
if isinstance(assets, (tuple, list)):
additional_assets += assets
except:
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name))
render_kwargs.update(dict(forcelogin_theming=additional_assets))
return make_response(render_template("forcelogin_index.jinja2", **render_kwargs))
def get_ui_custom_tracked_files(self):
from os.path import join as opj
paths = [opj("static", "css", "forcelogin.css"),
opj("static", "js", "main.js"),
opj("static", "js", "viewmodel.js"),
opj("static", "less", "forcelogin.less"),
opj("templates", "parts", "forcelogin_css.jinja2"),
opj("templates", "parts", "forcelogin_javascripts.jinja2"),
opj("templates", "forcelogin_index.jinja2")]
return [opj(self._basefolder, path) for path in paths]
def get_ui_preemptive_caching_enabled(self):
return False
def get_sorting_key(self, context=None):
if context == "UiPlugin.on_ui_render":
# If a plugin *really* wants to come before this plugin, it'll have to turn to negative numbers.
#
# This is obviously discouraged for security reasons, but very specific setups might make it necessary,
# so we make it possible. If this should get abused long term we can always turn this into -inf.
return 0
def get_before_request_handlers(self, plugin=None, *args, **kwargs):
def check_login_required():
if not self.active:
# not active, no handling
return
if flask.request.endpoint in ("api.login",):
return
if plugin is not None and not plugin.is_blueprint_protected():
return
user = flask_login.current_user
if user is None or user.is_anonymous() or not user.is_active():
return flask.make_response("Forbidden", 403)
return [check_login_required]
def access_validator(self, request):
if not self.active:
# not active, no handling
return
import tornado.web
from octoprint.server.util.flask import get_flask_user_from_request
user = get_flask_user_from_request(request)
if user is None or not user.is_authenticated():
raise tornado.web.HTTPError(403)
def socket_register_validator(self, socket, user):
if not self.active:
# not active, no limitation
return True
return user is not None and not user.is_anonymous() and user.is_active()
def socket_authed(self, socket, user):
with self._message_backlog_mutex:
backlog = self._message_backlog.pop(socket, [])
if len(backlog):
for message, payload in backlog:
socket._do_emit(message, payload)
self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog)))
def socket_emit_validator(self, socket, user, message, payload):
if not self.active:
# not active, no limitation
return True
if message in ("connected", "reauthRequired"):
return True
if user is not None and not user.is_anonymous() and user.is_active():
return True
with self._message_backlog_mutex:
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
self._message_backlog[socket].append((message, payload))
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
else:
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
return False
__plugin_name__ = "Force Login"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Forces users to login, disables read-only mode."
__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your "
"OctoPrint instance. Only disable this if you are comfortable with this, your "
"OctoPrint instance is not publicly reachable on the internet and you fully "
"trust everyone who has access to your local network!")
__plugin_implementation__ = ForceLoginPlugin()
__plugin_hooks__ = {
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
}
@@ -1 +0,0 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
@@ -1,59 +0,0 @@
/*
* Will get included into the login dialog, NOT into the regular OctoPrint
* web application.
*/
$(function() {
var overlayElement = $("#login-overlay");
var errorElement = $("#login-error");
var offlineElement = $("#login-offline");
var buttonElement = $("#login-button");
var reconnectElement = $("#login-reconnect");
buttonElement.click(function() {
var usernameElement = $("#login-user");
var passwordElement = $("#login-password");
var rememberElement = $("#login-remember");
var username = usernameElement.val();
var password = passwordElement.val();
var remember = rememberElement.prop("checked");
overlayElement.addClass("in");
errorElement.removeClass("in");
OctoPrint.browser.login(username, password, remember)
.done(function() {
location.reload();
})
.fail(function() {
usernameElement.val("");
passwordElement.val("");
overlayElement.removeClass("in");
errorElement.addClass("in");
});
return false;
});
var OctoPrint = window.OctoPrint;
OctoPrint.options.baseurl = BASE_URL;
OctoPrint.socket.onConnected = function() {
buttonElement.prop("disabled", false);
offlineElement.removeClass("in");
};
OctoPrint.socket.onDisconnected = function() {
buttonElement.prop("disabled", true);
offlineElement.addClass("in");
};
reconnectElement.click(function() {
OctoPrint.socket.reconnect();
});
OctoPrint.socket.connect();
});
@@ -1,17 +0,0 @@
/*
* View model that takes care to redirect to / on logout in the regular
* OctoPrint web application.
*/
$(function() {
function ForceLoginViewModel(parameters) {
var self = this;
self.onUserLoggedOut = function() {
location.reload();
}
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([ForceLoginViewModel, [], []]);
});
Loaded 100 of 349 files, more files were not shown because too many files have changed in this diff. Show more