Compare commits

..
Author SHA1 Message Date
Gina Häußge 18e7d2b72a 🔖 Preparing release of 1.3.11rc2 2019-04-04 14:26:01 +02:00
Gina Häußge 0b6dd7e76e 🐛 backup: exclude timelapse_tmp if timelapse is excluded
Fixes #3098
2019-04-01 14:28:40 +02:00
Gina Häußge d68c7bfc67 ☔ More resilience against platform startup issues
Might solve problems like #3100, but that is only a shot in the dark at
this point.
2019-04-01 13:57:29 +02:00
Gina Häußge c879ad27f4 ♻ Turn lines read from serial into unicode
Backported from devel branch.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Blocked by default: M0 and M1.

Pausing by default: M0, M1 and M25.

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

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

Implements #2904
2019-03-11 17:21:28 +01:00
Gina Häußge a1e8694073 🐛 Don't change to PRINTING state on resume if not RESUMING
See #2955
2019-03-11 16:02:20 +01:00
Gina Häußge e748b52098 🐛 Don't change to PAUSED state if not PAUSING
Fixes #2955
2019-03-11 15:34:11 +01:00
Gina Häußge 8668c6200a ✨ Decorator for timing methods
Probably mostly helpful during development...
2019-03-06 13:53:53 +01:00
Gina Häußge e01f391b30 ⚡ More intelligent use of copy & deepcopy
Improves performance of file manipulation, especially in cases with a
lot of files in the folder, without the added complexity of fully
decoupling metadata file serialization from general processing.

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

See also #3057

Cherry-picked from 15d3b2ca
2019-03-05 16:20:13 +01:00
Fabi0San 1b5a654a2d Hide Tool section in Control for machines with no extruders. Such as Lasers. 2019-03-04 19:00:08 -08:00
FabioSan f0ee7f343e Hides temperature tab if the machine has no heated bed nor extruders. 2019-03-04 18:34:55 -08:00
Gina Häußge 3e16f0901a Merge remote-tracking branch 'origin/maintenance' into maintenance 2019-03-01 11:21:01 +01:00
Gina Häußge 8866ed716d ☔ Better resilience against invalid SD status reports 2019-03-01 11:20:45 +01:00
Gina Häußge 0f157d3747 ♻ Load bundled plugins under octoprint.plugins.*
Makes more sense than putting them into sys.modules as <identifier>,
which also can cause conflicts (e.g. in the case of octoprint.plugins
.logging which then suddenly gets found instead of the built-in crucial
logging module).
2019-02-28 16:37:09 +01:00
Gina Häußge fdb4e75241 Merge pull request #3066 from fieldOfView/fix_docs_job_state
Add missing documentation about state in `jobs` endpoint
2019-02-28 12:34:35 +01:00
Gina Häußge 4dbb24ecd7 📝 state is not a sub data model but a string 2019-02-28 12:26:25 +01:00
fieldOfView a15e2de251 Fix datamodel structure 2019-02-28 12:17:35 +01:00
fieldOfView c652bed871 Add missing documentation about state in jobs endpoint 2019-02-28 11:40:22 +01:00
Gina Häußge 253a38c32d ♻ gcode => printables 2019-02-26 15:31:22 +01:00
Gina Häußge e08becbb4c Merge pull request #3055 from AndyQ/show_current_layer
Added ability to preview the current layer to be drawn
2019-02-26 13:54:43 +01:00
Gina Häußge 09a043b393 🐛 tracking: fix handling of missing print time
See also #3063
2019-02-26 13:50:35 +01:00
Gina Häußge 0c4f4383e3 ♻ Introduce type hints
For now we'll only use them to have our IDEs scream at us...
2019-02-22 11:44:45 +01:00
Gina Häußge 45aa26f13e ♻ Add central methods for getting python version 2019-02-20 15:32:07 +01:00
Gina Häußge 4a64bc6023 Merge branch 'improve/moreFlexiblePrinterSafetyChecks' into maintenance
# Conflicts:
#	src/octoprint/plugins/printer_safety_check/__init__.py
2019-02-20 14:41:09 +01:00
Gina Häußge 8e6773d19f 🐛 printer_safety_check: Fix some issues with new implementation 2019-02-20 14:39:21 +01:00
Gina Häußge dfcddea581 🎨 Fix some whitespace issues 2019-02-19 13:28:15 +01:00
Gina Häußge ff59e275bf Merge branch 'improve/errortracking_plugin' into maintenance 2019-02-19 13:11:38 +01:00
Gina Häußge 0f8f1ec8e0 ✨ Finalize first version of errortracking plugin
Also add docs for that & the Anonymous Usage Tracking plugin.
2019-02-19 13:11:25 +01:00
AndyQ 0e302d440f Added ability to preview the current layer to be drawn
If selected, the current layer is drawn at 30% opacity and then the progress is drawn over the top at 100%
Added additional checkbox on GCodeView page to include current layer as preview
2019-02-18 11:28:41 +01:00
Gina Häußge 980616519d Merge pull request #3054 from rgriebl/master
Fix python version detection on Debian testing/unstable
2019-02-18 10:46:56 +01:00
Gina Häußge 434751634f Merge pull request #3053 from AndyQ/MultipleFiliament_fix
Fixed error in GCode viewer where multiple filaments available (e.g. …
2019-02-18 10:44:33 +01:00
Robert Griebl c35708a422 Fix python version detection on Debian testing/unstable
The current 2.7 Python binary on Debian returns "2.7.15+" as its version, which
is not PEP440 compliant. Tthere is no feedback at all from Debian maintainers
regarding the bug report as of now:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=914072

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

Fixes #3049
2019-02-18 00:37:08 +01:00
AndyQ 64464a38ce Fixed error in GCode viewer where multiple filaments available (e.g. using Prusa MMU2), but only using a filament that isn't the first one
e.g. filament 4
2019-02-17 11:57:13 +00:00
Gina Häußge 0e482151fd Merge pull request #3051 from CapnBry/unfuzzy-timetips
Always show unfuzzy times for total print time and time left in tooltip
2019-02-14 15:59:34 +01:00
Gina Häußge c5bf58e1cc ♻️ == -> === 2019-02-14 15:56:09 +01:00
Bryan Mayland 38b7be0142 Fix whitespace 2019-02-14 14:52:24 +00:00
Bryan Mayland 28a515ba6a Always show unfuzzy times for total print time and time left in tooltip 2019-02-14 14:41:01 +00:00
Gina Häußge 38868303da 🐛 Fix tests 2019-02-13 14:55:48 +01:00
Gina Häußge fe65f18f78 💥 Unbundling the cura plugin
It lives on as curalegacy at

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

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

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

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

See MarlinFirmware/Marlin#13039
2019-02-11 18:19:47 +01:00
Gina Häußge de6da3f360 Merge branch 'master' into maintenance 2019-02-11 10:08:54 +01:00
Gina Häußge b744c341eb 💬 discourse.octoprint.org => community.octoprint.org 2019-02-11 09:58:39 +01:00
Gina Häußge 697af69e97 Merge branch 'master' into maintenance 2019-02-08 17:06:59 +01:00
Gina Häußge 601451a3f1 ✨ Setting to disable fuzzy estimates
Implements #3040
2019-02-08 16:44:25 +01:00
Gina Häußge 81d523b73d ♻ Backport to_str -> to_bytes from devel
Add unit tests.
2019-02-08 14:39:07 +01:00
Gina Häußge deacd9c188 Merge pull request #3041 from Microtome/add-klipper-to-firmware-autodetect
Add support for klipper in firmware autodetect
2019-02-08 14:02:37 +01:00
Daniel Joyce 6e0024149e Add support for klipper firmware autodetect 2019-02-07 07:36:11 -08:00
Gina Häußge dd3b318327 Merge branch 'pr/3036' into maintenance 2019-02-07 12:07:13 +01:00
Gina Häußge 069e83c63c Merge pull request #3039 from Microtome/improve-backup-filename
Improve backup filename, fix for #3030
2019-02-07 11:43:02 +01:00
Daniel Joyce 0cf345f29b Fix bug where if no plugins are installed, restore fails
* When no plugins are installed, backup does not create a
  plugin_list.json file.
* Restore then fails when it tries to read the missing file.
* Add check to ensure plugin_list.json exists before restoring
  from backup.
2019-02-06 21:06:19 -08:00
Daniel Joyce 0fda153d60 Provide a better name for backup files, use utility function for consistent name 2019-02-06 20:45:07 -08:00
Daniel Joyce 61ac8430d6 Added self to Authors file 2019-02-05 08:46:58 -08:00
Daniel Joyce 6b4dfcb960 Support opening serial port in exclusive mode.
* Slight cleanup and refactoring
2019-02-05 08:46:44 -08:00
Gina Häußge 61431c0df3 Merge remote-tracking branch 'origin/master' 2019-02-04 18:48:10 +01:00
Gina Häußge cc0b63cbb9 📝 Fix a formatting issue
No events are about to be removed in 1.4.0, only the payload fields
marked as deprecated. And for some reason ReST doesn't appear to allow
including that piece of information within the `deprecated` directive,
so now we have a slightly different way of expressing it...
2019-02-04 18:40:57 +01:00
Gina Häußge 020403dc54 💬 Correct typo in german translation
Closes #3029
2019-02-04 14:43:12 +01:00
Gina Häußge 21a82bbdb6 🐛 Fix enableWebcam render kwarg
Was using the wrong setting name.
2019-02-01 15:10:28 +01:00
Gina Häußge 727fd12939 🚸 CORS change needs restart to take effect 2019-02-01 10:55:24 +01:00
Gina Häußge 100fe5f290 🐛 Allow disabling CORS headers on SockJS endpoints
Fixes 2) of #3024
2019-02-01 10:40:37 +01:00
Gina Häußge 1acf69cb6d 🐛 Add CORS headers to tornado endpoints (if enabled)
Fixes 1) of #3024
2019-01-31 17:38:10 +01:00
Gina Häußge 3815c340a8 ☔ Protect against corrupt language packs 2019-01-31 17:07:10 +01:00
Gina Häußge c36a378b60 Merge branch 'hotfix/documentation_error' into maintenance 2019-01-30 15:08:41 +01:00
Gina Häußge 9a7ebde76b 📝 Fix documentation for firmware info & capability plugin hooks 2019-01-30 15:02:32 +01:00
Gina Häußge c23bafd788 ☔ Protect against callback errors in decorators on default view 2019-01-30 14:36:53 +01:00
Gina Häußge 1aea92a5f1 ☔ Protect against invalid preemptive cache config data
Fixes #3023
2019-01-30 14:36:52 +01:00
Gina Häußge fb38c396e8 Merge pull request #3010 from HarlemSquirrel/maintenance-disk-usage
Add system usage API endpoint
2019-01-28 18:33:38 +01:00
Gina Häußge 904b3c6cf5 🔧 Adjust default regex of temperature terminal filter (2nd try)
Should no longer match lines like

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

but should pass unit tests.

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

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

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

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

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

See MarlinFirmware/Marlin#12982
2019-01-28 14:32:10 +01:00
Gina Häußge d8088887e1 🐛 Fix bug introduced in bd58138acf 2019-01-28 13:45:09 +01:00
Gina Häußge 379411cea7 🔧 action_command_prompt: M876 as default command
See MarlinFirmware/Marlin#12982
2019-01-28 13:10:00 +01:00
Gina Häußge 5e953c12a1 💬 Rewording 2019-01-28 13:07:34 +01:00
Gina Häußge bd58138acf 🎨 Refactored for better code reuse 2019-01-28 13:05:27 +01:00
Gina Häußge 44b4c6cc40 🐛 sleep => time.sleep 2019-01-28 13:00:26 +01:00
Gina Häußge f3f1061f9d ❇️ Configurable terminal log size in comm layer
See https://discourse.octoprint.org/t/logging-terminal-information-on-failed-print/7047/3?u=foosel
2019-01-28 12:03:16 +01:00
Gina Häußge 68410cb3d7 🐛 Fix an issue with plugin sorting
If we just uninstalled a plugin there might not be a PluginInfo object.
In that case assume the plugin is not bundled (not False = True)
2019-01-25 16:14:45 +01:00
Gina Häußge db009e3ba2 🐛 backup: do not translate plugin name
Only translate it at template level, not before.

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

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

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

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

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

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

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

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

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

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

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

So a custom implementation it is. Hooray.

Implements #2983

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

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

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

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

Also fixes potential issues with using things like the unique_id when
it hasn't in fact been set due to disabled tracking.
2018-12-13 13:13:02 +01:00
Gina Häußge 49b995b234 Set 10min idle timeout on tornado under windows
Possible workaround for #2916
2018-12-12 16:06:15 +01:00
Gina Häußge 8cf5ca9589 tracking: Track firmware/communication errors 2018-12-12 15:41:36 +01:00
Gina Häußge ae36a3905a printer safety: Mark Malyan M200 fw 4.0+ as safe
Implements #2947
2018-12-12 15:25:38 +01:00
Gina Häußge bfd847f0a6 GCODE viewer: Bring back the layer count 2018-12-12 15:16:17 +01:00
Gina Häußge ef81702219 Merge remote-tracking branch 'origin/maintenance' into maintenance 2018-12-10 14:59:55 +01:00
Gina Häußge 7cbe6244ae Merge branch 'staging/maintenance' into maintenance 2018-12-10 14:59:39 +01:00
Gina Häußge 112a8b9c8b Merge branch 'rc/maintenance' 2018-12-10 13:01:23 +01:00
Gina Häußge 98b692d845 Preparing release of 1.3.10 2018-12-10 12:44:25 +01:00
Gina Häußge f4f7c87640 Always show actual received from printer instead of off
Regardless how cold the temperature is, display it in the table. Some
people otherwise seem to think that OctoPrint "can't handle"
temperatures below 10°C and will blame it for MINTEMP errors triggered
in the firmware.
2018-12-06 11:49:23 +01:00
Gina Häußge 5af5cbbb37 Merge branch 'staging/maintenance' into maintenance 2018-12-03 14:16:50 +01:00
Gina Häußge a657ebd528 staging/maintenance is now 1.3.10rc5.dev 2018-12-03 14:16:31 +01:00
Gina Häußge e628aedbc1 Preparing release of 1.3.10rc4 2018-12-03 12:42:28 +01:00
Gina Häußge 38fce1665b backup: signal restore done before reboot 2018-11-30 20:07:18 +01:00
Gina Häußge f51a98768c backup: more feedback during restore
The upload of a backup can take a while, so pop up the work dialog as
soon as that starts, not only when it is finished.
2018-11-30 20:06:57 +01:00
Gina Häußge 4d04c323f6 backup: use base version for version check 2018-11-30 20:06:24 +01:00
Gina Häußge 94116bfd53 backup: fix on_restore_failed calls 2018-11-30 18:33:58 +01:00
Gina Häußge a05761e63f backup: better error logging 2018-11-30 18:29:55 +01:00
Gina Häußge 89469d38ae printer safety: Fix localization of warning 2018-11-30 17:06:07 +01:00
Gina Häußge bd2616e888 backup: exclude generated, logs & watched
We don't need these in the backup, and in fact they only make things
more bloated and/or complicated.
2018-11-30 16:53:26 +01:00
Gina Häußge 02e996436d backup: restore is not supported on windows
Sadly the stupid file locking of windows makes it impossible to
hot swap the config directory. In order to support windows a two step
approach would be needed. Maybe at a later date, currently simply not
worth the effort tbh considering how seldomly windows is used as OS for
OctoPrint.
2018-11-30 16:53:19 +01:00
Gina Häußge a3f2e0b56c backup: fix plugin compatibility check on restore
Fixes #2920
2018-11-30 16:21:58 +01:00
Gina Häußge c4295d6a81 Merge branch 'staging/maintenance' into maintenance 2018-11-28 14:57:14 +01:00
Gina Häußge d60cab1962 staging/maintenance is now 1.3.10rc4.dev 2018-11-28 14:56:39 +01:00
Gina Häußge b01e327f9d Preparing release of 1.3.10rc3 2018-11-28 12:56:02 +01:00
Gina Häußge 09af2813d0 Add dedicated issue templates 2018-11-27 14:21:13 +01:00
Gina Häußge 2f69a84352 Use max of comm & temp timeout as serial timeout
That way we avoid issues if the user has set a longer temperature
reporting interval than (busy) communication timeout.

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

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

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

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

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

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

Closes #2873
2018-11-06 14:02:49 +01:00
Gina Häußge 0ba987e126 maintenance is now 1.3.11.dev 2018-11-06 12:31:53 +01:00
Gina Häußge 0325628693 staging/maintenance is now 1.3.10rc2.dev 2018-11-06 12:29:28 +01:00
Gina Häußge e14c00f135 Revert "Updated several dependencies to current version"
This reverts commit 4ed5f7e

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

We'll postpone them to 1.3.11, since OctoPrint 1.3.10 will then refuse
to upgrade in such environments anyhow.
2018-11-05 14:25:10 +01:00
Gina Häußge b0a4a49f99 Changelog for 1.3.10rc1 2018-11-05 13:18:05 +01:00
Gina Häußge 5b4839369e appkeys: Probe endpoint to check for workflow support
Also adjusted docs and js client lib accordingly.
2018-11-05 12:50:05 +01:00
Gina Häußge 1ff02b9f1c Update bundled German translation 2018-11-05 11:59:48 +01:00
Gina Häußge e2c1fa3d43 Appkeys: request creation should respond with 201 2018-11-02 17:04:58 +01:00
Gina Häußge 39a466e316 Appkeys: Make timeout thread safe 2018-11-02 12:53:30 +01:00
Gina Häußge 9e940eacc3 Merge branch 'fix_appkey_orphan_dialogs' of https://github.com/fieldOfView/OctoPrint into pr/2869 2018-11-02 12:27:16 +01:00
Gina Häußge 2e38f237de Fix cancel snippet for shared nozzle setups
See https://discourse.octoprint.org/t/prusa-mmu2-how-to-properly-configure/4937/
2018-11-02 12:20:05 +01:00
fieldOfView 7f36ffdafd Expire request_access when the client stops polling 2018-11-02 11:04:06 +01:00
Gina Häußge 39b2da3230 Merge pull request #2868 from gdombiak/extrude_speed2
Documentation fixed and extrusion speed value check
2018-11-02 10:52:42 +01:00
fieldOfView c489829efb Add myself to AUTHORS.md
because it's a requirement for a PR
2018-11-02 09:31:56 +01:00
fieldOfView e30e129e2a Close request_access dialogs on other open connections when a decision is made
Once a decision is made on one connection (browser window), dialogs on other connections are no longer relevant.
2018-11-02 09:22:30 +01:00
Gaston Dombiak 32d5b25013 Removed unnecessary variable initialization 2018-11-01 21:44:42 -07:00
Gaston Dombiak 6227a0dfb9 1) Fixed documentation about speed unit and 2) extrusion speed is now limited to printer profile max value 2018-10-31 20:45:56 -07:00
Gina Häußge e234c6146e Better detection of ipv6 support
Apparently socket.has_ipv6 doesn't actually do what it says in the docs
(state whether the underlying platform supports ipv6). It returns True
even when ipv6 has manually been disabled for whatever reason. So we
will no longer trust this but instead attempt to actually create a v6
socket and only if that succeeds assume that v6 is indeed supported on
the platform.
2018-10-31 13:39:54 +01:00
Gina Häußge c146731e5a Merge pull request #2865 from gdombiak/extrude_speed
Extrude speed
2018-10-31 11:58:28 +01:00
Gina Häußge 5ee242be4a Fix doc bug: mm/s => mm/min 2018-10-31 11:54:17 +01:00
Gaston Dombiak 556878a774 Merge branch 'maintenance' into extrude_speed 2018-10-30 19:09:05 -07:00
Gaston Dombiak 00aa4876e9 Added support to specify extrude/retract speed. Only at REST API. No UI changes were made 2018-10-30 19:01:20 -07:00
Gina Häußge 2f89082df2 Missed something in yesterday's changes to contrib guide 2018-10-19 13:14:52 +02:00
Gina Häußge 108db045ce Small changes to the contribution guidelines
* allow PRs against `maintenance` branch for improvements and small
    new features
  * suggest getting in touch on the forum for larger changes
2018-10-18 18:06:01 +02:00
193 changed files with 12389 additions and 8416 deletions

No files matched your search

@@ -1,3 +1,9 @@
---
name: Bug report
about: Create a report to help improve OctoPrint
---
<!--
READ THE FOLLOWING FIRST:
@@ -12,7 +18,7 @@ plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
discourse.octoprint.org, NOT here.
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (if you don't know
@@ -39,9 +45,10 @@ don't know what you did to get it to happen in the first place.
Ideally provide exact steps to follow in order to reproduce your problem:
-->
1. ...
2. ...
3. ...
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
<!--
If you encountered a problem with specific files of any sorts, make sure
+21
View File
@@ -0,0 +1,21 @@
---
name: Feature request
about: Suggest an idea for this project
---
<!--
Please make sure to add [Request] to your issue's title. Thank you!
-->
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+7 -7
View File
@@ -18,16 +18,16 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.9
# maintenance is currently the branch for preparation of maintenance release 1.3.11
# so are any fix/... and improve/... branches
maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.9rc5
# staging/maintenance is currently the branch for preparation of 1.3.11rc2
# so is regressionfix/...
staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
staging/maintenance 1.3.11rc2 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
regressionfix/.* 1.3.11rc2 73df8c2407f04756261acfe62ac3d72877f8a97d 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
View File
@@ -91,7 +91,14 @@ date of first contribution):
* [Ganey](https://github.com/ganey)
* [Sven Lohrmann](https://github.com/malnvenshorn)
* [Andy Castille](https://github.com/klikini)
* [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)
* [Daniel Joyce](https://github.com/DanielJoyce)
* [Andy Qua](https://github.com/AndyQ)
* [Fabio Santos](https://github.com/Fabi0San)
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
+299 -1017
View File
File diff suppressed because it is too large. Load diff
+9 -9
View File
@@ -36,14 +36,14 @@ nothing but ticket management.
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
something is **not** what qualifies as a request here, use the
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
[community forum at community.octoprint.org](https://community.octoprint.org) for
such support issues.
- If you are a **developer** that wants to brainstorm a pull request or possible
changes to the plugin system, please get in touch on the
[community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
[community forum at community.octoprint.org](https://community.octoprint.org/c/development).
- If you need **support**, have a **question** or some **other reason** that
doesn't fit any of the above categories, the issue tracker is not the right place.
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
Consult the [community forum at community.octoprint.org](https://community.octoprint.org/c/support) instead.
No matter what kind of ticket you create, never mix two or more "ticket reasons"
into one ticket: One ticket per bug, request, brainstorming thread please.
@@ -75,7 +75,7 @@ following section *completely* and also follow the instructions in the
**OctoPrint doesn't manage your network connection or your webcam nor
can it fix your printer not getting detected as a serial interface** -
if you have any kinds of problems with that, get in touch on the
[community forum](https://discourse.octoprint.org).
[community forum](https://community.octoprint.org).
**This is not the bug tracker of OctoPi**, which is the preconfigured
Raspberry Pi image including OctoPrint among other things - that one can be found
@@ -126,7 +126,7 @@ following section *completely* and also follow the instructions in the
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
very diligent here!
If in doubt about any of the above - get in touch on the [community forum](https://discourse.octoprint.org)
If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org)
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
there.
@@ -153,7 +153,7 @@ plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
discourse.octoprint.org, NOT here.
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (if you don't know
@@ -275,11 +275,11 @@ all requested information or your ticket will be closed.
### Where can I find which version and branch I'm on?
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
Please refer to [this FAQ entry](https://community.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
### Where can I find those log files you keep talking about?
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
Please refer to [this FAQ entry](https://community.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
### Where can I find my browser's error console?
@@ -302,7 +302,7 @@ the documentation.
system - maybe that's the actual PR you have been waiting for to contribute :)
2. If you plan to make **any large or otherwise disruptive changes to the
code or appearance, please get in touch on the
[forums](https://discourse.octoprint.org/c/development)** first so
[forums](https://community.octoprint.org/c/development)** first so
that we can determine if it's a good time for your specific pull
request. It might be that we're currently in the process of making
heavy changes to the code locations you'd target as well, or your
+9 -6
View File
@@ -3,7 +3,7 @@
![GitHub release](https://img.shields.io/github/release/foosel/OctoPrint.svg?colorB=brightgreen)
[![Travis build status](https://img.shields.io/travis/foosel/OctoPrint.svg)](https://travis-ci.org/foosel/OctoPrint)
[![Discourse topics](https://img.shields.io/discourse/https/discourse.octoprint.org/users.svg)](https://discourse.octoprint.org)
[![Discourse topics](https://img.shields.io/discourse/https/community.octoprint.org/users.svg)](https://community.octoprint.org)
[![IRC](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://chat.octoprint.org)
[![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d)
@@ -13,7 +13,7 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme).
The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme).
The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint).
@@ -32,7 +32,7 @@ You are currently looking at the source code repository of OctoPrint. If you alr
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
might be of more interest for you. You might also want to subscribe to join
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) where there are other active users who might be
[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be
able to help you with any questions you might have.
## Contributing
@@ -40,7 +40,7 @@ able to help you with any questions you might have.
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org)
[the community forum at community.octoprint.org](https://community.octoprint.org)
and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
If you think something is bad about OctoPrint or its documentation the way it is, please help
@@ -142,5 +142,8 @@ be edited from OctoPrint's settings dialog.
## Special Thanks
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
Cross-browser testing services are kindly provided by [BrowserStack](https://www.browserstack.com/).
Profiling is done with the help of [PyVmMonitor](https://www.pyvmmonitor.com).
Error tracking is powered and sponsored by [Sentry](https://sentry.io).
+13 -19
View File
@@ -6,58 +6,52 @@ thanks to everyone who contributed!
## Patreon Patrons
* Andre Bubel
* Andrew Moorby
* Arnljot Arntsen
* Bjorn Breckenridge
* Boris Hussein
* Brad Jackson
* Brian E. Tyler
* Christian Petropolis
* Christian Wolf
* COLLE+McVOY
* D Brian Kimmel
* DeltaMaker 3D Printers
* Dorian Gray
* E3D BigBox
* Eric Betts
* Ernesto Martinez
* F. Kunsmann
* Frank Sander
* George Robles
* günter weber
* Hydra Research LLC
* James Seigel
* Jeff Moe
* jean-claude migneault
* Jeff Renfer
* Jefferson Hunt
* Jeremiah Avery
* Joseph Payne
* Josh Daniels
* Joshua Wills
* Justin Kaufman
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kodama Inc.
* Lewis Newby
* LA 3D Printer Repair
* LulzBot®
* Makespace Madrid
* Mark Walker
* Martin Beattie
* Michael Aumock
* Miles Flavel
* mitchell hirsch
* Noe Ruiz
* Mosaic Manufacturing
* OMER MEHMET SUTAS
* Patrick McGinnis
* Prof Yuh Wen Chen
* Randy C. Will
* Robert Gusek
* Roger Strolz
* Roy Cortes
* Rudolff Vang
* Samer Najia
* Shawn Lewis
* Simon Hallam
* Stefan Krister
* Sven Mueller
* Symbiotic Devices
* Thomas Hatley
* Timothy D Hoogland
* TEVO 3D Printers
* Trent Shumay
* Ulrich Kempken
and 1351 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1509 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
-1
View File
@@ -36,7 +36,6 @@
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
* [chainmap](https://bitbucket.org/jeunice/chainmap): Python
* [Click](http://click.pocoo.org/): BSD
* [dateutil](https://dateutil.readthedocs.io/): BSD
* [emoji](https://github.com/carpedm20/emoji/): BSD
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
* [Flask](http://flask.pocoo.org/): BSD
+4
View File
@@ -11,6 +11,10 @@ Apps
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.
+1 -1
View File
@@ -59,7 +59,7 @@ Issue a connection command
Issue a connection command. Currently available command are:
connect
Instructs OctoPrint to connect to the printer. Additional parameters are:
Instructs OctoPrint to connect or, if already connected, reconnect to the printer. Additional parameters are:
* ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if
no preference is available auto detection will be attempted.
+7 -2
View File
@@ -212,7 +212,8 @@ Retrieve information about the current job
"filepos": 337942,
"printTime": 276,
"printTimeLeft": 912
}
},
"state": "Printing"
}
:statuscode 200: No error
@@ -243,4 +244,8 @@ Job information response
- 1
- :ref:`sec-api-datamodel-jobs-progress`
- Information regarding the progress of the current print job
* - ``state``
- 1
- String
- A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused",
"Cancelling", "Error" or "Offline".
+159 -4
View File
@@ -22,6 +22,11 @@ Bed
corresponding resource returns temperature information including an optional history. Note that Bed commands
are only available if the currently selected printer profile has a heated bed.
See :ref:`sec-api-printer-bedcommand`.
Chamber
Chamber commands allow setting the temperature and temperature offset for the printer's heated chamber. Querying
the corresponding resource returns temperature information including an option history. Note that Chamber commands
are only available if the currently selected printer profile has a heated chamber.
See :ref:`sec-api-printer-chambercommand`.
SD card
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
corresponding resource returns the current SD card state.
@@ -219,7 +224,7 @@ Issue a print head command
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
interpreted as an integer signifying the speed in mm/s, to append to the command.
interpreted as an integer signifying the speed in mm/min, to append to the command.
home
Homes the print head in all of the given axes. Additional parameters are:
@@ -362,6 +367,8 @@ Issue a tool command
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command.
flowrate
Changes the flow rate factor to apply to extrusion of the tool.
@@ -621,12 +628,12 @@ Issue a bed command
are:
target
Sets the given target temperature on the printer's tools. Additional parameters:
Sets the given target temperature on the printer's bed. Additional parameters:
* ``target``: Target temperature to set.
offset
Sets the given temperature offset on the printer's tools. Additional parameters:
Sets the given temperature offset on the printer's bed. Additional parameters:
* ``offset``: Offset to set.
@@ -708,7 +715,7 @@ Retrieve the current bed state
an :http:statuscode:`409`.
.. note::
If you want both tool and bed temperature information at the same time, take a look at
If you want tool, bed and chamber temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
**Example**
@@ -758,6 +765,154 @@ Retrieve the current bed state
:statuscode 409: If the printer is not operational or the selected printer profile
does not have a heated bed.
.. _sec-api-printer-chambercommand:
Issue a chamber command
=======================
.. http:post:: /api/printer/bed
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
are:
target
Sets the given target temperature on the printer's chamber. Additional parameters:
* ``target``: Target temperature to set.
offset
Sets the given temperature offset on the printer's chamber. Additional parameters:
* ``offset``: Offset to set.
All of these commands may only be sent if the printer is currently operational. Otherwise a :http:statuscode:`409`
is returned.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
If no heated chambed is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires user rights.
**Example Target Temperature Request**
Set the target temperature for the printer's heated chamber to 50°C.
.. sourcecode:: http
POST /api/printer/chamber HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "target",
"target": 50
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example Offset Temperature Request**
Set the temperature offset for the heated chamber to -5°C.
.. sourcecode:: http
POST /api/printer/chamber HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "offset",
"offset": -5
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``target`` or ``offset``.
:json object target: ``target`` command: The target temperature to set.
:json object offset: ``offset`` command: The offset temperature to set.
:statuscode 204: No error
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
request is otherwise invalid.
:statuscode 409: If the printer is not operational or the selected printer profile
does not have a heated chamber.
.. _sec-api-printer-chamberstate:
Retrieve the current chamber state
==================================
.. http:get:: /api/printer/chamber
Retrieves the current temperature data (actual, target and offset) plus optionally a (limited) history (actual, target,
timestamp) for the printer's heated chamber.
It's also possible to retrieve the temperature history by supplying the ``history`` query parameter set to ``true``. The
amount of returned history data points can be limited using the ``limit`` query parameter.
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
.. note::
If you want tool, bed and chamber temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
**Example**
Query the chamber temperature data and also include the temperature history but limit it to two entries.
.. sourcecode:: http
GET /api/printer/chamber?history=true&limit=2 HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"chamber": {
"actual": 50.221,
"target": 70.0,
"offset": 5
},
"history": [
{
"time": 1395651928,
"chamber": {
"actual": 50.221,
"target": 70.0
}
},
{
"time": 1395651926,
"chamber": {
"actual": 49.1123,
"target": 70.0
}
}
]
}
:query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response
too. If no ``limit`` parameter is given, all available temperature history data will be returned.
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
will be returned. Will be ignored if ``history`` is not enabled.
:statuscode 200: No error
:statuscode 409: If the printer is not operational or the selected printer profile
does not have a heated chamber.
.. _sec-api-printer-sdcommand:
Issue an SD command
+9
View File
@@ -52,6 +52,7 @@ Retrieve all printer profiles
"height": 200
},
"heatedBed": true,
"heatedChamber": false,
"axes": {
"x": {
"speed": 6000,
@@ -93,6 +94,7 @@ Retrieve all printer profiles
"height": 200
},
"heatedBed": true,
"heatedChamber": true,
"axes": {
"x": {
"speed": 6000,
@@ -184,6 +186,7 @@ Add a new printer profile
"height": 200
},
"heatedBed": true,
"heatedChamber": false,
"axes": {
"x": {
"speed": 6000,
@@ -267,6 +270,7 @@ Add a new printer profile
"height": 300
},
"heatedBed": false,
"heatedChamber": false,
"axes": {
"x": {
"speed": 6000,
@@ -352,6 +356,7 @@ Update an existing printer profile
"height": 200
},
"heatedBed": true,
"heatedChamber": false,
"axes": {
"x": {
"speed": 6000,
@@ -578,6 +583,10 @@ Profile
- 0..1
- ``boolean``
- Whether the printer has a heated bed (``true``) or not (``false``)
* - ``heatedChamber``
- 0..1
- ``boolean``
- Whether the printer has a heated chamber (``true``) or not (``false``)
* - ``axes``
- 0..1
- Object
+4 -4
View File
@@ -274,10 +274,10 @@ Fetch template data
"plugin_name": "Action Command Prompt Support"
},
{
"id": "plugin_cura",
"name": "CuraEngine (<= 15.04)",
"plugin_id": "cura",
"plugin_name": "CuraEngine (<= 15.04)"
"id": "plugin_curalegacy",
"name": "Cura Legacy",
"plugin_id": "curalegacy",
"plugin_name": "Cura Legacy"
}
],
"sidebar": [
+14 -14
View File
@@ -42,22 +42,22 @@ List All Slicers and Slicing Profiles
Content-Type: application/json
{
"cura": {
"key": "cura",
"displayName": "CuraEngine",
"curalegacy": {
"key": "curalegacy",
"displayName": "Cura Legacy",
"default": true,
"profiles": {
"high_quality": {
"key": "high_quality",
"displayName": "High Quality",
"default": false,
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
"resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality"
},
"medium_quality": {
"key": "medium_quality",
"displayName": "Medium Quality",
"default": true,
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
"resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality"
}
}
}
@@ -81,7 +81,7 @@ List Slicing Profiles of a Specific Slicer
.. sourcecode:: http
GET /api/slicing/cura/profiles HTTP/1.1
GET /api/slicing/curalegacy/profiles HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
@@ -95,13 +95,13 @@ List Slicing Profiles of a Specific Slicer
"key": "high_quality",
"displayName": "High Quality",
"default": false,
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
"resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality"
},
"medium_quality": {
"key": "medium_quality",
"displayName": "Medium Quality",
"default": true,
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
"resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality"
}
}
@@ -125,7 +125,7 @@ Retrieve Specific Profile
.. sourcecode:: http
GET /api/slicing/cura/profiles/quick_test HTTP/1.1
GET /api/slicing/curalegacy/profiles/quick_test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
@@ -137,7 +137,7 @@ Retrieve Specific Profile
{
"displayName": "Just a test",
"description": "This is just a test",
"resource": "http://example.com/api/slicing/cura/profiles/quick_test",
"resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test",
"data": {
"bottom_layer_speed": 20.0,
"bottom_thickness": 0.3,
@@ -174,14 +174,14 @@ Add Slicing Profile
.. sourcecode:: http
PUT /api/slicing/cura/profiles/quick_test HTTP/1.1
PUT /api/slicing/curalegacy/profiles/quick_test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: application/json
{
"displayName": "Just a test",
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
"description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count",
"data": {
"layer_height": 0.2,
"skirt_line_count": 3
@@ -197,8 +197,8 @@ Add Slicing Profile
{
"displayName": "Just a test",
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
"resource": "http://example.com/api/slicing/cura/profiles/quick_test"
"description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count",
"resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test"
}
:param slicer: The identifying key of the slicer for which to add the profile
+4 -2
View File
@@ -7,7 +7,8 @@ Version information
.. http:get:: /api/version
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
the API version, ``server`` containing the server version.
the API version, ``server`` containing the server version, ``text`` containing the server version including
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
**Example Request**
@@ -26,7 +27,8 @@ Version information
{
"api": "0.1",
"server": "1.1.0"
"server": "1.3.10",
"text": "OctoPrint 1.3.10"
}
:statuscode 200: No error
+57 -25
View File
@@ -40,15 +40,18 @@ of the following steps:
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
enters their username which is also their user ID into the App.
2. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
authorization process.
3. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
4. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
signals that no decision has been made yet.
5. The User either accepts or denies the access request which makes the Webinterface send a
6. The User either accepts or denies the access request which makes the Webinterface send a
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
6. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
an HTTP :http:statuscode:`404`.
@@ -61,31 +64,35 @@ of the following steps:
participant Webinterface
participant Server
note over User, Server: Step 1 & 2
note over User, Server: Step 1, 2 & 3
User->>App: enters URL of instance to connect to
User->>App: enters URL of instance to connect to and optional user_id
App->>Server: GET /plugin/appkeys/probe
alt Workflow unsupported
Server->>App: 404
App->>User: alternative workflow, copy-paste key manually
else Workflow supported
alt Limit to specific user
User->>App: enters user_id
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
else
App->>Server: POST /plugin/appkeys/request, (app_name)
end
note over User, Server: Step 3
note over User, Server: Step 4
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
Webinterface-->>User: Display confirmation dialog
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
note over User, Server: Step 4
note over User, Server: Step 5
loop
loop Poll for decision
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 202
end
note over User, Server: Step 5 & 6
note over User, Server: Step 6 & 7
alt User accepts
@@ -105,11 +112,27 @@ of the following steps:
end
end
.. _sec-bundledplugins-appkeys-api:
API
---
.. _sec-bundledplugins-appkeys-api-probe:
Probe for workflow support
..........................
.. http:get:: /plugin/appkeys/probe
Probes for support of the workflow.
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
:status 204: the workflow is supported
.. _sec-bundledplugins-appkeys-api-startauthprocess:
Start authorization process
@@ -131,12 +154,6 @@ Start authorization process
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
is logged in on.
.. note::
If this endpoint produces an HTTP :http:statuscode:`404` and the instance URL is correct, the bundled
Application Keys Plugin has in all likelihood been disabled by the user. Fall back on manual API key copy-pasting
by the user.
:json app: application identifier to use for the request, case insensitive
:json user: optional user id to restrict the decision to the specified user
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
@@ -154,6 +171,11 @@ Poll for decision on existing request
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
HTTP :http:statuscode:`404` if the request has been denied or timed out.
.. note::
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
for more than 5s.
:status 200: access granted, API key in response body
:status 202: no decision has been made yet, continue polling
:status 404: access denied or request timed out
@@ -452,6 +474,15 @@ JavaScript Client Library
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
Probes for workflow support.
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
Starts a new authorization request for the provided ``app`` identifier.
@@ -481,9 +512,10 @@ JavaScript Client Library
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
Convenience function that issues a request and then automatically starts polling for a decision on the returned
polling endpoint every 1s, until either a positive or negative decision is returned. On success the returned
promise is resolved with the generated API key as argument.
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
for the workflow, the promise is rejected.
**Example usage**
-130
View File
@@ -1,130 +0,0 @@
.. _sec-bundledplugins-cura:
Cura
====
The Cura Plugin allows slicing of STL files uploaded to OctoPrint directly via
the `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_ **up to and
including version 15.04.x** and supersedes the slicing support integrated into
OctoPrint so far. It comes bundled with OctoPrint starting with version 1.2.0.
.. note::
Versions of CuraEngine later than 15.04.x have changed their calling
parameters in such a way that the current implementation of OctoPrint's Cura plugin
is not compatible to it. For this reason, please use only CuraEngine versions up to
and including 15.04 for now, as available in the ``legacy`` branch of the CuraEngine
repository on Github.
The plugin offers a settings module that allows configuring the path to the
CuraEngine executable to use, as well as importing and managing slicing
profiles to be used. Please note that the Cura Plugin will use the printer
parameters you configured within OctoPrint (meaning bed size and extruder
count and offsets) for slicing.
.. _sec-bundledplugins-cura-firststeps:
First Steps
-----------
Before you can slice from within OctoPrint, you'll need to
#. :ref:`Install CuraEngine <sec-bundledplugins-cura-installing>`
#. :ref:`Configure the path to CuraEngine within OctoPrint <sec-bundledplugins-cura-configuring>`
#. :ref:`Export a slicing profile from Cura and import it within OctoPrint <sec-bundledplugins-cura-profiles>`
.. note::
OctoPi 0.12.0 and later ships with steps 1 and 2 already done, you only need to
supply one or more slicing profiles to get going :)
.. _sec-bundledplugins-cura-installing:
Installing CuraEngine
---------------------
You'll need a build of ``legacy`` branch of `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_
in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch
`here <https://github.com/ultimaker/curaengine/tree/legacy>`__.
If you previously used the `old variant of the Cura integration <https://github.com/foosel/OctoPrint/wiki/Cura-Integration>`_,
you probably still have a fully functional binary lying around in the
installation folder of the full install of Cura you used then -- just put the
path to that in the plugin settings.
.. _sec-bundledplugins-cura-installing-raspbian:
Compiling for Raspbian
++++++++++++++++++++++
Raspbian Jessie and later
~~~~~~~~~~~~~~~~~~~~~~~~~
Building on Raspbian Jessie and later is as easy as::
sudo apt-get -y install gcc-4.7 g++-4.7
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
cd CuraEngine
make
After this has completed, you'll find your shiny new build of CuraEngine in
the `build` folder (full path for above example:
``~/CuraEngine/build/CuraEngine``).
Raspbian Wheezy
~~~~~~~~~~~~~~~
You'll need to install a new version of gcc and g++ and patch CuraEngine's
Makefile (see `this post <http://umforum.ultimaker.com/index.php?/topic/5943-recent-build-of-curaengine-wont-compile-on-raspberry-pi/#entry58539>`_)
in order for the compilation to work on current Raspbian builds (e.g. OctoPi)::
sudo apt-get -y install gcc-4.7 g++-4.7
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
cd CuraEngine
wget http://bit.ly/curaengine_makefile_patch -O CuraEngine.patch
patch < CuraEngine.patch
make CXX=g++-4.7
After this has completed, you'll find your shiny new build of CuraEngine in
the `build` folder (full path for above example:
``~/CuraEngine/build/CuraEngine``).
.. _sec-bundledplugins-cura-configuring:
Configuring the plugin
----------------------
The Cura plugin needs to be configured with the full path to your copy of the
CuraEngine executable that it's supposed to use. You can do this either via
the Cura plugin settings dialog or by manually configuring the path to the
executable via ``config.yaml``, example:
.. code-block:: yaml
plugins:
cura:
cura_engine: /path/to/CuraEngine
.. _sec-bundledplugins-cura-profiles:
Using Cura Profiles
-------------------
The Cura Plugin supports importing your existing profiles for Cura **up to and
including Cura 15.04.x**. Newer Cura releases (e.g. 15.06 or 2.x) use a different
internal format that will *not* work with the current version of the Cura Plugin.
You can find downloads of Cura 15.04.x for Windows, Mac and Linux `on Ultimaker's download page <https://ultimaker.com/en/products/cura-software/list>`_.
In order to export a slicing profile from the Cura desktop UI, open it,
set up your profile, then click on "File" and there on "Save Profile". You can
import the .ini-file this creates via the "Import Profile" button in the
Cura Settings within OctoPrint.
.. _sec-bundledplugins-cura-sourcecode:
Source code
-----------
The source of the Cura plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/cura``.
+40
View File
@@ -0,0 +1,40 @@
.. _sec-bundledplugins-errortracking:
Error Tracking Plugin
=====================
The Error Tracking plugin will cause any logged exceptions in the server and the browser interface to be sent to
OctoPrint's `Sentry instance <https://sentry.io/>`_.
By enabling it you help to gather detailed information on the cause of bugs or other issues. This is especially
valuable on release candidates, which is why this plugin will also prompt you to enable error tracking if it detects
that you are subscribed to an RC release channel.
By default, even when enabled it will only be active if you are running a released OctoPrint version, so either a stable
release or a release candidate.
The Error Tracking plugin is using a Sentry instance kindly provided by `sentry.io <https://sentry.io/>`_. For information on their service
please refer to their `Security & Compliance documentation <https://sentry.io/security/>`_
and their `Privacy Policy <https://sentry.io/privacy/>`_.
The Error Tracking plugin has been bundled with OctoPrint since version 1.3.11.
.. _sec-bundledplugins-errortracking-configuration:
Configuring the plugin
----------------------
The plugin supports the following configuration keys:
* ``enabled``: Whether to enable error tracking. Defaults to ``false``.
* ``enabled_unreleased``: Whether to also enable tracking on unreleased OctoPrint versions (anything not stable releases
or release candidates). Defaults to ``false``.
* ``unique_id``: Unique instance identifier, auto generated on first activation
.. _sec-bundledplugins-errortracking-sourcecode:
Source Code
-----------
The source of the Error Tracking plugin is bundled with OctoPrint and can be
found in its source repository under ``src/octoprint/plugins/errortracking``.
+2 -1
View File
@@ -9,10 +9,11 @@ Bundled Plugins
action_command_prompt.rst
announcements.rst
tracking.rst
appkeys.rst
backup.rst
cura.rst
discovery.rst
errortracking.rst
forcelogin.rst
logging.rst
pluginmanager.rst
+39
View File
@@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
- hidden
- plugins
.. _sec-bundledplugins-pluginmanager-events:
Events
------
plugin_pluginmanager_install_plugin
A plugin was installed.
Payload:
* ``id``: the identifier of the installed plugin
* ``version``: the version of the installed plugin
* ``source``: source from which the plugin was installed, can be an URL or a path in the local file system
* ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path``
plugin_pluginmanager_uninstall_plugin
A plugin was uninstalled.
Payload:
* ``id``: the identifier of the uninstalled plugin
* ``version``: the version of the uninstalled plugin
plugin_pluginmanager_enable_plugin
A plugin was enabled.
Payload:
* ``id``: the identifier of the enabled plugin
* ``version``: the version of the enabled plugin
plugin_pluginmanager_disabled_plugin
A plugin was disabled.
Payload:
* ``id``: the identifier of the disabled plugin
* ``version``: the version of the disabled plugin
.. _sec-bundledplugins-pluginmanager-hooks:
Hooks
@@ -29,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl
unexpectedly and with `catastrophic <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
.. _sec-bundledplugins-printer_safety_check-events:
Events
------
warning
A printer safety warning was triggered.
Payload:
* ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``)
* ``check_name``: name of check that was triggered (e.g. ``aneta8``)
* ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``)
.. _sec-bundledplugins-printer_safety_check-source:
Source Code
+23
View File
@@ -325,6 +325,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing
branch: devel
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
.. _sec-bundledplugins-softwareupdate-events:
Events
------
plugin_softwareupdate_update_succeeded
An update succeeded.
Payload:
* ``target``: update target
* ``from_version``: version from which was updated
* ``to_version``: version to which was updated
plugin_softwareupdate_update_failed
An update failed.
Payload:
* ``target``: update target
* ``from_version``: version from which was updated
* ``to_version``: version to which was updated
.. _sec-bundledplugins-softwareupdate-hooks:
Hooks
+45
View File
@@ -0,0 +1,45 @@
.. _sec-bundledplugins-tracking:
Anonymous Usage Tracking Plugin
===============================
The Anonymous Usage Tracking plugin provides valuable insights into how many instances running what versions of
OctoPrint are out there, whether they are successfully completing print jobs and various other metrics.
By enabling it you help to identify problems with new releases and release candidates early on, and to better tailor
OctoPrint's future development to actual use.
For details on what gets tracked, please refer to `tracking.octoprint.org <https://tracking.octoprint.org>`_
and also the `Privacy Policy at tracking.octoprint.org <https://tracking.octoprint.org/privacy>`_.
The Anonymous Usage Tracking plugin has been bundled with OctoPrint since version 1.3.10.
.. _sec-bundledplugins-tracking-configuration:
Configuring the plugin
----------------------
The plugin supports the following configuration keys:
* ``enabled``: Whether to enable usage tracking. Defaults to ``false``.
* ``unique_id``: Unique instance identifier, auto generated on first activation
* ``server``: The tracking server to track against. Defaults to a tracking endpoint on ``https://tracking.octoprint.org``.
* ``ping``: How often to send a ``ping`` tracking event, in seconds. Defaults to a 15min interval.
* ``events``: Granular configuration of enabled tracking events. All default to ``true``.
* ``startup``: Whether to track startup/shutdown events
* ``printjob``: Whether to track print job related events (start, completion, cancel, ...)
* ``commerror``: Whether to track communication errors with the printer
* ``plugin``: Whether to track plugin related events (install, uninstall, ...)
* ``update``: Whether to track update related events (update successful or not, ...)
* ``printer``: Whether to track printer related events (connected, firmware, ...)
* ``printer_safety_check``: Whether to track warnings of the :ref:`Printer Safety Check <sec-bundledplugins-printer_safety_check>`
* ``throttled``: Whether to track throttle events detected on the underlying system
.. _sec-bundledplugins-tracking-sourcecode:
Source Code
-----------
The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be
found in its source repository under ``src/octoprint/plugins/tracking``.
+33 -4
View File
@@ -81,7 +81,8 @@ Settings for the REST API:
# Whether to allow cross origin access to the API or not
allowCrossOrigin: false
# Additional app api keys, see REST API > Apps in the docs
# Additional app api keys, see REST API > Apps in the docs.
# Deprecated since 1.3.11, to be removed in 1.4.0!
apps:
"some.app.identifier:some_version":
pubkey: <RSA pubkey>
@@ -322,6 +323,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# Whether the simulated printer should also simulate a heated bed or not
hasBed: true
# Whether the simulated printer should also simulate a heated chamber or not
hasChamber: false
# If enabled, reports the set target temperatures as separate messages from the firmware
#
# True: > M109 S220.0
@@ -562,6 +566,9 @@ Use the following settings to enable or disable OctoPrint features:
- M117
- M118
# whether G90/G91 also influence absolute/relative mode of extruders
g90InfluencesExtruder: false
.. _sec-configuration-config_yaml-folder:
Folder
@@ -806,6 +813,19 @@ Use the following settings to configure the serial connection to the printer:
additionalBaudrates:
- 123456
# Commands which should not be sent to the printer, e.g. because they are known to block serial
# communication until physical interaction with the printer as is the case on most firmwares with
# the default M0 and M1.
blockedCommands:
- M0
- M1
# Commands which should cause OctoPrint to pause any ongoing prints.
pausingCommands:
- M0
- M1
- M25
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
# homing, dwelling, auto leveling etc. Defaults to the below commands.
longRunningCommands:
@@ -1058,6 +1078,15 @@ Use the following settings to configure the server:
# How many days to leave unused entries in the preemptive cache config
until: 7
# Configuration of the client IP check to warn about connections from external networks
ipCheck:
# whether to enable the check, defaults to true
enabled: true
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
trustedSubnets: []
.. note::
@@ -1087,14 +1116,14 @@ Settings for the built-in slicing support:
slicing:
# Whether to enable slicing support or not
enabled:
enabled: true
# Default slicer to use
defaultSlicer: cura
defaultSlicer: null
# Default slicing profiles per slicer
defaultProfiles:
cura: ...
curalegacy: ...
.. _sec-configuration-config_yaml-system:
+2 -2
View File
@@ -39,8 +39,8 @@ A list of important components for which an increase in logging might be interes
* ``octoprint.filemanager``: the file management layer
* ``octoprint.plugin``: the plugin sub system
* ``octoprint.plugins.<plugin>``: the plugin ``<plugin>``, e.g. ``octoprint.plugins.discovery`` to change the log level of
the `Discovery plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_ or ``octoprint.plugins.cura``
to change the log level of the `Cura plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_.
the :ref:`Discovery plugin <sec-bundledplugins-discovery>` or ``octoprint.plugins.backup``
to change the log level of the :ref:`Backup plugin <sec-bundledplugins-backup>`.
* ``octoprint.slicing``: the slicing sub system
This list will be expanded when deemed necessary.
+68 -49
View File
@@ -6,15 +6,6 @@ Events
.. contents::
.. note::
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
to indicate what to do with the command contained.
.. _sec-events-configuration:
Configuration
@@ -85,6 +76,12 @@ and its origin via the placeholder ``{origin}``.
Available Events
================
.. note::
Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook <sec-plugins-hook-events-register_custom_events>`.
.. _sec-events-available_events-server:
Server
------
@@ -118,6 +115,8 @@ ConnectivityChanged
* ``old``: Old connectivity value (true for online, false for offline)
* ``new``: New connectivity value (true for online, false for offline)
.. _sec-events-available_events-printer_commmunication:
Printer communication
---------------------
@@ -141,7 +140,8 @@ Disconnected
The server has disconnected from the printer
Error
An error has occurred in the printer communication.
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
on the connection.
Payload:
@@ -156,6 +156,8 @@ PrinterStateChanged
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
* ``state_string``: Text representation of the new state.
.. _sec-events-available_events-file_handling:
File handling
-------------
@@ -169,9 +171,7 @@ Upload
.. deprecated:: 1.3.0
* ``file``: the file's path within its storage location
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
FileAdded
A file has been added to a storage.
@@ -253,9 +253,7 @@ MetadataAnalysisStarted
.. deprecated:: 1.3.0
* ``file``: the file's path within its storage location
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
MetadataAnalysisFinished
The metadata analysis of a file has finished.
@@ -269,9 +267,7 @@ MetadataAnalysisFinished
.. deprecated:: 1.3.0
* ``file``: the file's path within its storage location
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
FileSelected
A file has been selected for printing.
@@ -284,10 +280,8 @@ FileSelected
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
FileDeselected
No file is selected any more for printing.
@@ -311,6 +305,8 @@ TransferDone
* ``local``: the file's name as stored locally
* ``remote``: the file's name as stored on SD
.. _sec-events-available_events-printing:
Printing
--------
@@ -322,13 +318,14 @@ PrintStarted
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who started the print job (if available)
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintFailed
A print failed.
@@ -338,13 +335,15 @@ PrintFailed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the elapsed time of the print when it failed, in seconds (float)
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintDone
A print completed successfully.
@@ -354,14 +353,14 @@ PrintDone
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the time needed for the print, in seconds (float)
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintCancelling
The print is about to be cancelled.
@@ -371,6 +370,9 @@ PrintCancelling
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who cancelled the print job (if available)
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
PrintCancelled
@@ -381,7 +383,12 @@ PrintCancelled
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of cancelling, if available
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the elapsed time of the print when it was cancelled, in seconds (float)
* ``user``: the user who cancelled the print job (if available)
* ``position``: the print head position at the time of cancelling (if available, not available if recording of the
position on cancel is disabled)
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
@@ -395,10 +402,8 @@ PrintCancelled
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintPaused
The print has been paused.
@@ -408,7 +413,11 @@ PrintPaused
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of pausing, if available
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who paused the print job (if available)
* ``position``: the print head position at the time of pausing (if available, not available if the recording of
the position on pause is disabled or the pause is completely handled by the printer's firmware)
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
@@ -422,10 +431,8 @@ PrintPaused
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintResumed
The print has been resumed.
@@ -435,13 +442,16 @@ PrintResumed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who resumed the print job (if available)
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
.. _sec-events-available_events-gcode_processing:
GCODE processing
----------------
@@ -504,6 +514,8 @@ ToolChange
* ``old``: old tool index
* ``new``: new tool index
.. _sec-events-available_events-timelapses:
Timelapses
----------
@@ -558,6 +570,8 @@ MovieFailed
returned a non-0 return code, ``no_frames`` if no frames were captured that could be rendered
to a timelapse, or ``unknown`` for any other reason of failure to render.
.. _sec-events-available_events-slicing:
Slicing
-------
@@ -629,8 +643,13 @@ SlicingProfileDeleted
* ``slicer``: the slicer for which the profile was deleted
* ``profile``: the profile that was deleted
.. _sec-events-available_events-settings:
Settings
--------
SettingsUpdated
The internal settings were updated.
The settings were updated via the REST API.
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
+4
View File
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
.. code-block:: jinja
:caption: Default ``disable_hotends`` snippet
{% if printer_profile.extruder.sharedNozzle %}
M104 T0 S0
{% else %}
{% for tool in range(printer_profile.extruder.count) %}
M104 T{{ tool }} S0
{% endfor %}
{% endif %}
The ``disable_bed`` snippet is defined as follows:
+2 -2
View File
@@ -11,7 +11,7 @@ and released under the `GNU Affero General Public License V3 <http://www.gnu.org
Its website can be found at `octoprint.org <https://octoprint.org/>`_.
The community forum is available at `discourse.octoprint.org <https://discourse.octoprint.org/>`_.
The community forum is available at `community.octoprint.org <https://community.octoprint.org/>`_.
The FAQ can be accessed by following `faq.octoprint.org <https://faq.octoprint.org/>`_.
@@ -23,7 +23,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!
.. note::
This documentation currently focuses primarily on developers and less on end users. If you are interested in
helping to change this, please get in touch `on the forum <https://discourse.octoprint.org/>`_!
helping to change this, please get in touch `on the forum <https://community.octoprint.org/>`_!
Contents
========
+58
View File
@@ -210,6 +210,64 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.printer.getChamberState(data, opts)
Retrieves the current printer chamber state/temperature information, and optionally also the temperature
history.
The ``flags`` object can be used to specify the data to retrieve further via the following
properties:
* ``history``: a boolean value to specify whether the temperature history should be included (``true``)
or not (``false``), defaults to it not being included
* ``limit``: an integer value to specify how many history entries to include
See :ref:`Retrieve the current bed state <sec-api-printer-chamberstate>` for more details.
:param object flags: Flags that further specify which data to retrieve, see above for details
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.printer.setChamberTargetTemperature(target, opts)
Sets the given temperature on the printer's heated chamber (if available).
``target`` is expected to be the target temperature as a float value.
**Example:**
Set the chamber to 50°C.
.. code-block:: javascript
OctoPrint.printer.setChamberTargetTemperature(50.0);
See the ``target`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
:param float target: The target to set
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.printer.setChamberTemperatureOffset(offset, opts)
Sets the given temperature offset for the printer's heated chamber (if available).
``offset`` is expected to be the temperature offset to set.
**Example:**
Set the offset for the chamber to -5°C.
.. code-block:: javascript
OctoPrint.printer.setChamberTemperatureOffset(-5);
See the ``offset`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
:param object offsets: The offsets to set
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.printer.jog(amounts, opts)
Jogs the specified axes by the specified ``amounts``.
+6
View File
@@ -6,4 +6,10 @@ octoprint.util
.. automodule:: octoprint.util
:members:
.. _sec-modules-util-commandline:
octoprint.util.commandline
--------------------------
.. automodule:: octoprint.util.commandline
:members:
+145 -6
View File
@@ -208,6 +208,10 @@ 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.
@@ -380,10 +384,10 @@ octoprint.cli.commands
OctoPrint's CLI.
:rtype: list
.. _sec-plugins-hook-comm-firmware-info:
.. _sec-plugins-hook-comm-protocol-firmware-info:
octoprint.comm.firmware.info
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
octoprint.comm.protocol.firmware.info
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs)
@@ -413,10 +417,10 @@ octoprint.comm.firmware.info
:param str firmware_name: The name of the parsed capability
:param dict firmware_data: All data contained in the ``M115`` report
.. _sec-plugins-hook-comm-firmware-capabilities:
.. _sec-plugins-hook-comm-protocol-firmware-capabilities:
octoprint.comm.firmware.capabilities
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
octoprint.comm.firmware.protocol.capabilities
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs)
@@ -903,6 +907,34 @@ octoprint.comm.transport.serial.factory
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
optionally ``baudrate`` and ``timeout`` attributes as described above.
.. _sec-plugins-hook-events-register_custom_events:
octoprint.events.register_custom_events
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: register_custom_events_hook(*args, **kwargs)
Return a list of custom :ref:`events <sec-events>` to register in the system for your plugin.
Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object
will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_<IDENTIFIER>``. Their
value will be prefixed with ``plugin_<identifier>_``.
Example:
Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events
in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event``
and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``.
.. code-block:: python
:linenos:
def register_custom_events(*args, **kwargs):
return ["my_custom_event", "my_other_custom_event"]
:return: A list of custom events to register
:rtype: list
.. _sec-plugins-hook-filemanager-analysis-factory:
octoprint.filemanager.analysis.factory
@@ -1089,6 +1121,91 @@ octoprint.printer.estimation.factory
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
:rtype: class or function
.. _sec-plugins-hook-octoprint-printer-sdcardupload:
octoprint.printer.sdcardupload
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs)
Via this hook plugins can change the way files are being uploaded to the sd card of the printer.
Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback``
or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not.
The ``start_callback`` has the following signature:
.. code-block:: python
def start_callback(local_filename, remote_filename):
# ...
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
to be created on the ``sdcard`` storage.
``success_callback`` and ``failure_callback`` both have the following signature:
.. code-block:: python
def success_or_failure_callback(local_filename, remote_filename, elapsed):
# ...
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds.
If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard``
storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to
handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation
will be called.
**Example**
The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file
is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its
own thread, which is important in order to not block the main application!
.. code-block:: python
import threading
import logging
import time
def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs):
logger = logging.getLogger(__name__)
remote_name = printer._get_free_remote_name(filename)
logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name))
sd_upload_started(filename, remote_name)
def process():
logger.info("Sleeping 10s...")
time.sleep(10)
logger.info("And done!")
sd_upload_succeeded(filename, remote_name, 10)
thread = threading.Thread(target=process)
thread.daemon = True
thread.start()
return remote_name
__plugin_name__ = "No-op SDCard Upload Test"
__plugin_hooks__ = {
"octoprint.printer.sdcardupload": nop_upload_to_sd
}
.. versionadded:: 1.3.11
:param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from
:param str filename: filename on the ``local`` storage
:param str path: path of the file in the local file system
:param function sd_upload_started: callback for when the upload started
:param function sd_upload_success: callback for successful finish of upload
:param function sd_upload_failure: callback for failure of upload
:return: the name of the file on the ``sdcard`` storage or ``None``
:rtype: string or ``None``
.. _sec-plugins-hook-server-http-after_request:
octoprint.server.api.after_request
@@ -1211,6 +1328,14 @@ octoprint.server.http.routes
view of the blueprint will thus not be reachable since processing of the request will directly be handed over
to your defined handler class.
.. important::
If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_
needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of
:class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`,
:class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler`
already implement this mixin.
.. important::
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
@@ -1238,6 +1363,20 @@ octoprint.server.http.routes
:return: a list of 3-tuples with additional routes as defined above
:rtype: list
.. _sec-plugins-hook-server-sockjs-authed:
octoprint.server.sockjs.authed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
.. _sec-plugins-hook-server-sockjs-register:
octoprint.server.sockjs.register
+44 -9
View File
@@ -68,11 +68,14 @@ calls are done is as follows:
* Plugins with a return value that is not ``None`` for :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`
for the provided sorting context will be ordered among each other first. If the returned order number is equal for
two or more implementations, the plugin's identifier will be the next sorting criteria.
* After that follow plugins which returned ``None`` (the default). They are sorted by their identifier.
two or more implementations, they will be sorted first by whether they come bundled with OctoPrint or not, then by
their identifier.
* After that follow plugins which returned ``None`` (the default). They are first sorted by whether they come bundled
with OctoPrint or not, then by their identifier.
Example: Consider three plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
``plugin_a``, ``plugin_b`` and ``plugin_c``. ``plugin_a`` doesn't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
Example: Consider four plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
``plugin_a``, ``plugin_b``, ``plugin_c`` and ``plugin_d``, the latter coming bundled with OctoPrint. ``plugin_a``
and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise:
.. code-block:: python
@@ -99,7 +102,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
class PluginB(octoprint.plugin.StartupPlugin):
def get_sorting_key(context):
def get_sorting_key(self, context):
if context == "StartupPlugin.on_startup":
return 1
return None
@@ -120,7 +123,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
class PluginC(octoprint.plugin.StartupPlugin):
def get_sorting_key(context):
def get_sorting_key(self, context):
if context == "StartupPlugin.on_startup":
return 1
return None
@@ -134,13 +137,45 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
__plugin_implementation__ = PluginC()
.. code-block:: python
:linenos:
:caption: plugin_d.py
# in this example this is bundled with OctoPrint
import octoprint.plugin
class PluginD(octoprint.plugin.StartupPlugin):
def on_startup(self, *args, **kwargs):
self._logger.info("PluginD starting up")
def on_after_startup(self, *args, **kwargs):
self._logger.info("PluginD started up")
__plugin_implementation__ = PluginD()
OctoPrint will detect that ``plugin_b`` and ``plugin_c`` define a order number, and since it's identical for both (``1``)
will order both plugins based on their plugin identifier. ``plugin_a`` doesn't define a sort key and hence will be
put after the other two. The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_a``.
will order both plugins based first on their bundling status and then on their plugin identifier.
``plugin_a`` and ``plugin_d`` don't define a sort key and hence will be
put after the other two, with ``plugin_d`` coming *before* ``plugin_a`` since it comes bundled with OctoPrint.
The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_d``, ``plugin_a``.
Now, the execution order of the ``on_after_startup`` method will be determined based on another sorting context,
``StartupPlugin.on_after_startup`` for which all of the plugins return ``None``. Hence, the execution order of the
``on_after_startup`` method will be purely ordered by plugin identifier, ``plugin_a``, ``plugin_b``, ``plugin_c``.
``on_after_startup`` method will be ordered first by bundle status, then by plugin identifier: ``plugin_d``, ``plugin_a``, ``plugin_b``, ``plugin_c``.
This will result in the following messages to be generated:
.. code-block:: plain
Plugin B starting up
Plugin C starting up
Plugin D starting up
Plugin A starting up
Plugin D started up
Plugin A started up
Plugin B started up
Plugin C started up
.. _sec-plugins-mixins-injectedproperties:
+17
View File
@@ -0,0 +1,17 @@
# init/systemd files for OctoPrint.
Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different
setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly.
## init
```
octoprint.default => /etc/default/octoprint
octoprint.init => /etc/init.d/octoprint
```
## systemd
```
octoprint.service => /etc/systemd/service/octoprint.service
```
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=The snappy web interface for your 3D printer
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=pi
ExecStart=/home/pi/OctoPrint/venv/bin/octoprint
[Install]
WantedBy=multi-user.target
+26 -23
View File
@@ -13,52 +13,55 @@ import octoprint_setuptools
#-----------------------------------------------------------------------------------------------------------------------
# Supported python versions
PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11
PYTHON_REQUIRES = ">=2.7.9,<3"
# 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.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
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"Flask-Principal>=0.4,<0.5",
"Flask-Babel>=0.12,<0.13",
"Flask-Assets>=0.12,<0.13",
"werkzeug>=0.14.1,<0.15",
"PyYAML>=3.13,<4",
"werkzeug>=0.15.1,<0.16",
"cachelib>=0.1,<0.2",
"PyYAML>=5.1,<6",
"markdown>=3.0,<3.1",
"pyserial>=3.4,<3.5",
"netaddr>=0.7.19,<0.8",
"watchdog>=0.9.0,<0.10",
"sarge==0.1.5post0",
"netifaces>=0.10.7,<0.11",
"pylru>=1.1,<1.2",
"netifaces>=0.10.9,<0.11",
"pylru>=1.2,<1.3",
"rsa>=4.0,<5",
"pkginfo>=1.4.2,<1.5",
"requests>=2.20.0,<3",
"pkginfo>=1.5.0.1,<1.6",
"requests>=2.21.0,<3",
"semantic_version>=2.6,<2.7",
"psutil>=5.4.8,<5.5",
"psutil>=5.6.1,<5.7",
"Click>=7,<8",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3",
"chainmap>=1.0.2,<1.1",
"future>=0.17,<0.18",
"scandir>=1.9,<1.10",
"websocket-client>=0.53,<0.54",
"python-dateutil>=2.7.5,<2.8",
"wrapt>=1.10.11,<1.11",
"chainmap>=1.0.3,<1.1",
"future>=0.17.1,<0.18",
"scandir>=1.10,<1.11",
"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"
"frozendict>=1.2,<1.3",
"sentry-sdk==0.7.7",
"typing>=3.6.6,<4"
]
if sys.platform == "darwin":
@@ -74,7 +77,7 @@ EXTRA_REQUIRES = dict(
"ddt",
# Documentation dependencies
"sphinx>=1.8.1,<1.9",
"sphinx>=1.6,<1.7",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid>=0.3",
"sphinx_rtd_theme",
@@ -192,7 +195,7 @@ def params():
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
project_urls={
"Community Forum": "https://discourse.octoprint.org",
"Community Forum": "https://community.octoprint.org",
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
"Source": "https://github.com/foosel/OctoPrint",
"Funding": "https://donate.octoprint.org"
+11 -4
View File
@@ -103,8 +103,9 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
if callable(after_logging):
after_logging(**kwargs)
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
safe_mode = safe_mode or settings_safe_mode
settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None
settings_incomplete_startup_safemode = "incomplete_startup" if settings.getBoolean(["server", "incompleteStartup"]) else None
safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode
kwargs["safe_mode"] = safe_mode
if callable(after_safe_mode):
after_safe_mode(**kwargs)
@@ -141,7 +142,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
ignore_blacklist=ignore_blacklist,
connectivity_checker=connectivity_checker)
except Exception as ex:
raise FatalStartupError("Could not initialize settings manager", cause=ex)
raise FatalStartupError("Could not initialize plugin manager", cause=ex)
kwargs["plugin_manager"] = plugin_manager
if callable(after_plugin_manager):
@@ -342,9 +343,12 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
import os
# we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins
import octoprint.plugins
logger = log.getLogger(__name__ + ".startup")
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True),
settings.getBaseFolder("plugins")]
plugin_entry_points = ["octoprint.plugin"]
plugin_disabled_list = settings.get(["plugins", "_disabled"])
@@ -595,6 +599,9 @@ def main():
# cut off stuff from the beginning
args = args[-1 * sys_args_length:] if sys_args_length else []
from octoprint.util.fixes import patch_sarge_async_on_py2
patch_sarge_async_on_py2()
from octoprint.cli import octo
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
+4
View File
@@ -2,6 +2,10 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
import sys
if sys.version_info[0] >= 3:
raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
if __name__ == "__main__":
import octoprint
octoprint.main()
+46 -11
View File
@@ -1,3 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
@@ -9,13 +11,14 @@
# versioneer-0.15+dev (https://github.com/warner/python-versioneer)
"""Git implementation of _version.py."""
from __future__ import absolute_import, division, print_function
import errno
import io
import os
import re
import subprocess
import sys
import logging
def get_keywords():
@@ -41,7 +44,7 @@ def get_config():
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.style = "pep440-tag"
cfg.tag_prefix = ""
cfg.parentdir_prefix = ""
cfg.versionfile_source = "src/octoprint/_version.py"
@@ -130,7 +133,7 @@ def git_get_keywords(versionfile_abs):
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
f = io.open(versionfile_abs, "rt", encoding="utf-8")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
@@ -156,11 +159,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
refs = set(r.strip() for r in refnames.strip("()").split(","))
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
tags = set(r[len(TAG):] for r in refs if r.startswith(TAG))
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
@@ -169,7 +172,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
tags = set(r for r in refs if re.search(r'\d', r))
if verbose:
print("discarding '%s', no digits" % ",".join(refs-tags))
@@ -254,7 +257,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
abbrev_ref_out = run_command(GITS,
["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
if abbrev_ref_out is not None:
if abbrev_ref_out is not None and abbrev_ref_out != "HEAD":
pieces["branch"] = abbrev_ref_out.strip()
# now we have TAG-NUM-gHEX or HEX
@@ -305,17 +308,18 @@ def git_parse_lookup_file(path):
if not os.path.exists(path):
return []
import re
lookup = []
with open(path, "r") as f:
with io.open(path, "rt", encoding="utf-8") as f:
for line in f:
if '#' in line:
line = line[:line.rindex("#")]
line = line[:line.index("#")]
line = line.strip()
if not line:
continue
try:
split_line = map(lambda x: x.strip(), line.split())
split_line = list(map(lambda x: x.strip(), line.split()))
if not len(split_line):
continue
@@ -336,7 +340,8 @@ def git_parse_lookup_file(path):
continue
lookup.append(entry)
except:
except Exception:
logging.getLogger(__name__).exception("Versioneer problem")
break
return lookup
@@ -354,6 +359,9 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
current_branch = stdout.strip()
if current_branch == "HEAD":
raise NotThisMethod("not on a branch")
for matcher, render, tag, ref_commit in lookup:
if matcher.match(current_branch):
if tag is None or ref_commit is None:
@@ -441,6 +449,31 @@ def render_pep440(pieces):
return rendered
def render_pep440_tag(pieces):
"""TAG[[.postDISTANCE].dev0+gHEX] -- Just the tag if not dirty, else more info
Useful for projects that want commit based tracking on some branches
but have the master branch only report tags, to allow for commits that
do not modify actual code (e.g. to .github/* or docs).
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]+gHEX
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
return rendered
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
@@ -591,6 +624,8 @@ def render(pieces, style):
rendered = render_pep440_old(pieces)
elif style == "pep440-dev":
rendered = render_pep440_dev(pieces)
elif style == "pep440-tag":
rendered = render_pep440_tag(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
+3 -2
View File
@@ -34,6 +34,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
import time
import yaml
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
throttle_callback = None
@@ -52,7 +53,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = time.time()
start_time = monotonic_time()
progress_callback = None
if progress:
@@ -68,7 +69,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
max_extruders=maxt,
g90_extruder=g90_extruder)
click.echo("DONE:{}s".format(time.time() - start_time))
click.echo("DONE:{}s".format(monotonic_time() - start_time))
click.echo("RESULTS:")
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
+40 -15
View File
@@ -11,7 +11,7 @@ import sys
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode,
def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode,
ignore_blacklist, octoprint_daemon=None):
"""Initializes the environment and starts up the server."""
@@ -26,6 +26,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if safe_mode == "flag":
reason = "command line flag"
elif safe_mode == "settings":
reason = "setting in config.yaml"
elif safe_mode == "incomplete_startup":
reason = "problem during last startup"
else:
reason = "unknown"
logger.info("Reason for safe mode: {}".format(reason))
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
@@ -101,6 +110,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
@@ -111,9 +121,13 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
server_options = bulk_options([
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
help="Specify the host on which to bind the server."),
help="Specify the host address on which to bind the server."),
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
help="Specify the port on which to bind the server."),
click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."),
click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."),
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
help="Specify the config file to use for configuring logging."),
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
@@ -123,7 +137,7 @@ server_options = bulk_options([
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
help="Disable processing of the plugin blacklist.")
])
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6``
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
daemon_options = bulk_options([
@@ -153,11 +167,11 @@ def enable_safemode(ctx, **kwargs):
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
else:
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
@server_commands.command(name="serve")
@@ -172,6 +186,8 @@ def serve_command(ctx, **kwargs):
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
@@ -179,10 +195,13 @@ def serve_command(ctx, **kwargs):
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
run_server(basedir, configfile, host, port, debug,
if v4 and not host:
host = "0.0.0.0"
run_server(basedir, configfile, host, port, v6, debug,
allow_root, logging, verbosity, safe_mode,
ignore_blacklist)
@@ -209,6 +228,8 @@ if sys.platform != "win32" and sys.platform != "darwin":
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
@@ -217,9 +238,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
if v4 and not host:
host = "0.0.0.0"
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
@@ -227,14 +251,15 @@ if sys.platform != "win32" and sys.platform != "darwin":
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity,
safe_mode, ignore_blacklist):
def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config,
verbosity, safe_mode, ignore_blacklist):
Daemon.__init__(self, pidfile)
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._v6_only = v6_only
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
@@ -243,12 +268,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
self._ignore_blacklist = ignore_blacklist
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
self._ignore_blacklist, octoprint_daemon=self)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
safe_mode, ignore_blacklist)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging,
verbosity, safe_mode, ignore_blacklist)
if command == "start":
octoprint_daemon.start()
+9 -4
View File
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
import copy
import logging
import os
import platform
import sys
import threading
import yaml
@@ -16,6 +15,7 @@ import psutil
from octoprint.plugin import EnvironmentDetectionPlugin
from octoprint.util.platform import get_os
from octoprint.util.version import get_python_version_string
class EnvironmentDetector(object):
@@ -25,10 +25,15 @@ class EnvironmentDetector(object):
self._cache = None
self._cache_lock = threading.RLock()
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
self._logger = logging.getLogger(__name__)
try:
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
except Exception:
# just in case, see #3100...
self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager")
self._environment_plugins = []
@property
def environment(self):
with self._cache_lock:
@@ -70,7 +75,7 @@ class EnvironmentDetector(object):
# determine python version
try:
result["version"] = platform.python_version()
result["version"] = get_python_version_string()
except:
self._logger.exception("Error detecting python version")
+26 -7
View File
@@ -14,6 +14,7 @@ except ImportError:
import Queue as queue
import threading
import collections
import re
from octoprint.settings import settings
import octoprint.plugin
@@ -23,7 +24,7 @@ _instance = None
def all_events():
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)]
class Events(object):
@@ -119,6 +120,23 @@ class Events(object):
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
@classmethod
def register_event(cls, event, prefix=None):
name = cls._to_identifier(event)
if prefix:
event = prefix + event
name = cls._to_identifier(prefix) + name
setattr(cls, name, event)
return name, event
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
@classmethod
def _to_identifier(cls, name):
s1 = cls._first_cap_re.sub(r'\1_\2', name)
return cls._all_cap_re.sub(r'\1_\2', s1).upper()
def eventManager():
global _instance
@@ -135,6 +153,7 @@ class EventManager(object):
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
self._startup_signaled = False
self._shutdown_signaled = False
@@ -156,14 +175,14 @@ class EventManager(object):
self._shutdown_signaled = True
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
for listener in eventListeners:
self._logger.debug("Sending action to %r" % listener)
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except:
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
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",
@@ -211,7 +230,7 @@ class EventManager(object):
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
# TODO v1.3.0 Remove again
# TODO v1.4.0 Remove again
import copy
legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode"
@@ -227,7 +246,7 @@ class EventManager(object):
return
self._registeredListeners[event].append(callback)
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
def unsubscribe (self, event, callback):
"""
@@ -239,7 +258,7 @@ class EventManager(object):
return
self._registeredListeners[event].remove(callback)
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
self._logger.debug("Unsubscribed listener {!r} for event {}".format(callback, event))
def join(self, timeout=None):
self._worker.join(timeout)
+17 -12
View File
@@ -30,10 +30,6 @@ extensions = dict(
def full_extension_tree():
result = dict(
# extensions for 3d model files
model=dict(
stl=ContentTypeMapping(["stl"], "application/sla")
),
# extensions for printable machine code
machinecode=dict(
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
@@ -74,6 +70,16 @@ def full_extension_tree():
else:
return merged
slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
for plugin in slicer_plugins:
try:
plugin_result = plugin.get_slicer_extension_tree()
if plugin_result is None or not isinstance(plugin_result, dict):
continue
result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger)
except:
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from SlicerPlugin {name}".format(name=plugin.key))
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
for name, hook in extension_tree_hooks.items():
try:
@@ -87,7 +93,7 @@ def full_extension_tree():
return result
def get_extensions(type, subtree=None):
if not subtree:
if subtree is None:
subtree = full_extension_tree()
for key, value in subtree.items():
@@ -101,7 +107,7 @@ def get_extensions(type, subtree=None):
return None
def get_all_extensions(subtree=None):
if not subtree:
if subtree is None:
subtree = full_extension_tree()
result = []
@@ -120,7 +126,7 @@ def get_all_extensions(subtree=None):
return result
def get_path_for_extension(extension, subtree=None):
if not subtree:
if subtree is None:
subtree = full_extension_tree()
for key, value in subtree.items():
@@ -136,11 +142,11 @@ def get_path_for_extension(extension, subtree=None):
return None
def get_content_type_mapping_for_extension(extension, subtree=None):
if not subtree:
if subtree is None:
subtree = full_extension_tree()
for key, value in subtree.items():
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
if content_extension_matches or list_extension_matches:
@@ -345,7 +351,7 @@ class FileManager(object):
display=display, links=links, allow_overwrite=True,
printer_profile=printer_profile, analysis=_analysis)
end_time = time.time()
end_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
@@ -370,8 +376,7 @@ class FileManager(object):
slicer = self._slicing_manager.get_slicer(slicer_name)
import time
start_time = time.time()
start_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
"stl_location": source_location,
"gcode": dest_path,
+3 -2
View File
@@ -18,6 +18,7 @@ import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import monotonic_time
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
@@ -249,7 +250,7 @@ class AbstractAnalysisQueue(object):
self._current_progress = 0
try:
start_time = time.time()
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
"path": entry.path,
@@ -262,7 +263,7 @@ class AbstractAnalysisQueue(object):
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, time.time() - start_time))
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
self._finished_callback(self._current, result)
finally:
self._current = None
+103 -38
View File
@@ -8,9 +8,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import os
import pylru
import shutil
import re
import pylru
import copy
try:
from os import scandir, walk
@@ -19,7 +20,6 @@ except ImportError:
from octoprint.util import atomic_write
from contextlib import contextmanager
from copy import deepcopy
from past.builtins import basestring
@@ -28,7 +28,7 @@ from slugify import Slugify
import octoprint.filemanager
from octoprint.util import is_hidden_path, to_unicode
from octoprint.util import is_hidden_path, to_unicode, timing
class StorageInterface(object):
"""
@@ -485,6 +485,8 @@ class LocalFileStorage(StorageInterface):
import threading
self._metadata_lock_mutex = threading.RLock()
self._metadata_locks = dict()
self._persisted_metadata_lock_mutex = threading.RLock()
self._persisted_metadata_locks = dict()
self._metadata_cache = pylru.lrucache(10)
@@ -883,6 +885,8 @@ class LocalFileStorage(StorageInterface):
if not name in metadata:
return
metadata = self._copied_metadata(metadata, name)
if not key in metadata[name] or overwrite:
metadata[name][key] = data
metadata_dirty = True
@@ -907,6 +911,7 @@ class LocalFileStorage(StorageInterface):
if not key in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
del metadata[name][key]
self._save_metadata(path, metadata)
@@ -1050,10 +1055,7 @@ class LocalFileStorage(StorageInterface):
##~~ internals
def _add_history(self, name, path, data):
metadata = self._get_metadata(path)
if not name in metadata:
metadata[name] = dict()
metadata = self._copied_metadata(self._get_metadata(path), name)
if not "hash" in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
@@ -1071,6 +1073,8 @@ class LocalFileStorage(StorageInterface):
if not name in metadata or not "history" in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
try:
metadata[name]["history"][index].update(data)
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
@@ -1084,6 +1088,8 @@ class LocalFileStorage(StorageInterface):
if not name in metadata or not "history" in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
try:
del metadata[name]["history"][index]
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
@@ -1093,9 +1099,9 @@ class LocalFileStorage(StorageInterface):
def _calculate_stats_from_history(self, name, path, metadata=None, save=True):
if metadata is None:
metadata = self._get_metadata(path)
metadata = self._copied_metadata(self._get_metadata(path), name)
if not name in metadata or not "history" in metadata[name]:
if not "history" in metadata[name]:
return
# collect data from history
@@ -1164,12 +1170,9 @@ class LocalFileStorage(StorageInterface):
if file_type:
file_type = file_type[0]
metadata = self._get_metadata(path)
metadata = self._copied_metadata(self._get_metadata(path), name)
metadata_dirty = False
if not name in metadata:
metadata[name] = dict()
if not "hash" in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
@@ -1241,13 +1244,10 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def _remove_links(self, name, path, links):
metadata = self._get_metadata(path)
metadata = self._copied_metadata(self._get_metadata(path), name)
metadata_dirty = False
if not name in metadata or not "hash" in metadata[name]:
hash = self._create_hash(os.path.join(path, name))
else:
hash = metadata[name]["hash"]
hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name)))
for rel, data in links:
if (rel == "model" or rel == "machinecode") and "name" in data:
@@ -1255,6 +1255,7 @@ class LocalFileStorage(StorageInterface):
ref_rel = "model" if rel == "machinecode" else "machinecode"
for link in metadata[data["name"]]["links"]:
if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash:
metadata[data["name"]] = copy.deepcopy(metadata[data["name"]])
metadata[data["name"]]["links"].remove(link)
metadata_dirty = True
@@ -1330,10 +1331,14 @@ class LocalFileStorage(StorageInterface):
if entry_name in metadata and isinstance(metadata[entry_name], dict):
entry_metadata = metadata[entry_name]
if not "display" in entry_metadata and entry_display != entry_name:
if not metadata_dirty:
metadata = self._copied_metadata(metadata, entry_name)
metadata[entry_name]["display"] = entry_display
entry_metadata["display"] = entry_display
metadata_dirty = True
else:
if not metadata_dirty:
metadata = self._copied_metadata(metadata, entry_name)
entry_metadata = self._add_basic_metadata(path, entry_name,
display_name=entry_display,
save=False,
@@ -1363,10 +1368,14 @@ class LocalFileStorage(StorageInterface):
if entry_name in metadata and isinstance(metadata[entry_name], dict):
entry_metadata = metadata[entry_name]
if not "display" in entry_metadata and entry_display != entry_name:
if not metadata_dirty:
metadata = self._copied_metadata(metadata, entry_name)
metadata[entry_name]["display"] = entry_display
entry_metadata["display"] = entry_display
metadata_dirty = True
elif entry_name != entry_display:
if not metadata_dirty:
metadata = self._copied_metadata(metadata, entry_name)
entry_metadata = self._add_basic_metadata(path, entry_name,
display_name=entry_display,
save=False,
@@ -1450,6 +1459,8 @@ class LocalFileStorage(StorageInterface):
entry_data["display"] = display_name
entry_data.update(additional_metadata)
metadata = copy.copy(metadata)
metadata[entry] = entry_data
if save:
@@ -1481,6 +1492,8 @@ class LocalFileStorage(StorageInterface):
if not name in metadata:
return
metadata = copy.copy(metadata)
if "hash" in metadata[name]:
hash = metadata[name]["hash"]
for m in metadata.values():
@@ -1494,7 +1507,7 @@ class LocalFileStorage(StorageInterface):
def _update_metadata_entry(self, path, name, data):
with self._get_metadata_lock(path):
metadata = self._get_metadata(path)
metadata = copy.copy(self._get_metadata(path))
metadata[name] = data
self._save_metadata(path, metadata)
@@ -1513,41 +1526,62 @@ class LocalFileStorage(StorageInterface):
with self._get_metadata_lock(destination_path):
self._update_metadata_entry(destination_path, destination_name, source_data)
def _get_metadata(self, path):
with self._get_metadata_lock(path):
if path in self._metadata_cache:
return deepcopy(self._metadata_cache[path])
def _get_metadata(self, path, force=False):
import json
self._migrate_metadata(path)
if not force:
metadata = self._metadata_cache.get(path)
if metadata:
return metadata
metadata_path = os.path.join(path, ".metadata.json")
self._migrate_metadata(path)
metadata_path = os.path.join(path, ".metadata.json")
metadata = None
with self._get_persisted_metadata_lock(path):
if os.path.exists(metadata_path):
with open(metadata_path) as f:
try:
import json
metadata = json.load(f)
except:
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
else:
if isinstance(metadata, dict):
self._metadata_cache[path] = deepcopy(metadata)
return metadata
if isinstance(metadata, dict):
old_size = len(metadata)
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._save_metadata(path, metadata)
else:
with self._get_metadata_lock(path):
self._metadata_cache[path] = metadata
return metadata
else:
return dict()
def _save_metadata(self, path, metadata):
import json
with self._get_metadata_lock(path):
self._metadata_cache[path] = metadata
with self._get_persisted_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.json")
try:
import json
with atomic_write(metadata_path) as f:
json.dump(metadata, f, indent=4, separators=(",", ": "))
except:
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
else:
self._metadata_cache[path] = deepcopy(metadata)
def _delete_metadata(self, path):
with self._get_metadata_lock(path):
if path in self._metadata_cache:
del self._metadata_cache[path]
with self._get_persisted_metadata_lock(path):
metadata_files = (".metadata.json", ".metadata.yaml")
for metadata_file in metadata_files:
metadata_path = os.path.join(path, metadata_file)
@@ -1556,15 +1590,19 @@ class LocalFileStorage(StorageInterface):
os.remove(metadata_path)
except:
self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
if path in self._metadata_cache:
del self._metadata_cache[path]
@staticmethod
def _copied_metadata(metadata, name):
metadata = copy.copy(metadata)
metadata[name] = copy.deepcopy(metadata.get(name, dict()))
return metadata
def _migrate_metadata(self, path):
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
import yaml
import json
with self._get_metadata_lock(path):
with self._get_persisted_metadata_lock(path):
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
metadata_path_json = os.path.join(path, ".metadata.json")
@@ -1574,7 +1612,10 @@ class LocalFileStorage(StorageInterface):
if os.path.exists(metadata_path_json):
# already migrated
# TODO 1.3.10 Remove ".metadata.yaml" files
try:
os.remove(metadata_path_yaml)
except:
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
return
with open(metadata_path_yaml) as f:
@@ -1591,7 +1632,10 @@ class LocalFileStorage(StorageInterface):
with atomic_write(metadata_path_json) as f:
json.dump(metadata, f, indent=4, separators=(",", ": "))
# TODO 1.3.10 Remove ".metadata.yaml" files
try:
os.remove(metadata_path_yaml)
except:
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
@contextmanager
def _get_metadata_lock(self, path):
@@ -1613,3 +1657,24 @@ class LocalFileStorage(StorageInterface):
del self._metadata_locks[path]
else:
self._metadata_locks[path] = (counter, lock)
@contextmanager
def _get_persisted_metadata_lock(self, path):
with self._persisted_metadata_lock_mutex:
if path not in self._persisted_metadata_locks:
import threading
self._persisted_metadata_locks[path] = (0, threading.RLock())
counter, lock = self._persisted_metadata_locks[path]
counter += 1
self._persisted_metadata_locks[path] = (counter, lock)
yield lock
with self._persisted_metadata_lock_mutex:
counter = self._persisted_metadata_locks[path][0]
counter -= 1
if counter <= 0:
del self._persisted_metadata_locks[path]
else:
self._persisted_metadata_locks[path] = (counter, lock)
+18 -13
View File
@@ -21,6 +21,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import logging
import threading
from octoprint.settings import settings as s
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
@@ -32,16 +33,6 @@ from octoprint.util import deprecated
_instance = None
def _validate_plugin(phase, plugin_info):
if phase == "after_load":
if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin):
# transform app plugin into hook
import warnings
warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning)
hooks = plugin_info.hooks
if not "octoprint.accesscontrol.appkey" in hooks:
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
return True
def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None,
@@ -168,7 +159,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None,
initialized=True):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
@@ -206,7 +198,6 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
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.
"""
if not isinstance(types, (list, tuple)):
@@ -216,18 +207,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
if kwargs is None:
kwargs = dict()
logger = logging.getLogger(__name__)
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if initialized and not hasattr(plugin, "_identifier"):
continue
if hasattr(plugin, method):
logger.debug("Calling {} on {}".format(method, plugin._identifier))
try:
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(plugin._identifier, plugin, result)
except Exception as exc:
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
logger.exception("Error while calling plugin %s" % plugin._identifier)
if error_callback:
error_callback(plugin._identifier, plugin, exc)
@@ -303,6 +297,17 @@ class PluginSettings(object):
.. method:: set_boolean(path, value, force=False)
Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it.
.. method:: save(force=False, trigger_event=False)
Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings
will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated``
:ref:`event <sec-events-available_events-settings>` to get triggered.
:param force: Force saving to ``config.yaml`` even if there are no changes.
:type force: boolean
:param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event <sec-events-available_events-settings>` on save.
:type trigger_event: boolean
"""
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
+80 -61
View File
@@ -37,7 +37,9 @@ import inspect
import pkg_resources
import pkginfo
from past.builtins import basestring
from past.builtins import unicode
from octoprint.util import to_unicode
try:
from os import scandir
@@ -46,6 +48,7 @@ except ImportError:
EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version")
FolderOrigin = namedtuple("FolderOrigin", "type, folder")
ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder")
class PluginInfo(object):
"""
@@ -207,13 +210,13 @@ class PluginInfo(object):
def __str__(self):
if self.version:
return "{name} ({version})".format(name=self.name, version=self.version)
return u"{name} ({version})".format(name=self.name, version=self.version)
else:
return self.name
return to_unicode(self.name)
def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""),
show_location=False, location_str=" - {location}",
show_enabled=False, enabled_strs=("* ", " ", "X ")):
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 ")):
"""
Long string representation of the plugin's information. Will return a string of the format ``<enabled><str(self)><bundled><location>``.
@@ -242,17 +245,19 @@ class PluginInfo(object):
str: The long string representation of the plugin as described above
"""
if show_enabled:
ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1])
ret = to_unicode(enabled_strs[2]) if self.blacklisted \
else (to_unicode(enabled_strs[0]) if self.enabled
else to_unicode(enabled_strs[1]))
else:
ret = ""
ret = u""
ret += str(self)
ret += unicode(self)
if show_bundled:
ret += bundled_strs[0] if self.bundled else bundled_strs[1]
ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1])
if show_location and self.location:
ret += location_str.format(location=self.location)
ret += to_unicode(location_str).format(location=self.location)
return ret
@@ -652,7 +657,7 @@ class PluginManager(object):
result_added.update(added)
result_found += found
except:
self.logger.exception("Error fetching plugins from folders")
self.logger.exception(u"Error fetching plugins from folders")
if self.plugin_entry_points:
existing.update(result_added)
@@ -663,7 +668,7 @@ class PluginManager(object):
result_added.update(added)
result_found += found
except:
self.logger.exception("Error fetching plugins from entry points")
self.logger.exception(u"Error fetching plugins from entry points")
return result_added, result_found
@@ -674,15 +679,18 @@ class PluginManager(object):
for folder in folders:
try:
flagged_readonly = False
package = None
if isinstance(folder, (list, tuple)):
if len(folder) == 2:
folder, flagged_readonly = folder
elif len(folder) == 3:
folder, package, flagged_readonly = folder
else:
continue
actual_readonly = not os.access(folder, os.W_OK)
if not os.path.exists(folder):
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
self.logger.warn(u"Plugin folder {folder} could not be found, skipping it".format(folder=folder))
continue
for entry in scandir(folder):
@@ -714,16 +722,23 @@ class PluginManager(object):
bundled = flagged_readonly
plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled)
module_name = None
if package:
module_name = "{}.{}".format(package, key)
plugin = self._import_plugin_from_module(key, module_name=module_name, folder=folder, bundled=bundled)
if plugin:
plugin.origin = FolderOrigin("folder", folder)
if module_name:
plugin.origin = ModuleOrigin("module", module_name, folder)
else:
plugin.origin = FolderOrigin("folder", folder)
plugin.managable = not flagged_readonly and not actual_readonly
plugin.enabled = False
added[key] = plugin
except:
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
self.logger.exception(u"Error processing folder entry {!r} from folder {}".format(entry, folder))
except:
self.logger.exception("Error processing folder {}".format(folder))
self.logger.exception(u"Error processing folder {}".format(folder))
return added, found
@@ -753,8 +768,8 @@ class PluginManager(object):
try:
yield entry
except:
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?")
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?")
for group in groups:
for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)):
@@ -773,7 +788,7 @@ class PluginManager(object):
try:
entry_point_metadata = EntryPointMetadata(entry_point)
except:
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
self.logger.exception(u"Something went wrong while retrieving metadata for module {}".format(module_name))
else:
kwargs.update(dict(
name=entry_point_metadata.name,
@@ -803,7 +818,7 @@ class PluginManager(object):
added[key] = plugin
except:
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
self.logger.exception(u"Error processing entry point {!r} for group {}".format(entry_point, group))
return added, found
@@ -818,7 +833,7 @@ class PluginManager(object):
else:
return None
except:
self.logger.warn("Could not locate plugin {key}".format(key=key))
self.logger.warn(u"Could not locate plugin {key}".format(key=key))
return None
# Create a simple dummy entry first ...
@@ -827,11 +842,11 @@ class PluginManager(object):
plugin.bundled = bundled
if self._is_plugin_disabled(key):
self.logger.info("Plugin {} is disabled.".format(plugin))
self.logger.info(u"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("Plugin {} is blacklisted.".format(plugin))
self.logger.warn(u"Plugin {} is blacklisted.".format(plugin))
plugin.blacklisted = True
if not plugin.validate("before_import", additional_validators=self.plugin_validators):
@@ -839,12 +854,15 @@ class PluginManager(object):
# ... then create and return the real one
return self._import_plugin(key, *module,
name=name, version=version, summary=summary, author=author, url=url,
module_name=module_name, name=name, version=version, summary=summary, author=author, url=url,
license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata)
def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
def _import_plugin(self, key, f, filename, description, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
try:
instance = imp.load_module(key, f, filename, description)
if module_name:
instance = imp.load_module(module_name, f, filename, description)
else:
instance = imp.load_module(key, f, filename, description)
plugin = PluginInfo(key, filename, instance,
name=name,
version=version,
@@ -855,13 +873,13 @@ class PluginManager(object):
parsed_metadata=parsed_metadata)
plugin.bundled = bundled
except:
self.logger.exception("Error loading plugin {key}".format(key=key))
self.logger.exception(u"Error loading plugin {key}".format(key=key))
return None
if plugin.check():
return plugin
else:
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
self.logger.info(u"Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
return None
def _is_plugin_disabled(self, key):
@@ -881,7 +899,7 @@ class PluginManager(object):
self.plugin_blacklist))
def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None):
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(
self.logger.info(u"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))
))
@@ -925,7 +943,7 @@ class PluginManager(object):
try:
if plugin.loaded and not plugin.forced_disabled:
if plugin.blacklisted:
self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin))
self.logger.warn(u"Plugin {} is blacklisted. Not enabling it.".format(plugin))
continue
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
except PluginNeedsRestart:
@@ -938,9 +956,9 @@ class PluginManager(object):
force_reload=force_reload)
if len(self.enabled_plugins) <= 0:
self.logger.info("No plugins found")
self.logger.info(u"No plugins found")
else:
self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
self.logger.info(u"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()))
@@ -948,7 +966,7 @@ class PluginManager(object):
def mark_plugin(self, name, **kwargs):
if not name in self.plugins:
self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals()))
self.logger.debug(u"Trying to mark an unknown plugin {name}".format(**locals()))
for key, value in kwargs.items():
if value is None:
@@ -967,7 +985,7 @@ class PluginManager(object):
def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True):
if not name in self.plugins:
self.logger.warn("Trying to load an unknown plugin {name}".format(**locals()))
self.logger.warn(u"Trying to load an unknown plugin {name}".format(**locals()))
return
if plugin is None:
@@ -982,15 +1000,15 @@ class PluginManager(object):
self.on_plugin_loaded(name, plugin)
plugin.loaded = True
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
self.logger.debug(u"Loaded plugin {name}: {plugin}".format(**locals()))
except PluginLifecycleException as e:
raise e
except:
self.logger.exception("There was an error loading plugin %s" % name)
self.logger.exception(u"There was an error loading plugin %s" % name)
def unload_plugin(self, name):
if not name in self.plugins:
self.logger.warn("Trying to unload unknown plugin {name}".format(**locals()))
self.logger.warn(u"Trying to unload unknown plugin {name}".format(**locals()))
return
plugin = self.plugins[name]
@@ -1010,11 +1028,11 @@ class PluginManager(object):
plugin.loaded = False
self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals()))
self.logger.debug(u"Unloaded plugin {name}: {plugin}".format(**locals()))
except PluginLifecycleException as e:
raise e
except:
self.logger.exception("There was an error unloading plugin {name}".format(**locals()))
self.logger.exception(u"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:
@@ -1024,7 +1042,7 @@ class PluginManager(object):
def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False):
if not name in self.disabled_plugins:
self.logger.warn("Tried to enable plugin {name}, however it is not disabled".format(**locals()))
self.logger.warn(u"Tried to enable plugin {name}, however it is not disabled".format(**locals()))
return
if plugin is None:
@@ -1060,13 +1078,13 @@ class PluginManager(object):
plugin.implementation.on_plugin_enabled()
self.on_plugin_enabled(name, plugin)
self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals()))
self.logger.debug(u"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("Tried to disable plugin {name}, however it is not enabled".format(**locals()))
self.logger.warn(u"Tried to disable plugin {name}, however it is not enabled".format(**locals()))
return
if plugin is None:
@@ -1081,7 +1099,7 @@ class PluginManager(object):
except PluginLifecycleException as e:
raise e
except:
self.logger.exception("There was an error while disabling plugin {name}".format(**locals()))
self.logger.exception(u"There was an error while disabling plugin {name}".format(**locals()))
return False
else:
if name in self.enabled_plugins:
@@ -1093,7 +1111,7 @@ class PluginManager(object):
plugin.implementation.on_plugin_disabled()
self.on_plugin_disabled(name, plugin)
self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals()))
self.logger.debug(u"Disabled plugin {name}: {plugin}".format(**locals()))
return True
@@ -1105,7 +1123,7 @@ class PluginManager(object):
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
continue
self._plugin_hooks[hook].append((order, name, callback))
@@ -1124,7 +1142,7 @@ class PluginManager(object):
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
continue
try:
@@ -1271,7 +1289,7 @@ class PluginManager(object):
additional_pre_inits=additional_pre_inits,
additional_post_inits=additional_post_inits)
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
self.logger.info(u"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:
@@ -1326,7 +1344,7 @@ class PluginManager(object):
try:
return_value = factory(name, implementation)
except:
self.logger.exception("Exception while executing injection factory %r" % factory)
self.logger.exception(u"Exception while executing injection factory %r" % factory)
else:
if return_value is not None:
if isinstance(return_value, dict):
@@ -1350,12 +1368,12 @@ class PluginManager(object):
if isinstance(e, PluginLifecycleException):
raise e
else:
self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals()))
self.logger.exception(u"Exception while initializing plugin {name}, disabling it".format(**locals()))
return False
else:
self.on_plugin_implementations_initialized(name, plugin)
self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals()))
self.logger.debug(u"Initialized plugin mixin implementation for plugin {name}".format(**locals()))
return True
@@ -1372,7 +1390,7 @@ class PluginManager(object):
self.logger.log(level, message)
if len(all_plugins) <= 0:
_log("No plugins available")
_log(u"No plugins available")
else:
formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
bundled_strs=bundled_str,
@@ -1380,9 +1398,9 @@ class PluginManager(object):
location_str=location_str,
show_enabled=show_enabled,
enabled_strs=enabled_str),
sorted(self.plugins.values(), key=lambda x: str(x).lower())))
_log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
plugins=formatted_plugins))
sorted(self.plugins.values(), key=lambda x: unicode(x).lower())))
_log(u"{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
plugins=formatted_plugins))
def get_plugin(self, identifier, require_enabled=True):
"""
@@ -1474,16 +1492,17 @@ class PluginManager(object):
try:
sorting_value = impl[1].get_sorting_key(sorting_context)
except:
self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
self.logger.exception(u"Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
if sorting_value is not None:
try:
int(sorting_value)
sorting_value = int(sorting_value)
except ValueError:
self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
self.logger.warn(u"The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
sorting_value = None
return sorting_value is None, sorting_value, impl[0]
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0]
return [impl[1] for impl in sorted(result, key=sort_func)]
@@ -1558,7 +1577,7 @@ class PluginManager(object):
for client in self.registered_clients:
try: client(plugin, data)
except: self.logger.exception("Exception while sending plugin data to client")
except: self.logger.exception(u"Exception while sending plugin data to client")
def _sort_hooks(self, hook):
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
+38 -25
View File
@@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
# noinspection PyCompatibility
from past.builtins import basestring
class OctoPrintPlugin(Plugin):
"""
The parent class of all OctoPrint plugin mixins.
@@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
externally reachable, use :func:`on_after_startup` instead or additionally.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``StartupPlugin.on_startup``.
:param string host: the host the server will listen on, may be ``0.0.0.0``
@@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
"""
Called just after launch of the server, so when the listen loop is actually running already.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``StartupPlugin.on_after_startup``.
"""
@@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
"""
Called upon the imminent shutdown of OctoPrint.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``ShutdownPlugin.on_shutdown``.
"""
pass
@@ -785,7 +794,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
def get_ui_custom_etag(self):
"""
Allows to use a custom way to calculate the ETag, instead of the default method (hashing
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
OctoPrint's version, tracked file paths and ``LastModified`` value).
Returns:
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
@@ -1382,8 +1391,9 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
# noinspection PyMethodMayBeStatic
def is_blueprint_protected(self):
"""
Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts
access to the blueprint's dynamic methods, static files are always accessible without API key.
Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring
a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files
are always accessible.
"""
return True
@@ -1802,6 +1812,10 @@ class EventHandlerPlugin(OctoPrintPlugin):
"""
Called by OctoPrint upon processing of a fired event on the platform.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
Arguments:
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
for possible values
@@ -1840,8 +1854,9 @@ class SlicerPlugin(OctoPrintPlugin):
The human readable name of the slicer. This will be displayed to the user during slicer selection.
same_device
True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same
device will not be allowed to slice while a print is running due to performance reasons. Slice requests
against slicers running on the same device will result in an error.
device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a
print is running due to performance reasons. Slice requests against slicers running on the same device and
less than two cores will result in an error.
progress_report
``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise.
source_file_types
@@ -1864,6 +1879,21 @@ class SlicerPlugin(OctoPrintPlugin):
destination_extensions=["gco", "gcode", "g"]
)
# noinspection PyMethodMayBeStatic
def get_slicer_extension_tree(self):
"""
Fetch additional entries to put into the extension tree for accepted files
By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support
additional/other file types will want to override this.
For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook <sec-plugins-hook-filemanager-extensiontree>`.
Returns: (dict) a dictionary containing a valid extension subtree.
"""
from octoprint.filemanager import ContentTypeMapping
return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla")))
def get_slicer_profiles(self, profile_path):
"""
Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer.
@@ -2046,20 +2076,3 @@ class ProgressPlugin(OctoPrintPlugin):
:param int progress: Current progress as a value between 0 and 100
"""
pass
class AppPlugin(OctoPrintPlugin):
"""
Using the :class:`AppPlugin mixin` plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
.. deprecated:: 1.2.0
Refer to the :ref:`octoprint.accesscontrol.appkey hook <sec-plugins-hook-accesscontrol-appkey>` instead.
"""
# noinspection PyMethodMayBeStatic
def get_additional_apps(self):
return []
+2 -1
View File
@@ -1 +1,2 @@
# make our plugins testable
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import octoprint.plugin
from octoprint.server import user_permission
from octoprint.events import Events
import flask
from flask_babel import gettext
@@ -34,17 +35,28 @@ class Prompt(object):
class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
COMMAND = "M876"
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._selection_command = None
self._enable = "detected"
self._command = None
self._enable_emergency_sending = False
self._enable_signal_support = False
self._cap_prompt_support = False
def initialize(self):
self._selection_command = self._settings.get([b"selection_command"])
self._enable = self._settings.get([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"])
#~ AssetPlugin
@@ -52,14 +64,26 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
return dict(js=["js/action_command_prompt.js"],
clientjs=["clientjs/action_command_prompt.js"])
#~ EventHandlerPlugin
def on_event(self, event, payload):
if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
#~ SettingsPlugin
def get_settings_defaults(self):
return dict(selection_command=None)
return dict(enable="detected",
command=self.COMMAND,
enable_emergency_sending=True,
enable_signal_support=True)
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._selection_command = self._settings.get([b"selection_command"])
self._enable = self._settings.get([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"])
#~ SimpleApiPlugin
@@ -99,10 +123,6 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
if not action.startswith(b"prompt_"):
return
if self._selection_command is None:
self._logger.info("Got a prompt command from the printer but no selection command is defined")
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
@@ -138,21 +158,55 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
self._close_prompt()
self._prompt = None
#~ queuing handling
def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs):
if gcode != self._command:
return
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending:
return
if not "S" in cmd:
# we only force-send M876 Sx
return
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode)
#~ capability reporting
def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs):
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
#~ prompt handling
def _show_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._prompt.activate()
self._plugin_manager.send_plugin_message(self._identifier, dict(action="show",
text=self._prompt.text,
choices=self._prompt.choices))
def _close_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, dict(action="close"))
def _answer_prompt(self, choice):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._close_prompt()
self._printer.commands([self._selection_command.format(choice=choice)])
self._printer.commands(["{command} S{choice}".format(command=self._command,
choice=choice)])
__plugin_name__ = "Action Command Prompt Support"
@@ -163,5 +217,7 @@ __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.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
}
@@ -2,10 +2,43 @@
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Selection Command') }}</label>
<label class="control-label">{{ _('Enable support')}}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.selection_command">
<div class="help-block">{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace <code>{choice}</code> with the index of the selected choice. E.g. <code>M876 S{choice}</code> will become <code>M123 S1</code>') }}</div>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="detected" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('If detected as supported by the firmware (<code>PROMPT_SUPPORT</code> capability)') }}
</label>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="always" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('Always') }}
</label>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="never" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('Never') }}
</label>
</div>
</div>
<div class="advanced_options">
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<div class="control-group">
<label class="control-label">{{ _('Dialog command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.command">
<div class="help-block">{{ _('Use this to define the dialog command. Default is <code>M876</code>. You normally should not have to change this.') }}</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.action_command_prompt.enable_emergency_sending"> {{ _('Enable force sending of the configured command to bypass blocking firmware routines if detected as supported. You normally should not have to change this.') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.action_command_prompt.enable_signal_support"> {{ _('Enable signaling to the firmware that we support <code>prompt_*</code> actions if detected as supported. You normally should not have to change this.') }}
</label>
</div>
</div>
</div>
</div>
</form>
@@ -22,7 +22,7 @@ from collections import OrderedDict
from octoprint.server import admin_permission
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.util import utmify
from octoprint.util import utmify, monotonic_time
from flask_babel import gettext
from octoprint import __version__ as OCTOPRINT_VERSION
@@ -351,10 +351,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
url = config["url"]
try:
start = time.time()
start = monotonic_time()
r = requests.get(url, timeout=30)
r.raise_for_status()
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start))
except Exception as e:
self._logger.exception(
u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e)))
+49 -13
View File
@@ -15,24 +15,29 @@ import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, admin_permission
from octoprint.util import atomic_write, monotonic_time
from octoprint.users import DummyUser
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
class AppAlreadyExists(Exception):
pass
class PendingDecision(object):
def __init__(self, app_id, app_token, user_id, user_token):
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = monotonic_time()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
self.poll_timeout.start()
def external(self):
return dict(app_id=self.app_id,
user_id=self.user_id,
@@ -107,6 +112,11 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
@no_firstrun_access
def handle_probe(self):
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@no_firstrun_access
def handle_request(self):
@@ -126,14 +136,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
user_token=user_token,
user_id=user_id))
response = flask.jsonify(app_token=app_token)
response.status_code = 202
response.status_code = 201
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
return response
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
@no_firstrun_access
def handle_decision_poll(self, app_token):
if self._is_pending(app_token):
result = self._get_pending_by_app_token(app_token)
if result:
for pending_decision in result:
pending_decision.poll_timeout.reset()
response = flask.jsonify(message="Awaiting decision")
response.status_code = 202
return response
@@ -157,6 +171,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
if not result:
return flask.abort(404)
# Close access_request dialog for this request on all open OctoPrint connections
self._plugin_manager.send_plugin_message(self._identifier, dict(
type="end_request",
user_token=user_token
))
return NO_CONTENT
def is_blueprint_protected(self):
@@ -179,7 +199,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
keys = self._api_keys_for_user(user_id)
return flask.jsonify(keys=map(lambda x: x.external(), keys),
pending=dict((x.user_token, x.external()) for x in self._get_pending(user_id)))
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):
user_id = current_user.get_name()
@@ -221,20 +241,21 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
with self._pending_lock:
self._remove_stale_pending()
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token))
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
timeout_callback=self._expire_pending))
return app_token, user_token
def _is_pending(self, app_token):
def _get_pending_by_app_token(self, app_token):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.app_token == app_token:
return True
result.append(data)
return result
return False
def _get_pending(self, user_id):
def _get_pending_by_user_id(self, user_id):
result = []
with self._pending_lock:
self._remove_stale_pending()
@@ -243,6 +264,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
result.append(data)
return result
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)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._plugin_manager.send_plugin_message(self._identifier, dict(
type="end_request",
user_token=user_token
))
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
@@ -311,7 +344,10 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
with self._keys_lock:
for user_id, data in self._keys.items():
if filter(lambda x: x.api_key == api_key, data):
return self._user_manager.findUser(userid=user_id)
if self._user_manager.enabled:
return self._user_manager.findUser(userid=user_id)
elif user_id == "dummy":
return DummyUser()
return None
def _api_keys_for_user(self, user_id):
@@ -29,6 +29,10 @@
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
};
OctoPrintAppKeysClient.prototype.probe = function(opts) {
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
};
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
return this.requestForUser(app, undefined, opts);
};
@@ -45,37 +49,44 @@
var deferred = $.Deferred();
var client = this;
client.requestForUser(app, user)
.done(function(response) {
var token = response.app_token;
if (!token) {
// no token received, something went wrong
deferred.reject();
return;
}
var interval = 1000;
var poll = function() {
client.checkDecision(token)
.done(function(response) {
if (response.api_key) {
// got a decision, resolve the promise
deferred.resolve(response.api_key);
} else {
// no decision yet, poll a bit more
deferred.notify();
window.setTimeout(poll, interval);
}
})
.fail(function() {
// something went wrong
client.probe()
.done(function() {
client.requestForUser(app, user)
.done(function(response) {
var token = response.app_token;
if (!token) {
// no token received, something went wrong
deferred.reject();
});
};
window.setTimeout(poll, interval);
return;
}
var interval = 1000;
var poll = function() {
client.checkDecision(token)
.done(function(response) {
if (response.api_key) {
// got a decision, resolve the promise
deferred.resolve(response.api_key);
} else {
// no decision yet, poll a bit more
deferred.notify();
window.setTimeout(poll, interval);
}
})
.fail(function() {
// something went wrong
deferred.reject();
});
};
window.setTimeout(poll, interval);
})
.fail(function() {
// something went wrong
deferred.reject();
});
})
.fail(function() {
// something went wrong
// workflow unsupported
deferred.reject();
});
+180 -88
View File
@@ -11,7 +11,8 @@ 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.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version
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
try:
@@ -45,6 +46,14 @@ import traceback
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
BACKUP_FILE_PREFIX = "octoprint-backup"
BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S"
def build_backup_filename():
return "{}-{}.zip".format(BACKUP_FILE_PREFIX,
time.strftime(BACKUP_DATE_TIME_FMT))
class BackupPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
@@ -59,7 +68,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
self._in_progress = []
self._in_progress_lock = threading.RLock()
##~~ StarupPlugin
##~~ StartupPlugin
def on_after_startup(self):
self._clean_dir_backup(self._settings._basedir,
@@ -73,6 +82,11 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
css=["css/backup.css"],
less=["less/backup.less"])
##~~ TemplatePlugin
def get_template_configs(self):
return [dict(type="settings", name=gettext(u"Backup & Restore"))]
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@@ -83,7 +97,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(backups=backups,
backup_in_progress=len(self._in_progress) > 0,
unknown_plugins=unknown_plugins)
unknown_plugins=unknown_plugins,
restore_supported=is_os_compatible(["!windows"]))
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
@admin_permission.require(403)
@@ -115,7 +130,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
@admin_permission.require(403)
@restricted_access
def create_backup(self):
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
backup_file = build_backup_filename()
data = flask.request.json
exclude = data.get("exclude", [])
@@ -135,6 +150,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
self._logger.info(u"... done creating backup zip.")
def on_backup_error(name, exc_info):
with self._in_progress_lock:
try:
self._in_progress.remove(name)
except ValueError:
# we'll ignore that
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)
thread = threading.Thread(target=self._create_backup,
args=(backup_file,),
@@ -143,7 +169,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
plugin_manager=self._plugin_manager,
datafolder=self.get_plugin_data_folder(),
on_backup_start=on_backup_start,
on_backup_done=on_backup_done))
on_backup_done=on_backup_done,
on_backup_error=on_backup_error))
thread.daemon = True
thread.start()
@@ -172,6 +199,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
@admin_permission.require(403)
@restricted_access
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)
input_name = "file"
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
@@ -200,8 +230,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
self._send_client_message("logline", dict(line=line, type="stdout"))
for plugin in plugins:
octoprint_compatible = plugin["compatibility"]["octoprint"]
os_compatible = plugin["compatibility"]["os"]
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
@@ -251,6 +281,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
def on_restore_failed(path):
self._send_client_message("restore_failed")
def on_invalid_backup(line):
on_log_error(line)
archive = tempfile.NamedTemporaryFile(delete=False)
archive.close()
shutil.copy(path, archive.name)
@@ -264,6 +297,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
datafolder=self.get_plugin_data_folder(),
on_install_plugins=on_install_plugins,
on_report_unknown_plugins=on_report_unknown_plugins,
on_invalid_backup=on_invalid_backup,
on_log_progress=on_log_progress,
on_log_error=on_log_error,
on_restore_start=on_restore_start,
@@ -309,7 +343,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
Creates a new backup.
"""
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
backup_file = build_backup_filename()
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
@@ -372,8 +406,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
click.echo(u"\t{}".format(line))
for plugin in plugins:
octoprint_compatible = plugin["compatibility"]["octoprint"]
os_compatible = plugin["compatibility"]["os"]
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
@@ -420,7 +454,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
on_install_plugins=on_install_plugins,
on_report_unknown_plugins=on_report_unknown_plugins,
on_log_progress=on_log_progress,
on_log_error=on_log_error):
on_log_error=on_log_error,
on_invalid_backup=on_log_error):
click.echo(u"Restored from {}".format(path))
else:
click.echo(u"Restoring from {} failed".format(path), err=True)
@@ -492,11 +527,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
thread.start()
@classmethod
def _get_disk_size(cls, path):
def _get_disk_size(cls, path, ignored=None):
if ignored is None:
ignored = []
if path in ignored:
return 0
total = 0
for entry in scandir(path):
if entry.is_dir():
total += cls._get_disk_size(entry.path)
total += cls._get_disk_size(entry.path, ignored=ignored)
elif entry.is_file():
total += entry.stat().st_size
return total
@@ -571,81 +612,106 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
plugin_manager=None,
datafolder=None,
on_backup_start=None,
on_backup_done=None):
if exclude is None:
exclude = []
on_backup_done=None,
on_backup_error=None):
exclude_by_default = ("generated", "logs", "watched",)
configfile = settings._configfile
basedir = settings._basedir
try:
if exclude is None:
exclude = []
temporary_path = os.path.join(datafolder, ".{}".format(name))
final_path = os.path.join(datafolder, name)
if "timelapse" in exclude:
exclude.append("timelapse_tmp")
size = cls._get_disk_size(basedir)
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
configfile = settings._configfile
basedir = settings._basedir
own_folder = datafolder
defaults = [os.path.join(basedir, "config.yaml"),] + \
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
temporary_path = os.path.join(datafolder, ".{}".format(name))
final_path = os.path.join(datafolder, name)
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
own_folder = datafolder
defaults = [os.path.join(basedir, "config.yaml"),] + \
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
if callable(on_backup_start):
on_backup_start(name, temporary_path, exclude)
with zipfile.ZipFile(temporary_path, "w", compression) as zip:
def add_to_zip(source, target, ignored=None):
if ignored is None:
ignored = []
if source in ignored:
return
if os.path.isdir(source):
for entry in scandir(source):
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
elif os.path.isfile(source):
zip.write(source, arcname=target)
# add metadata
metadata = dict(version=get_octoprint_version_string(),
excludes=exclude)
zip.writestr("metadata.json", json.dumps(metadata))
# backup current config file
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
# backup configured folder paths
# check how much many bytes we are about to backup
size = os.stat(configfile).st_size
for folder in default_settings["folder"].keys():
if folder in exclude:
if folder in exclude or folder in exclude_by_default:
continue
add_to_zip(settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[own_folder,])
size += cls._get_disk_size(settings.global_get_basefolder(folder),
ignored=[own_folder,])
size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,])
# backup anything else that might be lying around in our basedir
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
# since we can't know the compression ratio beforehand, we assume we need the same amount of space
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
# add list of installed plugins
plugins = []
plugin_folder = settings.global_get_basefolder("plugins")
for key, plugin in plugin_manager.plugins.items():
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
# ignore anything bundled or from the plugins folder we already include in the backup
continue
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
plugins.append(dict(key=plugin.key,
name=plugin.name,
url=plugin.url))
if callable(on_backup_start):
on_backup_start(name, temporary_path, exclude)
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip:
def add_to_zip(source, target, ignored=None):
if ignored is None:
ignored = []
os.rename(temporary_path, final_path)
if source in ignored:
return
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
if os.path.isdir(source):
for entry in scandir(source):
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
elif os.path.isfile(source):
zip.write(source, arcname=target)
# add metadata
metadata = dict(version=get_octoprint_version_string(),
excludes=exclude)
zip.writestr("metadata.json", json.dumps(metadata))
# backup current config file
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
# backup configured folder paths
for folder in default_settings["folder"].keys():
if folder in exclude or folder in exclude_by_default:
continue
add_to_zip(settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[own_folder,])
# backup anything else that might be lying around in our basedir
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
# add list of installed plugins
plugins = []
plugin_folder = settings.global_get_basefolder("plugins")
for key, plugin in plugin_manager.plugins.items():
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
# ignore anything bundled or from the plugins folder we already include in the backup
continue
plugins.append(dict(key=plugin.key,
name=plugin.name,
url=plugin.url))
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
shutil.move(temporary_path, final_path)
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
except:
if callable(on_backup_error):
exc_info = sys.exc_info()
try:
on_backup_error(name, exc_info)
finally:
del exc_info
raise
@classmethod
def _restore_backup(cls, path,
@@ -660,6 +726,13 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
on_restore_start=None,
on_restore_done=None,
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")
if callable(on_restore_failed):
on_restore_failed(path)
return False
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
basedir = settings._basedir
@@ -683,15 +756,19 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
except KeyError:
if callable(on_invalid_backup):
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
if callable(on_restore_failed):
on_restore_failed(path)
return False
metadata_bytes = zip.read(metadata_zipinfo)
metadata = json.loads(metadata_bytes)
backup_version = get_comparable_version(metadata["version"])
if backup_version > get_octoprint_version():
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")
if callable(on_restore_failed):
on_restore_failed(path)
return False
# unzip to temporary folder
@@ -710,6 +787,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if not os.path.exists(configfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks config.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
import yaml
@@ -722,14 +801,19 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if not os.path.exists(userfile):
if callable(on_invalid_backup):
on_invalid_backup(u"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")
# install available plugins
with codecs.open(os.path.join(temp, "plugin_list.json"), "r") as f:
plugins = json.load(f)
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:
plugins = json.load(f)
known_plugins = []
unknown_plugins = []
@@ -769,18 +853,18 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if callable(on_log_progress):
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
os.rename(basedir, basedir_backup)
shutil.move(basedir, basedir_backup)
try:
if callable(on_log_progress):
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
os.rename(basedir_extracted, basedir)
shutil.move(basedir_extracted, basedir)
except:
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")
os.rename(basedir_backup, basedir)
shutil.move(basedir_backup, basedir)
if callable(on_restore_failed):
on_restore_failed(path)
@@ -808,10 +892,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
shutil.rmtree(temp)
except:
if callable(on_log_error):
on_log_error(u"Error while running restore", exc_info=sys.exc_info())
if callable(on_restore_failed):
on_restore_failed(path)
exc_info = sys.exc_info()
try:
if callable(on_log_error):
on_log_error(u"Error while running restore", exc_info=exc_info)
if callable(on_restore_failed):
on_restore_failed(path)
finally:
del exc_info
return False
finally:
@@ -826,6 +914,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if callable(on_log_progress):
on_log_progress(u"Restarting...")
if callable(on_restore_done):
on_restore_done(path)
try:
sarge.run(restart_command, async_=True)
except:
@@ -835,8 +926,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
on_log_error(u"Please restart OctoPrint manually")
return False
if callable(on_restore_done):
on_restore_done(path)
else:
if callable(on_restore_done):
on_restore_done(path)
return True
@@ -852,7 +944,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
class InsufficientSpace(Exception):
pass
__plugin_name__ = gettext(u"Backup & Restore")
__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 "
@@ -27,6 +27,7 @@ $(function() {
self.excludeFromBackup = ko.observableArray([]);
self.backupInProgress = ko.observable(false);
self.restoreSupported = ko.observable(true);
self.backupUploadButton = $("#settings-backup-upload");
self.backupUploadData = undefined;
@@ -66,6 +67,7 @@ $(function() {
self.fromResponse = function(response) {
self.backups.updateItems(response.backups);
self.unknownPlugins(response.unknown_plugins);
self.restoreSupported(response.restore_supported);
};
self.createBackup = function() {
@@ -88,7 +90,15 @@ $(function() {
};
self.restoreBackup = function(backup) {
if (!self.restoreSupported()) return;
var perform = function() {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Preparing to restore...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
OctoPrint.plugins.backup.restoreBackup(backup);
};
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
@@ -99,6 +109,12 @@ $(function() {
if (self.backupUploadData === undefined) return;
var perform = function() {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
self.backupUploadData.submit();
};
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
@@ -155,14 +171,24 @@ $(function() {
if (data.type === "backup_done") {
self.requestData();
self.backupInProgress(false);
new PNotify({
title: gettext("Backup created successfully"),
type: "success"
});
} else if (data.type === "backup_started") {
self.backupInProgress(true);
} else if (data.type === "backup_error") {
self.requestData();
self.backupInProgress(false);
new PNotify({
title: gettext("Creating the backup failed"),
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
type: "error",
hide: false
});
} else if (data.type === "restore_started") {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
} else if (data.type === "restore_failed") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
@@ -46,7 +46,7 @@
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></td>
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()">&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
</tr>
</tbody>
</table>
@@ -91,30 +91,36 @@
</div>
</form>
<h3>{{ _('Restore from uploaded backup') }}</h3>
<div data-bind="visible: restoreSupported()">
<h3>{{ _('Restore from uploaded backup') }}</h3>
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Backup file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
</span>
<span class="add-on" data-bind="text: backupUploadName"></span>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Backup file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
</span>
<span class="add-on" data-bind="text: backupUploadName"></span>
</div>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
</div>
</div>
</div>
</form>
</form>
</div>
<div data-bind="visible: !restoreSupported()">
{{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to <a href="%(url)s" target="_blank" rel="noopener noreferrer">restore your backups manually for now</a>.', url='https://faq.octoprint.org/manual-restore') }}
</div>
<div id="settings_plugin_backup_restoredialog" class="modal hide fade">
<div class="modal-header">
@@ -170,10 +170,6 @@ $(function() {
return false;
};
self.onWizardPreventSettingsRefreshDialog = function() {
return self.active;
};
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
};
@@ -252,10 +248,6 @@ $(function() {
return false;
};
self.onWizardPreventSettingsRefreshDialog = function() {
return self.active;
};
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required;
};
-532
View File
@@ -1,532 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import logging.handlers
import os
import flask
import math
import octoprint.plugin
import octoprint.util
import octoprint.slicing
import octoprint.settings
from octoprint.util.paths import normalize as normalize_path
from octoprint.util import to_unicode
from .profile import Profile
from .profile import GcodeFlavors
from .profile import parse_gcode_flavor
class CuraPlugin(octoprint.plugin.SlicerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin):
# noinspection PyMissingConstructor
def __init__(self):
self._logger = logging.getLogger("octoprint.plugins.cura")
self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine")
# setup job tracking across threads
import threading
self._slicing_commands = dict()
self._cancelled_jobs = []
self._job_mutex = threading.Lock()
def _is_engine_configured(self, cura_engine=None):
if cura_engine is None:
cura_engine = normalize_path(self._settings.get(["cura_engine"]))
return cura_engine is not None and os.path.isfile(cura_engine) and os.access(cura_engine, os.X_OK)
def _is_profile_available(self):
return bool(self._slicing_manager.all_profiles("cura", require_configured=False))
##~~ TemplatePlugin API
def get_template_vars(self):
return dict(
homepage=__plugin_url__
)
##~~ WizardPlugin API
def is_wizard_required(self):
return not self._is_engine_configured() or not self._is_profile_available()
def get_wizard_details(self):
return dict(
engine=self._is_engine_configured(),
profile=self._is_profile_available()
)
##~~ StartupPlugin API
def on_startup(self, host, port):
# setup our custom logger
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
cura_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), when="D", backupCount=3)
cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
cura_logging_handler.setLevel(logging.DEBUG)
self._cura_logger.addHandler(cura_logging_handler)
self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL)
self._cura_logger.propagate = False
engine = self._settings.get(["cura_engine"])
if not self._is_engine_configured(cura_engine=engine):
self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), "
u"Cura will not be selectable for slicing" % engine)
##~~ BlueprintPlugin API
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
def import_cura_profile(self):
import datetime
input_name = "file"
input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
filename = flask.request.values[input_upload_name]
try:
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
except Exception as e:
self._logger.exception(u"Error while converting the imported profile")
return flask.make_response(u"Something went wrong while converting imported profile: {message}".format(message=str(e)), 500)
else:
self._logger.warn(u"No profile file included for importing, aborting")
return flask.make_response(u"No file included", 400)
if profile_dict is None:
self._logger.warn(u"Could not convert profile, aborting")
return flask.make_response(u"Could not convert Cura profile", 400)
name, _ = os.path.splitext(filename)
# default values for name, display name and description
profile_name = _sanitize_name(name)
profile_display_name = name
profile_description = u"Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
profile_allow_overwrite = False
profile_make_default = False
# overrides
from octoprint.server.api import valid_boolean_trues
if "name" in flask.request.values:
profile_name = flask.request.values["name"]
if "displayName" in flask.request.values:
profile_display_name = flask.request.values["displayName"]
if "description" in flask.request.values:
profile_description = flask.request.values["description"]
if "allowOverwrite" in flask.request.values:
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
if "default" in flask.request.values:
profile_make_default = flask.request.values["default"] in valid_boolean_trues
try:
self._slicing_manager.save_profile("cura",
profile_name,
profile_dict,
allow_overwrite=profile_allow_overwrite,
display_name=profile_display_name,
description=profile_description)
except octoprint.slicing.ProfileAlreadyExists:
self._logger.warn(u"Profile {profile_name} already exists, aborting".format(**locals()))
return flask.make_response(u"A profile named {profile_name} already exists for slicer cura".format(**locals()), 409)
if profile_make_default:
try:
self._slicing_manager.set_default_profile("cura", profile_name)
except octoprint.slicing.UnknownProfile:
self._logger.warn(u"Profile {profile_name} could not be set as default, aborting".format(**locals()))
return flask.make_response(u"The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500)
result = dict(
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
name=profile_name,
displayName=profile_display_name,
description=profile_description
)
r = flask.make_response(flask.jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
##~~ AssetPlugin API
def get_assets(self):
return {
"js": ["js/cura.js"],
"less": ["less/cura.less"],
"css": ["css/cura.css"]
}
##~~ SettingsPlugin API
def on_settings_save(self, data):
old_engine = self._settings.get(["cura_engine"])
old_debug_logging = self._settings.get_boolean(["debug_logging"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
new_engine = self._settings.get(["cura_engine"])
new_debug_logging = self._settings.get_boolean(["debug_logging"])
if old_engine != new_engine and not self._is_engine_configured(new_engine):
self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), "
u"Cura will not be selectable for slicing" % new_engine)
if old_debug_logging != new_debug_logging:
if new_debug_logging:
self._cura_logger.setLevel(logging.DEBUG)
else:
self._cura_logger.setLevel(logging.CRITICAL)
def get_settings_defaults(self):
return dict(
cura_engine=None,
default_profile=None,
debug_logging=False
)
##~~ SlicerPlugin API
def is_slicer_configured(self):
cura_engine = normalize_path(self._settings.get(["cura_engine"]))
return self._is_engine_configured(cura_engine=cura_engine)
def get_slicer_properties(self):
return dict(
type="cura",
name="CuraEngine",
same_device=True,
progress_report=True,
source_file_types=["stl"],
destination_extensions=["gco", "gcode", "g"]
)
def get_slicer_default_profile(self):
path = self._settings.get(["default_profile"])
if not path:
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml")
return self.get_slicer_profile(path)
def get_slicer_profile(self, path):
profile_dict = self._load_profile(path)
display_name = None
description = None
if "_display_name" in profile_dict:
display_name = profile_dict["_display_name"]
del profile_dict["_display_name"]
if "_description" in profile_dict:
description = profile_dict["_description"]
del profile_dict["_description"]
properties = self.get_slicer_properties()
return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description)
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
new_profile = Profile.merge_profile(profile.data, overrides=overrides)
if profile.display_name is not None:
new_profile["_display_name"] = profile.display_name
if profile.description is not None:
new_profile["_description"] = profile.description
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None,
on_progress=None, on_progress_args=None, on_progress_kwargs=None):
try:
with self._job_mutex:
if not profile_path:
profile_path = self._settings.get(["default_profile"])
if not machinecode_path:
path, _ = os.path.splitext(model_path)
machinecode_path = path + ".gco"
if position and isinstance(position, dict) and "x" in position and "y" in position:
pos_x = position["x"]
pos_y = position["y"]
else:
pos_x = None
pos_y = None
if on_progress:
if not on_progress_args:
on_progress_args = ()
if not on_progress_kwargs:
on_progress_kwargs = dict()
self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}"
.format(to_unicode(model_path, errors="replace"),
to_unicode(machinecode_path, errors="replace"),
to_unicode(profile_path, errors="replace")))
executable = normalize_path(self._settings.get(["cura_engine"]))
if not executable:
return False, u"Path to CuraEngine is not configured "
working_dir = os.path.dirname(executable)
slicing_profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y)
# NOTE: We can assume an extruder count of 1 here since the only way we currently
# support dual extrusion in this implementation is by using the second extruder for support (which
# the engine conversion will automatically detect and adapt accordingly).
#
# We currently do only support STL files as sliceables, which by default can only contain one mesh,
# so no risk of having to slice multi-objects at the moment, which would necessitate a full analysis
# of the objects to slice to determine amount of needed extruders to use here. If we ever decide to
# also support dual extrusion slicing (including composition from multiple STLs or support for OBJ or
# AMF files and the like), this code needs to be adapted!
#
# The extruder count is needed to decide which start/end gcode will be used from the Cura profile.
# Stock Cura implementation counts the number of objects in the scene for this (and also takes a look
# at the support usage, like the engine conversion here does). We only ever have one object.
engine_settings = self._convert_to_engine(profile_path, printer_profile,
pos_x=pos_x, pos_y=pos_y,
used_extruders=1)
# Start building the argument list for the CuraEngine command execution
args = [executable, '-v', '-p']
# Add the settings (sorted alphabetically) to the command
for k, v in sorted(engine_settings.items(), key=lambda s: s[0]):
args += ["-s", "%s=%s" % (k, str(v))]
args += ["-o", machinecode_path, model_path]
self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"),
args)),
working_dir))
import sarge
p = sarge.run(args, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p.wait_events()
self._slicing_commands[machinecode_path] = p.commands[0]
try:
layer_count = None
step_factor = dict(
inset=0,
skin=1,
export=2
)
analysis = None
while p.returncode is None:
line = p.stderr.readline(timeout=0.5)
if not line:
p.commands[0].poll()
continue
line = to_unicode(line, errors="replace")
self._cura_logger.debug(line.strip())
if on_progress is not None:
# The Cura slicing process has three individual steps, each consisting of <layer_count> substeps:
#
# - inset
# - skin
# - export
#
# So each layer will be processed three times, once for each step, resulting in a total amount of
# substeps of 3 * <layer_count>.
#
# The CuraEngine reports the calculated layer count and the continuous progress on stderr.
# The layer count gets reported right at the beginning in a line of the format:
#
# Layer count: <layer_count>
#
# The individual progress per each of the three steps gets reported on stderr in a line of
# the format:
#
# Progress:<step>:<current_layer>:<layer_count>
#
# Thus, for determining the overall progress the following formula applies:
#
# progress = <step_factor> * <layer_count> + <current_layer> / <layer_count> * 3
#
# with <step_factor> being 0 for "inset", 1 for "skin" and 2 for "export".
if line.startswith(u"Layer count:") and layer_count is None:
try:
layer_count = float(line[len(u"Layer count:"):].strip())
except:
pass
elif line.startswith(u"Progress:"):
split_line = line[len(u"Progress:"):].strip().split(":")
if len(split_line) == 3:
step, current_layer, _ = split_line
try:
current_layer = float(current_layer)
except:
pass
else:
if not step in step_factor:
continue
on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3)
on_progress(*on_progress_args, **on_progress_kwargs)
elif line.startswith(u"Print time:"):
try:
print_time = int(line[len(u"Print time:"):].strip())
if analysis is None:
analysis = dict()
analysis["estimatedPrintTime"] = print_time
except:
pass
# Get the filament usage
elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"):
if line.startswith(u"Filament:"):
filament_str = line[len(u"Filament:"):].strip()
tool_key = "tool0"
else:
filament_str = line[len(u"Filament2:"):].strip()
tool_key = "tool1"
try:
filament = int(filament_str)
if analysis is None:
analysis = dict()
if not "filament" in analysis:
analysis["filament"] = dict()
if not tool_key in analysis["filament"]:
analysis["filament"][tool_key] = dict()
if slicing_profile.get_float("filament_diameter") is not None:
if slicing_profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or slicing_profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
analysis["filament"][tool_key] = _get_usage_from_volume(filament, slicing_profile.get_float("filament_diameter"))
else:
analysis["filament"][tool_key] = _get_usage_from_length(filament, slicing_profile.get_float("filament_diameter"))
except:
pass
finally:
p.close()
with self._job_mutex:
if machinecode_path in self._cancelled_jobs:
self._cura_logger.info(u"### Cancelled")
raise octoprint.slicing.SlicingCancelled()
self._cura_logger.info(u"### Finished, returncode %d" % p.returncode)
if p.returncode == 0:
return True, dict(analysis=analysis)
else:
self._logger.warn(u"Could not slice via Cura, got return code %r" % p.returncode)
return False, "Got returncode %r" % p.returncode
except octoprint.slicing.SlicingCancelled as e:
raise e
except:
self._logger.exception(u"Could not slice via Cura, got an unknown error")
return False, "Unknown error, please consult the log file"
finally:
with self._job_mutex:
if machinecode_path in self._cancelled_jobs:
self._cancelled_jobs.remove(machinecode_path)
if machinecode_path in self._slicing_commands:
del self._slicing_commands[machinecode_path]
self._cura_logger.info("-" * 40)
def cancel_slicing(self, machinecode_path):
with self._job_mutex:
if machinecode_path in self._slicing_commands:
self._cancelled_jobs.append(machinecode_path)
command = self._slicing_commands[machinecode_path]
if command is not None:
command.terminate()
self._logger.info(u"Cancelled slicing of {}"
.format(to_unicode(machinecode_path, errors="replace")))
def _load_profile(self, path):
import yaml
profile_dict = dict()
with open(path, "r") as f:
try:
profile_dict = yaml.safe_load(f)
except:
raise IOError(u"Couldn't read profile from {path}".format(path=path))
if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)):
profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"])
self._save_profile(path, profile_dict)
return profile_dict
def _save_profile(self, path, profile, allow_overwrite=True):
import yaml
with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
def _convert_to_engine(self, profile_path, printer_profile, pos_x=None, pos_y=None, used_extruders=1):
profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y)
return profile.convert_to_engine(used_extruders=used_extruders)
def _sanitize_name(name):
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError(u"name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name.lower()
def _get_usage_from_volume(filament_volume, filament_diameter):
# filament_volume is expressed in mm^3
# usage["volume"] is in cm^3 and usage["length"] is in mm
usage = dict()
usage["volume"] = filament_volume / 1000.0
radius_in_mm = filament_diameter / 2.0
usage["length"] = filament_volume / (math.pi * radius_in_mm * radius_in_mm)
return usage
def _get_usage_from_length(filament_length, filament_diameter):
# filament_length is expressed in mm
# usage["volume"] is in cm^3 and usage["length"] is in mm
usage = dict()
usage["length"] = filament_length
radius_in_cm = (filament_diameter / 10.0) / 2.0
length_in_cm = filament_length / 10.0
usage["volume"] = length_in_cm * math.pi * radius_in_cm * radius_in_cm
return usage
__plugin_name__ = "CuraEngine (<= 15.04)"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html"
__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint"
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = CuraPlugin()
File diff suppressed because it is too large. Load diff
@@ -1,4 +0,0 @@
layer_height: 0.2
print_temperature:
- 220.0
- 220.0
@@ -1 +0,0 @@
table th.settings_plugin_cura_profiles_key,table td.settings_plugin_cura_profiles_key{text-overflow:ellipsis;text-align:left;width:200px}table th.settings_plugin_cura_profiles_name,table td.settings_plugin_cura_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_cura_profiles_actions,table td.settings_plugin_cura_profiles_actions{text-align:center;width:100px}table th.settings_plugin_cura_profiles_actions a,table td.settings_plugin_cura_profiles_actions a{text-decoration:none;color:#000}table th.settings_plugin_cura_profiles_actions a.disabled,table td.settings_plugin_cura_profiles_actions a.disabled{color:#ccc;cursor:default}
@@ -1,328 +0,0 @@
$(function() {
function CuraViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settingsViewModel = parameters[1];
self.slicingViewModel = parameters[2];
self.pathBroken = ko.observable(false);
self.pathOk = ko.observable(false);
self.pathText = ko.observable();
self.pathHelpVisible = ko.pureComputed(function() {
return self.pathBroken() || self.pathOk();
});
self.fileName = ko.observable();
self.placeholderName = ko.observable();
self.placeholderDisplayName = ko.observable();
self.placeholderDescription = ko.observable();
self.profileName = ko.observable();
self.profileDisplayName = ko.observable();
self.profileDescription = ko.observable();
self.profileAllowOverwrite = ko.observable(true);
self.profileMakeDefault = ko.observable(false);
self.profileFirst = ko.observable(false);
// make sure to update form data if any of the metadata changes
self.profileName.subscribe(function() { self.copyProfileMetadata(); });
self.profileDisplayName.subscribe(function() {
if (self.profileDisplayName()) {
self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase());
}
self.copyProfileMetadata();
});
self.profileDescription.subscribe(function() { self.copyProfileMetadata(); });
self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); });
self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); });
self.unconfiguredCuraEngine = ko.observable();
self.unconfiguredSlicingProfile = ko.observable();
self.uploadDialog = $("#settings_plugin_cura_import");
self.uploadElement = $("#settings-cura-import");
self.uploadData = ko.observable(undefined);
self.uploadBusy = ko.observable(false);
self.uploadEnabled = ko.pureComputed(function() {
return self.fieldsEnabled();
});
self.fieldsEnabled = ko.pureComputed(function() {
return self.uploadData() && !self.uploadBusy()
&& (self.profileName() || self.placeholderName())
&& (self.profileDisplayName() || self.placeholderDisplayName())
&& (self.profileDescription() || self.placeholderDescription());
});
self.profiles = new ItemListHelper(
"plugin_cura_profiles",
{
"id": function(a, b) {
if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1;
if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1;
return 0;
},
"name": function(a, b) {
// sorts ascending
var aName = a.name();
if (aName === undefined) {
aName = "";
}
var bName = b.name();
if (bName === undefined) {
bName = "";
}
if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1;
if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1;
return 0;
}
},
{},
"id",
[],
[],
5
);
self._sanitize = function(name) {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
self.performUpload = function() {
if (self.uploadData()) {
self.uploadData().submit();
}
};
self.copyProfileMetadata = function(form) {
form = form || (self.uploadData() ? self.uploadData().formData : {});
if (self.profileName() !== undefined) {
form["name"] = self.profileName();
} else if (self.placeholderName() !== undefined) {
form["name"] = self.placeholderName();
}
if (self.profileDisplayName() !== undefined) {
form["displayName"] = self.profileDisplayName();
} else if (self.placeholderDisplayName() !== undefined) {
form["displayName"] = self.placeholderDisplayName();
}
if (self.profileDescription() !== undefined) {
form["description"] = self.profileDescription();
} else if (self.placeholderDescription() !== undefined) {
form["description"] = self.placeholderDescription();
}
if (self.profileMakeDefault()) {
form["default"] = true;
}
return form;
};
self.clearUpload = function() {
self.uploadData(undefined);
self.fileName(undefined);
self.placeholderName(undefined);
self.placeholderDisplayName(undefined);
self.placeholderDescription(undefined);
self.profileName(undefined);
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
var firstProfile = self.profiles.items().length === 0;
self.profileMakeDefault(firstProfile);
self.profileFirst(firstProfile);
};
self.uploadElement.fileupload({
dataType: "json",
maxNumberOfFiles: 1,
autoUpload: false,
headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
if (data.files.length == 0) {
// no files? ignore
return false;
}
if (self.uploadData()) {
// data already defined? ignore (should never happen)
return false;
}
self.fileName(data.files[0].name);
var name = self.fileName().substr(0, self.fileName().lastIndexOf("."));
self.placeholderName(self._sanitize(name).toLowerCase());
self.placeholderDisplayName(name);
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
var form = {
allowOverwrite: self.profileAllowOverwrite()
};
data.formData = self.copyProfileMetadata(form);
self.uploadData(data);
},
submit: function(e, data) {
self.copyProfileMetadata();
self.uploadBusy(true);
},
done: function(e, data) {
self.uploadBusy(false);
self.clearUpload();
self.uploadDialog.modal("hide");
self.requestData();
self.slicingViewModel.requestData();
},
error: function(jqXHR, textStatus, errorThrown) {
self.uploadBusy(false);
new PNotify({
title: gettext("Profile import failed"),
text: gettext("Could not import the provided profile, it might be invalid. Check <code>octoprint.log</code> for details"),
type: "error",
hide: false
});
}
});
self.removeProfile = function(data) {
if (!data.resource) {
return;
}
self.profiles.removeItem(function(item) {
return (item.key == data.key);
});
OctoPrint.slicing.deleteProfileForSlicer("cura", data.key, {url: data.resource()})
.done(function() {
self.requestData();
self.slicingViewModel.requestData();
});
};
self.makeProfileDefault = function(data) {
if (!data.resource) {
return;
}
_.each(self.profiles.items(), function(item) {
item.isdefault(false);
});
var item = self.profiles.getItem(function(item) {
return item.key == data.key;
});
if (item !== undefined) {
item.isdefault(true);
}
OctoPrint.slicing.updateProfileForSlicer("cura", data.key, {default: true}, {url: data.resource()})
.done(function() {
self.requestData();
});
};
self.showImportProfileDialog = function() {
self.clearUpload();
self.uploadDialog.modal("show");
};
self.testEnginePath = function() {
OctoPrint.util.testExecutable(self.settings.plugins.cura.cura_engine())
.done(function(response) {
if (!response.result) {
if (!response.exists) {
self.pathText(gettext("The path doesn't exist"));
} else if (!response.typeok) {
self.pathText(gettext("The path is not a file"));
} else if (!response.access) {
self.pathText(gettext("The path is not an executable"));
}
} else {
self.pathText(gettext("The path is valid"));
}
self.pathOk(response.result);
self.pathBroken(!response.result);
});
};
self.requestData = function() {
self.slicingViewModel.requestData();
};
self.fromResponse = function(data) {
var profiles = [];
_.each(_.keys(data), function(key) {
profiles.push({
key: key,
name: ko.observable(data[key].displayName),
description: ko.observable(data[key].description),
isdefault: ko.observable(data[key].default),
resource: ko.observable(data[key].resource)
});
});
self.profiles.updateItems(profiles);
};
self.onBeforeBinding = function () {
self.settings = self.settingsViewModel.settings;
};
self.onAllBound = function() {
self.uploadDialog.on("hidden", function(event) {
if (event.target.id == "settings_plugin_cura_import") {
self.clearUpload();
}
});
};
self.onSettingsShown = function() {
self.requestData();
};
self.onSettingsHidden = function() {
self.resetPathTest();
};
self.onSlicingData = function(data) {
if (data && data.hasOwnProperty("cura") && data.cura.hasOwnProperty("profiles")) {
self.fromResponse(data.cura.profiles);
}
};
self.resetPathTest = function() {
self.pathBroken(false);
self.pathOk(false);
self.pathText("");
};
self.onWizardDetails = function(response) {
if (!response.hasOwnProperty("cura") || !response.cura.required) return;
if (response.cura.details.hasOwnProperty("engine")) {
self.unconfiguredCuraEngine(!response.cura.details.engine);
}
if (response.cura.details.hasOwnProperty("profile")) {
self.unconfiguredSlicingProfile(!response.cura.details.profile);
}
};
self.onWizardFinish = function() {
self.resetPathTest();
};
}
OCTOPRINT_VIEWMODELS.push({
construct: CuraViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
elements: ["#settings_plugin_cura", "#wizard_plugin_cura"]
});
});
@@ -1,29 +0,0 @@
table {
th, td {
&.settings_plugin_cura_profiles_key {
text-overflow: ellipsis;
text-align: left;
width: 200px;
}
&.settings_plugin_cura_profiles_name {
text-overflow: ellipsis;
text-align: left;
}
&.settings_plugin_cura_profiles_actions {
text-align: center;
width: 100px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
}
}
@@ -1,25 +0,0 @@
<h4>{{ _('General') }}</h4>
<p>{% trans %}
Specify the path to the CuraEngine binary. Note that only
<strong>versions up to and including 15.04</strong> are supported.
CuraEngine version 15.06 or newer is <strong>not</strong>
compatible with this plugin.
{% endtrans %}</p>
<form class="form-horizontal">
{% include "snippets/settings/cura/enginePath.jinja2" %}
{% include "snippets/settings/cura/engineLog.jinja2" %}
</form>
<h4>{{ _('Profiles') }}</h4>
{% include "snippets/settings/cura/profiles.jinja2" %}
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
<div style="clear: both">
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
</div>
{% include "snippets/settings/cura/profileImporter.jinja2" %}
@@ -1,36 +0,0 @@
<div data-bind="visible: unconfiguredCuraEngine">
<h3>{{ _('Configure CuraEngine') }}</h3>
<p>{% trans %}
The path to CuraEngine has not yet been set up, in order to be able to use
CuraEngine for slicing it needs to be specified.
{% endtrans %}</p>
<div style="margin-top: 1em">
<form class="form-horizontal">
{% include "snippets/settings/cura/enginePath.jinja2" %}
</form>
</div>
</div>
<div data-bind="visible: unconfiguredSlicingProfile">
<h3>{{ _('Set up a slicing profile') }}</h3>
<p>{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine
yet. If you plan on slicing from within OctoPrint then you should do this now.
Otherwise just skip this step.{% endtrans %}</p>
<div>
{% include "snippets/settings/cura/profiles.jinja2" %}
</div>
<button class="btn btn-block" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
<div style="clear: both; margin-top: 20px;">
<small>{% trans %}
<strong>Don't know where to get a profile?</strong> In order to export
a slicing profile from the Cura desktop UI up to and including version 15.04.06 (not versions
2.1 and later which are actually newer than 15.04), open it, set up your profile, then click
on "File" and there on "Save Profile". You can import the <code>.ini</code> file this creates
via the "Import Profile" button.
{% endtrans %}</small>
</div>
</div>
@@ -1,7 +0,0 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
</label>
</div>
</div>
@@ -1,10 +0,0 @@
<div class="control-group" data-bind="css: {error: pathBroken(), success: pathOk()}">
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine, valueUpdate: 'afterkeydown'" id="settings-cura-path">
<button class="btn" type="button" data-bind="click: testEnginePath, enable: settings.plugins.cura.cura_engine(), css: {disabled: !settings.plugins.cura.cura_engine()}">{{ _('Test') }}</button>
</div>
<span class="help-block" data-bind="visible: pathBroken() || pathOk(), text: pathText"></span>
</div>
</div>
@@ -1,64 +0,0 @@
<div id="settings_plugin_cura_import" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Import Existing Cura Profile') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Profile ini file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}" accept=".ini">
</span>
<span class="add-on" data-bind="text: fileName"></span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, valueUpdate: 'afterkeydown', attr: {placeholder: placeholderDisplayName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Description') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileMakeDefault, enable: fieldsEnabled() && !profileFirst(), css: {disabled: !fieldsEnabled() || profileFirst()}"> {{ _('Make default profile') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileAllowOverwrite, enable: fieldsEnabled() && !profileFirst(), css: {disabled: !fieldsEnabled() || profileFirst()}"> {{ _('Overwrite existing file') }}
</label>
</div>
</div>
</form>
<small>{% trans %}
You can import your existing profile <code>.ini</code> files from <strong>Cura 15.04.x or older</strong>
here. Anything but those are <strong>not supported</strong>. That especially means that <code>.json</code>
profiles from Cura 15.06.x and <code>.curaprofile</code> profiles from Cura 2.x will not work, and neither
will custom Cura profile formats that third party tools like e.g. Repetier create.
{% endtrans %}</small>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" data-bind="click: performUpload, enable: uploadEnabled, css: {disabled: !uploadEnabled()}" id="settings-cura-import-start"><i class="fa fa-spinner fa-spin" data-bind="visible: uploadBusy"></i> {{ _('Confirm') }}</button>
</div>
</div>
@@ -1,34 +0,0 @@
<div data-bind="visible: profiles.items().length > 0" style="display: none">
<div class="pull-right">
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
</div>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: profiles.paginatedItems">
<tr data-bind="attr: {title: description}">
<td class="settings_plugin_cura_profiles_key"><span class="fa fa-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
<td class="settings_plugin_cura_profiles_actions">
<a href="#" class="fa fa-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-trash-o" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: profiles.pages">
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
</ul>
</div>
</div>
+2 -3
View File
@@ -562,9 +562,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
"""
import socket
import time
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > time.time():
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > octoprint.util.monotonic_time():
# we just sent an alive, no need to send another one now
return
@@ -603,7 +602,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
except:
pass
self._ssdp_last_notify = time.time()
self._ssdp_last_notify = octoprint.util.monotonic_time()
def _ssdp_monitor(self, timeout=5):
"""
@@ -0,0 +1,165 @@
# 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 octoprint.plugin
import logging
from octoprint.util.version import get_octoprint_version_string, is_released_octoprint_version
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"
SETTINGS_DEFAULTS = dict(enabled=False,
enabled_unreleased=False,
unique_id=None,
url_server=SENTRY_URL_SERVER,
url_coreui=SENTRY_URL_COREUI)
IGNORED_EXCEPTIONS = [
(SerialException, "octoprint.util.comm"),
]
class ErrorTrackingPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SimpleApiPlugin):
def get_template_configs(self):
return [
dict(type="settings",
name=gettext("Error Tracking"),
template="errortracking_settings.jinja2",
custom_bindings=False),
dict(type="generic", template="errortracking_javascripts.jinja2")
]
def get_template_vars(self):
enabled = self._settings.get_boolean(["enabled"])
enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"])
return dict(enabled=_is_enabled(enabled, enabled_unreleased),
unique_id=self._settings.get(["unique_id"]),
url_coreui=self._settings.get(["url_coreui"]))
def get_assets(self):
return dict(js=["js/sentry.min.js", "js/errortracking.js"])
def get_settings_defaults(self):
return SETTINGS_DEFAULTS
def on_settings_save(self, data):
old_enabled = _is_enabled(self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]))
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
enabled = _is_enabled(self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]))
if old_enabled != enabled:
_enable_errortracking()
def on_api_get(self, request):
return jsonify(**self.get_template_vars())
_enabled = False
def _enable_errortracking():
# this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible
# and hence can't wait until our implementation is initialized and injected with settings
from octoprint.settings import settings
global _enabled
if _enabled:
return
version = get_octoprint_version_string()
s = settings()
plugin_defaults = dict(plugins=dict(errortracking=SETTINGS_DEFAULTS))
enabled = s.getBoolean(["plugins", "errortracking", "enabled"], defaults=plugin_defaults)
enabled_unreleased = s.getBoolean(["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults)
url_server = s.get(["plugins", "errortracking", "url_server"], defaults=plugin_defaults)
unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults)
if unique_id is None:
import uuid
unique_id = str(uuid.uuid4())
s.set(["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults)
s.save()
if _is_enabled(enabled, enabled_unreleased):
import sentry_sdk
from octoprint.plugin import plugin_manager
def _before_send(event, hint):
if not "exc_info" in hint:
# we only want exceptions
return None
handled = True
logger = event.get("logger", "")
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
elif isinstance(ignore, type):
if isinstance(hint["exc_info"][1], ignore):
# exception ignored
return None
if event.get("exception") and event["exception"].get("values"):
handled = not any(map(lambda x: x.get("mechanism") and x["mechanism"].get("handled", True) == False,
event["exception"]["values"]))
if handled:
# error is handled, restrict further based on logger
if logger != "" and not (logger.startswith("octoprint.") or logger.startswith("tornado.")):
# we only want errors logged by loggers octoprint.* or tornado.*
return None
if logger.startswith("octoprint.plugins."):
plugin_id = logger.split(".")[2]
plugin_info = plugin_manager().get_plugin_info(plugin_id)
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,
release=version,
before_send=_before_send)
with sentry_sdk.configure_scope() as scope:
scope.user = dict(id=unique_id)
logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking")
_enabled = True
def _is_enabled(enabled, enabled_unreleased):
return enabled and (enabled_unreleased or is_released_octoprint_version())
def __plugin_enable__():
_enable_errortracking()
__plugin_name__ = "Error Tracking"
__plugin_author__ = "Gina Häußge"
__plugin_implementation__ = ErrorTrackingPlugin()
@@ -0,0 +1,103 @@
$(function() {
function ErrorTrackingViewModel(parameters) {
var self = this;
self.settings = parameters[0];
self.loginState = parameters[1];
var notification = undefined;
var performCheck = function() {
if (!self.loginState.isAdmin()) return;
// already enabled?
if (self.settings.settings.plugins.errortracking.enabled()) return;
// RC release channel?
var releaseChannel = self.settings.settings.plugins.softwareupdate.octoprint_release_channel();
if (releaseChannel === "rc/maintenance" || releaseChannel === "rc/devel") {
if (notification !== undefined) return;
// ignored?
try {
var ignoredString = localStorage["plugin.errortracking.notification_ignored"];
var ignored = false;
if (ignoredString) {
ignored = JSON.parse(ignoredString);
}
if (ignored) return;
} catch (ex) {
log.error("Error while reading plugin.errortracking.notification_ignored from local storage");
}
// show notification
notification = new PNotify({
title: gettext("Enable error reporting?"),
text: gettext("<p>It looks like you are tracking an OctoPrint RC release channel. It " +
"would be great if you would enable error reporting so that any kind of errors that occur " +
"with an RC can be looked into more easily. Thank you!</p>" +
"<p><small>You can find more information on error reporting " +
"under Settings > Error Tracking</small></p>"),
hide: false,
confirm: {
confirm: true,
buttons: [{
text: gettext("Ignore"),
click: function() {
notification.remove();
notification = undefined;
new PNotify({
text: gettext("You can still enable error tracking via \"Settings\" > \"Error Tracking\"")
});
if (Modernizr.localstorage) {
localStorage["plugin.errortracking.notification_ignored"] = JSON.stringify(true);
}
}
}, {
text: gettext("Enable"),
addClass: "btn-primary",
click: function() {
self.settings.saveData({
plugins: {
errortracking: {
enabled: true
}
}
}).done(function() {
notification.remove();
notification = undefined;
location.reload(true);
});
}
}]
},
buttons: {
closer: false,
sticker: false
}
});
// not an RC release channel, close notification
} else if (notification !== undefined) {
notification.remove();
notification = undefined;
}
};
var subbed = false;
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function() {
performCheck();
if (self.settings && self.settings.settings && self.settings.settings.plugins && self.settings.settings.plugins.softwareupdate && !subbed) {
subbed = true;
self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe(performCheck);
}
};
}
OCTOPRINT_VIEWMODELS.push({
construct: ErrorTrackingViewModel,
dependencies: ["settingsViewModel", "loginStateViewModel"]
});
});
@@ -0,0 +1,3 @@
/*! @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
@@ -0,0 +1,24 @@
<script type="text/javascript">
var ERRORTRACKING_ENABLED = {% if plugin_errortracking_enabled -%} true; {% else %} false; {%- endif %}
var ERRORTRACKING_ENABLE = function() {
var errortracking_url_coreui = "{{ plugin_errortracking_url_coreui }}";
var errortracking_unique_id = "{{ plugin_errortracking_unique_id }}";
Sentry.init({
dsn: errortracking_url_coreui,
release: VERSION
});
Sentry.configureScope(function (scope) {
scope.setUser({"id": errortracking_unique_id});
});
ERRORTRACKING_ENABLED = true;
log.info("Initialized error tracking");
};
$(function() {
if (ERRORTRACKING_ENABLED) {
ERRORTRACKING_ENABLE();
}
});
</script>
@@ -0,0 +1,42 @@
<h3>{{ _('Error Tracking') }}</h3>
{% trans %}
<p>
Error tracking will cause any logged exceptions in the server and the browser interface to be sent
to OctoPrint's <a href="https://sentry.io/" target="_blank" rel="noopener noreferer">Sentry instance</a>.
</p>
<p>
By enabling it you help to gather detailed information on the cause of bugs or other issues. This is especially valuable
on release candidates, which is why this plugin will also prompt you to enable error tracking if it detects that
you are subscribed to an RC release channel.
</p>
<p>
Please enable this if you are running a release candidate, or are prompted to do so while debugging an issue that you reported.
</p>
{% endtrans %}
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.errortracking.enabled"> {{ _('Enable error tracking') }}
</label>
<span class="help-block">{{ _('Please reload the page after enabling/disabling & saving') }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label" title="{{ _('Random unique instance ID') }}">{{ _('Instance ID') }}</label>
<div class="controls">
<span style="padding-top: 5px; margin-bottom: 5px; display: inline-block" data-bind="text: settings.plugins.errortracking.unique_id() || 'N/A'"></span>
</div>
</div>
</form>
{% trans %}
<p>
The Error Tracking plugin is using a Sentry instance kindly provided by
<a href="https://sentry.io/" target="_blank" rel="noopener noreferer">sentry.io</a>. For information on their service
please refer to their <a href="https://sentry.io/security/" target="_blank" rel="noopener noreferer">Security & Compliance documentation</a>
and their <a href="https://sentry.io/privacy/" target="_blank" rel="noopener noreferer">Privacy Policy</a>.
</p>
{% endtrans %}
+72 -13
View File
@@ -10,9 +10,23 @@ 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(
@@ -20,15 +34,29 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
)
def will_handle_ui(self, request):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
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:
# passive login successful, no need to handle that
# successful? No need for handling the UI
return False
else:
return True
@@ -80,15 +108,26 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
def get_ui_preemptive_caching_enabled(self):
return False
def get_before_request_handlers(self):
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 self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
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)
@@ -96,8 +135,8 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
return [check_login_required]
def access_validator(self, request):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
if not self.active:
# not active, no handling
return
import tornado.web
@@ -108,21 +147,40 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
raise tornado.web.HTTPError(403)
def socket_register_validator(self, socket, user):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
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 self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
if not self.active:
# not active, no limitation
return True
if message in ("connected", "reauthRequired"):
return True
return user is not None and not user.is_anonymous() and user.is_active()
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"
@@ -138,5 +196,6 @@ __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
}
@@ -17,7 +17,7 @@ $(function() {
var username = usernameElement.val();
var password = passwordElement.val();
var remember = rememberElement.checked;
var remember = rememberElement.prop("checked");
overlayElement.addClass("in");
errorElement.removeClass("in");
@@ -41,19 +41,6 @@ $(function() {
OctoPrint.options.baseurl = BASE_URL;
OctoPrint.socket.onMessage("connected", function(data) {
var payload = data.data;
OctoPrint.options.apikey = payload.apikey;
// update the API key directly in jquery's ajax options too,
// to ensure the fileupload plugin and any plugins still using
// $.ajax directly still work fine too
UI_API_KEY = payload["apikey"];
$.ajaxSetup({
headers: {"X-Api-Key": UI_API_KEY}
});
});
OctoPrint.socket.onConnected = function() {
buttonElement.prop("disabled", false);
offlineElement.removeClass("in");
@@ -1,7 +1,14 @@
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OctoPrint Login</title>
<link rel="shortcut icon" href="{{ url_for('static', filename='img/tentacle-32x32.png') }}">
<link rel="mask-icon" href="{{ url_for('static', filename='img/mask.svg') }}" color="#56BE37">
<link rel="mask-icon-theme" href="{{ url_for('static', filename='img/mask-theme.svg') }}" color="#56BE37">
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
{% include "parts/forcelogin_css.jinja2" %}
{% include "parts/forcelogin_javascripts.jinja2" %}
@@ -1 +1 @@
table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
@@ -9,6 +9,8 @@ $(function() {
self.configuredLoggers = ko.observableArray();
self.configuredLoggersChanged = false;
self.markedForDeletion = ko.observableArray([]);
self.availableLoggersSorted = ko.computed(function() {
return _.sortBy(self.availableLoggers());
});
@@ -114,8 +116,37 @@ $(function() {
};
self.removeFile = function(filename) {
OctoPrint.plugins.logging.deleteLog(filename)
.done(self.requestData);
var perform = function() {
OctoPrint.plugins.logging.deleteLog(filename)
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: filename}),
perform);
};
self.markFilesOnPage = function() {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.listHelper.paginatedItems(), "name"))));
};
self.markAllFiles = function() {
self.markedForDeletion(_.map(self.listHelper.allItems, "name"));
};
self.clearMarkedFiles = function() {
self.markedForDeletion.removeAll();
};
self.removeMarkedFiles = function() {
var perform = function() {
self._bulkRemove(self.markedForDeletion(), "files")
.done(function() {
self.markedForDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d log files."), {count: self.markedForDeletion().length}),
perform);
};
self.onSettingsShown = function() {
@@ -134,6 +165,47 @@ $(function() {
console.log("ConfiguredLoggers has not changed. Not saving.");
}
};
self._bulkRemove = function(files) {
var title = gettext("Deleting log files");
var message = _.sprintf(gettext("Deleting %(count)d log files..."), {count: files.length});
var handler = function(filename) {
return OctoPrint.plugins.logging.deleteLog(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
};
var deferred = $.Deferred();
var promise = deferred.promise();
var options = {
title: title,
message: message,
max: files.length,
output: true
};
showProgressModal(options, promise);
var requests = [];
_.each(files, function(filename) {
var request = handler(filename);
requests.push(request)
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -1,5 +1,14 @@
table {
th, td {
&.settings_logs_checkbox {
text-align: center;
width: 10px;
input[type="checkbox"] {
margin-top: 0;
}
}
&.settings_logs_name {
text-overflow: ellipsis;
text-align: left;
@@ -1,13 +1,31 @@
<h3>{{ _('Logs') }}</h3>
<div class="pull-right">
<small>
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
</small>
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-wrench"></i> <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('name'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('modification'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'modification' ? 'visible' : 'hidden'}"></i> {{ _('Sort by modification date') }} ({{ _('descending') }})</a></li>
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('size'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
</ul>
</div>
</div>
<div class="pull-left">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
</ul>
</div>
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForDeletion().length > 0">{{ _('Delete selected') }}</button>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
<thead>
<tr>
<th class="settings_logs_checkbox"></th>
<th class="settings_logs_name">{{ _('Name') }}</th>
<th class="settings_logs_size">{{ _('Size') }}</th>
<th class="settings_logs_date">{{ _('Date') }}</th>
@@ -16,6 +34,7 @@
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_logs_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForDeletion"></td>
<td class="settings_logs_name" data-bind="text: name"></td>
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
+34 -5
View File
@@ -12,6 +12,7 @@ from flask_babel import gettext
from octoprint.util import RepeatedTimer
import octoprint.plugin
import octoprint.events
_PROC_DT_MODEL_PATH = "/proc/device-tree/model"
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
@@ -35,10 +36,9 @@ _FLAG_PAST_UNDERVOLTAGE = 1 << 16
_FLAG_PAST_FREQ_CAPPED = 1 << 17
_FLAG_PAST_THROTTLED = 1 << 18
class ThrottleState(object):
@classmethod
def from_value(cls, value):
def from_value(cls, value=0):
if value == 0:
return ThrottleState()
@@ -47,10 +47,12 @@ class ThrottleState(object):
throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED,
past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED)
past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
raw_value=value)
return ThrottleState(**kwargs)
def __init__(self, **kwargs):
self._raw_value = kwargs.get('raw_value', -1)
self._undervoltage = False
self._freq_capped = False
self._throttled = False
@@ -111,7 +113,8 @@ class ThrottleState(object):
and self._past_throttled == other._past_throttled
def as_dict(self):
return dict(current_undervoltage=self.current_undervoltage,
return dict(raw_value=self._raw_value,
current_undervoltage=self.current_undervoltage,
past_undervoltage=self.past_undervoltage,
current_overheat=self.current_overheat,
past_overheat=self.past_overheat,
@@ -242,6 +245,16 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
def _check_throttled_state_condition(self):
return self._throttle_functional
def get_throttle_state(self, run_now=False):
"""Exposed as public helper."""
if run_now:
self._check_throttled_state()
if not self._throttle_functional:
return False
return self._throttle_state.as_dict()
def _check_throttled_state(self):
command = self._settings.get(["vcgencmd_throttle_check_command"])
@@ -279,6 +292,13 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
state=self._throttle_state.as_dict()))
# noinspection PyUnresolvedReferences
self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict())
def register_custom_events(*args, **kwargs):
return ["throttle_state",]
__plugin_name__ = "Pi Support Plugin"
__plugin_author__ = "Gina Häußge"
@@ -299,5 +319,14 @@ def __plugin_check__():
return "raspberry pi" in proc_dt_model.lower()
def __plugin_load__():
plugin = PiSupportPlugin()
global __plugin_implementation__
__plugin_implementation__ = PiSupportPlugin()
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events
}
global __plugin_helpers__
__plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state)
@@ -27,7 +27,7 @@ $(function() {
var octoPrintVersion = $(".footer span.version");
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>")
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>");
$(octoPiVersion).insertAfter(octoPrintVersion);
})
};
@@ -41,11 +41,34 @@ $(function() {
self.pastIssue(state.past_issue);
};
self.issuePopoverContent = function() {
return "<p><strong><i class=\"fa fa-bolt\"></i><i class=\"fa fa-exclamation\"></i></strong></strong> - " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "</p>"
+ "<p><strong><i class=\"fa fa-thermometer-full\"></i><i class=\"fa fa-exclamation\"></i></strong> - " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "</p>"
+ "<p>" + gettext("A blinking icon indicates an acute issue!") + "</p>"
};
self.popoverContent = ko.pureComputed(function() {
var undervoltageParagraphClasses = "muted";
var undervoltageSymbolClasses = "";
var overheatParagraphClasses = "muted";
var overheatSymbolClasses = "";
if (self.currentUndervoltage()) {
undervoltageSymbolClasses = "text-error pi_support_state_pulsate";
undervoltageParagraphClasses = "";
} else if (self.pastUndervoltage()) {
undervoltageSymbolClasses = "text-error";
undervoltageParagraphClasses = "";
}
if (self.currentOverheat()) {
overheatSymbolClasses = "text-error pi_support_state_pulsate";
overheatParagraphClasses = "";
} else if (self.pastOverheat()) {
overheatSymbolClasses = "text-error";
overheatParagraphClasses = "";
}
return "<p class='" + undervoltageParagraphClasses + "'><strong class='" + undervoltageSymbolClasses + "'><i class=\"fa fa-bolt\"></i><i class=\"fa fa-exclamation\"></i></strong></strong> - " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "</p>"
+ "<p class='" + overheatParagraphClasses + "'><strong class='" + overheatSymbolClasses + "'><i class=\"fa fa-thermometer-full\"></i><i class=\"fa fa-exclamation\"></i></strong> - " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "</p>"
+ "<p>" + gettext("A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up.") + "</p>"
+ "<p><small>" + gettext("Click the symbol in the navbar for more information.") + "</small></p>";
});
self.onStartup = function() {
self.requestData();
@@ -1,4 +1,4 @@
<a href="javascript:void(0)" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('Issues reported by the Pi') }}', html: true, content: issuePopoverContent(), trigger: 'hover' }" style="display: none">
<a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('What do the symbols mean?') }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage') }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat') }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
</a>
+33 -15
View File
@@ -16,6 +16,7 @@ from octoprint.server import admin_permission
from octoprint.util.pip import LocalPipCaller
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
from octoprint.util.platform import get_os, is_os_compatible
from octoprint.events import Events
from flask import jsonify, make_response
from flask_babel import gettext
@@ -27,10 +28,11 @@ import requests
import re
import os
import copy
import dateutil.parser
import time
import threading
from datetime import datetime
_DATA_FORMAT_VERSION = "v2"
@@ -363,7 +365,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
raise ValueError("Either URL or path must be provided")
self._logger.info("Installing plugin from {}".format(source))
pip_args = ["install", sarge.shell_quote(source), '--no-cache-dir']
pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(source), "--no-cache-dir"]
if dependency_links or self._settings.get_boolean(["dependency_links"]):
pip_args.append("--process-dependency-links")
@@ -485,10 +487,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._plugin_manager.log_all_plugins()
self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version))
self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key,
version=new_plugin.version,
source=source,
source_type=source_type))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key,
version=new_plugin.version,
source=source,
source_type=source_type))
result = dict(result=True,
source=source,
@@ -521,7 +525,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if origin is None:
origin = plugin.origin[2]
pip_args = ["uninstall", "--yes", origin]
pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin]
try:
self._call_pip(pip_args)
except:
@@ -580,8 +584,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._plugin_manager.reload_plugins()
self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key,
version=plugin.version))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, dict(id=plugin.key,
version=plugin.version))
result = dict(result=True,
needs_restart=needs_restart,
@@ -723,8 +728,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
elif not plugin.enabled and plugin.key not in self._pending_enable:
self._pending_enable.add(plugin.key)
self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key,
version=plugin.version))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, dict(id=plugin.key,
version=plugin.version))
def _mark_plugin_disabled(self, plugin, needs_restart=False):
disabled_list = list(self._settings.global_get(["plugins", "_disabled"],
@@ -743,8 +749,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key)
self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key,
version=plugin.version))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, dict(id=plugin.key,
version=plugin.version))
def _fetch_all_data(self, do_async=False):
def run():
@@ -862,7 +869,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
key = notice["plugin"]
try:
parsed_date = dateutil.parser.parse(notice["date"])
# Jekyll turns "%Y-%m-%d %H:%M:%SZ" into "%Y-%m-%d %H:%M:%S +0000", so be sure to ignore "+0000"
#
# Being able to use dateutil here would make things way easier but sadly that can no longer get
# installed (from source) under OctoPi 0.14 due to its setuptools-scm dependency, so we have to do
# without it for now until we can drop support for OctoPi 0.14.
parsed_date = datetime.strptime(notice["date"], "%Y-%m-%d %H:%M:%S +0000")
notice["timestamp"] = parsed_date.timetuple()
except Exception as e:
self._logger.warn("Error while parsing date {!r} for plugin notice "
@@ -961,6 +973,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
versions=notification.get("versions", []),
important=notification.get("important", False))
def _register_custom_events(*args, **kwargs):
return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"]
__plugin_name__ = "Plugin Manager"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
@@ -974,5 +991,6 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
"octoprint.events.register_custom_events": _register_custom_events
}
@@ -1 +1 @@
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
@@ -31,7 +31,7 @@ $(function() {
"name",
[],
[],
5
0
);
self.repositoryplugins = new ItemListHelper(
@@ -1,21 +1,32 @@
table {
th, td {
&.settings_plugin_plugin_manager_plugins_name {
text-overflow: ellipsis;
text-align: left;
}
#settings_plugin_pluginmanager_pluginlist {
display: block;
width: auto;
height: 500px;
overflow-x: hidden;
overflow-y: scroll;
padding-right: 2px;
margin-bottom: 1em;
&.settings_plugin_plugin_manager_plugins_actions {
text-align: center;
width: 80px;
table {
a {
text-decoration: none;
color: #000;
th, td {
&.settings_plugin_plugin_manager_plugins_name {
text-overflow: ellipsis;
text-align: left;
}
&.disabled {
color: #ccc;
cursor: default;
&.settings_plugin_plugin_manager_plugins_actions {
text-align: center;
width: 80px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
}
@@ -37,42 +37,33 @@
<h3>{{ _('Installed Plugins') }}</h3>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted') }}" data-bind="visible: blacklisted"></i></div>
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
</div>
</td>
<td class="settings_plugin_plugin_manager_plugins_actions">
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: plugins.currentPage() === 0}"><a href="#" data-bind="click: plugins.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: plugins.pages">
<li data-bind="css: { active: $data.number === $root.plugins.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.plugins.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: plugins.currentPage() === plugins.lastPage()}"><a href="#" data-bind="click: plugins.nextPage">»</a></li>
</ul>
<div id="settings_plugin_pluginmanager_pluginlist">
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted') }}" data-bind="visible: blacklisted"></i></div>
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
</div>
</td>
<td class="settings_plugin_plugin_manager_plugins_actions">
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
</td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
@@ -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"
@@ -8,7 +8,8 @@ import octoprint.plugin
from octoprint.events import Events
from octoprint.server import user_permission
from octoprint.util.version import get_comparable_version
from .checks.firmware_unsafe import FirmwareUnsafeChecks
import flask
from flask_babel import gettext
@@ -24,47 +25,10 @@ Learn more at https://faq.octoprint.org/warning-{warning_type}
"""
# Anet A8
ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_")
# Anycubic MEGA
ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower()
ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower()
ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower())
# Creality CR-10s
CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower()
CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower()
# Malyan M200 aka Monoprice Select Mini
MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200"
# Any Repetier versions < 0.92
REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92")
# THERMAL_PROTECTION capability reported as disabled
THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled
SAFETY_CHECKS = {
"firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST, REPETIER_BEFORE_092_M115_TEST),
received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST),
cap=(THERMAL_PROTECTION_CAP_TEST,),
message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \
u"thermal runaway protection). This is a fire risk.")
"firmware-unsafe": FirmwareUnsafeChecks.as_dict()
}
def extract_repetier_version(name):
"""
Extracts the Repetier version number from the firmware name.
Example: "Repetier_0.91" => 0.91
"""
version = None
if "_" in name:
_, version = name.split("_", 1)
version = get_comparable_version(version, base=True)
return version
class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SimpleApiPlugin,
@@ -99,6 +63,8 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
def on_event(self, event, payload):
if event == Events.DISCONNECTED:
self._reset_warnings()
self._reset_state()
self._reset_checks()
##~~ SimpleApiPlugin API
@@ -131,14 +97,37 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
changes = False
for warning_type, check_data in SAFETY_CHECKS.items():
checks = check_data.get(check_type)
checks = check_data.get("checks")
message = check_data.get("message")
if not checks or not message:
continue
if any(x(*args, **kwargs) for x in checks):
self._register_warning(warning_type, message)
changes = True
for check in checks:
if not check.active:
# skip non active checks
continue
method = getattr(check, check_type, None)
if not callable(method):
# skip uncallable checks
continue
# execute method
try:
method(*args, **kwargs)
except:
self._logger.exception("There was an error running method {} on check {!r}".format(check_type, check))
continue
# check if now triggered
if check.triggered:
self._register_warning(warning_type, message)
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING, dict(check_name=check.name,
warning_type=warning_type))
changes = True
break
if changes:
self._ping_clients()
@@ -152,6 +141,18 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
self._warnings.clear()
self._ping_clients()
def _reset_state(self):
self._scan_received = True
def _reset_checks(self):
for warning_type, check_data in SAFETY_CHECKS.items():
checks = check_data.get("checks")
if not checks:
continue
for check in checks:
check.reset()
def _log_to_terminal(self, message):
if self._printer:
lines = message.split("\n")
@@ -160,6 +161,11 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
def _ping_clients(self):
self._plugin_manager.send_plugin_message(self._identifier, dict(type="update"))
def register_custom_events(*args, **kwargs):
return ["warning",]
__plugin_name__ = "Printer Safety Check"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html"
@@ -172,6 +178,7 @@ __plugin_implementation__ = PrinterSafetyCheckPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received,
"octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received,
"octoprint.events.register_custom_events": register_custom_events
}
@@ -0,0 +1,55 @@
# -*- 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"
class Check(object):
name = None
def __init__(self):
self._active = True
self._triggered = False
def received(self, line):
"""Called when receiving a new line from the printer"""
pass
def m115(self, name, data):
"""Called when receiving the response to an M115 from the printer"""
pass
def cap(self, cap, enabled):
"""Called when receiving a capability report line"""
pass
@property
def active(self):
"""Whether this check is still active"""
return self._active
@property
def triggered(self):
"""Whether the check has been triggered"""
return self._triggered
def reset(self):
self._active = True
self._triggered = False
class AuthorCheck(Check):
authors = ()
AUTHOR = "| Author: ".lower()
def received(self, line):
if not line:
return
lower_line = line.lower()
if self.AUTHOR in lower_line:
self._triggered = any(map(lambda x: x in lower_line, self.authors))
self._active = False
@@ -0,0 +1,180 @@
# -*- 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 flask_babel import gettext
from octoprint.util.version import get_comparable_version
from . import Check, AuthorCheck
class FirmwareUnsafeChecks(object):
@classmethod
def as_dict(cls):
return dict(checks=(AnetA8Check(), AnycubicCheck(), CrealityCR10sCheck(), CrealityEnder3Check(),
MalyanM200Check(), Micro3DIMECheck(), Micro3DStockCheck(), RepetierBefore092Check(),
ThermalProtectionCapCheck()),
message=gettext("Your printer's firmware is known to lack mandatory safety features (e.g. "
"thermal runaway protection). This is a fire risk."))
class AnetA8Check(Check):
"""
Anet A8 stock firmware
Identified through firmware name "ANET_A8_".
"""
name = "anet_a8"
def m115(self, name, data):
self._triggered = name and name.lower().startswith("anet_a8_")
self._active = False
class AnycubicCheck(Check):
"""
Anycubic MEGA stock firmware
Identified through "Author: (Jolly, xxxxxxxx.CO.)" or "| Author: (**Jolly, xxxxxxxx.CO.**)" in startup messages
combined with "echo:Vx.y.z" in startup messages, with x.y.z < 1.1.2.
"""
name = "anycubic"
AUTHOR = "| Author: ".lower()
VERSION = "echo:V"
CRITICAL_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower()
CRITICAL_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower()
FIXED_VERSION = get_comparable_version("1.1.2")
def __init__(self):
Check.__init__(self)
self._author_matches = None
self._version_matches = None
def received(self, line):
if not line:
return
lower_line = line.lower()
if self.AUTHOR in lower_line:
self._author_matches = self.CRITICAL_AUTHOR1 in lower_line or self.CRITICAL_AUTHOR2 in lower_line
elif line.startswith(self.VERSION):
self._version_matches = self._broken_version(line)
else:
return
self._evaluate()
def _broken_version(self, line):
version_str = line[len(self.VERSION):]
version = get_comparable_version(version_str, base=True)
if version is not None and version <= self.FIXED_VERSION:
return True
else:
return False
def _evaluate(self):
if self._author_matches is None or self._version_matches is None:
return
self._triggered = self._author_matches and self._version_matches
self._active = False
def reset(self):
Check.reset(self)
self._author_matches = None
self._version_matches = None
class CrealityCR10sCheck(AuthorCheck):
"""
Creality CR10s
Identified through " | Author: (CR-10Slanguage)" in startup messages.
"""
name = "creality_cr10s"
authors = (" | Author: (CR-10Slanguage)".lower(),)
class CrealityEnder3Check(AuthorCheck):
"""
Creality Ender3
Identified through " | Author: (Ender3)" in startup messages.
"""
name = "creality_ender3"
authors = (" | Author: (Ender3)".lower(),)
class MalyanM200Check(Check):
"""
Malyan M200 stock firmware prior to version 4.0
Identified through firmware name "Malyan*", model "M200" and version < 4.0.
"""
name = "malyan_m200"
FIXED_VERSION = get_comparable_version("4.0")
def m115(self, name, data):
self._triggered = name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" and get_comparable_version(data.get("VER", "0")) < self.FIXED_VERSION
self._active = False
class Micro3DIMECheck(Check):
"""
Micro3D with IME firmware
Identified through firmware name "iME*".
"""
name = "micro3d_ime"
def m115(self, name, data):
self._triggered = name and name.lower().startswith("ime")
self._active = False
class Micro3DStockCheck(Check):
"""
Micro3D with IME firmware
Identified through firmware name "Micro3D*".
"""
name = "micro3d"
def m115(self, name, data):
self._triggered = name and name.lower().startswith("micro3d")
self._active = False
class RepetierBefore092Check(Check):
"""
Repetier firmware prior to version 0.92
Identified through firmware name "Repetier_x.y.z" with x.y.z < 0.92
"""
name = "repetier_before_092"
FIXED_VERSION = get_comparable_version("0.92")
def m115(self, name, data):
if name and name.lower().startswith("repetier"):
version = self._extract_repetier_version(name)
self._triggered = version is not None and version < self.FIXED_VERSION
self._active = False
def _extract_repetier_version(self, name):
"""
Extracts the Repetier version number from the firmware name.
Example: "Repetier_0.91" => 0.91
"""
version = None
if "_" in name:
_, version = name.split("_", 1)
version = get_comparable_version(version, base=True)
return version
class ThermalProtectionCapCheck(Check):
"""
Firmware reporting disabled THERMAL_PROTECTION capability
"""
name = "capability"
def cap(self, cap, enabled):
if cap == "THERMAL_PROTECTION":
self._triggered = not enabled
self._active = False
@@ -23,7 +23,7 @@ $(function() {
self.fromResponse = function(data) {
var warnings = [];
_.each(data, function(message, warning_type) {
warnings.push({type: warning_type, message: message});
warnings.push({type: warning_type, message: gettext(message)});
});
self.warnings(warnings);
};
@@ -27,7 +27,7 @@ from flask_babel import gettext
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
from octoprint.util import dict_merge, to_unicode
from octoprint.util.version import get_comparable_version
from octoprint.util.version import get_comparable_version, get_python_version_string
from octoprint.util.pip import LocalPipCaller
import octoprint.settings
@@ -69,7 +69,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache_dirty = False
self._version_cache_timestamp = None
self._environment_supported = False
self._environment_supported = True
self._environment_versions = dict()
self._environment_ready = threading.Event()
@@ -99,15 +99,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._console_logger.propagate = False
def on_after_startup(self):
# refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from
# the server startup
def fetch_data():
self.get_current_versions()
self._check_environment()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
self._check_environment()
self.get_current_versions()
def _get_configured_checks(self):
with self._configured_checks_mutex:
@@ -117,6 +110,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
check_providers = self._settings.get(["check_providers"], merged=True)
if not isinstance(check_providers, dict):
check_providers = dict()
effective_configs = dict()
for name, hook in update_check_hooks.items():
@@ -178,13 +174,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
return self._configured_checks
def _check_environment(self):
from platform import python_version
import pkg_resources
local_pip = LocalPipCaller()
# check python and setuptools version
versions = dict(python=python_version(),
versions = dict(python=get_python_version_string(),
setuptools=pkg_resources.get_distribution("setuptools").version,
pip=local_pip.version_string)
supported = get_comparable_version(versions["python"]) >= get_comparable_version(MINIMUM_PYTHON) \
@@ -513,7 +508,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
force = flask.request.values.get("force", "false") in octoprint.settings.valid_boolean_trues
def view():
self._environment_ready.wait()
self._environment_ready.wait(timeout=30.0)
try:
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
@@ -948,17 +943,21 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
target_result = None
def trigger_event(success, **additional_payload):
from octoprint.events import Events
if success:
event = "update_succeeded"
# noinspection PyUnresolvedReferences
event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED
else:
event = "update_failed"
# noinspection PyUnresolvedReferences
event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED
payload = copy.copy(additional_payload)
payload.update(dict(target=target,
from_version=information["local"]["value"],
to_version=target_version))
self._event_bus.fire("plugin_softwareupdate_{}".format(event), payload=payload)
self._event_bus.fire(event, payload=payload)
### The actual update procedure starts here...
@@ -1202,6 +1201,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
return None
def _register_custom_events(*args, **kwargs):
return ["update_succeeded", "update_failed"]
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
@@ -1224,7 +1227,8 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.cli.commands": cli.commands
"octoprint.cli.commands": cli.commands,
"octoprint.events.register_custom_events": _register_custom_events
}
@@ -29,20 +29,20 @@ def _log(lines, prefix=None, stream=None):
output_stream = sys.stderr
for line in lines:
to_print = _to_str(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")),
errors="replace")
to_print = _to_bytes(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")),
errors="replace")
print(to_print, file=output_stream)
def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a unicode string."""
if isinstance(s_or_u, str):
if isinstance(s_or_u, bytes):
return s_or_u.decode(encoding, errors=errors)
else:
return s_or_u
def _to_str(s_or_u, encoding="utf-8", errors="strict"):
def _to_bytes(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a str."""
if isinstance(s_or_u, unicode):
return s_or_u.encode(encoding, errors=errors)
@@ -1 +1 @@
td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more