Compare commits

...
353 Commits
Author SHA1 Message Date
Gina Häußge e46e8fa17a 🔖 Preparing release of 1.5.2 2020-12-10 12:34:21 +01:00
Gina Häußge 12d6de51da 🐛 Replace _.merge with object only deepMerge
It turns out _.merge will also merge arrays, which in turn will re-add
anything we've just removed from a setting that happens to be an
array, thus as blocked commands or temperature presets.

Fixes #3855
Fixes #3867
2020-12-10 12:13:56 +01:00
Gina Häußge 424dc0a13d 📌 Pin watchdog to 0.10.4
New version 0.10.5 restricts upper Python version limit to <=3.6.
That won't work for Python 3 OctoPrint installs out there, so we
stick to the (for us) perfectly working 0.10.4

Dear library maintainers, please don't push breaking changes on
patch releases...
2020-12-10 12:12:59 +01:00
Gina Häußge d9fef47e78 Merge branch 'master' into staging/hotfix 2020-12-10 12:11:21 +01:00
Gina Häußge 222b9997a1 🔀 Merge pull request #3864 from cp2004/patch-2
Document new virtual printer options in 1.5.0
2020-12-10 12:06:41 +01:00
Brian Vanderbusch 3124c08927 🔀 Add canary job for trigger docker workflow (#3863)
* update event-type in trigger-docker workflow
* add dispatch_canary job
* change canary to trigger from maintenance
* add bleeding release type for trigger_docker.yml
* make things uglier to make prettier happy
2020-12-10 11:40:06 +01:00
Gina Häußge 2697bd7a42 Merge pull request #3861 from cp2004/patch-1
Fix /api/job example response
2020-12-08 14:35:10 +01:00
Charlie Powell a2d4fc08a5 📝 Document new virtual printer options in 1.5.0 2020-12-05 16:41:33 +00:00
Charlie Powell bdeb765f75 Fix /api/job example response
Closes #3860
2020-12-05 10:29:44 +00:00
Gina Häußge 84b61e01f4 🔖 staging/hotfix is now 1.5.2.dev 2020-12-04 12:02:02 +01:00
Gina Häußge 38256815ef Merge branch 'staging/hotfix' into master 2020-12-04 10:41:45 +01:00
Gina Häußge c111054fd6 🔖 Preparing release of 1.5.1 2020-12-04 10:37:15 +01:00
Gina Häußge 82dd94d51b 🐛 Better fix for folder listing on files API
We don't want children to be included on api/files or api/files/origin,
but we do want them on api/files/origin/path as that gets taken from
a file listing itself. So a level parameter is introduced on the storage
interface, defaulting to 0 and thus the former behaviour (remove
children), but setting it to a value > 0 will only remove grand children
and thus give us a way to query what we want on the detail endpoint.

See #3844
2020-12-03 18:28:26 +01:00
Gina Häußge 1536ed6da3 🐛 Fix folder listing on files API
Children were not being included without the recursive parameter when it
should in fact only have been grandchildren and later generations.

Closes #3844
2020-12-03 17:59:48 +01:00
Gina Häußge 9f9d0fc788 🐛 Discovery: Never announce loopback addresses
Possible fix for #3852
2020-12-03 17:59:48 +01:00
Gina Häußge a23daa7c81 🔖 staging/hotfix is 1.5.1.dev 2020-12-03 17:59:48 +01:00
Gina Häußge 82d308c9ac Merge pull request #3837 from HackerHappyHour/send-release-type-for-docker-trigger-payload 2020-12-01 13:38:33 +01:00
Gina Häußge fe7437388a Merge pull request #3839 from HackerHappyHour/add-CODEOWNERS-support 2020-12-01 13:36:06 +01:00
Brian Vanderbusch 28a1c8bb4f Merge branch 'master' into send-release-type-for-docker-trigger-payload 2020-11-30 12:53:10 -06:00
Gina Häußge f67c15a9a4 🔖 Preparing release of 1.5.0 2020-11-30 14:30:46 +01:00
Brian Vanderbusch a74309d650 remove default assignment 2020-11-29 11:28:48 -06:00
Brian Vanderbusch 220979bf68 implement CODEOWNERS support 2020-11-29 11:25:15 -06:00
Brian Vanderbusch 49cd9d3283 update Trigger docker build workflow
set payload event-type key to use value from event.action
2020-11-28 12:34:10 -06:00
Gina Häußge 308ac450e7 Merge branch 'master' into staging/maintenance 2020-11-25 15:44:32 +01:00
Gina Häußge d80a27a64a 📝 settings API: only document differences to config.yaml 2020-11-25 15:44:19 +01:00
Gina Häußge a4630df622 📌 Pin prettier and black versions 2020-11-25 11:35:40 +01:00
Gina Häußge 149161694d 🔖 staging/maintenance is now 1.5.0rc4.dev 2020-11-18 16:31:01 +01:00
Gina Häußge 5e7ea35239 🔖 Preparing release of 1.5.0rc3 2020-11-18 13:53:07 +01:00
Gina Häußge 4768a7eb5a 🐛 Value AND key might need str-conversion
Closes #3825
2020-11-18 13:09:51 +01:00
Gina Häußge 84fb97f82a 🐛 PMGR: Don't use jsonify outside flask context
We've moved `_command_install_archive` into its own thread, so we
must return results instead of jsonify'ing them.

As discovered through #3825
2020-11-18 13:07:58 +01:00
Gina Häußge c30673fac0 🔖 staging/maintenance is now 1.5.0rc3.dev 2020-11-17 16:00:51 +01:00
Gina Häußge 9f5781eff4 🔖 Preparing release of 1.5.0rc2 2020-11-17 14:34:53 +01:00
Gina Häußge f2ed1ebc74 🥅 Prevent assignment of dangerous permissions to guests
If we don't, chances are high someone will happily assign the admin
group as a subgroup to the guest group and then publicly expose their
instance on the internet, thus completely defeating the purpose of
making access control mandatory.

We'll also automatically sanitize such configurations now but log a
warning. I don't see a better way to protect the innocent, sorry.
2020-11-17 14:11:59 +01:00
Gina Häußge e7e731800b ♻️ Prefer configured addresses over standard addresses
That way, if OctoPrint is running on a device with network
`192.168.1.0/24` and we query with an address from that range, we'll
actually get that subnet address back instead of the more general
`192.168.0.0/16`.
2020-11-16 18:07:34 +01:00
Gina Häußge 89f3edcb27 ✨ New util API command: address
Allows to test a provided or the client's address whether it is a LAN
address, and if so returns the subnet address in CIDR notation.
2020-11-16 17:55:49 +01:00
Gina Häußge c44e90302d Merge branch 'master' into staging/maintenance 2020-11-16 14:25:07 +01:00
Tobias Wellnitz 5b5163c812 update gcode_scripts.rst with correct UI path for print & resume
Small update to the docs to be coherent with the octoprint Settings UI for the `Log position on pause` option.
2020-11-16 14:24:44 +01:00
Gina Häußge d311fb18e0 Merge pull request #3815 from cp2004/fix/language-pack-upload 2020-11-16 14:07:37 +01:00
cp2004 ab5d19bf12 🐛 Fix uploading a language pack
In Python 3, `filter()` returns an iterable rather than a list. Whilst this is better for performance, our list is not long and it means we can call `len()` on the list.

Tested using reproduction steps in #3814 and verified that language packs can now be installed properly.

Closes #3814
2020-11-16 14:03:18 +01:00
Gina Häußge 75796dafbc 🎨 prettier pre-commit hook has moved 2020-11-16 13:57:04 +01:00
Gina Häußge 2670d16407 Merge branch 'master' into staging/maintenance 2020-11-13 18:18:32 +01:00
Gina Häußge 54f98a5ad1 📝 Document accessControl.salt 2020-11-13 16:38:02 +01:00
Gina Häußge 1238edf1b9 🐛 zeroconf: Add missing answers to PTR query
Backported from upstream.

Closes #3813
2020-11-13 13:24:14 +01:00
Gina Häußge 5f2a95d154 🎨 Run zeroconf through black
We can't update that from upstream anymore anyhow as this is a version
that's no longer maintained (py2 compatible) and upstream now uses
black too.
2020-11-13 12:21:07 +01:00
Gina Häußge 8cd51103d9 🐛 BackupPlugin: Don't use unset self._logger on CLI
Closes #3812
2020-11-12 14:36:10 +01:00
Gina Häußge b94424411a 🥅 Better handling of corrupted user storage
Missing users.yaml should already trigger the wizard to pop up again,
but corrupted users.yaml so far made the user manager to mark itself as
customized and THEN fall on its face.

We now first make sure we can actually load stuff (and if not raise an
exception and a critical error in the log), and only then mark the user
manager as successfully customized.

Implements #3804
2020-11-12 14:14:26 +01:00
Gina Häußge fabf331197 ♻️ ️ Only check resend ratio after 100 transmitted lines
Implements #3811
2020-11-12 11:31:21 +01:00
Gina Häußge bed0f8d1c8 🐛 Children is a dict, not a list
Closes #3805
2020-11-11 10:31:31 +01:00
Gina Häußge f55d7e29f7 📝 Remove accessControl.enabled from docs 2020-11-10 17:12:51 +01:00
Gina Häußge 33dbfd2b3b 🔖 staging/maintenance is now 1.5.0rc2.dev 2020-11-10 15:59:09 +01:00
Gina Häußge b7a45b79bf ➕ Python 2 needs enum34 dep 2020-11-10 12:56:02 +01:00
Gina Häußge 1b41ab8567 🥅 SWU: Prevent issues if no rate limit info is available 2020-11-10 12:32:52 +01:00
Gina Häußge d857779d67 ⬆️ Update FirmwareCheck and FileCheck deps 2020-11-10 12:13:08 +01:00
Gina Häußge 4166ef1556 🐛 Fix wizard
Updated dependency turned out to have some backwards incompatible
side effects, fixed those to return to old behaviour and documented
accordingly.
2020-11-10 12:10:07 +01:00
Gina Häußge 6a695c851a 🔖 Preparing release of 1.5.0rc1 2020-11-10 11:19:32 +01:00
Gina Häußge 84b41e70a6 Merge pull request #3798 from jneilliii/fix_webcam_permissions
if webcam permissions are not set for user this will prevent the webc…
2020-11-09 14:18:51 +01:00
jneilliii fe6a865c13 if webcam permissions are not set for user this will prevent the webcam html code from loading. 2020-11-07 11:12:20 -05:00
Gina Häußge e82eced346 📝 Fix a typo in the docs 2020-11-06 17:00:10 +01:00
Gina Häußge 959b8637db ✨ Allow UiPlugins to not require login 2020-11-06 16:32:25 +01:00
Gina Häußge e5f893d2ba 📈 tracking: Add 32/64bits to ping/pong payload 2020-11-05 15:55:06 +01:00
Gina Häußge e94c248f23 Merge branch 'pr/3793' into maintenance 2020-11-05 15:44:08 +01:00
Gina Häußge 7483a24efa 💄 Direct About link in footer as well
See #3793
2020-11-05 15:43:22 +01:00
Gina Häußge 1480dcf6e0 📝 Document resends and plugins in push messages 2020-11-05 15:41:12 +01:00
Gina Häußge ca62d15aac ✨ Resend ratio tracking & warning
Implements #3672
2020-11-05 12:56:05 +01:00
cp2004 b5ce6281d8 💄 Make about button always open 'About OctoPrint'
While the 'About OctoPrint' button opened the dialog, it creates confusing behaviour if a user clicks 'System info' first, since 'About OctoPrint' will then open the system info too.

This PR adjusts this, to force 'About OctoPrint' to open to the about page.
2020-11-04 22:16:54 +00:00
Gina Häußge cb9e5b401f ✨ Virtual printer: Support noise simulation on line
Using the config setting resend_ratio or the resend_ratio DEBUG command,
a percentage of lines to request a resend for can be set. Setting the
value to 0 disables the simulation.

Added to test #3672
2020-11-04 16:46:38 +01:00
Gina Häußge 3bd7004733 ⚡️ SWU: Improve pip caller caching behaviour
We want to synchronize so we don't try to determine the pip caller again
and again for all registered checks that are being processed
concurrently.
2020-11-04 11:44:40 +01:00
Gina Häußge 4110287349 ✨ Support central local pip command in server.pip
Plugin Manager, Software Update and Backup will use that if set.
Otherwise the old default of using LocalPipCaller is used.

Not exposed via the UI as this REALLY should only be used by people who
know what they are doing and the majority of users out there will never
ever have to use it.

Implements #3700
2020-11-04 11:41:19 +01:00
Gina Häußge a5e18300ea 🐛 Get rid of unnecessary double load of plugins 2020-11-03 18:07:26 +01:00
Gina Häußge ee63eea02f 🐛 Make systeminfo command also work w/ plugin env data
At least as long as the plugins that provide said env data only require
a limited set of injected properties.
2020-11-03 18:07:05 +01:00
Gina Häußge caa63017cf ♻️ Extract some init functions from server init
We want to be able to reuse them in a CLI context
2020-11-03 18:06:01 +01:00
Gina Häußge 837b5a65ea ⬆️ Upgrade JS dependencies 2020-11-03 16:07:22 +01:00
Gina Häußge 0aa5be6709 ♻️ pi_support: report only raw throttle value in env 2020-11-03 14:56:34 +01:00
Gina Häußge 7f4dcaa5f1 ✅ pi_support: Use flag file for local debug mode 2020-11-03 14:55:43 +01:00
Gina Häußge 7bdda2e2a6 💚 Rewrite unit test to work in py 2&3 2020-11-03 09:05:41 +01:00
Gina Häußge 7d49f20571 ✨ environment: include 64bit flag 2020-11-02 18:35:37 +01:00
Gina Häußge 95ddb184a0 💚 Fix unit tests 2020-11-02 18:29:37 +01:00
Gina Häußge eec43e31c2 💄 New link icons in about dialog 2020-11-02 18:25:14 +01:00
Gina Häußge ee4eb72014 ✨ pi_support: include throttle state in environment 2020-11-02 18:25:14 +01:00
Gina Häußge a58e02940d ✨ New system info collection, ready for copy/paste
Should hopefully make it easier in the future to collect data needed
for ticket processing. Can be accessed through System Information in the
About dialog (also directly linked from the footer and the settings),
via a new sub command `octoprint systeminfo` on the command
line and on the recovery page.

Currently included:

  * octoprint version
  * safe mode yes/no
  * printer firmware name (if connected)
  * browser user agent (if dump happens through API)
  * everything reported by the environment detector (that includes data
    from plugins as well that add to that, e.g. pi_support)
  * connectivity check information

Might be extended more in the future.
2020-11-02 18:24:59 +01:00
Gina Häußge d41feaec6d ✨ discovery: Allow address/interface restriction
Implements #3791
2020-11-02 12:02:42 +01:00
Gina Häußge de29cdb7e5 📝 Remove install from source from README
It's still available in the developer docs on docs.octoprint.org

See #3789
2020-11-02 10:34:04 +01:00
Gina Häußge 18e4025c47 Merge remote-tracking branch 'origin/maintenance' into maintenance 2020-11-02 10:22:02 +01:00
Gina Häußge 79f0b06150 ⬆️ feedparser >=6.0.2 for Python 3 2020-11-02 10:21:28 +01:00
Gina Häußge 189d3bbbdf ♻️ Prefer collections.abc over collections import 2020-11-02 10:20:52 +01:00
Gina Häußge 60f14e1f99 Merge branch 'master' into maintenance 2020-11-02 10:02:39 +01:00
Gina Häußge d0ad6c6223 📝 file upload requires content-length
Closes #3786
2020-11-02 10:01:17 +01:00
Gina Häußge 6c1eaad083 Merge pull request #3787 from cp2004/fix/virtual_eeprom_py2
Fix Virtual EEPROM on Python 2 and decimal places oversight
2020-10-27 18:55:40 +01:00
cp2004 27ced65a4d 🐛 Fix virtual eeprom on Python 2 & decimal place handling
It was requiring 2 dp, rather than optional
2020-10-27 17:21:41 +00:00
Gina Häußge 1e0f549fb6 🐛 Fix some bindings, assets and icons 2020-10-26 16:50:49 +01:00
Gina Häußge 9fed67306e Merge branch 'pr/3785' into maintenance 2020-10-26 15:23:04 +01:00
Gina Häußge 0267250af4 ♻️ Move knockout init to an earlier point 2020-10-26 15:22:48 +01:00
Charlie Powell b12e5a6e00 ✨ Add option to turn off internal filename (#3783)
Closes #3636
2020-10-26 15:14:12 +01:00
Gina Häußge 60a40d55b6 Merge branch 'pr/3782' into maintenance
# Conflicts:
#	src/octoprint/static/css/octoprint.css
2020-10-26 14:22:34 +01:00
Gina Häußge 8500584c02 💄 Remove custom SD card icon
FA5 includes one.
2020-10-26 14:21:57 +01:00
Gina Häußge 5246ca85f0 Merge pull request #3772 from cp2004/feature/virtual_eeprom
Virtual: Add Virtual EEPROM to virtual printer
2020-10-26 12:06:09 +01:00
j7126 900d7c36d2 update to knockout 3.5.1 2020-10-25 19:06:46 +10:00
Gina Häußge dbc012fa4c 🎨 Fix some left over set calls 2020-10-23 16:42:32 +02:00
Gina Häußge f21653510f 🎨 pre-commit: newer codemods version 2020-10-23 14:37:17 +02:00
cp2004 065b87d694 ⬆️ Upgrade FontAwesome to 5.15.1
This is not a breaking change, due to the inclusion of the v4-shims. All icons should aim to use fontawesome 5 styles, full guide on breaking changes can be found at:

https://fontawesome.com/how-to-use/on-the-web/setup/upgrading-from-version-4

I've aimed to update all icons I could find, but due to the compatibility layer if there are a couple missed, they still all work fine.
2020-10-22 20:31:23 +01:00
Gina Häußge 7986ba7072 💄 Use monospace font for GCODE scripts 2020-10-22 18:36:59 +02:00
cp2004 8793495edd Merge branch 'maintenance' of https://github.com/OctoPrint/OctoPrint into maintenance 2020-10-22 16:29:53 +01:00
Gina Häußge 16161fdb0a ♻️ Remove errant assert
The comment lies, it works just fine (for OctoPrint's purpose at least)
2020-10-22 14:39:23 +02:00
Gina Häußge a3dd2c6b34 📝 Remove requirement to test w/o ACL as that just got removed 2020-10-21 14:29:20 +02:00
Gina Häußge c0c6dd7c7b 🥅 Make access control mandatory
Apparently no matter how often you tell people to not put their stuff
unsecured on the public internet, they still will do that happily and
then I get the resulting fallout from the security community.

So you now will HAVE to enable access control. No more disabled ACL.
Apparently you can't trust people with this kind of responsibility.

If you want a bit more convenience, look into the trusted network
settings in config.yaml. And get a password manager. And stop port
forwarding and exposing your OctoPrint on the public internet please -
it can be found, you are not invisible, and you are putting yourself at
risk. Learn what a VPN is and to set one up on your router, that is a
valuable skill in any case.
2020-10-21 14:23:40 +02:00
Gina Häußge fd319fc82f 🥅 PiSupport: Warning if run on a zero/zero w 2020-10-21 11:54:46 +02:00
Gina Häußge 0d90bb9e8f 📝 New SWU settings & config CLI 2020-10-20 12:07:56 +02:00
cp2004 3db176e77f 🐛 Fix reset if eeprom not enabled 2020-10-19 17:50:02 +01:00
Gina Häußge 6c18931153 ✨ SWU: Support Github API key to work around rate limits
If someone needs to check updates more often than the rate limiting with
anonymous access allows, they can now configured a personal access token
from Github via `plugins.softwareupdate.credentials.github`. This
setting is and will not be exposed via the UI.

See #3777
2020-10-19 15:08:48 +02:00
Gina Häußge 688188777f 🚸 SWU: Clear message on rate limit exceed
See #3777
2020-10-19 14:45:23 +02:00
Gina Häußge 83c411b308 🥅 Logging for start/pause/resume/cancel print
Always logs responsible user or plugin to comm INFO log.

Implements #3766
2020-10-19 11:03:21 +02:00
Gina Häußge 2acf4764c2 Merge branch 'pr/3769' into maintenance 2020-10-19 10:24:44 +02:00
cp2004 021748e81a ✨ Add more EEPROM commands
Adds:
* M201 Max acceleration
* M204 Starting acceleration
* M206 Home offset
* M851 Z probe offset
* M200 filament
* M666 endstop adjustment
* M665 delta
* M420 Bed levelling
* M900 Linear advance
* M205 Advanced
* M145 Material heating
* M301 PID tool
* M304 PID bed
2020-10-17 11:19:04 +01:00
Gina Häußge 1d689d0b87 Merge branch 'master' into maintenance
# Conflicts:
#	README.md
2020-10-16 14:45:06 +02:00
Gina Häußge c20c9946f8 📝 Add CoC and update README 2020-10-16 13:04:40 +02:00
Gina Häußge 8294eae6d9 ♻️ Some clean-up 2020-10-15 14:34:52 +02:00
Gina Häußge 79814905fa 🚸 Event & notifications for suppressed commands
Seems to confuse people with incorrectly configured printer profiles,
see various forum threads and issues on the issue tracker. This will
hopefully make such cases more transparent, though a bit spammy (hence
there's also a setting).
2020-10-15 14:33:45 +02:00
Gina Häußge 4dea9f08ef 🚸 Highlight warnings in terminal 2020-10-15 13:55:11 +02:00
Gina Häußge 9494db9568 🐛 Use a recursive merge in SettingsViewModel
Otherwise we will overwrite any changes to settings not represented as
properties on the view model on settings save.
2020-10-15 13:50:49 +02:00
Gina Häußge 4bafd14bef 🚸 ACNotifcations: Clear button in header & sort order button
Implements #3768
2020-10-14 16:49:33 +02:00
Gina Häußge 706210a483 ♻ Extract local storage helper 2020-10-14 16:48:47 +02:00
Gina Häußge 69644593f7 Merge branch 'master' into maintenance 2020-10-14 13:33:20 +02:00
Gina Häußge c5051ddb30 👷‍ Automatically set/unset done labels 2020-10-14 13:20:54 +02:00
Gina Häußge e7d037d3d4 🐛 SWU: Fix issue with check config persistence from plugins
If we want to be able to in-place overlay the effective config, we MUST
do a deepcopy of the default or we'll actually operate on the default,
effectively leading to any changes to plugin check configs to be cleaned
up from the config file.

Closes #3765
Closes #3767
2020-10-14 12:24:45 +02:00
cp2004 3478aa1305 🐛 Fix issue with commands if EEPROM disabled 2020-10-11 19:14:43 +01:00
cp2004 8033692873 ✨ Add M503, M504, refactor parsing to helper methods 2020-10-11 19:09:07 +01:00
Manuel McLure 257deabbbe Improve detection of virtual env. 2020-10-10 19:11:21 -07:00
cp2004 78f26de1d8 ✨ Initial implementation of EEPROM in Virtual 2020-10-10 23:22:26 +01:00
Gina Häußge b96f7657e6 🥅 Detect and deny duplicate folder path config
Closes #3754
2020-10-09 13:53:00 +02:00
Gina Häußge de81591b26 Merge branch 'master' into maintenance 2020-10-08 16:22:33 +02:00
Gina Häußge 90130dcd7d 👷‍️ Fix access to current issue data 2020-10-08 15:21:16 +02:00
Gina Häußge 4392ca7352 👷‍️ Fix a syntax error in github script 2020-10-08 15:10:44 +02:00
Gina Häußge 23b6bd1101 👷‍️ Update labeler workflow with new labels 2020-10-08 15:05:53 +02:00
Gina Häußge d62b9f00de 📝 Fix documented default enable logic on custom controls
They are only disabled when the printer is disconnected, not when it
is printing. This behaviour can be overridden with the `enabled`
property.

Closes #3758
2020-10-08 13:40:13 +02:00
Gina Häußge f291fa898e Merge branch 'master' into maintenance 2020-10-08 13:01:32 +02:00
Gina Häußge 1688d8f22a 📝 Feedback controls only work if defined in config.yaml
Closes #3759
2020-10-08 12:56:55 +02:00
Gina Häußge 3c31d98c50 📝 Backport dev/contrib docs from maintenance 2020-10-08 12:56:19 +02:00
Gina Häußge 446e1b7ece 🐛 Fix issues pointed out by flake-bugbear 2020-10-08 11:50:24 +02:00
Gina Häußge bc785141e5 📝 Document daemon parameter 2020-10-08 11:21:26 +02:00
Gina Häußge 1e5d6786da Merge branch 'maintenance' into pr/3760 2020-10-08 11:20:10 +02:00
Gina Häußge d3cf2a8e35 🎨 Some additional pre-commit checks 2020-10-07 21:16:48 +02:00
cp2004 aafbd62c2d Merge remote-tracking branch 'upstream/maintenance' into maintenance 2020-10-07 18:17:43 +01:00
Gina Häußge 29726b15d1 Merge pull request #3762 from OctoPrint/improve/codestyling
Switch to using black, isort, prettier, various pre-commit hooks
2020-10-07 19:08:54 +02:00
Gina Häußge a653628acb 🎨 git-blame-ignore-revs entry for prettier 2020-10-07 18:54:40 +02:00
Gina Häußge 6b44909f21 🎨 Add prettier for js, less, yaml, json, ... 2020-10-07 18:53:49 +02:00
Gina Häußge eb37b72dc1 📝 Document .git-blame-ignore-revs 2020-10-07 18:04:07 +02:00
Gina Häußge 9ab1a56935 📝 Document coding style 2020-10-07 17:35:44 +02:00
Gina Häußge 8427383b31 🐛 Don't touch BOM test files with pre-commit 2020-10-07 17:25:46 +02:00
Gina Häußge 7c4582a0fe 🐛 Fix some bugs introduced by code styling 2020-10-07 17:12:13 +02:00
Gina Häußge 86255c7bbe 🎨 Update git-blame-ignore-revs 2020-10-07 17:11:45 +02:00
Gina Häußge a788fc255d 📝 Document pre-commit setup in pycharm 2020-10-07 16:40:49 +02:00
Gina Häußge 7599a09b0d 🎨 pre-commit: run codemods only on manual stage 2020-10-07 16:40:38 +02:00
Gina Häußge b5be8f3eae 🎨 Add codemods to pre-commit, fix flake8 2020-10-07 16:27:11 +02:00
Gina Häußge 6d6671c2a1 👷‍️ Add pre-commit linting to build workflow 2020-10-07 13:59:04 +02:00
Gina Häußge cae6730ea8 🎨 EOF/trailing whitespace/TOML&YAML check
And armed and documented pre-commit
2020-10-07 13:45:49 +02:00
Gina Häußge fbfb34df58 🎨 Switch to use of isort 2020-10-07 13:15:52 +02:00
Gina Häußge 1f93b2355a 🎨 Switch to black formatting 2020-10-07 13:13:06 +02:00
Gina Häußge 60f45ffaf6 🎨 Add git blame ignore file
To be used with --ignore-revs-file
2020-10-06 17:04:01 +02:00
cp2004 aba033ae63 🐛 Make octoprint.util.ResettableTimer daemon thread by default
See also:
* https://github.com/j7126/OctoPrint-Dashboard/pull/219

* https://github.com/jneilliii/OctoPrint-TPLinkSmartplug/pull/200

Affects plugins that use multiprocessing, since it blocks the shutdown (and release of server address binding), breaking the server.

Shouldn't be a breaking change, since it should be run daemon=True anyway to avoid the shutdown problems.
2020-10-06 15:40:15 +01:00
Gina Häußge 986312b6ae 🎨 Change set constructors to literals 2020-10-06 16:00:35 +02:00
Gina Häußge af60fd6428 🎨 Change dict constructors to literals 2020-10-06 14:57:47 +02:00
Gina Häußge 559c9b4e52 🐛 discovery: Send three SSDP notify as defined in spec 2020-10-05 11:45:50 +02:00
Gina Häußge 21c8095b8a 🥅 Protect against potential deadlock 2020-10-02 11:05:41 +02:00
Gina Häußge 8377b59217 🚸 Add new upload state "Refreshing list"
That will hopefully make it easier to determine whether any slow uploads
are caused by file processing (e.g. by plugins) in the backend during
saving, or by refreshing the file list from the backend after successful
upload.

As discussed here: https://community.octoprint.org/t/24644/13
2020-10-02 11:05:11 +02:00
Gina Häußge d06e0c5e94 📝 Document Bearer token option 2020-10-01 15:58:29 +02:00
Gina Häußge db0cf4082d 📝 Fix property name 2020-10-01 15:56:08 +02:00
Gina Häußge 0747a4d850 📝 Add version info 2020-10-01 15:53:58 +02:00
Gina Häußge 3b19d4b6fb Merge remote-tracking branch 'origin/maintenance' into maintenance 2020-10-01 15:53:29 +02:00
Gina Häußge 8a3a4ff653 ✨ New /api/server endpoint incl. safe mode info 2020-10-01 15:53:18 +02:00
Gina Häußge d652524cef Merge pull request #3756 from mjrider/Adding-bearer-token
Adding support for bearer token
2020-10-01 13:36:57 +02:00
Robbert Müller 3c1aaa24f5 Adding support for bearer token 2020-10-01 13:05:20 +02:00
Gina Häußge 26151b3c42 ⚡️ Even more aggressive caching of uploads
The LocalFileStorage now maintains its own internal cache for all
tracked folders and will only refresh entries if the last modification
of a (sub)folder has changed.
2020-10-01 11:44:50 +02:00
Gina Häußge 9a7712ed11 ✨ Support for including func args in time_this log 2020-10-01 11:43:46 +02:00
Gina Häußge 098e5f2516 🐛 Fix time_this decorator
Wasn't actually working as a decorator with parameters, and
monotonic_time also turned out to be too unprecise a time source.
2020-09-30 16:58:57 +02:00
Gina Häußge 687e6ad900 💚 Make flake8 happy again 2020-09-30 14:16:18 +02:00
Gina Häußge 22ce8e4c24 ✨ New plugin timings logging feature
If enabled (via Settings > Server > Debug options) this will write two
new files to the logging dir, plugintimings.log and plugintimings.csv,
which contain timing information for each and every hook or
implementation call on plugins registered with OctoPrint. This should
be helpful to debug any kind of performance issues caused by third
party plugins. It should also be a valuable tool to debug performance
issues with bundled plugins.

As requested in #1241
2020-09-30 13:58:47 +02:00
Gina Häußge 24204efab6 🐛 Keep null check after all 2020-09-29 15:08:12 +02:00
Gina Häußge 9611172b88 🐛 Fix caching wrapper on endpoints
At some point the last modified implementation broke, and for some
reason current Firefox also appears to be even sending an
If-Modified-Since header if an ETag is present.

This fixes caching again so that if both If-Modified-Since and
If-None-Match are present, Last-Modified and ETag will be checked,
if onlye one is present only that one will be checked, and if neither
is present the cache will always be considered stale.

Possible (at least partial) solution for #1241
2020-09-29 14:37:17 +02:00
Gina Häußge a808c58091 📝 Even more docs for octoprint.plugin.core 2020-09-29 13:58:30 +02:00
Gina Häußge d19ce0a67e ✨ backup: config flag/env var to mark restore as unsupported
cc @LongLiveCHIEF
2020-09-29 13:27:42 +02:00
Gina Häußge 3672f7bad7 ✨ Disable logout button for authheader/apikey login 2020-09-29 12:26:37 +02:00
Gina Häußge 855cdad612 ♻️ Slimmed down a method a bit 2020-09-29 11:39:50 +02:00
Gina Häußge b857fd1e24 📝 More docs for PluginInfo and PluginManager 2020-09-29 11:32:05 +02:00
Gina Häußge 9dce1e5291 🐛 Always do a passive login 2020-09-28 18:41:57 +02:00
Gina Häußge 126d370b34 🐛 Fix backwards logic 2020-09-28 18:39:19 +02:00
Gina Häußge 37210a76fa 🐛 Fix logging in via HTTP Basic Auth
We need to make sure we actually try to log in a user from API key or
auth header before checking permissions. This used to be part of the
loginui plugin that was bundled in 1.4.x, but got forgotten when
implementing that in the shape of the new dedicated login dialog that
supports custom permissions to check and redirect URLs.

Closes #3747
2020-09-28 18:02:42 +02:00
Gina Häußge e92e69b35b ⚡️ in_place option for dict_merge
Thanks for the idea, @amrsoll
2020-09-28 15:05:37 +02:00
Gina Häußge b218cbab92 Merge branch 'master' into maintenance 2020-09-28 11:49:10 +02:00
Gina Häußge 6746e8777a 👷‍️ Fix workflow syntax
It helps to actually use the correct syntax. I hate mondays.
2020-09-28 11:48:39 +02:00
Gina Häußge 81b295726f Merge branch 'master' into maintenance 2020-09-28 11:42:05 +02:00
Gina Häußge b7d749ec90 👷‍️ Have CI run on PR too
No idea why that got left out 🤦‍♀️ Thanks for the heads-up @frenkh
2020-09-28 11:39:53 +02:00
Gina Häußge 87102407c7 ✨ SWU: Fix CLI
As mentioned in

  https://community.octoprint.org/t/24481
2020-09-25 15:42:47 +02:00
Gina Häußge 8668e5d66b ✨ client: fix socket authentication 2020-09-25 14:39:05 +02:00
Gina Häußge 0b9158f727 📝 More version added info 2020-09-24 18:08:20 +02:00
Gina Häußge d98b793705 📝 Added version added info to all hooks 2020-09-23 19:10:07 +02:00
Gina Häußge 0d96f1b8ca ✨ New hook octoprint.printer.additional_state_data
Use to inject additional data into the regular state pushes to
PrinterCallbacks, including the push socket.

As requested in OctoPrint/plugins.octoprint.org#553
2020-09-23 18:55:29 +02:00
Gina Häußge 290de2f15c Merge remote-tracking branch 'origin/maintenance' into maintenance 2020-09-23 16:09:41 +02:00
Gina Häußge d30b3a398f 🐛 Fix tooltip on freshly initialized slider
Closes #3743
2020-09-23 16:09:31 +02:00
Gina Häußge fc56327e79 Merge pull request #3745 from frenck/frenck-2020-0002
Add pyenv local version to .gitignore
2020-09-23 14:59:23 +02:00
Franck Nijhof 03918703d9 Add pyenv local version to .gitignore 2020-09-23 14:45:17 +02:00
Gina Häußge 8feb5b2ff9 Merge pull request #3744 from frenck/frenck-2020-0001
Add unique ID TXT record to ZeroConf service
2020-09-23 14:10:09 +02:00
Franck Nijhof cf16ce6e64 Add unique ID TXT record to ZeroConf service 2020-09-23 13:42:45 +02:00
Gina Häußge fb6248c624 Merge branch 'master' into maintenance 2020-09-23 12:31:33 +02:00
Gina Häußge 10827e56aa 📝 Move branching/versioning into docs
... and improve phrasing.

Hopefully solves #3741
2020-09-23 12:02:47 +02:00
Gina Häußge 107926dd7e Merge pull request #3742 from cp2004/update-language-pack-link
✏️ Update link to language packs
2020-09-23 11:27:14 +02:00
Gina Häußge c0495d22c9 🐛 Remove default submit from settings forms
We only want explicitly defined form behaviour.
Otherwise stuff might be triggered by hitting
the enter key that should not be triggered.

Closes #3740
2020-09-23 11:25:32 +02:00
cp2004 030f9ac6d3 ✏️ Update link to language packs 2020-09-22 20:56:43 +01:00
Gina Häußge 786e2f860f 🐛 remove should behave the same as set and get regarding defaults 2020-09-22 16:31:09 +02:00
Gina Häußge a6fc1e715a ♻️ SWU: Clean up the settings processing 2020-09-22 16:30:26 +02:00
Gina Häußge 917dd262f9 🐛 SWU: Fix overlay_ttl updating 2020-09-22 15:00:33 +02:00
Gina Häußge d85d3f346e 🐛 SWU: Fix defaults being written to config 2020-09-22 14:59:25 +02:00
Gina Häußge 4b0ad7dc1f ✨ SWU: Support disabling individual update notifications
Implements #3733
2020-09-21 17:15:24 +02:00
Gina Häußge dd78fd3ed3 🚸 Clarify tool selection purpose & limitations
Closes #3738
2020-09-21 14:11:06 +02:00
Gina Häußge cac1e4b0bd 🐛 PMGR: Ensure log notification is actually visible
Caused by a change while analysing/solving #3729
2020-09-21 13:07:54 +02:00
Gina Häußge b8294f2cb7 ✨ SWU: Support update check overlay from plugin repo
In the future this will allow us to push changes to the update endpoints
straight to people's instances without having to ask them to manually
switch over to a new version of the plugin hosted elsewhere.

Should make future maintainer changes way easier, but also accidentally
misconfigured plugins can be fixed this way and even OctoPrint core.
2020-09-18 15:20:34 +02:00
Gina Häußge 40c21acf38 ✨ Support settings overlays from plugins 2020-09-18 12:37:12 +02:00
Gina Häußge 250842e561 ✨ Support removal of settings overlays 2020-09-17 18:23:51 +02:00
Gina Häußge 1cbc322904 🐛 Fix settings overlays
Defaults were not being merged
2020-09-17 18:23:09 +02:00
Gina Häußge 30cfc57b03 🐛 SWU: Reset config version back to 8
Comitting 9 was an accident.
2020-09-17 16:43:55 +02:00
Gina Häußge 5a9ef80f4c Merge remote-tracking branch 'origin/maintenance' into maintenance 2020-09-17 15:25:40 +02:00
Gina Häußge dee7f31e55 Merge branch 'master' into maintenance 2020-09-17 15:24:46 +02:00
Gina Häußge 9a688ab1bd 📝 SWU: Fix check docs 2020-09-17 15:24:16 +02:00
Gina Häußge cb43f46b83 🐛 SWU: Fix modification while iterating error 2020-09-17 15:23:33 +02:00
Gina Häußge cfb9c93e65 ✨ SWU: UI for release channels by plugins 2020-09-17 15:23:11 +02:00
Gina Häußge e781e9c3e8 Merge pull request #3727 from Sophist-UK/patch-1
Add terminal filter for busy protocol
2020-09-16 17:35:24 +02:00
Sophist b51d5fecd1 Add "Suppress processing responses" filter 2020-09-16 16:15:38 +01:00
Gina Häußge 64b57186da ✨ Backup: Event on creation of a backup
See #3728
2020-09-16 16:43:50 +02:00
Gina Häußge a5a3b9f8ee 🐛 Fix exception on log download upon file change
Closes #3731
2020-09-16 15:06:43 +02:00
Gina Häußge 9e5d1e9ad6 ♻️ PMGR: Further limitation of concurrent requests
Prevent multiple concurrent enabling/disabling actions and use central
promise for regular data updates from the backend.

Related to #3729
2020-09-16 13:36:59 +02:00
Gina Häußge 6ea2caa770 🐛 PMGR: Fix saving of plugin settings 2020-09-15 18:51:23 +02:00
Gina Häußge 0b92c63734 🐛 PMGR: Fix display of affected version
If we use pluginversions instead of versions for matching those should
also be the ones made available to the frontend.
2020-09-15 18:43:14 +02:00
Gina Häußge ef8903902c ✨ PMGR: Support version ranges for notices 2020-09-15 18:21:38 +02:00
Gina Häußge 9f289a0e9c 🥅 PMGR: Make sure we only fire off one request at a time
Possibly related to #3729
2020-09-15 16:08:48 +02:00
Gina Häußge 80f2ab86c1 ♻️ PMGR: Reuse notification
So far we were constantly removing and recreating a notification on each
plugin manager log event. We now only create the notification once and
then reuse/update it.

Potentially related to #3729
2020-09-15 16:07:16 +02:00
Gina Häußge ec4e2c7193 🔥 PMGR: Get rid of unused code 2020-09-15 16:04:44 +02:00
Gina Häußge cdce9a6feb 🥅 Better resilience against broken analysis queues
Closes #3726
2020-09-15 10:20:57 +02:00
Gina Häußge c1fa23d745 💚 Fix a merge error and make CI happy 2020-09-14 13:58:58 +02:00
Gina Häußge 5f7c7ecfd8 ♻️ Some minor refactoring
* better naming
  * better error resilience
2020-09-14 12:45:05 +02:00
Gina Häußge b80826dd0c Merge branch 'pr/3719' into maintenance 2020-09-14 12:44:02 +02:00
Gina Häußge d320b1c7a3 ✨ Support for "start" action command
Will (re)start the currently selected print job. Allows job control
through the printer control if supported by the firmware.

Cc @InsanityAutomation
2020-09-14 09:48:37 +02:00
Gina Häußge 7657544d74 🐛 backup: open unknown plugin file in text mode
Closes #3722
2020-09-11 10:00:59 +02:00
Gina Häußge 44b5ce144c 💚 Make flake8 happy 2020-09-10 18:17:19 +02:00
Gina Häußge 65eb45c56a ✨ backup: allow plugins to flag excludes among their data
Plugins may now implement the hook octoprint.plugin.backup.additional_excludes
to flag entries inside their data folder (or the whole data folder
in case of .) as to be excluded from backups. The list of currently
excluded folders is supplied to the hook handler as well in order
to make such a decision conditionally.

Implements #3720
2020-09-10 18:04:38 +02:00
Gina Häußge 0dd43d7bcc ✨ virtual printer: format strings for temp report 2020-09-08 15:09:38 +02:00
Gina Häußge 4cf2a673c8 🐛 pmgr: turn install API command fully async
Fixes #3668
2020-09-07 17:11:11 +02:00
Tobias Frost e83e2a4467 Hint mkstemp to create directory in the destination directory. 2020-09-07 15:10:50 +02:00
Gina Häußge 497cf925ab 🐛 Fix renames not triggering watched folder
Closes #3705
2020-09-07 13:56:52 +02:00
Gina Häußge 1d09914f8c Merge pull request #3718 from cp2004/fix/action-notification-height
Fix action command notification max height
2020-09-07 10:02:43 +02:00
cp2004 497af61712 💄 Fix max height of action command notification output 2020-09-05 21:09:55 +01:00
Gina Häußge e91fcd6387 🐛 Fix exception not being retrieved on socket error
This should hopefully close #3689

The actual result of writing to the web socket is async and a future,
since `write_message` (https://github.com/tornadoweb/tornado/blob/v5.1.1/tornado/websocke.py#L848)
returns a future. The error handling inside `send_pack` however
so far assumed synchronous behaviour (same for `rawwebsocket.py`).
Thus the exception handler there will not trigger if there's an error
while writing, and thus the connection will not have `on_close` called.

This commit works around this through a `done_callback` on the future,
which should hopefully solve it. I say should because even though I did
my best in trying to simulate the error scenario, I was never able to
trigger even the "retrieved" message, let alone a whole storm of them.
2020-09-04 17:37:29 +02:00
Gina Häußge b3bc1e75aa 🐛 Ensure download directory 2020-09-04 10:31:02 +02:00
Gina Häußge 6132f481ce 🐛 Better fix for #3701
Use the url encoded path_url for installing, don't shell quote under
windows.
2020-09-04 10:22:16 +02:00
Gina Häußge 966c473507 🐛 Fix sending of M876 while printing
We need to immediately force it into the send queue and not allow it to
get pushed into the command queue. Otherwise it will be stuck there
waiting for busy state to end instead of the emergency sending routine
triggering.

Closes #3699
2020-09-03 17:48:31 +02:00
Gina Häußge f415010337 ✨ virtual printer: M600 with busy wait & prompt
Needed for testing #3699
2020-09-03 17:46:46 +02:00
Gina Häußge cbf1fe71a5 📝 Fix docs for prompt plugin
Part 1 of fixing #3699
2020-09-03 17:29:58 +02:00
Gina Häußge e72aab3448 🐛 Fix plugin installation under Windows
If the temporary file contained characters blacklisted by
sarge.shell_quote, e.g. a ~, the shell quote would break the install
path on windows.

Considering that the path will now always be a temporary path as
generated by Tempfile, we just get rid of shell_quote altogether as it
doesn't seem to really serve any purpose now anymore.

Closes #3701
2020-09-03 17:24:27 +02:00
Gina Häußge 98c7fc8197 🐛 Fix action command parsing
Introduce two new parameters `name` and `params` for hooks to use.
2020-09-03 13:12:39 +02:00
Timofei Korostelev 105078f4b1 🎥 Added HLS webcam support.
Cherry-picked from 9e36208fed

See also #3647
2020-09-03 12:43:58 +02:00
Gina Häußge e57adfac08 Merge branch 'master' into maintenance 2020-09-03 12:38:05 +02:00
Gina Häußge bdb68ae28b Merge pull request #3690 from HackerHappyHour/update-docker-release-workflow
Update docker release workflow
2020-09-03 12:36:53 +02:00
Gina Häußge b7fab60023 Merge branch 'pr/3703' into maintenance 2020-09-03 12:34:17 +02:00
Gina Häußge 98a83e89d0 💄 Move alert box
Most of the serial connection settings require a reconnect to become
effective, not just those in the protocol fine tuning. Thus moving the
corresponding alert box to apply to the whole serial settings, not just
one sub section.

Followup to #3703, related to #3696
2020-09-03 12:32:22 +02:00
Gina Häußge fadbe7bffe Merge pull request #3702 from cp2004/maintenance
Fix Application keys manual registration not showing with no keys registered
2020-09-03 12:22:31 +02:00
Gina Häußge c4a807c090 Merge branch 'maintenance' into maintenance 2020-09-03 12:21:52 +02:00
OllisGit 513a7bf4b1 Fix JS ErrorHandling issue 3704 (#3706)
* #3704 Correction of Sentry Handling
2020-09-03 12:19:43 +02:00
Gina Häußge 69247460a1 Merge pull request #3707 from cp2004/fix/plugin-manager-tar.gz
Fix plugin manager tar.gz detection
2020-09-03 12:17:13 +02:00
cp2004 bd7ed94b4a 🐛 Fix detection of tar.gz plugins as archive type 2020-08-27 22:08:43 +01:00
cp2004 8357f344af 🐛 Make note translatable 2020-08-25 09:37:29 +01:00
cp2004 045d4b9856 ✏️ Correct spelling & formatting of alert
Silly errors...
2020-08-24 22:12:27 +01:00
cp2004 ed3a775ad2 ✏️ Add note about requiring restart for command filtering 2020-08-24 22:06:57 +01:00
cp2004 52b08b9959 ✏️ Added cp2004 to AUTHORS.md 2020-08-24 21:41:15 +01:00
cp2004 16c8eb2689 📝 Update docs screenshot to reflect change
Just replaced image, same name so hopefully still builds ok?
2020-08-24 21:33:10 +01:00
cp2004 89544ba9fb 🐛 Make manual appkeys generation visible if no keys exist 2020-08-24 21:18:00 +01:00
Brian Vanderbusch c7ef487f2b fix AUTHORS.md
accidentally left in conflict characters from rebase
2020-08-14 10:06:31 -05:00
Brian Vanderbusch 711aae9c85 cast event-type 2020-08-14 09:55:52 -05:00
Brian Vanderbusch b09c0d6819 updated AUTHORS.md 2020-08-14 09:54:54 -05:00
Brian Vanderbusch 6fed292ef1 update payload 2020-08-14 09:54:10 -05:00
Brian Vanderbusch 3dc181e3fb flatten payload
removes duplication of data, since all the points of data that we were explicitly
setting were already children of the github.event object
2020-08-14 09:54:10 -05:00
Brian Vanderbusch c235b12201 update target repository
changing to reflect updates to the OctoPrint/docker repo changing name to
OctoPrint/octoprint-docker
2020-08-14 09:54:10 -05:00
Brian Vanderbusch 5cd93e4e0f changed Repo Dispatch step values
- changed token value to use , so as to be both
more descriptive of exactly what it is used for, and also leave room for future
uses of the same token for different events (for example triggering a test workflow
on pushes or merges)

- changed repository reference to use context instead of hard coded value, to allow
workflows to work for users who fork
2020-08-14 09:54:10 -05:00
Gina Häußge 641f27af3c 🥅 Treat wss/ws as https/http in origin check
See https://community.octoprint.org/t/22819/37
2020-08-12 12:28:15 +02:00
Gina Häußge 72eec66208 Merge branch 'maintenance' of github.com:OctoPrint/OctoPrint into maintenance 2020-08-12 12:04:43 +02:00
Gina Häußge 2fb60bd40f Merge branch 'master' into maintenance 2020-08-12 12:04:30 +02:00
Gina Häußge f79d217ffa 📝 More docs updates 2020-08-12 12:04:17 +02:00
Gina Häußge ab016b5ccd Merge pull request #3687 from urish/fix-action-pause
Fix: "pause" action command doesn't work with filament runout detection on Marlin
2020-08-12 12:02:18 +02:00
Uri Shaked a11c3895ef 🐛 Fix pause action command on Marlin
When Marlin pauses due the filament run out, it sends the following line:

```
//action:pause filament_runout 0
```

The current code compares the entire string with `pause`, so Marlin's action is silently ignored.
This fix compares the first word with `pause`, so it should work correctly with Marlin filament run out detection feature.
2020-08-11 23:52:18 +03:00
Gina Häußge 82754a5213 📝 Update appearance config docs 2020-08-11 12:49:24 +02:00
Gina Häußge 5ca20f741a 🐛 Disable Set button when no rate is entered 2020-08-11 11:58:52 +02:00
Gina Häußge 4d82f2a4c6 🐛 Fix default extrusion length display
Closes #3686
2020-08-11 10:19:12 +02:00
Gina Häußge 0de671a1de Merge branch 'master' into maintenance 2020-08-10 16:32:30 +02:00
Gina Häußge 1306c6f7be 📝 Fix docs build against Sphinx 3.2.0 2020-08-10 16:28:21 +02:00
Gina Häußge 2a19480084 📝 Update versioning scheme and PR instructions 2020-08-10 16:07:35 +02:00
Gina Häußge 5df72729d1 🐛 Fix login behind prefix URL 2020-08-10 14:38:37 +02:00
Gina Häußge 4bf2896413 🔖 maintenance is now actually 1.5.0.dev
We are switching to PROPER semver and going forward will release
maintenance releases with increased minor instead of patch, and leave
patch increases to hotfixes.
2020-08-10 14:27:01 +02:00
Gina Häußge 09c2800181 🐛 Fix a wrong settings key
Closes #3679
2020-08-06 17:53:11 +02:00
Gina Häußge 3111846ddc 🐛 Gracefully handle non existing Accept-Encoding header
See https://community.octoprint.org/t/22738
2020-08-06 16:12:41 +02:00
Gina Häußge 33d28e6226 🥅 Increase default sockjs timeout
See #3502
2020-08-06 15:02:02 +02:00
Gina Häußge 8ea4adce56 Merge branch 'staging/hotfix' into maintenance
# Conflicts:
#	.versioneer-lookup
2020-08-06 12:42:17 +02:00
Gina Häußge 45d3e7c864 🔖 Preparing hotfix release of 1.4.2 2020-08-06 12:41:11 +02:00
Gina Häußge 89412a761a 🐛 Work around for a watchdog Py2 bug
If the PollingObserver is used under Py2 on a directory that contains
utf8 file names, the default listdir implementation (scandir isn't
natively available under Py2) will generate unicode instead of str. Due
to an insufficent instance check in watchdog that will lead to a
misidentification of an entry as an DirEntry object instead of a str,
and the attempt to read the name property from that will cause an
AttributeError.

We monkey patch watchdog to use our bundled scandir backport where
needed instead of trying to fix the instance check, as that will perform
better anyhow.

Closes #3676
2020-08-06 12:19:41 +02:00
Gina Häußge b8b3cdde53 🥅 Better resilience against watchdog errors on startup
See #3676
2020-08-06 12:19:41 +02:00
Gina Häußge 8c829048af 🐛 pmgr: fix max upload size
Closes #3674
2020-08-06 12:19:41 +02:00
Gina Häußge 14a5f89b59 🐛 Fix download filename parsing
Closes #3678
2020-08-06 12:19:41 +02:00
Khoi 65d5d8963b remove any double quotes from filename obtained from content-disposition header, if any 2020-08-06 12:19:41 +02:00
Gina Häußge ea58e48dad 🔖 staging/hotfix is 1.4.2.dev, maintenance is 1.4.3.dev 2020-08-06 12:19:41 +02:00
Gina Häußge 0a605ccb12 👷‍️ Action based issue labeling 2020-08-05 16:24:12 +02:00
Gina Häußge 5a33ecf63b 🐛 pmgr: fix max upload size
Closes #3674
2020-08-05 12:20:01 +02:00
Gina Häußge abbbd926bc 🐛 discovery: fix an exception during shutdown 2020-08-05 11:51:50 +02:00
Gina Häußge ad6230074a 🐛 Work around for a watchdog Py2 bug
If the PollingObserver is used under Py2 on a directory that contains
utf8 file names, the default listdir implementation (scandir isn't
natively available under Py2) will generate unicode instead of str. Due
to an insufficent instance check in watchdog that will lead to a
misidentification of an entry as an DirEntry object instead of a str,
and the attempt to read the name property from that will cause an
AttributeError.

We monkey patch watchdog to use our bundled scandir backport where
needed instead of trying to fix the instance check, as that will perform
better anyhow.

Closes #3676
2020-08-05 11:10:04 +02:00
Gina Häußge 58fa6004bb 🥅 Better resilience against watchdog errors on startup
See #3676
2020-08-05 11:07:21 +02:00
Gina Häußge 1d55e488ae 🥅 Enable checksum when manually streaming
Apparently some firmware variants (?) out there now require that, and
it actually makes sense in general.

Closes #3659
2020-08-04 17:43:37 +02:00
Gina Häußge ffb2a0ed73 Merge branch 'master' into maintenance 2020-08-04 14:24:58 +02:00
Gina Häußge 0364130dd3 ⬆️ Upgrade cypress 2020-08-04 14:14:47 +02:00
Gina Häußge ac967499f3 Merge branch 'master' into maintenance 2020-08-04 12:03:09 +02:00
Gina Häußge e49d0b0c22 💚 Use fixed umask for tests 2020-08-03 10:50:57 +02:00
Gina Häußge a846fd8f83 ✅ Add E2E for basic settings dialog behaviour 2020-08-03 10:31:25 +02:00
Gina Häußge c9186edd34 Merge branch 'master' into maintenance
# Conflicts:
#	.github/workflows/test_install.yml
#	docs/development/environment.rst
2020-08-03 10:02:00 +02:00
Gina Häußge e7e04271fd 💚 Fix tests broken by 894178918 2020-08-03 09:59:56 +02:00
Gina Häußge 894178918b 🐛 Set sensible permissions on (uploaded) files
chmod to 0o664 $ ~UMASK after moving to final destination.

Should fix #3571
2020-07-31 16:52:42 +02:00
Gina Häußge 05cd917693 ♻ Remove no longer needed compatibility layer 2020-07-31 15:12:51 +02:00
Gina Häußge ffde393c66 ♻ Use vendored zeroconf only on Py2
Adjusted vendored version to match (used) signatures of current py3
only versions. Use official builds under Py3
2020-07-31 15:05:40 +02:00
Gina Häußge 252b9b7e41 🐛 Fix two __eq__ methods in vendored zeroconf lib 2020-07-31 13:34:31 +02:00
Gina Häußge b0247597f9 ⚡️ Speed improvements
Backported from jstasiak/python-zeroconf#205 by @nallath
2020-07-31 13:28:14 +02:00
Gina Häußge fb8fcb0685 ♻ Vendor bundle python-zeroconf
We need to use an older version for Python 2 compatibility reasons but
need to fix some things on that.
2020-07-31 13:13:41 +02:00
Gina Häußge cae900b1fb 🥅 Try up to three times to check for connectivity
Apparently some machines out there are a bit flaky after boot and it can
take a bit for connectivity to work. As suggested by @fieldOfView in

  https://community.octoprint.org/t//177/9

we thus check connectivity three times in a row if negative before
reporting it as negative.
2020-07-31 13:04:27 +02:00
Gina Häußge 65937a9244 💚 Make flake 8 happy 2020-07-31 12:50:02 +02:00
Gina Häußge 06637280e5 ♻ Discovery: Switch to python-zeroconf
Pybonjour is no longer maintained and Python 2 only.

Closes #3664
2020-07-31 12:45:23 +02:00
Gina Häußge c57c2b5a2b Merge branch 'staging/maintenance' into maintenance
# Conflicts:
#	src/octoprint/server/util/sockjs.py
2020-07-29 12:21:17 +02:00
Gina Häußge 462f90979d Merge pull request #3658 from shaver/patch-1
Fix typo in appkeys key response spec
2020-07-29 11:19:00 +02:00
Mike Shaver 3b6be8b4b9 Fix typo in appkeys key response spec
The documentation labels the field as being `apikey`, but it's `api_key` on the wire.
2020-07-27 15:56:34 -04:00
Gina Häußge 87cd0a88fb Merge branch 'staging/maintenance' into maintenance 2020-07-22 14:52:41 +02:00
Gina Häußge 6165e5b0f0 💚 Fix flaky connect test 2020-07-22 14:48:15 +02:00
Gina Häußge d47ea73dfc 🐛 Only ever send 1 line on continue_sending
Otherwise we might spam our send queue leading to a bunch of lines
piling up inside it, making cancelling/pausing take longer and longer.

Potential fix for #3649
2020-07-22 14:31:50 +02:00
Gina Häußge f62addc5e8 🎨 Fix some comments & log output 2020-07-22 14:30:42 +02:00
Gina Häußge 8b939d89a5 ✨ Basic printer control & backup/restore on recovery page 2020-07-21 15:59:21 +02:00
Gina Häußge b973b5fab2 ✨ Login dialog now supports permission check
That way we can display a login dialog if we require a specific set of
permissions, which then also gets displayed if the user is logged in but
lacks them.

If the user is already logged in and has the requested permissions, an
immediate redirect to the redirect URI is triggered.
2020-07-21 15:58:50 +02:00
Gina Häußge c1bddcd594 ✏️ Fix a comment 2020-07-21 15:56:05 +02:00
Gina Häußge b1e2121682 ✨ New recovery endpoint & refactoring
At /recovery/ there's now a (for now basic) recovery dialog that
currently allows the core functionality from the system command menu, so
shutting down and rebooting the system, restarting OctoPrint and
restarting OctoPrint in safe mode. The most important part here is the
ability to restart in safe mode, as that will allow to get OctoPrint
back into working order if an errant third party plugin or language
pack has made the standard UI non functional.

For that reason, no third party plugins are enabled or utilized on the
recovery dialog, even the theming hook is aggressively error resilient.

In order to still allow to authenticate the user (no one but ADMIN
should be allowed to use the recovery UI) the loginui plugin has been
merged into core as its own endpoint /login/ which coreui and recovery
can redirect to. This is a welcome change considering that the loginui
was absolutely necessary anyhow, and it being a plugin was merely a side
effect of backporting from forcelogin. This has now been cleaned up.
2020-07-20 17:00:31 +02:00
Gina Häußge b3d094db02 👷‍️ Allow manually triggering the build 2020-07-15 17:17:03 +02:00
Gina Häußge bc015da547 🚸 Default to libx264 for timelapses
Hopefully the hardware out there should be up to it by now and combined
with the in-browser video reviews it would be a pity to still default
to mpeg2.
2020-07-15 17:10:09 +02:00
Gina Häußge a9ad2aa2fa Merge branch 'pr/3625' into maintenance
# Conflicts:
#	src/octoprint/static/css/octoprint.css
2020-07-15 17:08:06 +02:00
Gina Häußge 232d5ce54f ♻ Use isTimelapseViewable
... and fix its logic ;)
2020-07-15 17:07:25 +02:00
Gina Häußge 8f508067e6 Merge branch 'staging/maintenance' into maintenance 2020-07-15 14:21:51 +02:00
Gina Häußge dbd7f719f6 📝 Document new virtual printer settings 2020-07-13 14:32:09 +02:00
Gina Häußge 63135a4b2b Merge branch 'staging/maintenance' into maintenance 2020-07-13 14:27:30 +02:00
Gina Häußge 003b80689e ✨ Support parsing of M33 and M20 w/ long names
As to my knowledge no firmware currently implements M20 with long file
names like this:

  Begin file list
  UGLYNA~1.GCO 2342 Uglyname with some_longer-name.gcode
  End file list

However, as proposed by myself back in 2016 that would make the most
sense (contrary to M33, which requires n+1 requests to get all metadata
from the printer), so OctoPrint now supports it and firmwares are
welcome to implement it accordingly to finally implement a *usable* way
to retrieve long filenames that doesn't saturate the serial connection
for an undeterminable amount of time just to retrieve a list of file
names.

Compare MarlinFirmware/Marlin#4733.

Also add parsing of the (not really parser friendly) output of M33.

Note that OctoPrint will not send M33 on its own even though it now
supports parsing its response. There's no capability flag for this as
far as documented, and there appears to exist a GCODE clash according
to https://reprap.org/wiki/G-code, so just blindly sending M33 to the
printer from core might cause severe issues.

Users may instead add active querying for the long name (if not included
in the M20 response) through a plugin, as demonstrated in

  https://gist.github.com/foosel/cadc38123687a46816a1d3e1d160d48a

Closes #1600
2020-07-13 13:48:14 +02:00
Gina Häußge df66dd9abf ✨ Virtual: Support M33 & M20 w/ long name 2020-07-13 13:39:58 +02:00
Gina Häußge b20c15f56d 🚸 Improve disconnect response while not operational
We don't want to try to send our beforeDisconnect script if we aren't
properly connected, as that will severely delay Disconnect execution, so
we now limit that to operational states and thus allow a quick(er)
connection abort during auto detection or connection attempt.
2020-07-09 15:41:46 +02:00
Gina Häußge 1b05e782bf 🐛 Don't drop state messages due to rate limits
Instead hold them back until the next slot.

Otherwise we might never get the final switch to Offline as after that
there are no current data upgrades anymore.
2020-07-09 14:00:36 +02:00
Gina Häußge d628f11388 Merge branch 'staging/maintenance' into maintenance 2020-07-08 13:58:47 +02:00
Gina Häußge 6c891a3e29 Merge branch 'staging/maintenance' into maintenance 2020-07-06 22:30:58 +02:00
Gina Häußge 7f6d2c9582 🔖 maintenance is now 1.4.2.dev 2020-07-06 14:33:16 +02:00
jneilliii 1746820d69 enables a timelapse preview modal for mp4 files 2020-07-04 20:46:49 -04:00
577 changed files with 132277 additions and 83391 deletions

No files matched your search

+11 -7
View File
@@ -8,19 +8,23 @@ end_of_line = lf
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
max_line_length = 90
[**.py]
indent_style = tab
indent_size = 4
[src/octoprint/vendor/sockjs/**.py]
indent_style = space
indent_size = 4
[**.yaml]
indent_size = 2
[src/octoprint/static/js/app/**.js]
indent_style = space
indent_size = 4
[.travis.yml]
indent_style = space
[src/octoprint/static/js/login/**.js]
indent_size = 4
[src/octoprint/static/js/recovery/**.js]
indent_size = 4
[src/octoprint/static/less/octoprint.less]
indent_size = 2
+16
View File
@@ -0,0 +1,16 @@
# refs to ignore during git blame, use with --ignore-revs-file
# Switch to black formatting
1f93b2355a2816918e11a55e61b42010d15a6720
5f2a95d154650366078b0d387e5b01427c4340c0
# Switch to prettier formatting
6b44909f21ee39237b7504cd31ffa6cf28275c33
# EOF/trailing whitespace check
#cae6730ea87da18bd6ebfeaf3e1e9cd354390939
# dict_to_literal, set_to_literal, not_in, flake8 fixes
#af60fd642832736966104ae71d852d745397c749
#986312b6ae7eeadcaf620cc99d53b23794be83b6
#b5be8f3eaec18ae2a88110a3a16c552931d493dd
+3
View File
@@ -0,0 +1,3 @@
# someone from the docker-maintainers team will be requested for review
# whenever the trigger_docker workflow is changed in a Pull Request
.github/workflows/trigger_docker.yml @OctoPrint/docker-maintainers
+3 -3
View File
@@ -17,7 +17,7 @@ or request features within OctoPrint (not OctoPi, not any OctoPrint
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
question ..."), that belongs on the community forum at
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
@@ -37,7 +37,7 @@ Thank you!
#### What were you doing?
<!--
<!--
Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
@@ -61,7 +61,7 @@ to also include a link to a file with which to reproduce the problem.
#### Did the same happen when running OctoPrint in safe mode?
<!--
<!--
Test if you can reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.
+4 -4
View File
@@ -16,15 +16,15 @@ checklist:
made sure your changes don't interfere with current development by
talking it through with the maintainers, e.g. through a
Brainstorming ticket
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
new feature, or maintenance if it's a bug fix or improvement of
existing functionality for the current stable version (no PRs
existing functionality for the current stable version (no PRs
against master or anything else please)
* [ ] Your PR was opened from a custom branch on your repository
(no PRs from your version of master, maintenance or devel please),
e.g. dev/my_new_feature or fix/my_bugfix
* [ ] Your PR only contains relevant changes: no unrelated files,
no dead code, ideally only one commit - rebase and squash your PR
no dead code, ideally only one commit - rebase and squash your PR
if necessary!
* [ ] Your changes follow the existing coding style
* [ ] If your changes include style sheets: You have modified the
@@ -37,7 +37,7 @@ checklist:
* [ ] You have added yourself to the AUTHORS.md file :)
<!--
Describe your PR further using the template provided below. The more
Describe your PR further using the template provided below. The more
details the better!
-->
+15 -15
View File
@@ -1,18 +1,18 @@
accessControl:
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
plugins:
virtual_printer:
enabled: true
tracking:
enabled: false
virtual_printer:
enabled: true
tracking:
enabled: false
server:
firstRun: false
onlineCheck:
enabled: false
pluginBlacklist:
enabled: false
secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
seenWizards:
backup: null
corewizard: 3
tracking: null
firstRun: false
onlineCheck:
enabled: false
pluginBlacklist:
enabled: false
secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
seenWizards:
backup: null
corewizard: 3
tracking: null
+14 -14
View File
@@ -1,22 +1,22 @@
admin:
active: true
apikey: null
groups:
active: true
apikey: null
groups:
- admins
- users
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
permissions: []
roles:
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
permissions: []
roles:
- user
- admin
settings: {}
settings: {}
user:
active: true
apikey: null
groups:
active: true
apikey: null
groups:
- users
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
permissions: []
roles:
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
permissions: []
roles:
- user
settings: {}
settings: {}
+73 -18
View File
@@ -1,8 +1,11 @@
name: Build
on:
push:
pull_request:
types: [opened, sychronize, reopened]
release:
types: [published, prereleased]
workflow_dispatch:
jobs:
build:
@@ -28,6 +31,70 @@ jobs:
name: dist
path: dist
lint-black:
name: 🧹 black
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run black
run: |
pre-commit run --hook-stage manual black --all-files --show-diff-on-failure
lint-prettier:
name: 🧹 prettier
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run prettier
run: |
pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure
lint-isort:
name: 🧹 isort
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run isort
run: |
pre-commit run --hook-stage manual isort --all-files --show-diff-on-failure
lint-flake8:
name: 🧹 Flake8
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run flake8
run: |
pre-commit run --hook-stage manual flake8 --all-files
test-unit:
name: 🧪 Unit tests
strategy:
@@ -47,22 +114,6 @@ jobs:
run: |
pytest
test-flake8:
name: 🧪 Flake8
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up test dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run test suite
run: |
flake8 src/ tests setup.py
test-install:
name: 🧪 Installation tests
needs: build
@@ -121,8 +172,8 @@ jobs:
with:
working-directory: tests/cypress
browser: chrome
start: 'octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000'
wait-on: 'http://127.0.0.1:5000/online.txt'
start: "octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000"
wait-on: "http://127.0.0.1:5000/online.txt"
- name: ⬆ Upload screenshots
uses: actions/upload-artifact@v1
@@ -141,6 +192,10 @@ jobs:
name: 📦 Publish on TestPyPI
if: github.event_name == 'release'
needs:
- lint-black
- lint-prettier
- lint-isort
- lint-flake8
- test-unit
- test-install
- test-e2e
+64
View File
@@ -0,0 +1,64 @@
name: "Issue Labeler"
on:
issues:
types: [opened, edited, closed, reopened]
jobs:
label-opened-and-edited:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
let labels = [];
let setLabels = false;
context.payload.issue.labels.forEach(label => { labels.push(label.name) });
switch (context.payload.action) {
case 'opened':
case 'edited': {
if (context.payload.issue.title.match(/\[request\]|feature request/i)) {
labels.push('request');
labels = labels.filter(label => label !== 'triage');
setLabels = true;
}
if (context.payload.issue.title.match(/\[rc feedback\]/i)) {
labels.push('rc feedback');
labels = labels.filter(label => label !== 'triage');
setLabels = true;
}
if (labels.length === 0) {
labels.push('triage');
setLabels = true;
}
break;
}
case 'closed': {
if (labels.includes('bug') || labels.includes('request') || labels.includes('improvement')) {
labels.push('done');
setLabels = true;
}
break;
}
case 'reopened': {
if (labels.includes('done')) {
labels = labels.filter(label => label !== 'done');
setLabels = true;
}
break;
}
}
if (setLabels) {
github.issues.setLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
labels: labels
})
}
+4 -4
View File
@@ -1,8 +1,8 @@
name: 'Lock outdated issues & PRs'
name: "Lock outdated issues & PRs"
on:
schedule:
- cron: '0 0 * * *'
- cron: "0 0 * * *"
jobs:
lock:
@@ -12,5 +12,5 @@ jobs:
uses: dessant/lock-threads@v2
with:
github-token: ${{ github.token }}
issue-lock-comment: ''
pr-lock-comment: ''
issue-lock-comment: ""
pr-lock-comment: ""
+5 -5
View File
@@ -6,7 +6,7 @@ on:
- master
workflow_dispatch:
schedule:
- cron: '0 */12 * * *'
- cron: "0 */12 * * *"
jobs:
install-branch:
@@ -35,14 +35,14 @@ jobs:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful'
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful"
- name: 📧 Discord failure notification
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed'
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed"
install-latest:
name: Install latest release
@@ -69,11 +69,11 @@ jobs:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful'
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful"
- name: 📧 Discord failure notification
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed'
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed"
+33 -4
View File
@@ -4,15 +4,44 @@ on:
types:
- released
- prereleased
push:
branches:
- maintenance
- devel
jobs:
trigger:
dispatch_releases:
runs-on: ubuntu-latest
if: github.event_name != 'push'
steps:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
repository: OctoPrint/docker
event-type: octoprint-release
client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}", "event-name": "${{ github.event_name }}", "event-type": "${{ github.event.action }}"}'
repository: ${{ github.repository_owner }}/octoprint-docker
event-type: ${{ github.event_name }}
client-payload: '{"tag_name": "${{ github.event.release.tag_name }}"}'
dispatch_canary:
runs-on: ubuntu-latest
if: github.event_name == 'push' && github.ref == 'refs/heads/maintenance'
steps:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
repository: ${{ github.repository_owner }}/octoprint-docker
event-type: "canary"
client-payload: '{"tag_name": "${{ github.sha }}"}'
dispatch_bleeding:
runs-on: ubuntu-latest
if: github.event_name == 'push' && github.ref == 'refs/heads/devel'
steps:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
repository: ${{ github.repository_owner }}/octoprint-docker
event-type: "bleeding"
client-payload: '{"tag_name": "${{ github.sha }}"}'
+2
View File
@@ -2,6 +2,7 @@ src/octoprint/templates/_data/AUTHORS.md
src/octoprint/templates/_data/CHANGELOG.md
src/octoprint/templates/_data/SUPPORTERS.md
src/octoprint/templates/_data/THIRDPARTYLICENSES.md
src/octoprint/plugins/pi_support/.local_debug
docs/_build
devtools
@@ -35,6 +36,7 @@ pypy
.eggs
.mypy_cache
.pytest_cache
.python-version
.tox
venv*
+44
View File
@@ -0,0 +1,44 @@
exclude: ^(src/octoprint/vendor/|src/octoprint/static/js/lib|src/octoprint/static/vendor|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/|.*\.css|.*\.svg)
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-case-conflict
- id: check-json
- id: check-yaml
- id: check-toml
- id: check-merge-conflict
- id: fix-encoding-pragma
- repo: https://github.com/OctoPrint/codemods
rev: devel
hooks:
- id: codemod_dict_to_literal
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- id: codemod_set_to_literal
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- id: codemod_not_in
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.5.4
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
- id: black
args: ["--config", "black.toml"]
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.1
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.1.2
hooks:
- id: prettier
+15
View File
@@ -0,0 +1,15 @@
src/octoprint/static/js/lib
src/octoprint/static/vendor
src/octoprint/static/less/bootstrap
src/octoprint/static/less/font-awesome.less
*.md
*.css
**/package.json
**/package-lock.json
**/*.min.js
docs
build
dist
venv
venv2
venv3
+11
View File
@@ -0,0 +1,11 @@
printWidth: 90
tabWidth: 4
semi: true
trailingComma: "none"
singleQuote: false
quoteProps: consistent
bracketSpacing: false
overrides:
- files: ["*.yaml", "*.yml", "*.json", "*.less"]
options:
tabWidth: 2
-1
View File
@@ -5,4 +5,3 @@ host = https://www.transifex.com
file_filter = translations/<lang>/LC_MESSAGES/messages.po
source_file = translations/messages.pot
source_lang = en
+12 -9
View File
@@ -18,19 +18,22 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.4.1
# maintenance is currently the branch for preparation of maintenance release 1.5.0
# so are any fix/... and improve/... branches
maintenance 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
fix/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
improve/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
maintenance 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev
fix/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev
improve/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.4.1rc5
# staging/hotfix is the branch for preparation of the 1.5.2 hotfix release
staging/hotfix 1.5.2 38256815ef6d6dd602e0fac949a17fbf8f30f838 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.5.0rc4
# so is regressionfix/...
staging/maintenance 1.4.1rc5 458ab91f915307857941f839a1b743430b8786a4 pep440-dev
regressionfix/.* 1.4.1rc5 458ab91f915307857941f839a1b743430b8786a4 pep440-dev
staging/maintenance 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev
regressionfix/.* 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev
# staging/devel is currently inactive (but has the 1.4.1rc4 namespace)
staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev
# every other branch is a development branch and thus gets resolved to 1.5.0-dev for now
.* 1.5.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
# every other branch is a development branch and thus gets resolved to 2.0.0.dev for now
.* 2.0.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
+8
View File
@@ -121,7 +121,15 @@ date of first contribution):
* [Josh Friend](https://github.com/joshfriend)
* [Lachlan Cresswell](https://github.com/lachyc)
* [Khoi Pham](https://github.com/osubuu)
* [Timofei Korostelev](https://github.com/chudsaviet)
* [Federico Nembrini](https://github.com/FedericoNembrini)
* [Uri Shaked](https://github.com/urish)
* [Brian Vanderbusch](https://github.com/LongLiveCHIEF)
* [Charlie Powell](https://github.com/cp2004)
* [Ollis Git](https://github.com/OllisGit)
* [Sophist](https://github.com/Sophist-UK)
* [Manuel McLure](https://github.com/ManuelMcLure)
* ["j7126"](https://github.com/j7126)
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
+1
View File
@@ -0,0 +1 @@
OctoPrint's Code of Conduct can be found at [octoprint.org/conduct/](https://octoprint.org/conduct/).
+62 -117
View File
@@ -39,7 +39,7 @@ nothing but ticket management.
[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
changes to the plugin system, please get in touch on the
[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.
@@ -49,7 +49,7 @@ 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.
> 👉 **Note**
>
>
> A bot is in place that monitors new tickets, automatically
> categorizes them and checks new bug reports for usage of the provided template.
> That bot will only bother you if you open a ticket that appears to be a bug (no
@@ -71,12 +71,12 @@ following section *completely* and also follow the instructions in the
1. **Make sure you are at the right location**. This is the bug tracker
of the official version of OctoPrint, which is the 3D print server and
corresponding web interface itself.
**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
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://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
[here](https://github.com/guysoft/OctoPi). If you have any kind of specific
@@ -125,17 +125,17 @@ following section *completely* and also follow the instructions in the
makes it more difficult due to on top of having to figure out the original problem
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://community.octoprint.org)
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
there.
### What should I include in a bug report?
First of all make sure your use **a descriptive title**. "It doesn't work"
and similar unspecific complaints are NOT descriptive titles.
**Always use the following template, even if only adding a "me too" to an
**Always use the following template, even if only adding a "me too" to an
existing ticket**:
```
@@ -152,7 +152,7 @@ or request features within OctoPrint (not OctoPi, not any OctoPrint
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
question ..."), that belongs on the community forum at
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
@@ -172,7 +172,7 @@ Thank you!
#### What were you doing?
<!--
<!--
Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
@@ -195,7 +195,7 @@ to also include a link to a file with which to reproduce the problem.
#### Did the same happen when running OctoPrint in safe mode?
<!--
<!--
Test if you can reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.
@@ -287,9 +287,10 @@ See [How to open the Javascript Console in different browsers](https://webmaster
## Setting up a development environment
See [the corresponding chapter in the documentation](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment).
This also includes information on how to run the test suite and how to build
the documentation.
See [the corresponding chapter in the documentation](https://docs.octoprint.org/en/master/development/environment.html).
This also includes information on how to run the test suite and how to build
the documentation, the bundled virtual printer plugin and OctoPrint's versioning
and branching strategy.
## Pull requests
@@ -297,11 +298,12 @@ the documentation.
consider if it wouldn't be better suited for a plugin.** As a general rule
of thumb, any feature that is only of interest to a small sub group should
be moved into a plugin. If the current plugin system doesn't allow you to
implement your feature as a plugin, create a "Brainstorming" ticket to get
implement your feature as a plugin, please get in touch on the
[forums](https://community.octoprint.org/c/development) to get
the discussion going on how best to solve *this* in OctoPrint's plugin
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
code or appearance, please get in touch on the
[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
@@ -310,19 +312,20 @@ the documentation.
just cause unnecessary work and frustration for everyone or
possibly get the PR rejected.
3. Create your pull request **from a custom branch** on your end (e.g.
`dev/myNewFeature`)[1].
`improve/myNewFeature`)[1].
4. Create your pull request **only against the `maintenance` or `devel` branch**:
* if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
*small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
* otherwise: `devel` branch
* if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
*small* backwards compatible new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
* if it's a bigger backwards compatible new feature: please [get in touch](https://community.octoprint.org/c/development) first to avoid
wasting work that doesn't match the current direction of the project or implement as a plugin.
* if it's any breaking backwards incompatible change: `devel` branch. In case of big changes, [get in touch](https://community.octoprint.org/c/development) first.
5. Create **one pull request per feature/bug fix**.
6. Make sure there are **only relevant changes** included in your PR. No
changes to unrelated files, no additional files that don't belong (e.g.
commits of your full virtual environment). Make sure your PR consists
**ideally of only one commit** (use git's rebase and squash functionality).
7. Make sure you **follow the current coding style**. This means:
* Tabs instead of spaces in the Python files[2]
* Spaces instead of tabs in the JavaScript sources
* Spaces for indenting and alignment, indentation width 4.
* English language (code, variables, comments, ...)
* Comments where necessary: Tell *why* the code does something like it does
it, structure your code
@@ -333,29 +336,41 @@ the documentation.
from experiments).
8. Ensure your changes **pass the existing unit tests**. PRs that break
those cannot be accepted. You can run the unit tests locally (after
[initial development environment setup with "develop" dependencies](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment))
[initial development environment setup with "develop" dependencies](https://docs.octoprint.org/en/master/development/environment.html))
by running
```
nosetests --with-doctest
pytest
```
in the OctoPrint checkout folder. A [travis build](https://travis-ci.org/foosel/OctoPrint)
is also setup so that if the tests should fail, your PR will be marked
in the OctoPrint checkout folder. An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild)
is also setup so that if the tests should fail, your PR will be marked
accordingly.
9. **Test your changes thoroughly**. That also means testing with usage
scenarios you don't normally use, e.g. if you only use access control, test
without and vice versa. If you only test with your printer, test with the
virtual printer and vice versa. State in your pull request how you tested
your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
department, but we are trying to change that, so any new code already covered
with a test suite helps a lot!
10. In your pull request's description, **state what your pull request does**,
9. Run the **pre-commit check suite** against your changes. You can run that (after
[initial development environment setup with "develop" dependencies](https://docs.octoprint.org/en/master/development/environment.html))
by running
```
pre-commit run --hook-stage manual --all-files
```
in the OctoPrint checkout folder. If you install the pre-commit hooks via
`pre-commit install` (which you really should!) this will even be taken care of for you prior to committing.
An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild)
is in place that will run these checks - if they fail your PR will be marked accordingly.
10. **Test your changes thoroughly**. That also means testing with usage
scenarios you don't normally use. If you only test with your printer, test with the
virtual printer and vice versa. State in your pull request how you tested
your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
department, but we are trying to change that, so any new code already covered
with a test suite helps a lot!
11. In your pull request's description, **state what your pull request does**,
as in, what feature does it implement, what bug does it fix. The more
thoroughly you explain your intent behind the PR here, the higher the
chances it will get merged fast. There is a template provided below
that can help you here.
11. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
12. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
file** :)
Template to use for Pull Request descriptions:
@@ -374,81 +389,13 @@ Template to use for Pull Request descriptions:
#### Further notes
```
## How is OctoPrint versioned?
See [the corresponding chapter in the documentation](https://docs.octoprint.org/en/master/development/versioning.html).
## What do the branches mean?
There are three main branches in OctoPrint:
* `master`: The master branch always contains the current stable release. It
is *only* updated on new releases. Will have a version number following
the scheme `<x>.<y>.<z>` (e.g. `1.2.9`) or - if it's absolutely necessary to
add a commit after release to this branch - `<x>.<y>.<z>.post<commits since x.y.z>`
(e.g. `1.2.9.post1`).
* `maintenance`: Improvements and fixes of the current release that make up
the next release go here. More or less continuously updated. You can consider
this a preview of the next release version. It should be very stable at all
times. Anything you spot in here helps tremendously with getting a rock solid
next stable release, so if you want to help out development, running the
`maintenance` branch and reporting back anything you find is a very good way
to do that. Will usually have a version number following the scheme
`<x>.<y>.<z+1>.dev<commits since increase of z>` for an OctoPrint version of `<x>.<y>.<z>`
(e.g. `1.2.10.dev12`).
* `devel`: Ongoing development of new features that will go into the next bigger
release (MINOR version number increases) will happen on this branch. Usually
kept stable, sometimes stuff can break though or lose backwards compatibility
temporarily. Can be considered the "bleeding edge". All PRs should target
*this* branch. Important improvements and fixes from PRs here are backported to
`maintenance` as needed. Will usually have a version number following the
scheme `<x>.<y+1>.0.dev<commits since increase of y>` for a current OctoPrint version
of `<x>.<y>.<z>` (e.g. `1.3.0.dev123`).
* `rc/maintenance`: This branch is reserved for future releases that have graduated from
the `maintenance` branch and are now being pushed on the "Maintenance"
pre release channel for further testing. Version number follows the scheme
`<x>.<y>.<z>rc<n>` (e.g. `1.2.9rc1`).
* `staging/maintenance`: Any preparation for potential follow-up RCs takes place here.
Version number follows the scheme `<x>.<y>.<z>rc<n+1>.dev<commits since increase of n>` (e.g.
`1.2.9rc1.dev3`) for a current Maintenance RC of `<x>.<y>.<z>rc<n>`.
* `rc/devel`: This branch is reserved for future releases that have graduated from
the `devel` branch and are now being pushed on the "Devel" pre release channel
for further testing. Version number follows the scheme `<x>.<y+1>.0rc<n>` (e.g. `1.3.0rc1`)
for a current stable OctoPrint version of `<x>.<y>.<z>`.
* `staging/devel`: Any preparation for potential follow-up Devel RCs takes place
here. Version number follows the scheme `<x>.<y>.0rc<n+1>.dev<commits since increase of n>` (e.g.
`1.3.0rc1.dev12`) for a current Devel RC of `<x>.<y>.0rc<n>`.
Additionally, from time to time you might see other branches pop up in the repository.
Those usually have one of the following prefixes:
* `fix/...`: Fixes under development that are to be merged into the `maintenance`
and `devel` branches.
* `improve/...`: Improvements under development that are to be merged into the
`maintenance` and `devel` branches.
* `dev/...` or `feature/...`: New functionality under development that is to be merged
into the `devel` branch.
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a few
older development branches that are slowly being migrated or deleted.
## How OctoPrint is versioned
OctoPrint follows the [semantic versioning scheme](http://semver.org/) of **MAJOR.MINOR.PATCH**.
The **PATCH** version number is the one increasing most often due to OctoPrint's maintenance releases.
Releases that only change the patch number indicate that they contain bug fixes and small improvements
of existing functionality. Example: 1.2.8 to 1.2.9.
The **MINOR** version number increases with releases that add a lot of new functionality and
large features. Example: 1.2.x to 1.3.0.
Finally, the **MAJOR** version number increases if there are breaking API changes that concern any of the
documented interfaces (REST API, plugin interfaces, ...). So far this hasn't happened. Example: 1.x.y to 2.0.0.
OctoPrint's version numbers are automatically generated using [versioneer](https://github.com/warner/python-versioneer)
and depend on the selected git branch, nearest git tag and commits. The generated version number
should always be [PEP440](https://www.python.org/dev/peps/pep-0440/) compatible. Unless a git tag
is used for version number determination, the version number will also contain the git hash within
the local version identifier to allow for an exact determination of the active code base
(e.g. `1.2.9.dev68+g46c7a9c`). Additionally, instances with active uncommitted changes will contain
`.dirty` in the local version identifier.
See [the corresponding chapter in the documentation](https://docs.octoprint.org/en/master/development/branches.html).
## History
@@ -477,14 +424,12 @@ the local version identifier to allow for an exact determination of the active c
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
* 2018-10-18: Allow PRs against `maintenance` branch for improvements and small
new features, suggest getting in touch on the forum for larger changes
* 2020-08-10: Update versioning scheme and PR instructions
* 2020-09-23: Move branch & versioning into development docs
* 2020-10-07: Introduce `pre-commit`
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
to your PR's branch will also become part of your PR, so if you create a
PR from your version of `devel` chances are high you'll add changes to the
PR that do not belong to the PR.
* [2] - Yes, we know that this goes against PEP-8. OctoPrint started out as
a fork of Cura and hence stuck to the coding style found therein. Changing
it now would make the history and especially `git blame` completely
unusable, so for now we'll have to deal with it (this decision might be
revisited in the future).
+17 -17
View File
@@ -1,13 +1,20 @@
# OctoPrint
<p align="center"><img src="https://octoprint.org/assets/img/logo.png" alt="OctoPrint's logo" /></p>
<h1 align="center">OctoPrint</h1>
![GitHub release](https://img.shields.io/github/v/release/OctoPrint/OctoPrint?logo=github&logoColor=white)
![PyPI](https://img.shields.io/pypi/v/OctoPrint?logo=python&logoColor=white)
![Build status](https://img.shields.io/github/workflow/status/OctoPrint/OctoPrint/Build)
[![Community Forum](https://img.shields.io/discourse/users?logo=discourse&logoColor=white&server=https%3A%2F%2Fcommunity.octoprint.org)](https://community.octoprint.org)
[![Discord](https://img.shields.io/discord/704958479194128507?label=discord&logo=discord&logoColor=white)](https://discord.octoprint.org)
[![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d)
<p align="center">
<img src="https://img.shields.io/github/v/release/OctoPrint/OctoPrint?logo=github&logoColor=white" alt="GitHub release"/>
<img src="https://img.shields.io/pypi/v/OctoPrint?logo=python&logoColor=white" alt="PyPI"/>
<img src="https://img.shields.io/github/workflow/status/OctoPrint/OctoPrint/Build" alt="Build status"/>
<a href="https://community.octoprint.org"><img src="https://img.shields.io/discourse/users?logo=discourse&logoColor=white&server=https%3A%2F%2Fcommunity.octoprint.org" alt="Community Forum"/></a>
<a href="https://discord.octoprint.org"><img src="https://img.shields.io/discord/704958479194128507?label=discord&logo=discord&logoColor=white" alt="Discord"/></a>
<a href="https://twitter.com/OctoPrint3d"><img src="https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow" alt="Twitter Follow"/></a>
<a href="https://octoprint.org/conduct/"><img src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg" alt="Contributor Covenant"/></a>
<a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code style: black"/></a>
<a href="https://github.com/prettier/prettier"><img src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square" alt="Code style: prettier"/></a>
<a href="https://pycqa.github.io/isort/"><img src="https://img.shields.io/badge/%20imports-isort-%231674b1" alt="Imports: isort"/></a>
<a href="https://github.com/pre-commit/pre-commit"><img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white" alt="pre-commit"/></a>
</p>
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
@@ -27,7 +34,7 @@ The official plugin repository can be reached at [plugins.octoprint.org](https:/
**OctoPrint's development wouldn't be possible without the [financial support by its community](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
If you enjoy OctoPrint, please consider becoming a regular supporter!**
![Screenshot](http://i.imgur.com/dF3noFp.png)
![Screenshot](https://octoprint.org/assets/img/screenshot-readme.png)
You are currently looking at the source code repository of OctoPrint. If you already installed it
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
@@ -56,7 +63,7 @@ For information about how to go about submitting bug reports or pull requests, p
Installation instructions for installing from source for different operating
systems can be found [on the forum](https://community.octoprint.org/tags/c/support/guides/15/setup).
If you want to run OctoPrint on a Raspberry Pi, you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
If you want to run OctoPrint on a Raspberry Pi, you really should take a look at [OctoPi](https://github.com/guysoft/OctoPi)
which is a custom SD card image that includes OctoPrint plus dependencies.
The generic steps that should basically be done regardless of operating system
@@ -69,13 +76,6 @@ you already have Python 2.7, 3.6 or 3.7, pip and virtualenv and their dependenci
parameter, e.g. `virtualenv --python=python3 venv`.
2. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install OctoPrint`
Or alternatively, for an install from source:
1. Checkout OctoPrint: `git clone https://github.com/OctoPrint/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
3. Create a user-owned virtual environment therein: `virtualenv venv`
4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .`
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
for details.
+1 -1
View File
@@ -6,6 +6,6 @@ Always update to the latest version of OctoPrint to keep up with security patche
## Reporting a Vulnerability
Email to security@octoprint.org.
Email to security@octoprint.org.
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
+8 -5
View File
@@ -18,18 +18,20 @@ thanks to everyone who contributed!
* D Brian Kimmel
* DeltaMaker 3D Printers
* Dennis Breining
* Eric Berry
* Eric Betts
* Ernesto Martinez
* Franziska Kunsmann
* GadgetAngel
* George Robles
* Greg Holloway
* Hog Duske
* Hopewell Medical Acupuncture Center
* Hugh Blemings
* jean-claude migneault
* Jefferson Hunt
* Jeremy Cole
* Joe Pasqua
* John Robinson
* John Gregory Robinson
* Joshua Wills
* Justin Kaufman
* Kaile Riser
@@ -41,10 +43,11 @@ thanks to everyone who contributed!
* Kyle Menigoz
* LA 3D Printer Repair
* Lee Dohm
* Loyal Moses
* Makespace Madrid
* Mark Walker
* Marvin Nahmias
* Michael Aumock
* Michael Begala
* Miles Flavel
* Mosaic Manufacturing
* Neil R. Goldberg
@@ -54,6 +57,7 @@ thanks to everyone who contributed!
* Raise3D
* Randy C. Will
* Ranjib Dey
* Richard McGuire
* Richard Michaud
* Rigid3D
* Robert Gusek
@@ -62,8 +66,7 @@ thanks to everyone who contributed!
* Sebastien Andrivet
* Stefan Krister
* Steve Thompson
* Stewart Danos
* Sven Mueller
* Ulrich Kempken
and 1932 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
and 2147 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
+1
View File
@@ -12,6 +12,7 @@
* [css-element-queries](https://github.com/marcj/css-element-queries): MIT
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
* [Flot](http://www.flotcharts.org/): MIT
* [HLS.js](https://github.com/video-dev/hls.js): Apache License 2.0
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
* [JQuery](http://jquery.com/): MIT
* [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
+21
View File
@@ -0,0 +1,21 @@
[tool.black]
line-length = 90
include = '''
(
(
src
| tests
| .github
).*\.pyi?$
)|(
setup\.py
)
'''
exclude = '''
(
src/octoprint/vendor # we want to still be able to apply patches from upstream w/o
# match issues
)
'''
+25
View File
@@ -145,6 +145,31 @@ Temperature offset
- Number
- Temperature offset for the printer's heated bed.
.. _sec-api-datamodel-printer-resends:
Resend stats
------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``count``
- 1
- int
- Number of resend requests received since connecting.
* - ``transmitted``
- 1
- int
- Number of transmitted lines since connecting.
* - ``ratio``
- 1
- int
- Percentage of resend requests vs transmitted lines. Value between 0 and 100.
.. _sec-api-datamodel-jobs:
+7 -3
View File
@@ -319,7 +319,8 @@ Upload file or create folder
Upload a file to the selected ``location`` or create a new empty folder on it.
Other than most of the other requests on OctoPrint's API which are expected as JSON, this request is expected as
``Content-Type: multipart/form-data`` due to the included file upload.
``Content-Type: multipart/form-data`` due to the included file upload. A ``Content-Length`` header specifying
the full length of the request body is required as well.
To upload a file, the request body must at least contain the ``file`` form field with the
contents and file name of the file to upload.
@@ -341,6 +342,7 @@ Upload file or create folder
Host: example.com
X-Api-Key: abcdef...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Length: 430
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode"
@@ -350,7 +352,7 @@ Upload file or create folder
T0
G21
G90
...
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Disposition: form-data; name="select"
@@ -400,6 +402,7 @@ Upload file or create folder
Host: example.com
X-Api-Key: abcdef...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Length: 263
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Disposition: form-data; name="file"; filename*=utf-8''20mm-%C3%BCml%C3%A4ut-b%C3%B6x.gcode
@@ -409,7 +412,7 @@ Upload file or create folder
T0
G21
G90
...
------WebKitFormBoundaryDeC2E3iWbTv1PwMC--
.. sourcecode:: http
@@ -440,6 +443,7 @@ Upload file or create folder
Host: example.com
X-Api-Key: abcdef...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMD
Content-Length: 246
------WebKitFormBoundaryDeC2E3iWbTv1PwMD
Content-Disposition: form-data; name="foldername"
+9 -1
View File
@@ -18,7 +18,7 @@ authorization workflow implemented by the bundled :ref:`Application Keys Plugin
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
The API key must either be supplied in the custom HTTP header ``X-Api-Key``, e.g.
.. sourcecode:: http
@@ -26,6 +26,14 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
Host: example.com
X-Api-Key: abcdef...
or as a ``Bearer`` token in the ``Authorization`` header, e.g.
.. sourcecode:: http
GET /api/files HTTP/1.1
Host: example.com
Authorization: Bearer abcdef...
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
.. sourcecode:: http
+1
View File
@@ -9,6 +9,7 @@ REST API
general.rst
version.rst
server.rst
connection.rst
files.rst
job.rst
+4 -2
View File
@@ -205,8 +205,10 @@ Retrieve information about the current job
},
"estimatedPrintTime": 8811,
"filament": {
"length": 810,
"volume": 5.36
"tool0": {
"length": 810,
"volume": 5.36
}
}
},
"progress": {
+9
View File
@@ -177,6 +177,15 @@ Data model
- 0..*
- List of String
- Lines for the serial communication log (special messages)
* - ``resends``
- 1
- :ref:`Resend stats <sec-api-datamodel-printer-resends>`
- Current resend statistics for the connection
* - ``plugins``
- 0..1
- Map of plugin identifiers to additional data
- Additional data injected by plugins via the :ref:`octoprint.printer.additional_state_data hook <sec-plugins-hooks-plugin-printer-additional_state_data>`,
indexed by plugin identifier. Structure of additional data is determined by the plugin.
.. _sec-api-push-datamodel-event:
+36
View File
@@ -0,0 +1,36 @@
.. _sec-api-server:
******************
Server information
******************
.. http:get:: /api/server
.. versionadded:: 1.5.0
Retrieve information regarding server status. Returns a JSON object with two keys, ``version`` containing
the server version and ``safemode`` containing one of ``settings``, ``incomplete_startup`` or ``flag``
to indicate the reason the server is running in safe mode, or the boolean value of ``false`` if it's not
running in safe mode.
**Example Request**
.. sourcecode:: http
GET /api/server HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
**Example Response**
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"server": "1.5.0",
"safemode": "incomplete_startup"
}
:statuscode 200: No error
+2 -112
View File
@@ -354,84 +354,22 @@ Data model
==========
The data model on the settings API mostly reflects the contents of
:ref:`config.yaml <sec-configuration-config_yaml>`. The settings tree
returned by the API contains the following fields, which are directly
mapped from the same fields in ``config.yaml`` unless otherwise noted:
:ref:`config.yaml <sec-configuration-config_yaml>`, which are directly
mapped, with the following exceptions:
.. list-table::
:header-rows: 1
* - Field
- Notes
* - ``api.enabled``
-
* - ``api.key``
- Only maps to ``api.key`` in ``config.yaml`` if request is sent with admin rights, set to ``n/a`` otherwise.
Starting with OctoPrint 1.3.3 setting this field via :ref:`the API <sec-api-settings-save>` is not possible,
only :ref:`regenerating it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
possible through `config.yaml`.
* - ``api.allowCrossOrigin``
-
* - ``appearance.name``
-
* - ``appearance.color``
-
* - ``appearance.colorTransparent``
-
* - ``appearance.defaultLanguage``
-
* - ``appearance.showFahrenheitAlso``
-
* - ``feature.gcodeViewer``
- Maps to ``gcodeViewer.enabled`` in ``config.yaml``
* - ``feature.sizeThreshold``
- Maps to ``gcodeViewer.sizeThreshold`` in ``config.yaml``
* - ``feature.mobileSizeThreshold``
- Maps to ``gcodeViewer.mobileSizeThreshold`` in ``config.yaml``
* - ``feature.temperatureGraph``
-
* - ``feature.waitForStart``
-
* - ``feature.alwaysSendChecksum``
-
* - ``feature.neverSendChecksum``
-
* - ``feature.sdSupport``
-
* - ``feature.sdRelativePath``
-
* - ``feature.sdAlwaysAvailable``
-
* - ``feature.swallowOkAfterResend``
-
* - ``feature.repetierTargetTemp``
-
* - ``feature.externalHeatupDetection``
-
* - ``feature.keyboardControl``
-
* - ``feature.pollWatched``
-
* - ``feature.ignoreIdenticalResends``
-
* - ``feature.modelSizeDetection``
-
* - ``feature.firmwareDetection``
-
* - ``feature.printCancelConfirmation``
-
* - ``feature.blockWhileDwelling``
-
* - ``folder.uploads``
-
* - ``folder.timelapse``
-
* - ``folder.timelapseTmp``
- Maps to ``folder.timelapse_tmp`` in ``config.yaml``
* - ``folder.logs``
-
* - ``folder.watched``
-
* - ``plugins``
- Plugin settings as available from ``config.yaml`` and :class:`~octoprint.plugin.SettingsPlugin` implementations
* - ``printer.defaultExtrusionLength``
@@ -446,8 +384,6 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
- Available serial ports
* - ``serial.baudrateOptions``
- Available serial baudrates
* - ``serial.autoconnect``
-
* - ``serial.timeoutConnection``
- Maps to ``serial.timeout.connection`` in ``config.yaml``
* - ``serial.timeoutDetection``
@@ -460,50 +396,18 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
- Maps to ``serial.timeout.temperatureTargetSet`` in ``config.yaml``
* - ``serial.timeoutSdStatus``
- Maps to ``serial.timeout.sdStatus`` in ``config.yaml``
* - ``serial.log``
-
* - ``serial.additionalPorts``
-
* - ``serial.additionalBaudrates``
-
* - ``serial.longRunningCommands``
-
* - ``serial.checksumRequiringCommands``
-
* - ``serial.helloCommand``
-
* - ``serial.ignoreErrorsFromFirmware``
-
* - ``serial.disconnectOnErrors``
-
* - ``serial.triggerOkForM29``
-
* - ``serial.supportResendsWIthoutOk``
-
* - ``serial.maxTimeoutsIdle``
- Maps to ``serial.maxCommunicationTimeouts.idle`` in ``config.yaml``
* - ``serial.maxTimeoutsPrinting``
- Maps to ``serial.maxCommunicationTimeouts.printing`` in ``config.yaml``
* - ``serial.maxTimeoutsLong``
- Maps to ``serial.maxCommunicationTimeouts.long`` in ``config.yaml``
* - ``server.commands.systemShutdownCommand``
-
* - ``server.commands.systemRestartCommand``
-
* - ``server.commands.serverRestartCommand``
-
* - ``server.diskspace.warning``
-
* - ``server.diskspace.critical``
-
* - ``system.actions``
- Whole subtree taken from ``config.yaml``
* - ``system.events``
- Whole subtree taken from ``config.yaml``
* - ``temperature.profiles``
- Whole subtree taken from ``config.yaml``
* - ``temperature.cutoff``
-
* - ``terminalFilters``
- Whole subtree taken from ``config.yaml``
* - ``webcam.streamUrl``
@@ -512,17 +416,3 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
- Maps to ``webcam.snapshot`` in ``config.yaml``
* - ``webcam.ffmpegPath``
- Maps to ``webcam.ffmpeg`` in ``config.yaml``
* - ``webcam.bitrate``
-
* - ``webcam.ffmpegThreads``
-
* - ``webcam.ffmpegVideoCodec``
-
* - ``webcam.watermark``
-
* - ``webcam.flipH``
-
* - ``webcam.flipV``
-
* - ``webcam.rotate90``
-
+90 -2
View File
@@ -6,8 +6,8 @@ Util
.. _sec-api-util-test:
Test paths or URLs
==================
Various tests
=============
.. http:post:: /api/util/test
@@ -107,6 +107,15 @@ Test paths or URLs
The ``resolution`` command returns :http:statuscode:`200` with a :ref:`Resolution test result <sec-api-util-datamodel-resolutiontestresult>`
when the test could be performed. The status code of the response does NOT reflect the test result!
address
Tests whether a provided address (or, if none is provided, the client's remote address) is
a LAN address and if so returns the subnet specifier in CIDR format.
* ``address``: the address to test. If not set, the client's remote address will be used
The ``address`` command return :http:statuscode:`200` with a :ref:`Address test result <sec-api-util-datamodel-addresstestresult>`
when the test could be performed. The status code of the response does NOT reflect the test result!
Requires the ``ADMIN`` permission.
**Example 1**
@@ -320,6 +329,58 @@ Test paths or URLs
"result": true
}
**Example 8**
Test whether the client's address is a LAN address.
.. sourcecode:: http
POST /api/util/test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: application/json
{
"command": "address"
}
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"address": "192.168.1.3",
"is_lan_address": true,
"subnet": "192.168.0.0/16"
}
**Example 9**
Test whether ``8.8.8.8`` is a LAN address.
.. sourcecode:: http
POST /api/util/test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: application/json
{
"command": "address",
"address": "8.8.8.8"
}
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"address": "8.8.8.8",
"is_lan_address": false
}
:json command: The command to execute, currently either ``path`` or ``url``
:json path: ``path`` command only: the path to test
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
@@ -337,6 +398,7 @@ Test paths or URLs
:json port: ``server`` command only: the port to test
:json protocol: ``server`` command only: the protocol to test
:json name: ``resolution`` command only: the host name to test
:json address: ``address`` command only: the address to test
:statuscode 200: No error occurred
.. _sec-api-util-datamodel:
@@ -466,3 +528,29 @@ Resolution test result
- 1
- bool
- ``true`` if the check passed.
.. _sec-api-util-datamodel-addresstestresult:
Address test result
-------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``address``
- 1
- string
- The address that was tested.
* - ``is_lan_address``
- 1
- bool
- ``true`` if the address is a LAN address, false otherwise.
* - ``subnet``
- 0..1
- string
- The detected subnet, if address is a LAN address.
+1 -1
View File
@@ -6,7 +6,7 @@ Version information
.. http:get:: /api/version
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
Retrieve information regarding server and API version. Returns a JSON object with three keys, ``api`` containing
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).
@@ -3,7 +3,9 @@
Action Command Notification support
===================================
The OctoPrint Action Command Notification Support Plugin comes bundled with OctoPrint (starting with 1.4.1).
.. versionadded:: 1.4.1
The OctoPrint Action Command Notification Support Plugin comes bundled with OctoPrint.
It allows firmware to trigger notifications users with the ``PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW`` permission
using :ref:`action commands <sec-features-action_commands>` about relevant events. These notifications will be shown
@@ -3,7 +3,9 @@
Action Command Prompt support
=============================
The OctoPrint Action Command Prompt Support Plugin comes bundled with OctoPrint (starting with 1.3.9).
.. versionadded:: 1.3.9
The OctoPrint Action Command Prompt Support Plugin comes bundled with OctoPrint.
It allows firmware to trigger dialog prompts for logged in users using :ref:`action commands <sec-features-action_commands>`, e.g. to wait
for user acknowledgement or allow the user to choose between options, and also to close the dialog again
@@ -72,8 +74,7 @@ To display the :ref:`above dialog <fig-bundledplugins-action_command_prompt-exam
//action:prompt_choice Filament swapped
//action:prompt_show
If the user clicks the button, assuming a ``selection_command`` of ``M876 S{choice}`` is configured, OctoPrint
will send back ``M876 S0`` (0-based index).
If the user clicks the button, OctoPrint will send back ``M876 S0`` (0-based index).
A more complicated example with three options would be the following:
+3 -1
View File
@@ -3,7 +3,9 @@
Announcement Plugin
===================
The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11).
.. versionadded:: 1.2.11
The OctoPrint Announcement Plugin comes bundled with OctoPrint.
It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new
plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels
+4 -2
View File
@@ -3,7 +3,9 @@
Application Keys Plugin
=======================
The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10).
.. versionadded:: 1.3.10
The OctoPrint Application Keys Plugin comes bundled with OctoPrint.
It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it
on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed
@@ -320,7 +322,7 @@ Key response
- Multiplicity
- Type
- Description
* - ``apikey``
* - ``api_key``
- 1
- str
- the API key generated for the application
+126 -4
View File
@@ -3,9 +3,11 @@
Backup Plugin
=============
.. versionadded:: 1.3.10
The OctoPrint Backup Plugin comes bundled with OctoPrint (starting with 1.3.10).
It allows the creation and restoration of backups of OctoPrint's settings, data and installed plugins [#]_.
It allows the creation and restoration [#1]_ of backups of OctoPrint's settings, data and installed plugins [#2]_.
This allows easy migration
to newly setup instances as well as making regular backups to prevent data loss.
@@ -21,6 +23,19 @@ As long as plugins adhere to the standard of storing their data and settings in
data will be part of the backup. Note that the backups made by the Backup Plugin will *not* be part of any backups -
you'll need to persist the resulting zip files yourself!
.. _sec-bundledplugins-backup-configuration:
Configuring the plugin
----------------------
The plugin supports the following configuration keys:
* ``restore_unsupported``: If the system you are installing OctoPrint on doesn't support restoring backups or you
want to disable that feature for other reasons, set this to `true`. Alternatively you can also set the
environment variable `OCTOPRINT_BACKUP_RESTORE_UNSUPPORTED` to `true`. OctoPrint will then disable the restore
functionality. Under normal circumstances you should not have to touch this setting (OctoPrint will do its
best to autodetect whether it's able to perform restores), thus it is not exposed in the Settings dialog.
.. _sec-bundledplugins-backup-cli:
Command line usage
@@ -57,6 +72,111 @@ It adds two new commands, ``backup:backup`` and ``backup:restore``.
The ``backup:backup`` command can be useful in combination with a cronjob to create backups in regular intervals.
.. _sec-bundledplugins-backup-events:
Events
------
*Events will not be triggered by CLI operations.*
plugin_backup_backup_created
A new backup was created. On the push socket only available with a valid login session with ``Backup Access``
permission.
Payload:
* ``name``: the name of the backup
* ``path``: the path to the backup
* ``excludes``: the list of parts excluded from the backup
.. versionadded:: 1.5.0
.. _sec-bundledplugins-backup-hooks:
Hooks
-----
.. _sec-bundledplugins-backup-hooks-excludes:
octoprint.plugin.backup.additional_excludes
+++++++++++++++++++++++++++++++++++++++++++
.. py:function:: additional_excludes_hook(excludes, *args, **kwargs)
.. versionadded:: 1.5.0
Use this to provide additional paths on your plugin's data folder to exclude from the backup. Your handler also
get a list of currently excluded sub paths in the base folder, so you can react to them. E.g. exclude things
in your data folder that relate to uploaded GCODE files if `uploads` is excluded, or exclude things that relate
to timelapses if `timelapse` is excluded.
Expects a list of additional paths relative to your plugin's data folder. If you return a single `.`, your whole
plugin's data folder will be excluded from the backup.
**Example 1**
The following example plugin will create two files ``foo.txt`` and ``bar.txt`` in its data folder, but flag
``foo.txt`` as not to be backed up.
.. code-block:: python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import octoprint.plugin
import os
import io
class BackupExcludeTestPlugin(octoprint.plugin.OctoPrintPlugin):
def initialize(self):
with io.open(os.path.join(self.get_plugin_data_folder(), "foo.txt"), "w", encoding="utf-8") as f:
f.write("Hello\n")
with io.open(os.path.join(self.get_plugin_data_folder(), "bar.txt"), "w", encoding="utf-8") as f:
f.write("Hello\n")
def additional_excludes_hook(self, excludes, *args, **kwargs):
return ["foo.txt"]
__plugin_implementation__ = BackupExcludeTestPlugin()
__plugin_hooks__ = {
"octoprint.plugin.backup.additional_excludes": __plugin_implementation__.additional_excludes_hook
}
**Example 2**
In this example the plugin will create a file ``foo.txt`` in its data folder and flag its whole data folder as excluded from the
backup if uploaded GCODE files are also excluded:
.. code-block:: python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import octoprint.plugin
import os
import io
class BackupExcludeTestPlugin(octoprint.plugin.OctoPrintPlugin):
def initialize(self):
with io.open(os.path.join(self.get_plugin_data_folder(), "foo.txt"), "w", encoding="utf-8") as f:
f.write("Hello\n")
def additional_excludes_hook(self, excludes, *args, **kwargs):
if "uploads" in excludes:
return ["."]
return []
__plugin_implementation__ = BackupExcludeTestPlugin()
__plugin_hooks__ = {
"octoprint.plugin.backup.additional_excludes": __plugin_implementation__.additional_excludes_hook
}
:param excludes list: A list of paths already flagged as excluded in the backup
:return: A list of paths to exclude, relative to your plugin's data folder
:rtype: list
.. _sec-bundledplugins-backup-sourcecode:
Source code
@@ -65,6 +185,8 @@ Source code
The source of the Backup plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/backup``.
.. [#] Note that only those plugins that are available on `OctoPrint's official plugin repository <https://plugins.octoprint.org>`_
can be automatically restored. If you have plugins installed that are not available on there you'll get their
names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them.
.. [#1] Note that restore is currently unavailable on OctoPrint servers running on Windows. Additionally they may be
disabled through a config flag or an environment variable as documented :ref:`here <sec-bundledplugins-backup-configuration>`.
.. [#2] Note that only those plugins that are available on `OctoPrint's official plugin repository <https://plugins.octoprint.org>`_
can be automatically restored. If you have plugins installed that are not available on there you'll get their
names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them.
+11 -43
View File
@@ -3,11 +3,12 @@
Discovery Plugin
================
The OctoPrint Discovery Plugin comes bundled with OctoPrint (starting with 1.2.0).
.. versionadded:: 1.2.0
It allows discovery of the OctoPrint instances via SSDP/UPNP. If
`pybonjour <https://pypi.python.org/pypi/pybonjour>`_ is installed OctoPrint
will additionally support discovery via ZeroConf, also known as Bonjour or Avahi.
The OctoPrint Discovery Plugin comes bundled with OctoPrint.
It allows discovery of the OctoPrint instances via SSDP/UPNP and ZeroConf
(also known as Bonjour or Avahi).
The SSDP/UPNP support allows OctoPrint to announce itself to machines on the same
network running Microsoft Windows. You will be able to just double click on the
@@ -28,45 +29,6 @@ line) to scan for available instances.
Various discovered OctoPrint instances in Windows Explorer
.. _sec-bundledplugins-discovery-firststeps:
First Steps
-----------
.. _sec-bundledplugins-discovery-firststeps-pybonjour:
Installing pybonjour
++++++++++++++++++++
.. note::
OctoPi versions 0.12.0 and later already come with pybonjour installed and ready to go,
you don't need to perform these steps there.
.. note::
Currently there are no releases for pybonjour available on the Python Package Index PyPI. The latest pybonjour
release is still available in the `Google Code Archive <https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/pybonjour/pybonjour-1.1.1.tar.gz>`_.
Since that URL is hilariously long though, a shortened version is provided with https://goo.gl/SxQZ06 and
used in the installation instructions below.
In order for the Zeroconf discovery to work, the
`pybonjour package <https://pypi.python.org/pypi/pybonjour>`_ needs to be available
to the Python installation running OctoPrint.
It can be installed via ``pip``. Let's assume you installed OctoPrint manually
into some folder ``~/OctoPrint``. You executed ``python setup.py install`` within a
virtualenv in the same folder called ``venv``. In order to install ``pybonjour``
so it will be available to OctoPrint you'll need to do the following::
venv/bin/pip install https://goo.gl/SxQZ06
**Linux users:** You'll need to install an additional dependency for this to work, the
libdnssd compatibility layer for libavahi. On Debian/Ubuntu that can be achieved with::
sudo apt-get install libavahi-compat-libdnssd-dev
.. _sec-bundledplugins-discovery-configuration:
Configuring the plugin
@@ -74,6 +36,10 @@ Configuring the plugin
The plugin supports the following configuration keys:
* ``addresses``: List of IP addresses for which to enable discovery, if unset all
addresses available on the host will be used
* ``interfaces``: List of network interfaces for which to enable discovery, if unset
all interfaces on the host will be used
* ``publicPort``: Public port number OctoPrint is reachable under,
optional, if not set the port OctoPrint itself was started under will be used
* ``pathPrefix``: Path prefix OctoPrint is running under, optional, if not
@@ -128,6 +94,8 @@ The following snippet is a valid configuration example for the discovery plugin
plugins:
discovery:
interfaces:
- eth0
publicPort: 443
useSsl: true
zeroConf:
+2
View File
@@ -3,6 +3,8 @@
Error Tracking Plugin
=====================
.. versionadded:: 1.3.11
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/>`_.
+2
View File
@@ -3,5 +3,7 @@
File Check
==========
.. versionadded:: 1.4.1
The file check plugin - while considered bundled with OctoPrint - is a separate project on its own release
cycle and documented on `its Github repository <https://github.com/OctoPrint/OctoPrint-FileCheck>`_.
+4
View File
@@ -3,5 +3,9 @@
Firmware Check
==============
.. versionadded:: 1.3.7
The firmware check plugin - while considered bundled with OctoPrint - is a separate project on its own release
cycle and documented on `its Github repository <https://github.com/OctoPrint/OctoPrint-FirmwareCheck>`_.
It was formerly called "Printer Safety Check" and directly bundled with OctoPrint.
+2
View File
@@ -3,6 +3,8 @@
GCode Viewer Plugin
===================
.. versionchanged:: 1.4.1
The GCode Viewer plugin provides a GCode viewer based on `Alex Ustyantsev's work <https://github.com/hudbrog/gCodeViewer>`_.
.. _fig-bundledplugins-gcodeviewer-example:
-1
View File
@@ -19,7 +19,6 @@ Bundled Plugins
firmware_check.rst
gcodeviewer.rst
logging.rst
loginui.rst
pluginmanager.rst
printer_safety_check.rst
softwareupdate.rst
+2 -2
View File
@@ -3,9 +3,9 @@
Logging
=======
The OctoPrint Logging plugin comes bundled with OctoPrint starting with version 1.3.7.
.. versionadded:: 1.3.7
It implements the log management functionality that was formerly part of the core application and adds features to
The OctoPrint Logging plugin implements the log management functionality that was formerly part of the core application and adds features to
configure logging levels for sub modules through the included settings dialog.
.. _fig-bundledplugins-logging-settings:
+1 -61
View File
@@ -3,64 +3,4 @@
Login UI
========
The Login UI plugin has been bundled since OctoPrint 1.4.0 and replaces the ForceLogin plugin bundled with prior
versions since 1.3.10.
If anonymous read-only access is disabled in the :ref:`Access Control settings <sec-features-access_control>`
it provides a stand alone login dialog that gets displayed instead of OctoPrint's regular UI.
.. _fig-bundledplugins-loginui:
.. figure:: ../images/bundledplugins-loginui-dialog.png
:align: center
:alt: Login dialog
OctoPrint's login dialog.
The plugin allows theming of the dialog through :ref:`a plugin hook <sec-bundledplugins-loginui-hooks-theming>`.
.. warning::
Since the plugin is absolutely required for the case of anonymous read-only access because in this case the
UI itself could not even fully initialize due to a lack of permissions required to do so, it is hidden in the plugin
manager and cannot be disabled through that.
.. _sec-bundledplugins-loginui-hooks:
Hooks
-----
.. _sec-bundledplugins-loginui-hooks-theming:
octoprint.plugin.loginui.theming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: loginui_theming_hook(*args, **kwargs)
Support theming of the login dialog, just in case the core UI is themed as well. Use to return a list of additional
CSS file URLs to inject into the login dialog HTML.
Example usage by a plugin:
.. code-block:: python
def loginui_theming():
from flask import url_for
return [url_for("plugin.myplugin.static", filename="css/loginui_theme.css")]
__plugin_hooks__ = {
"octoprint.plugin.loginui.theming": loginui_theming
}
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
url_for like in the example above to be prepared for any configured prefix URLs.
:return: A list of additional CSS URLs to inject into the login dialog.
:rtype: A list of strings.
.. _sec-bundledplugins-loginui-sourcecode:
Source Code
-----------
The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be
found in its source repository under ``src/octoprint/plugins/loginui``.
The Login UI plugin's functionality has been merged into OctoPrint's core as of OctoPrint 1.4.2.
+3 -2
View File
@@ -3,8 +3,9 @@
Plugin Manager
==============
The OctoPrint Plugin Manager comes bundled with OctoPrint starting with
version 1.2.0.
.. versionadded:: 1.2.0
The OctoPrint Plugin Manager comes bundled with OctoPrint.
It allows management of installed plugins (listing, enabling, disabling
and uninstalling) and installing new plugins from the official
+171 -15
View File
@@ -3,10 +3,14 @@
Software Update Plugin
======================
.. versionadded:: 1.2.0
The Software Update Plugin allows receiving notifications about new releases
of OctoPrint or installed plugins which registered with it and -- if properly
configured -- also applying the found updates.
It comes bundled with OctoPrint.
.. _sec-bundledplugins-softwareupdate-firststeps:
First Steps
@@ -24,7 +28,7 @@ Settings Dialog, navigate to the Software Update section therein and once you ar
wrench icon in the upper right corner.
.. _fig-bundledplugins-softwareupdate-plugin-configuration:
.. figure:: ../images/bundledplugins-softwareupdate-plugin-configuration.png
.. figure:: ../images/bundledplugins-softwareupdate-configuration.png
:align: center
:alt: Software Update plugin configuration dialog
@@ -34,21 +38,25 @@ There you can adjust the following settings:
* **OctoPrint version tracking**: Whether you want to track OctoPrint *releases* or every *commit*. Usually you want to
select "Release" here which is also the default, unless you are a developer.
* **OctoPrint Release Channel** (if tracking releases): The release channel of OctoPrint to track for updates. If you only want stable versions,
select "Stable" here which is also the default. "Maintenance RCs" will also allow you to update to maintenance release
candidates, "Devel RCs" will also allow you to update to development release candidates. If in doubt, leave it at
"Stable". `Read more about Release Channels here <https://community.octoprint.org/t/how-to-use-the-release-channels-to-help-test-release-candidates/402>`_.
* **OctoPrint checkout folder** (if tracking git commits): This must be the path to OctoPrint's git checkout folder
* **Tracked branch** (if tracking is set to "Github Commit"): The branch that will be tracked if you set version tracking to "Github Commit".
* **OctoPrint ``pip`` target** (if tracking is set to "Release" or "Github Commit"): The argument that will be provided to ``pip`` when updating OctoPrint.
Usually you don't want to change this from its default value of ``https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip``.
* **OctoPrint checkout folder** (if tracking is set to "Local checkout"): This must be the path to OctoPrint's git checkout folder
(``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide <https://community.octoprint.org/t/setting-up-octoprint-on-a-raspberry-pi-running-raspbian/2337/>`_).
Note that since OctoPrint 1.3.6 you will no longer need to set this to be able to update to releases, only if you
want to be able to update against some bleeding edge git branch.
* **Enable ``pip`` update checks**: Whether to have OctoPrint automatically check for updates of
the ``pip`` tool that is used for updating most components.
* **Version cache TTL**: The "time to live" of the cache OctoPrint will use to temporarily persist the version information
for the various components registered with the plugin, so that they don't have to be queried from the internet every time
you load the page. Defaults to 24h, you usually shouldn't need to change that value.
* **Show notifications to users**: Whether to display update notifications (without "Update now" button) to users that cannot
apply updates.
* **Minimum free disk space**: The minimum amount of free disk space needed in order to allow software updates to be run.
More settings are available by :ref:`editing the corresponding section in config.yaml <sec-bundledplugins-softwareupdate-configuration>`.
That restart commands for OctoPrint and the whole server can be configured under Settings > Server.
Restart commands for OctoPrint and the whole server can be configured under Settings > Server.
.. _sec-bundledplugins-softwareupdate-cli:
@@ -119,9 +127,6 @@ Configuring the Plugin
plugins:
softwareupdate:
# the time-to-live of the version cache, in minutes
cache_ttl: 60
# configured version check and update methods
checks:
# "octoprint" is reserved for OctoPrint
@@ -141,6 +146,41 @@ Configuring the Plugin
# used - should normally NOT be necessary and hence set
pip_command: /path/to/pip
# the time-to-live of the version cache, in minutes, defaults to 24h
cache_ttl: 1440
# whether to show update notifications to users that cannot apply updates
notify_users: true
# whether to ignore the system throttled state reported by the pisupport plugin and
# allow updating even when the system is not running stable - really not recommended
ignore_throttled: false
# minimum free storage in MB for updates to be enabled
minimum_free_storage: 150
# URL from which to fetch check overlays
check_overlay_url: https://plugins.octoprint.org/update_check_overlay.json
# time to live of the overlay cache, defaults to 6h
check_overlay_ttl: 360
# global credentials to provide to version checks
credentials:
# GitHub API token to use for the github_release and github_commit version checks.
# Helpful if you regularly run into rate limit issues with the GitHub API using
# the default anonymous access. Use a personal access token:
# https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token
# Unset by default
github:
# Bitbucket user name and password, used by the bitbucket_commit version check if
# provided, but only if the check doesn't specify credentials on its own.
# Unset by default
bitbucket_user:
bitbucket_password:
.. _sec-bundledplugins-softwareupdate-configuration-versionchecks:
Version checks
@@ -156,10 +196,28 @@ types are currently recognized:
* ``repo``: (mandatory) Github repository to check
* ``prerelease``: ``True`` or ``False``, default ``False``, set to
``True`` to also include releases on Github marked as prerelease.
* ``release_branch``: Branch name to check against ``target_comittish``
field in Github release data - release will only be included if the
values match. Defaults to being unset, in which case no match will
be performed.
* ``prerelease_branches``: Prerelease channel definitions, optional. List of:
* ``branch``: Branch associated with the channel, acts as ID
* ``name``: Human readable name of the release channel
* ``committish``: List of values to check against ``target_comittish``
field in Github release data - release will only be included if the
values match. Defaults to being unset, in which case the ``branch``
will be matched.
.. versionadded:: 1.2.16
* ``stable_branch``: Stable channel definition, optional. Structure:
* ``branch``: Branch associated with the channel, acts as ID
* ``name``: Human readable name of the release channel
* ``commitish``: List of values to check against ``target_comittish``
field in Github release data - release will only be included if the
values match. Defaults to being unset, in which case the ``branch``
will be matched.
.. versionadded:: 1.2.16
* ``prerelease_channel``: Release channel to limit updates to. If set only
those releases will be included if their ``target_comittish`` matches
the ones associated with the release channel identified by this, either
included in ``prerelease_channels`` or the ``stable_channel``. Only
taken into account if ``prerelease`` is ``true``.
.. versionadded:: 1.2.16
* ``release_compare``: Method to use to compare between current version
information and release versions on Github. One of ``python`` (version
comparison using ``pkg_resources.parse_version``, newer version detected
@@ -193,6 +251,8 @@ types are currently recognized:
``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate
a new app password. App passwords are user specific on Bitbucket.
.. versionadded:: 1.3.5
* ``git_commit``: Checks a local git repository for new commits on its
configured remote. Additional config parameters:
@@ -204,6 +264,8 @@ types are currently recognized:
* ``package``: (mandatory) Name of the package which to check.
.. versionadded:: 1.4.0
* ``httpheader``: Checks an HTTP header on a defined URL for changes. This can be used for easy checks
against things like ``ETag`` or ``Last-Modified`` headers. Additional
config parameters:
@@ -215,12 +277,16 @@ types are currently recognized:
* ``header_prefix``: Prefix to use for the obtained value in the version display. If not provided ``header_name``
will be used. If set to an empty string, no prefix will be added.
.. versionadded:: 1.4.1
* ``jsondata``: Checks the provided JSON endpoint for changes. The JSON endpoint must return an object with the
property ``version``, which should contain the latest version, e.g. ``{"version":"1.2.3"}``. Additional
config parameters:
* ``jsondata``: (mandatory) URL from which to fetch the JSON data
.. versionadded:: 1.4.1
* ``command_line``: Uses a provided script to determine whether an update
is available. Additional config parameters:
@@ -243,12 +309,16 @@ types are currently recognized:
* ``current_version``: Version to report for both local and remote version.
.. versionadded:: 1.3.7
* ``never_current``: Always reports that an update is necessary. Useful for debugging
software update mechanisms during development. Additional config parameters:
* ``local_version``: Current local version. Defaults to ``1.0.0``.
* ``remote_version``: Remote version to offer update to. Defaults to ``1.0.1``.
.. versionadded:: 1.3.7
.. _sec-bundledplugins-softwareupdate-configuration-updatemethods:
Update methods
@@ -294,6 +364,8 @@ supported:
a countdown in the meantime. Useful for debugging software update mechanisms
during development.
.. versionadded:: 1.3.7
.. note::
To allow default configurations for multiple update methods, if more than one of
@@ -357,7 +429,69 @@ tracked:
repo: OctoPrint-SomePlugin
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
The same, but tracking all commits pushed to branch ``devel`` (thus allowing
The same, but declaring three release channels "Stable", "Maintenance RCs" (tagged on ``rc/maintenance`` or ``master``,
id ``rc/maintenance``) and "Devel RCs" (tagged on ``rc/maintenance``, ``rc/devel`` or ``master``, id ``rc/devel``),
but with "Stable" active:
.. code-block:: yaml
plugins:
softwareupdate:
checks:
some_plugin:
type: github_release
user: someUser
repo: OctoPrint-SomePlugin
stable_branch:
name: Stable
branch: master
comittish:
- master
prerelease_branches:
- name: Maintenance RCs
branch: rc/maintenance
comittish:
- rc/maintenance
- master
- name: Devel RCs
branch: rc/devel
comittish:
- rc/devel
- rc/maintenance
- master
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
And now with "Maintenance RCs" active (note the ``prerelease`` and ``prerelease_channel`` settings):
plugins:
softwareupdate:
checks:
some_plugin:
type: github_release
user: someUser
repo: OctoPrint-SomePlugin
stable_branch:
name: Stable
branch: master
comittish:
- master
prerelease_branches:
- name: Maintenance RCs
branch: rc/maintenance
comittish:
- rc/maintenance
- master
- name: Devel RCs
branch: rc/devel
comittish:
- rc/devel
- rc/maintenance
- master
prerelease: True
prerelease_channel: rc/maintenance
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
The same plugin again, but tracking all commits pushed to branch ``devel`` (thus allowing
"bleeding edge" updates):
.. code-block:: yaml
@@ -403,6 +537,28 @@ commit identifier. E.g. ``https://gist.githubusercontent.com/<user>/<gistid>/raw
``https://gist.githubusercontent.com/<user>/<gistid>/raw/<commit>/my_plugin.py``. Note that these URLs will
be cached by Github for a bit, so an update will not be immediately picked up.
.. _sec-bundledplugins-softwareupdate-configuration-credentials:
Global credentials
++++++++++++++++++
.. versionadded:: 1.5.0
Starting with OctoPrint 1.5.0, the Software Update Plugin supports supplyting a GitHub
API token to use for the ``github_release`` and ``github_commit`` version check types,
to work around possible rate limit problems if a lot of checks are to be made from a single
external IP. You may create a `personal access token <https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token>`_
and configure that as ``plugins.softwareupdate.credentials.github`` via
:ref:`config.yaml <sec-configuration-config_yaml>` in order to get a higher rate limit than with purely anonymous access.
Additionally, the username and password to use with the ``bitbucket_commit`` version check
type may also be configured via ``plugins.softwareupdate.credentials.bitbucket_user`` and
``plugins.softwareupdate.credentials.bitbucket_password`` respectively.
None of these configuration options are currently exposed on the UI and can only be used
via :ref:`config.yaml <sec-configuration-config_yaml>` or the
:ref:`config command line interface <sec-configuration-cli>`.
.. _sec-bundledplugins-softwareupdate-events:
Events
+2
View File
@@ -3,6 +3,8 @@
Anonymous Usage Tracking Plugin
===============================
.. versionadded:: 1.3.10
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.
+2
View File
@@ -3,6 +3,8 @@
Virtual Printer
===============
.. versionchanged:: 1.4.1
The Virtual Printer plugin provides a virtual printer to connect to during development. It is able to simulate various
firmware quirks, communication issues and can be heavily configured through ``config.yaml``. See
:ref:`the development documentation on details and usage <sec-development-virtual-printer>`.
+89 -69
View File
@@ -18,8 +18,8 @@ import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../src/'))
sys.path.append(os.path.abspath('sphinxext'))
sys.path.insert(0, os.path.abspath("../src/"))
sys.path.append(os.path.abspath("sphinxext"))
import octoprint._version
from datetime import date
@@ -30,32 +30,46 @@ year_current = date.today().year
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.3'
needs_sphinx = "1.3"
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid', 'sphinx.ext.intersphinx']
extensions = [
"codeblockext",
"onlineinclude",
"sphinx.ext.todo",
"sphinx.ext.autodoc",
"sphinxcontrib.httpdomain",
"sphinx.ext.napoleon",
"sphinxcontrib.mermaid",
"sphinx.ext.intersphinx",
]
todo_include_todos = True
intersphinx_mapping = {'python': ('https://docs.python.org/3', None),
'python2': ('https://docs.python.org/2', None),
'pyserial': ('https://pythonhosted.org/pyserial', None)}
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
"python2": ("https://docs.python.org/2", None),
"pyserial": ("https://pythonhosted.org/pyserial", None),
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = '.rst'
source_suffix = ".rst"
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# General information about the project.
project = 'OctoPrint'
copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since
project = "OctoPrint"
copyright = (
"%d-%d, Gina Häußge" % (year_since, year_current)
if year_current > year_since
else "%d, Gina Häußge" % year_since
)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -68,133 +82,136 @@ release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# keep_warnings = False
numfig = True
# -- Options for HTML output ---------------------------------------------------
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of built-in themes.
#html_theme = "sphinx_rtd_theme"
# html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the built-in static files,
# so a file named "default.css" will overwrite the built-in "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]
def setup(app):
app.add_css_file("theme_overrides.css")
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'OctoPrintDoc'
htmlhelp_basename = "OctoPrintDoc"
# -- Options for LaTeX output --------------------------------------------------
#latex_elements = {
# latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
@@ -203,47 +220,44 @@ htmlhelp_basename = 'OctoPrintDoc'
# Additional stuff for the LaTeX preamble.
#'preamble': '',
#}
# }
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
#latex_documents = [
# latex_documents = [
# ('index', 'OctoPrint.tex', 'OctoPrint Documentation',
# 'Gina Häußge', 'manual'),
#]
# ]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# latex_logo = None
# For "manual" documents, if this is true, then top-level headings are parts,
# not chapters.
#latex_use_parts = False
# latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'octoprint', 'OctoPrint Documentation',
['Gina Häußge'], 1)
]
man_pages = [("index", "octoprint", "OctoPrint Documentation", ["Gina Häußge"], 1)]
# If true, show URL addresses after external links.
#man_show_urls = False
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
@@ -252,19 +266,25 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'OctoPrint', 'OctoPrint Documentation',
'Gina Häußge', 'OctoPrint', 'One line description of project.',
'Miscellaneous'),
(
"index",
"OctoPrint",
"OctoPrint Documentation",
"Gina Häußge",
"OctoPrint",
"One line description of project.",
"Miscellaneous",
),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# texinfo_no_detailmenu = False
+110
View File
@@ -0,0 +1,110 @@
.. _sec-configuration-cli:
CLI
===
.. versionadded:: 1.3.0
OctoPrint provides a basic command line interface for manipulation of :ref:`config.yaml <sec-configuration-config_yaml>`:
.. code-block::
$ octoprint config --help
Usage: octoprint config [OPTIONS] COMMAND [ARGS]...
Basic config manipulation.
Options:
--help Show this message and exit.
Commands:
append_value Appends value to list behind config path.
effective Retrieves the full effective config.
get Retrieves value from config path.
insert_value Inserts value at index of list behind config key.
remove Removes a config path.
remove_value Removes value from list at config path.
set Sets a config path to the provided value.
.. code-block::
$ octoprint config append_value --help
Usage: octoprint config append_value [OPTIONS] PATH VALUE
Appends value to list behind config path.
Options:
--json
--help Show this message and exit.
.. code-block::
$ octoprint config effective --help
Usage: octoprint config effective [OPTIONS]
Retrieves the full effective config.
Options:
--json Output value formatted as JSON
--yaml Output value formatted as YAML
--raw Output value as raw string representation
--help Show this message and exit.
.. code-block::
$ octoprint config get --help
Usage: octoprint config get [OPTIONS] PATH
Retrieves value from config path.
Options:
--json Output value formatted as JSON
--yaml Output value formatted as YAML
--raw Output value as raw string representation
--help Show this message and exit.
.. code-block::
$ octoprint config insert_value --help
Usage: octoprint config insert_value [OPTIONS] PATH INDEX VALUE
Inserts value at index of list behind config key.
Options:
--json
--help Show this message and exit.
.. code-block::
$ octoprint config remove --help
Usage: octoprint config remove [OPTIONS] PATH
Removes a config path.
Options:
--help Show this message and exit.
.. code-block::
$ octoprint config remove_value --help
Usage: octoprint config remove_value [OPTIONS] PATH VALUE
Removes value from list at config path.
Options:
--json
--help Show this message and exit.
.. code-block::
$ octoprint config set --help
Usage: octoprint config set [OPTIONS] PATH VALUE
Sets a config path to the provided value.
Options:
--bool Interpret value as bool
--float Interpret value as float
--int Interpret value as int
--json Parse value from json
--help Show this message and exit.
+50 -6
View File
@@ -10,6 +10,7 @@ you can just create it - it will only get created by OctoPrint once you save set
settings.
Note that many of these settings are available from the "Settings" menu in OctoPrint itself.
They can also be configured via :ref:`config command line interface <sec-configuration-cli>`.
.. contents::
@@ -23,9 +24,6 @@ Use the following settings to enable access control:
.. code-block:: yaml
accessControl:
# whether to enable access control or not. Defaults to true
enabled: true
# The user manager implementation to use for accessing user information. Currently only a filebased
# user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml
# in the default configuration folder, see below)
@@ -74,6 +72,10 @@ Use the following settings to enable access control:
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
addRemoteUsers: false
# Secret salt used for password hashing, DO NOT TOUCH. If changed you will no longer be able to log in with your
# existing accounts.
salt: someSecretSalt
.. _sec-configuration-config_yaml-api:
API
@@ -123,6 +125,10 @@ appearance or to modify the order and presence of the various UI components:
# acrylic for its frame ;)
colorTransparent: false
# Show the internal filename in the files sidebar, if necessary
# UI change only
showInternalFilename: true
# Configures the order and availability of the UI components
components:
@@ -146,10 +152,14 @@ appearance or to modify the order and presence of the various UI components:
navbar:
- settings
- systemmenu
- plugin_announcements
- plugin_logging
- plugin_pi_support
- login
# order of sidebar items
sidebar:
- plugin_firmware_check
- connection
- state
- files
@@ -158,7 +168,7 @@ appearance or to modify the order and presence of the various UI components:
tab:
- temperature
- control
- gcodeviewer
- plugin_gcodeviewer
- terminal
- timelapse
@@ -175,17 +185,40 @@ appearance or to modify the order and presence of the various UI components:
- features
- webcam
- accesscontrol
- plugin_gcodeviewer
- api
- plugin_appkeys
- section_octoprint
- folders
- appearance
- logs
- plugin_logging
- plugin_pluginmanager
- plugin_softwareupdate
- plugin_announcements
- plugin_backup
- plugin_tracking
- plugin_errortracking
# order of user settings
usersettings:
- access
- interface
# order of wizards
wizard:
- plugin_backup
- plugin_corewizard_acl
# order of about dialog entries
about:
- about
- plugin_pi_support
- supporters
- authors
- license
- thirdparty
- plugin_pluginmanager
# order of generic templates
generic: []
@@ -222,7 +255,7 @@ appearance or to modify the order and presence of the various UI components:
tab:
- plugin_helloworld
OctoPrint will then display the tabs in the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``,
OctoPrint will then display the tabs in the order ``plugin_helloworld``, ``temperature``, ``control``, ``plugin_gcodeviewer``,
``terminal``, ``timelapse`` plus any other plugins.
@@ -774,6 +807,9 @@ Use the following settings to configure the serial connection to the printer:
# the response skips on the ok)
triggerOkForM29: true
# Percentage of resend requests among all sent lines that should be considered critical
resendRatioThreshold: 10
capabilities:
# Whether to enable temperature autoreport in the firmware if its support is detected
@@ -913,6 +949,12 @@ Use the following settings to configure the server:
# Command to shut down the system OctoPrint is running on, defaults to being unset
systemShutdownCommand: sudo shutdown -h now
# pip command associated with OctoPrint, used for installing plugins and updates,
# if unset (default) the command will be autodetected based on the current python
# executable - unless you have a really special setup this is the right way to do
# it and there should be no need to ever even touch this setting
localPipCommand: None
# Configuration of the regular online connectivity check
onlineCheck:
# whether the online check is enabled, defaults to false due to valid privacy concerns
@@ -1095,6 +1137,8 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
- name: Suppress wait responses
regex: 'Recv: wait'
- name: Suppress processing responses
regex: 'Recv: (echo:\s*)?busy:\s*processing'
.. _sec-configuration-config_yaml-webcam:
+1
View File
@@ -10,3 +10,4 @@ Configuration
yaml.rst
config_yaml.rst
logging_yaml.rst
cli.rst
+75
View File
@@ -0,0 +1,75 @@
.. _sec-development-branches:
OctoPrint's branching model
===========================
There are three main branches in OctoPrint:
``master``
The master branch always contains the current stable release plus any changes
since made to *documentation*, *CI related tests* or *Github meta files*. OctoPrint's actual
code will only be modified on new releases. Will have a version number following
the scheme ``<x>.<y>.<z>`` (e.g. ``1.5.1``).
``maintenance``
Improvements and fixes of the current release that make up
the next release go here. More or less continuously updated. You can consider
this a preview of the next release version. It should be very stable at all
times. Anything you spot in here helps tremendously with getting a rock solid
next stable release, so if you want to help out development, running the
``maintenance`` branch and reporting back anything you find is a very good way
to do that. Will usually have a version number following the scheme
``<x>.<y+1>.<0>.dev<commits since increase of y>`` for an OctoPrint version of ``<x>.<y>.<z>``
(e.g. ``1.5.0.dev114``).
``devel``
Ongoing development of what will go into the next big
release (MAJOR version number increases) will happen on this branch. Usually
kept stable, sometimes stuff can break though. Backwards incompatible changes will
be encountered here. Can be considered the "bleeding edge". Will usually have a version
number following the scheme ``<x+1>.<0>.0.dev<commits since increase of y>`` for a current
OctoPrint version of ``<x>.<y>.<z>`` (e.g. ``2.0.0.dev123``).
There are couple more RC and staging branches that see regular use:
``staging/hotfix``
Any preparation for potential hotfix releases takes place here.
Version number follows the scheme ``<x>.<y>.<z+1>`` (e.g. ``1.5.1``) for a current release
of ``<x>.<y>.<z>``.
``rc/maintenance``
This branch is reserved for future releases that have graduated from
the ``maintenance`` branch and are now being pushed on the "Maintenance"
pre release channel for further testing. Version number follows the scheme
``<x>.<y>.<z>rc<n>`` (e.g. ``1.5.0rc1``).
``staging/maintenance``
Any preparation for potential follow-up RCs takes place here.
Version number follows the scheme ``<x>.<y>.<z>rc<n+1>.dev<commits since increase of n>`` (e.g.
``1.5.0rc2.dev3``) for a current Maintenance RC of ``<x>.<y>.<z>``.
``rc/devel``
This branch is reserved for future releases that have graduated from
the ``devel`` branch and are now being pushed on the "Devel" pre release channel
for further testing. Version number follows the scheme ``<x+1>.0.0rc<n>`` (e.g. ``2.0.0rc1``)
for a current stable OctoPrint version of ``<x>.<y>.<z>``.
``staging/devel``
Any preparation for potential follow-up Devel RCs takes place
here. Version number follows the scheme ``<x>.0.0rc<n+1>.dev<commits since increase of n>`` (e.g.
``2.0.0rc2.dev12``) for a current Devel RC of ``<x>.0.0rc<n>``.
Additionally, from time to time you might see other branches pop up in the repository.
Those usually have one of the following prefixes:
``hotfix/...``
Hotfixes under development that are to be merged into the ``staging/hotfix``
and later the ``master`` branch.
``fix/...``
Fixes under development that are to be merged into the ``maintenance``
and ``devel`` branches.
``improve/...``
Improvements under development that are to be merged into the
``maintenance`` and ``devel`` branches.
``dev/...`` or ``feature/...``
New functionality under development that is to be merged
into the ``devel`` branch.
There are also a few older development branches that are slowly being migrated or deleted.
All these branches and branch patterns are set up to automatically get a correct :ref:`version number <sec-development-versions>`
generated through versioneer and thus should also be adhered to during development.
+33 -4
View File
@@ -13,8 +13,8 @@ below.
* Prerequisites:
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository:
@@ -26,8 +26,8 @@ below.
installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning
issues for the dependencies with system wide installed instances:
* PY2: ``virtualenv --python=python2 venv2``
* PY3: ``virtualenv --python=python3 venv3``
* PY2: ``virtualenv --python=python2 venv2``
.. note::
@@ -35,10 +35,11 @@ below.
binaries cannot be found on your ``PATH`` like this you'll need to specify the full paths to them here,
e.g. ``virtualenv --python=/path/to/python2/bin/python venv2``
* Activate one of the virtual environments:
* Activate one of the virtual environments (the Python 3 venv should be considered the
primary one at this point):
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
@@ -49,10 +50,20 @@ below.
* ``pip install -e '.[develop,plugins]'``
* Set up the pre-commit hooks that make sure any changes you do adhere to the styling rules:
* ``pre-commit install``
* Tell ``git`` where to find the file with revisions to exclude for ``git blame``:
* ``git config blame.ignoreRevsFile .git-blame-ignore-revs``
When the virtual environment is activated you can then:
* run the OctoPrint server via ``octoprint serve``
* run the test suite from the checked out source folder via ``pytest``
* trigger the pre-commit check suite manually from the checked out source folder via
``pre-commit run --hook-stage manual --all-files``
To switch the activated virtual environment, simply activate the new environment as described above.
@@ -106,6 +117,8 @@ Then:
source ./venv3/bin/activate
pip install --upgrade pip
pip install -e .[develop,plugins,docs]
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments.
@@ -149,6 +162,8 @@ Open the Git Bash you just installed and in that:
source ./venv3/Scripts/activate
pip install --upgrade pip
pip install -e .[develop,plugins,docs]
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-mac:
@@ -198,6 +213,8 @@ You'll need a user account with administrator privileges.
source venv/bin/activate
pip install --upgrade pip
pip install -e .[develop,plugins]
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-ides:
@@ -276,6 +293,18 @@ PyCharm
Note that this requires you to also have installed the additional ``docs`` dependencies into the Python 3 venv as
described above via ``pip install -e .[develop,plugins,docs]``.
- Settings > Tools > File Watchers (you might have to enable this, it's a bundled plugin), add new:
* Name: pre-commit
* File type: Python
* Scope: Module 'OctoPrint'
* Program: ``<OctoPrint venv3 folder>/bin/pre-commit`` (Linux) or ``<OctoPrint venv3 folder>/Scripts/pre-commit`` (Windows)
* Arguments: ``run --hook-stage manual --files $FilePath$``
* Output paths to refresh: ``$FilePath$``
* Working directory: ``$ProjectFileDir$``
* disable "Auto-save edited files to trigger the watched"
* enable "Trigger the watched on external changes"
To switch between Python 2 and 3, all you need to do now is change the Project Default Interpreter and restart
OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE.
Otherwise go through Settings.
+6 -1
View File
@@ -7,6 +7,11 @@ Development
.. toctree::
:maxdepth: 3
versioning.rst
branches.rst
environment.rst
virtual_printer.rst
profiling.rst
request-profiling.rst
If you are interested in contributing code to OctoPrint, first of all: Thank you! Please make sure to read the
`Contribution Guidelines <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md>`_!
+31
View File
@@ -0,0 +1,31 @@
.. _sec-development-versions:
OctoPrint's versioning strategy
===============================
OctoPrint's version numbers follow `PEP440 <https://www.python.org/dev/peps/pep-0440/>`_, with a version format of
**MAJOR.MINOR.PATCH** following the contract of `semantic versioning <http://semver.org/>`_.
The **PATCH** version number will increase in case of hotfix releases [#f1]_.
Releases that only change the patch number indicate that they only contain bug fixes, and usually
only hotfixes at that. Example: ``1.5.0`` to ``1.5.1``.
The **MINOR** version number increases with releases that add new functionality while maintaining
backwards compatibility on the documented APIs (both internal and external). Example: ``1.4.x`` to ``1.5.0``.
Finally, the **MAJOR** version number increases if there are breaking API changes that concern any of the
documented interfaces (REST API, plugin interfaces, ...). Example: ``1.x.y`` to ``2.0.0``.
OctoPrint's version numbers are automatically generated using a customized version of
`versioneer <https://github.com/warner/python-versioneer>`_ and depend on the selected git branch, nearest
git tag and commits. Unless a git tag is used for version number determination, the version number will
also contain the git hash within the local version identifier to allow for an exact determination of the
active code base (e.g. ``1.2.9.dev68+g46c7a9c``). Additionally, instances with active uncommitted changes
will contain ``.dirty`` in the local version identifier.
.. rubric:: Footnotes
.. [#f1] Up until 1.4.2, the PATCH version segment was the one increasing most often
due to OctoPrint's maintenance releases but with 1.5.0 this will *fully* adhere
to the concepts in semantic versioning mandating only bug fixes in patch releases.
Maintenance releases will henceforth increase the MINOR segment.
+38 -5
View File
@@ -110,11 +110,19 @@ There many configuration options via ``config.yaml`` for the virtual printer tha
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
smoothieTemperatureReporting: false
# Whether M20 responses will include filesize or not
#
# True: <filename> <filesize in bytes>
# False: <filename>
extendedSdFileList: false
# Settings related to the SD file list output
sdFiles:
# Whether M20 responses will include filesize or not
#
# True: <filename> <filesize in bytes>
# False: <filename>
size: true
# Whether M20 responses will include longname or not (only if size = true as well)
#
# True: <filename> <filesize in bytes> <longname>
# False: <filename> <filesize in bytes>
longname: false
# Forced pause for retrieving from the outgoing buffer
throttle: 0.01
@@ -192,6 +200,31 @@ There many configuration options via ``config.yaml`` for the virtual printer tha
# Simulated ambient temperature in °C
ambientTemperature: 21.3
# Response to M105 when there is a target
# Placeholders:
# - heater: The heater id (eg. T0, T1, B)
# - actual: The actual temperature of the heater
# - target: The target temperature of heater
m105TargetFormatString: {heater}:{actual:.2f}/ {target:.2f}
# Response to M105 when there is no target
# Placeholders:
# - heater: The heater id (eg. T0, T1, B)
# - actual: The actual temperature of the heater
m105NoTargetFormatString: {heater}:{actual:.2f}
# Enable virtual EEPROM
# If enabled, a file `eeprom.json` will be created in the plugin data folder
# to enable settings persistence across connections. Enables M500/1/2/4 commmands
# And a selection of other settings commands. Responses modeled on Marlin 2.0
enable_eeprom: true
# Support M503
support_m503: true
# Resend ratio to simulate noise on the line
resend_ratio: 0
.. _sec-development-virtual-printer-log:
+93
View File
@@ -109,6 +109,9 @@ ClientOpened
**Note:** Name changed in version 1.1.0
.. versionchanged:: 1.1.0
.. versionchanged:: 1.4.0
ClientAuthed
A client has authenticated a user session on the push socket.
@@ -118,6 +121,8 @@ ClientAuthed
valid login session.
* ``username``: the name of the user who authed. On the push socket only available with a valid login session.
.. versionadded:: 1.4.0
ClientClosed
A client has disconnected from the push socket.
@@ -133,12 +138,16 @@ UserLoggedIn
* ``username``: the name of the user who logged in
.. versionadded:: 1.4.0
UserLoggedOut
A user logged out. On the push socket only available with a valid login session with admin rights.
Payload:
* ``username``: the name of the user who logged out
.. versionadded:: 1.4.0
ConnectivityChanged
The server's internet connectivity changed
@@ -147,6 +156,8 @@ ConnectivityChanged
* ``old``: Old connectivity value (true for online, false for offline)
* ``new``: New connectivity value (true for online, false for offline)
.. versionadded:: 1.3.5
.. _sec-events-available_events-printer_commmunication:
Printer communication
@@ -155,6 +166,8 @@ Printer communication
Connecting
The server is attempting to connect to the printer.
.. versionadded:: 1.3.0
Connected
The server has connected to the printer.
@@ -168,6 +181,8 @@ Disconnecting
event might not always be sent when the server and printer get disconnected
from each other. Do not depend on this for critical life cycle management.
.. versionadded:: 1.3.0
Disconnected
The server has disconnected from the printer
@@ -191,6 +206,8 @@ PrinterStateChanged
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
* ``state_string``: Text representation of the new state.
.. versionadded:: 1.3.0
.. _sec-events-available_events-file_handling:
File handling
@@ -211,6 +228,8 @@ Upload
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
.. versionchanged:: 1.4.0
FileAdded
A file has been added to a storage.
@@ -226,6 +245,8 @@ FileAdded
A copied file triggers this for its new path. A moved file first triggers ``FileRemoved`` for its original
path and then ``FileAdded`` for the new one.
.. versionadded:: 1.3.3
FileRemoved
A file has been removed from a storage.
@@ -240,6 +261,8 @@ FileRemoved
A moved file first triggers ``FileRemoved`` for its original path and then ``FileAdded`` for the new one.
.. versionadded:: 1.3.3
FolderAdded
A folder has been added to a storage.
@@ -253,6 +276,8 @@ FolderAdded
A copied folder triggers this for its new path. A moved folder first triggers ``FolderRemoved`` for its original
path and then ``FolderAdded`` for the new one.
.. versionadded:: 1.3.3
FolderRemoved
A folder has been removed from a storage.
@@ -265,6 +290,8 @@ FolderRemoved
A moved folder first triggers ``FolderRemoved`` for its original path and then ``FolderAdded`` for the new one.
.. versionadded:: 1.3.3
UpdatedFiles
A file list was modified.
@@ -279,6 +306,7 @@ UpdatedFiles
reasons of backwards compatibility and will also be sent on modification of ``printables``. It will however
be removed with 1.4.0.
.. versionchanged:: 1.4.0
MetadataAnalysisStarted
The metadata analysis of a file has started.
@@ -293,6 +321,8 @@ MetadataAnalysisStarted
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
.. versionchanged:: 1.4.0
MetadataAnalysisFinished
The metadata analysis of a file has finished.
@@ -307,6 +337,8 @@ MetadataAnalysisFinished
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
.. versionchanged:: 1.4.0
FileSelected
A file has been selected for printing.
@@ -321,6 +353,8 @@ FileSelected
* ``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.
.. versionchanged:: 1.4.0
FileDeselected
No file is selected any more for printing.
@@ -334,6 +368,8 @@ TransferStarted
**Note:** Name changed in version 1.1.0
.. versionchanged:: 1.1.0
TransferDone
A file transfer to the printer's SD has finished.
@@ -365,6 +401,8 @@ PrintStarted
* ``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.
.. versionchanged:: 1.4.0
PrintFailed
A print failed.
@@ -383,6 +421,8 @@ PrintFailed
* ``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.
.. versionchanged:: 1.4.0
PrintDone
A print completed successfully.
@@ -400,6 +440,8 @@ PrintDone
* ``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.
.. versionchanged:: 1.4.0
PrintCancelling
The print is about to be cancelled.
@@ -413,6 +455,8 @@ PrintCancelling
* ``user``: the user who cancelled the print job (if available)
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
.. versionadded:: 1.3.7
PrintCancelled
The print has been cancelled.
@@ -443,6 +487,8 @@ PrintCancelled
* ``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.
.. versionchanged:: 1.4.0
PrintPaused
The print has been paused.
@@ -472,6 +518,8 @@ PrintPaused
* ``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.
.. versionchanged:: 1.4.0
PrintResumed
The print has been resumed.
@@ -489,6 +537,8 @@ PrintResumed
* ``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.
.. versionchanged:: 1.4.0
.. _sec-events-available_events-gcode_processing:
GCODE processing
@@ -543,6 +593,8 @@ PositionUpdate
* ``t``: last tool selected *through OctoPrint*
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
.. versionadded:: 1.3.0
ToolChange
A tool change command was sent to the printer. The payload contains the former current tool index and the
new current tool index.
@@ -552,6 +604,34 @@ ToolChange
* ``old``: old tool index
* ``new``: new tool index
.. versionadded:: 1.3.5
CommandSuppressed
A command was suppressed by OctoPrint due to according configuration and will not be
sent to the printer.
Payload:
* ``command``: the command that was suppressed
* ``message``: a message containing an explanation of the command suppression
* ``severity``: a severity level, either ``warn`` or ``info`` - ``warn`` indicates
that the command was suppressed probably due to a misconfiguration either inside
OctoPrint or the firmware and that it should be investigated by the user
.. versionadded:: 1.5.0
InvalidToolReported
The firmware reported a tool as invalid upon trying to select it. It has thus been marked
as invalid and further attempts to select said tool will result in the tool command
to get suppressed (and ``SuppressedCommand`` to be generated).
Payload:
* ``tool``: the tool number that was reported as invalid by the firmware
* ``fallback``: the tool number that OctoPrint will revert to
.. versionadded:: 1.5.0
.. _sec-events-available_events-timelapses:
Timelapses
@@ -577,6 +657,8 @@ CaptureFailed
* ``file``: the name of the image file that should have been saved
* ``error``: the error that was caught
.. versionadded:: 1.3.0
MovieRendering
The timelapse movie has started rendering.
@@ -669,6 +751,8 @@ SlicingProfileAdded
* ``slicer``: the slicer for which the profile was added
* ``profile``: the profile that was added
.. versionadded:: 1.2.12
SlicingProfileModified
A slicing profile was modified.
@@ -677,6 +761,8 @@ SlicingProfileModified
* ``slicer``: the slicer for which the profile was modified
* ``profile``: the profile that was modified
.. versionadded:: 1.2.12
SlicingProfileDeleted
A slicing profile was deleted.
@@ -685,6 +771,8 @@ SlicingProfileDeleted
* ``slicer``: the slicer for which the profile was deleted
* ``profile``: the profile that was deleted
.. versionadded:: 1.2.12
.. _sec-events-available_events-settings:
Settings
@@ -696,6 +784,8 @@ SettingsUpdated
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
.. versionadded:: 1.2.0
.. _sec-events-available_events-printer_profile:
Printer Profile
@@ -707,3 +797,6 @@ PrinterProfileModified
Payload:
* ``identifier``: the identifier of the modified printer profile
.. versionadded:: 1.3.12
+2
View File
@@ -3,6 +3,8 @@
Access Control
==============
.. versionchanged:: 1.4.0
OctoPrint's bundled access control feature allows granular permission control
over which users or user groups are allowed to access which parts of OctoPrint.
+7 -1
View File
@@ -21,8 +21,14 @@ Action commands are a feature defined for the GCODE based RepRap communication p
OctoPrint out of the box supports handling of the above mentioned commands:
start
When this command is received from the printer, a job is currently selected and *not* active, OctoPrint
will start it just like if the "Start"/"Restart" button had been clicked.
.. versionadded:: 1.5.0
cancel
When this command is received from the printer, OctoPrint will cancel a current print job like if the
When this command is received from the printer, OctoPrint will cancel a current print job just like if the
"Cancel" button had been clicked.
pause
+2
View File
@@ -3,6 +3,8 @@
@ Commands
==========
.. versionadded:: 1.3.7
@ commands (also known as host commands elsewhere) are special commands you may include in GCODE files streamed
through OctoPrint to your printer or send as part of GCODE scripts, through the Terminal Tab, the API or plugins.
Contrary to other commands they will never be sent to the printer but instead trigger functions inside OctoPrint.
+15 -3
View File
@@ -172,9 +172,10 @@ Controls
turn the button red.
* - ``enabled``
- (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control
should be enabled or not. This allow to override the default logic for this (disabled if printer is offline
or currently printing). The JavaScript snippet is ``eval``'d and processed in a context where the control
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
should be enabled or not. This allows to override the default logic for the enable state
of the control (disabled if printer is offline). The JavaScript snippet is ``eval``'d and processed
in a context where the control it is part of is provided as local variable ``data`` and the
``ControlViewModel`` is available as ``self``.
* - ``input``
- (Optional) A list of definitions of input parameters for a ``command`` or ``commands``, to be rendered as
additional input fields. ``command``/``commands`` may contain placeholders to be replaced by the values obtained
@@ -213,17 +214,28 @@ Controls
- (Optional) A :ref:`regular expression <re-syntax>` to
match against lines received from the printer to retrieve information from it (e.g. specific output). Together
with ``template`` this allows rendition of received data from the printer within the UI.
**Please also read the note below**.
* - ``template``
- (Optional) A template to use for rendering the match of ``regex``. May contain placeholders in
:ref:`Python Format String Syntax <formatstrings>` for either named
groups within the regex (e.g. ``Temperature: {temperature}`` for a regex ``T:\s*(?P<temperature>\d+(\.\d*)``)
or positional groups within the regex (e.g. ``Position: X={0}, Y={1}, Z={2}, E={3}`` for a regex
``X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)``).
**Please also read the note below**.
* - ``confirm``
- (Optional) A text to display to the user to confirm his button press. Can be used with sensitive custom controls
like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation
dialog like in :numref:`fig-configuration-customcontrols-confirm`.
.. note::
``regex`` and ``template`` are only supported for controls that are defined through
``config.yaml``. These control properties aren't supported for controls added only in
the frontend by the :ref:`getAdditionalControls <sec-plugins-viewmodels-callbacks>`
view model callback.
.. _fig-configuration-customcontrols-confirm:
.. figure:: ../images/features-custom_controls-confirm.png
:align: center
+1 -1
View File
@@ -184,7 +184,7 @@ More nifty pause and resume
...........................
If you do not have a multi-extruder setup, aren't printing from SD and have "Log position on pause" enabled under
Settings > Serial > Advanced options, the following ``afterPrintPaused`` and
Settings > Serial Connection > Behaviour > Pausing, the following ``afterPrintPaused`` and
``beforePrintResumed`` scripts might be interesting for you. With something like them in place, OctoPrint will move your print head
out of the way to a safe rest position (here ``G1 X0 Y0``, you might want to adjust that) on pause and move it back
to the persisted pause position on resume, making sure to also reset the extruder and feedrate.
+2
View File
@@ -4,6 +4,8 @@
Plugins
*******
.. versionadded:: 1.2.0
Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually
extend OctoPrint's functionality.
+3
View File
@@ -4,6 +4,9 @@
Safe mode
*********
.. versionadded:: 1.3.0
.. versionchanged:: 1.3.13
With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language
packs instead of OctoPrint itself.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

+156 -3
View File
@@ -207,6 +207,8 @@ octoprint.access.permissions
.. py:function:: additional_permissions_hook(*args, **kwargs)
.. versionadded:: 1.4.0
Return a list of additional permissions to register in the system on behalf of the plugin. Use this
to add granular permissions to your plugin which can be configured for users and user groups in the general
access control settings of OctoPrint.
@@ -261,6 +263,8 @@ octoprint.access.users.factory
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
.. versionadded:: 1.4.0
Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will
be called only once during initial server startup.
@@ -295,6 +299,8 @@ octoprint.accesscontrol.keyvalidator
.. py:function:: acl_keyvalidator_hook(apikey, *args, **kwargs)
.. versionadded:: 1.3.6
Via this hook plugins may validate their own customized API keys to be used to access OctoPrint's API.
``apikey`` will be the API key as read from the request headers.
@@ -326,6 +332,8 @@ octoprint.cli.commands
.. py:function:: cli_commands_hook(cli_group, pass_octoprint_ctx, *args, **kwargs)
.. versionadded:: 1.3.0
By providing a handler for this hook plugins may register commands on OctoPrint's command line interface (CLI).
Handlers are expected to return a list of callables annotated as `Click commands <http://click.pocoo.org/5/>`_ to register with the
@@ -449,6 +457,8 @@ octoprint.comm.protocol.firmware.info
.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs)
.. versionadded:: 1.3.9
Be notified of firmware information received from the printer following an ``M115``.
Hook handlers may use this to react/adjust behaviour based on reported firmware data. OctoPrint parses the received
@@ -482,6 +492,8 @@ octoprint.comm.protocol.firmware.capabilities
.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs)
.. versionadded:: 1.3.9
Be notified of capability report entries received from the printer.
Hook handlers may use this to react to custom firmware capabilities. OctoPrint parses the received capability
@@ -507,7 +519,9 @@ octoprint.comm.protocol.firmware.capabilities
octoprint.comm.protocol.action
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: protocol_action_hook(comm_instance, line, action, *args, **kwargs)
.. py:function:: protocol_action_hook(comm_instance, line, action, name='', params='', *args, **kwargs)
.. versionadded:: 1.2.0
React to a :ref:`action command <sec-features-action_commands>` received from the printer.
@@ -534,8 +548,12 @@ octoprint.comm.protocol.action
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str line: The complete line as received from the printer, format ``// action:<command>``
:param str action: The parsed out action command, so for a ``line`` like ``// action:some_command`` this will be
:param str action: The parsed out action command incl. parameters, so for a ``line`` like ``// action:some_command key value`` this will be
``some_command key value``
:param str name: The action command name, for a ``line`` like ``// action:some_command key value`` this will be
``some_command``
:param str params: The action command's parameter, for a ``line`` like ``// action:some_command key value`` this will
be ``key value``
.. _sec-plugins-hook-comm-protocol-atcommand-phase:
@@ -549,6 +567,8 @@ This describes actually two hooks:
.. py:function:: protocol_atcommandphase_hook(comm_instance, phase, command, parameters, tags=None, *args, **kwargs)
.. versionadded:: 1.3.7
Trigger on :ref:`@ commands <sec-features-atcommands>` as they progress through the ``queuing`` and ``sending``
phases of the comm layer. See :ref:`the gcode phase hook <sec-plugins-hook-comm-protocol-gcode-phase>` for a
detailed description of each of these phases.
@@ -588,7 +608,7 @@ This describes actually two hooks:
octoprint.comm.protocol.gcode.<phase>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This describes actually four hooks:
This actually describes four hooks:
* ``octoprint.comm.protocol.gcode.queuing``
* ``octoprint.comm.protocol.gcode.queued``
@@ -597,6 +617,8 @@ This describes actually four hooks:
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs)
.. versionadded:: 1.2.0
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
are the following:
@@ -750,6 +772,8 @@ octoprint.comm.protocol.gcode.received
.. py:function:: gcode_received_hook(comm_instance, line, *args, **kwargs)
.. versionadded:: 1.3.0
Get the returned lines sent by the printer. Handlers should return the received line or in any case, the modified
version of it. If the handler returns None, processing will be aborted and the communication layer will get an
empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
@@ -783,6 +807,8 @@ octoprint.comm.protocol.gcode.error
.. py:function:: gcode_error_hook(comm_instance, error_message, *args, **kwargs)
.. versionadded:: 1.3.7
Get the messages of any errors messages sent by the printer, with the leading ``Error:`` or ``!!`` already
stripped. Handlers should return True if they handled that error internally and it should not be processed by
the system further. Normal processing of these kinds of errors - depending on the configuration of error
@@ -820,6 +846,9 @@ octoprint.comm.protocol.scripts
.. py:function:: protocol_scripts_hook(comm_instance, script_type, script_name, *args, **kwargs)
.. versionadded:: 1.2.0
.. versionchanged:: 1.3.7
Return a prefix to prepend, postfix to append, and optionally a dictionary of variables to provide to the script ``script_name`` of type ``type``. Handlers should
make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match
handled scripts. If not, None should be returned directly.
@@ -864,6 +893,8 @@ octoprint.comm.protocol.temperatures.received
.. py:function:: protocol_temperatures_received_hook(comm_instance, parsed_temperatures, *args, **kwargs)
.. versionadded:: 1.3.6
Get the parsed temperatures returned by the printer, allowing handlers to modify them prior to handing them off
to the system. Handlers are expected to either return ``parsed_temperatures`` as-is or a modified copy thereof.
@@ -897,6 +928,8 @@ octoprint.comm.transport.serial.additional_port_names
.. py:function:: additional_port_names_hook(candidates, *args, **kwargs)
.. versionadded:: 1.4.1
Return additional port names (not glob patterns!) to use as a serial connection to the printer. Expected to be
``list`` of ``string``s.
@@ -916,6 +949,8 @@ octoprint.comm.transport.serial.factory
.. py:function:: serial_factory_hook(comm_instance, port, baudrate, read_timeout, *args, **kwargs)
.. versionadded:: 1.2.0
Return a serial object to use as serial connection to the printer. If a handler cannot create a serial object
for the specified ``port`` (and ``baudrate``), it should just return ``None``.
@@ -992,6 +1027,8 @@ octoprint.events.register_custom_events
.. py:function:: register_custom_events_hook(*args, **kwargs)
.. versionadded:: 1.3.11
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
@@ -1020,6 +1057,8 @@ octoprint.filemanager.analysis.factory
.. py:function:: analysis_queue_factory_hook(*args, **kwargs)
.. versionadded:: 1.3.9
Return additional (or replacement) analysis queue factories used for analysing uploaded files.
Should return a dictionary to merge with the existing dictionary of factories, mapping from extension tree leaf
@@ -1058,6 +1097,8 @@ octoprint.filemanager.extension_tree
.. py:function:: file_extension_hook(*args, **kwargs)
.. versionadded:: 1.2.0
Return additional entries for the tree of accepted file extensions for uploading/handling by the file manager.
Should return a dictionary to merge with the existing extension tree, adding additional extension groups to
@@ -1094,6 +1135,8 @@ octoprint.filemanager.preprocessor
.. py:function:: file_preprocessor_hook(path, file_object, links=None, printer_profile=None, allow_overwrite=False, *args, **kwargs)
.. versionadded:: 1.2.0
Replace the ``file_object`` used for saving added files to storage by calling :func:`~octoprint.filemanager.util.AbstractFileWrapper.save`.
``path`` will be the future path of the file on the storage. The file's name is accessible via
@@ -1121,11 +1164,22 @@ octoprint.filemanager.preprocessor
:return: The `file_object` as passed in or None, or a replaced version to use instead for further processing.
:rtype: AbstractFileWrapper or None
.. _sec-plugins-hook-plugin-backup-excludes:
octoprint.plugin.backup.additional_excludes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 1.5.0
See :ref:`here <sec-bundledplugins-backup-hooks-excludes>`.
.. _sec-plugins-hook-plugin-loginui-theming:
octoprint.plugin.loginui.theming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 1.4.0
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
.. _sec-plugins-hook-plugin-pluginmanager-reconnect:
@@ -1133,6 +1187,8 @@ See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
octoprint.plugin.pluginmanager.reconnect_hooks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 1.4.0
See :ref:`here <sec-bundledplugins-pluginmanager-hooks-reconnect_hooks>`.
.. _sec-plugins-hook-plugin-softwareupdate-check_config:
@@ -1140,8 +1196,39 @@ See :ref:`here <sec-bundledplugins-pluginmanager-hooks-reconnect_hooks>`.
octoprint.plugin.softwareupdate.check_config
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 1.2.0
See :ref:`here <sec-bundledplugins-softwareupdate-hooks-check_config>`.
.. _sec-plugins-hooks-plugin-printer-additional_state_data
octoprint.printer.additional_state_data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: additional_state_data_hook(initial=False, *args, **kwargs)
.. versionadded:: 1.5.0
Use this to inject additional data into the data structure returned from the printer backend to the frontend
on the push socket or other registered :ref:`~octoprint.printer.PrinterCallback`s. Anything you return here
will be located beneath ``plugins.<your plugin id>`` in the resulting initial and current data push structure.
The ``initial`` parameter will be ``True`` if this the additional update sent to the callback. Your handler should
return a ``dict``, or ``None`` if nothing should be included.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you could stall the whole state monitor and thus updates being pushed to the frontend.
This includes I/O of any kind.
Cache your data!
:param boolean initial: True if this is the initial update, False otherwise
:return: Additional data to include
:rtype: dict
.. _sec-plugins-hook-printer-factory:
octoprint.printer.factory
@@ -1149,6 +1236,8 @@ octoprint.printer.factory
.. py:function:: printer_factory_hook(components, *args, **kwargs)
.. versionadded:: 1.3.0
Return a :class:`~octoprint.printer.PrinterInstance` instance to use as global printer object. This will
be called only once during initial server startup.
@@ -1180,6 +1269,8 @@ octoprint.printer.estimation.factory
.. py:function:: print_time_estimator_factory(*args, **kwargs)
.. versionadded:: 1.3.9
Return a :class:`~octoprint.printer.estimation.PrintTimeEstimator` subclass (or factory) to use for print time
estimation. This will be called on each start of a print or streaming job with a single parameter ``job_type``
denoting the type of job that was just started: ``local`` meaning a print of a local file through the serial connection,
@@ -1226,6 +1317,8 @@ octoprint.printer.sdcardupload
.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs)
.. versionadded:: 1.3.11
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``
@@ -1311,6 +1404,8 @@ octoprint.server.api.after_request
.. py:function:: after_request_handlers_hook(*args, **kwargs)
.. versionadded:: 1.3.10
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods.
@@ -1326,6 +1421,8 @@ octoprint.server.api.before_request
.. py:function:: after_request_handlers_hook(*args, **kwargs)
.. versionadded:: 1.3.10
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods.
@@ -1341,6 +1438,8 @@ octoprint.server.http.access_validator
.. py:function:: access_validator_hook(request, *args, **kwargs)
.. versionadded:: 1.3.10
Allows adding additional access validators to the default tornado routers.
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further.
@@ -1356,6 +1455,8 @@ octoprint.server.http.bodysize
.. py:function:: server_bodysize_hook(current_max_body_sizes, *args, **kwargs)
.. versionadded:: 1.2.0
Allows extending the list of custom maximum body sizes on the web server per path and HTTP method with custom entries
from plugins.
@@ -1398,6 +1499,8 @@ octoprint.server.http.routes
.. py:function:: server_route_hook(server_routes, *args, **kwargs)
.. versionadded:: 1.2.0
Allows extending the list of routes registered on the web server.
This is interesting for plugins which want to provide their own download URLs which will then be delivered statically
@@ -1465,6 +1568,8 @@ octoprint.server.sockjs.authed
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
.. versionadded:: 1.3.10
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
:param object socket: the socket object which is about to be registered
@@ -1477,6 +1582,8 @@ octoprint.server.sockjs.register
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
.. versionadded:: 1.3.10
Allows plugins to prevent a new :ref:`push socket client <sec-api-push>` to be registered to the system.
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
@@ -1496,6 +1603,8 @@ octoprint.server.sockjs.emit
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
.. versionadded:: 1.3.10
Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection <sec-api-push>`.
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
@@ -1516,6 +1625,8 @@ octoprint.timelapse.extensions
.. py:function:: timelapse_extension_hook(*args, **kwargs)
.. versionadded:: 1.3.10
Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of
additional file extensions.
@@ -1542,6 +1653,8 @@ octoprint.ui.web.templatetypes
.. py:function:: templatetype_hook(template_sorting, template_rules, *args, **kwargs)
.. versionadded:: 1.2.0
Allows extending the set of supported template types in the web interface. This is interesting for plugins which want
to offer other plugins to hook into their own offered UIs. Handlers must return a list of additional template
specifications in form of 3-tuples.
@@ -1648,6 +1761,42 @@ octoprint.ui.web.templatetypes
:return: a list of 3-tuples (template type, rule, sorting spec)
:rtype: list
.. _sec-plugins-hook-theming-dialog:
octoprint.theming.<dialog>
~~~~~~~~~~~~~~~~~~~~~~~~~~
This actually describes two hooks:
* ``octoprint.theming.login``
* ``octoprint.theming.recovery``
.. py:function:: ui_theming_hook(*args, **kwargs)
.. versionadded:: 1.5.0
Support theming of the login or recovery dialog, just in case the core UI is themed as well. Use to return a list of additional
CSS file URLs to inject into the dialog HTML.
Example usage by a plugin:
.. code-block:: python
def loginui_theming():
from flask import url_for
return [url_for("plugin.myplugin.static", filename="css/loginui_theme.css")]
__plugin_hooks__ = {
"octoprint.theming.login": loginui_theming
}
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
``url_for`` like in the example above to be prepared for any configured prefix URLs.
:return: A list of additional CSS URLs to inject into the login or recovery dialog.
:rtype: A list of strings.
.. _sec-plugins-hook-timelapse-capture-pre:
octoprint.timelapse.capture.pre
@@ -1655,6 +1804,8 @@ octoprint.timelapse.capture.pre
.. py:function:: capture_pre_hook(filename)
.. versionadded:: 1.4.0
Perform specific actions prior to capturing a timelapse frame.
``filename`` will be the future path of the frame to be saved.
@@ -1670,6 +1821,8 @@ octoprint.timelapse.capture.post
.. py:function:: capture_post_hook(filename, success)
.. versionadded:: 1.4.0
Perform specific actions after capturing a timelapse frame.
``filename`` will be the path of the frame that should have been saved.
+5
View File
@@ -238,6 +238,11 @@ getAdditionalControls()
Your view model may return additional custom control definitions for inclusion on the "Control" tab of OctoPrint's
interface. See :ref:`the custom control feature<sec-features-custom_controls>`.
.. note::
Controls injected from a view model do not support feedback controls (as defined by
``regex`` and ``template``).
onSettingsShown()
Called when the settings dialog is shown.
+213 -193
View File
@@ -2,15 +2,13 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__license__ = "The MIT License <http://opensource.org/licenses/MIT>"
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
from sphinx.directives.code import CodeBlock
import sphinx.highlighting
from sphinx.highlighting import PygmentsBridge
from sphinx.ext import doctest
from sphinx.util.texescape import tex_hl_escape_map_new
from docutils import nodes
from docutils.parsers.rst import directives
@@ -23,241 +21,263 @@ from pygments.lexers.python import PythonConsoleLexer
from pygments.util import ClassNotFound
if False:
# For type annotation
from typing import Any, Dict, List, Tuple # NOQA
# For type annotation
from typing import Any, Dict, List, Tuple # NOQA
def _merge_dict(a, b):
"""
Little helper to merge two dicts a and b on the fly.
"""
result = dict(a)
result.update(b)
return result
"""
Little helper to merge two dicts a and b on the fly.
"""
result = dict(a)
result.update(b)
return result
class literal_block_ext(nodes.General, nodes.FixedTextElement):
"""
Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced
in order to be able to have a custom visitor.
"""
"""
Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced
in order to be able to have a custom visitor.
"""
@classmethod
def from_literal_block(cls, block):
"""
Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a
custom ``tagname``.
"""
new = literal_block_ext()
for a in (
"attributes",
"basic_attributes",
"child_text_separator",
"children",
"document",
"known_attributes",
"line",
"list_attributes",
"local_attributes",
"parent",
"rawsource",
"source",
):
setattr(new, a, getattr(block, a))
new.tagname = "literal_block_ext"
return new
@classmethod
def from_literal_block(cls, block):
"""
Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a
custom ``tagname``.
"""
new = literal_block_ext()
for a in ("attributes", "basic_attributes", "child_text_separator", "children", "document", "known_attributes",
"line", "list_attributes", "local_attributes", "parent", "rawsource", "source"):
setattr(new, a, getattr(block, a))
new.tagname = "literal_block_ext"
return new
class CodeBlockExt(CodeBlock):
"""
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
code blocks.
"""
"""
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
code blocks.
"""
option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag))
option_spec = _merge_dict(CodeBlock.option_spec, {"whitespace": directives.flag})
def run(self):
# type: () -> List[nodes.Node]
# get result from parent implementation
code_block = CodeBlock.run(self)
def run(self):
# type: () -> List[nodes.Node]
# get result from parent implementation
code_block = CodeBlock.run(self)
def find_and_wrap_literal_block(node):
"""
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
"""
def find_and_wrap_literal_block(node):
"""
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
"""
if isinstance(node, nodes.container):
# container node => handle all children
children = []
for child in node.children:
children.append(find_and_wrap_literal_block(child))
node.children = children
return node
if isinstance(node, nodes.container):
# container node => handle all children
children = []
for child in node.children:
children.append(find_and_wrap_literal_block(child))
node.children = children
return node
elif isinstance(node, nodes.literal_block):
# literal block => replace it
return self._wrap_literal_block(node)
elif isinstance(node, nodes.literal_block):
# literal block => replace it
return self._wrap_literal_block(node)
else:
# no idea what that is => leave it alone
return node
else:
# no idea what that is => leave it alone
return node
# replace all created literal_blocks with literal_block_ext instances
return list(map(find_and_wrap_literal_block, code_block))
# replace all created literal_blocks with literal_block_ext instances
return list(map(find_and_wrap_literal_block, code_block))
def _wrap_literal_block(self, node):
literal = literal_block_ext.from_literal_block(node)
literal["whitespace"] = "whitespace" in self.options
return literal
def _wrap_literal_block(self, node):
literal = literal_block_ext.from_literal_block(node)
literal["whitespace"] = "whitespace" in self.options
return literal
class PygmentsBridgeExt(object):
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
"""
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
"""
def __init__(self, bridge, whitespace):
self._bridge = bridge
self._whitespace = whitespace
def __init__(self, bridge, whitespace):
self._bridge = bridge
self._whitespace = whitespace
def __getattr__(self, item):
return getattr(self._bridge, item)
def __getattr__(self, item):
return getattr(self._bridge, item)
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
if not self._whitespace:
return self._bridge.highlight_block(source, lang, opts=opts, warn=warn, force=force, **kwargs)
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
if not self._whitespace:
return self._bridge.highlight_block(
source, lang, opts=opts, warn=warn, force=force, **kwargs
)
# We are still here => we need to basically do everything the parent implementation does (and does so in a very
# inextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run
# and remove it afterwards so the lexer can be safely reused.
#
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
# We are still here => we need to basically do everything the parent implementation does (and does so in a very
# inextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run
# and remove it afterwards so the lexer can be safely reused.
#
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
class whitespace(object):
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
self._orig_tabsize = lexer.tabsize
class whitespace(object):
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
self._orig_tabsize = lexer.tabsize
def __enter__(self):
new_filters = list(self._orig_filters)
new_filters.append(VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize))
self._lexer.filters = new_filters
self._lexer.tabsize = 0
return self._lexer
def __enter__(self):
new_filters = list(self._orig_filters)
new_filters.append(
VisibleWhitespaceFilter(
spaces=True, tabs=True, tabsize=self._lexer.tabsize
)
)
self._lexer.filters = new_filters
self._lexer.tabsize = 0
return self._lexer
def __exit__(self, type, value, traceback):
self._lexer.filters = self._orig_filters
self._lexer.tabsize = self._orig_tabsize
def __exit__(self, type, value, traceback):
self._lexer.filters = self._orig_filters
self._lexer.tabsize = self._orig_tabsize
# Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves
# into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original
# "highlight_block" method, with no means for external code to inject different functionality.
#
# Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
# lies with the respective authors.
# Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves
# into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original
# "highlight_block" method, with no means for external code to inject different functionality.
#
# Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
# lies with the respective authors.
if not isinstance(source, text_type):
source = source.decode()
if not isinstance(source, text_type):
source = source.decode()
# find out which lexer to use
if lang in ('py', 'python'):
if source.startswith('>>>'):
# interactive session
lexer = sphinx.highlighting.lexers['pycon']
elif not force:
# maybe Python -- try parsing it
if self.try_parse(source):
lexer = sphinx.highlighting.lexers['python']
else:
lexer = sphinx.highlighting.lexers['none']
else:
lexer = sphinx.highlighting.lexers['python']
elif lang in ('python3', 'py3') and source.startswith('>>>'):
# for py3, recognize interactive sessions, but do not try parsing...
lexer = sphinx.highlighting.lexers['pycon3']
elif lang == 'guess':
# try:
lexer = sphinx.highlighting.guess_lexer(source)
# except Exception:
# lexer = sphinx.highlighting.lexers['none']
else:
if lang in sphinx.highlighting.lexers:
lexer = sphinx.highlighting.lexers[lang]
else:
try:
lexer = sphinx.highlighting.lexers[lang] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
except ClassNotFound:
if warn:
warn('Pygments lexer name %r is not known' % lang)
lexer = sphinx.highlighting.lexers['none']
else:
raise
else:
lexer.add_filter('raiseonerror')
# find out which lexer to use
if lang in ("py", "python"):
if source.startswith(">>>"):
# interactive session
lexer = sphinx.highlighting.lexers["pycon"]
elif not force:
# maybe Python -- try parsing it
if self.try_parse(source):
lexer = sphinx.highlighting.lexers["python"]
else:
lexer = sphinx.highlighting.lexers["none"]
else:
lexer = sphinx.highlighting.lexers["python"]
elif lang in ("python3", "py3") and source.startswith(">>>"):
# for py3, recognize interactive sessions, but do not try parsing...
lexer = sphinx.highlighting.lexers["pycon3"]
elif lang == "guess":
# try:
lexer = sphinx.highlighting.guess_lexer(source)
# except Exception:
# lexer = sphinx.highlighting.lexers['none']
else:
if lang in sphinx.highlighting.lexers:
lexer = sphinx.highlighting.lexers[lang]
else:
try:
lexer = sphinx.highlighting.lexers[
lang
] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
except ClassNotFound:
if warn:
warn("Pygments lexer name %r is not known" % lang)
lexer = sphinx.highlighting.lexers["none"]
else:
raise
else:
lexer.add_filter("raiseonerror")
if not isinstance(source, text_type):
source = source.decode()
if not isinstance(source, text_type):
source = source.decode()
# trim doctest options if wanted
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
source = doctest.blankline_re.sub('', source)
source = doctest.doctestopt_re.sub('', source)
# trim doctest options if wanted
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
source = doctest.blankline_re.sub("", source)
source = doctest.doctestopt_re.sub("", source)
# highlight via Pygments
formatter = self._bridge.get_formatter(**kwargs)
try:
# MODIFIED: replaced by whitespace wrapped call
with whitespace(lexer) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
except ErrorToken:
# this is most probably not the selected language,
# so let it pass unhighlighted
# highlight via Pygments
formatter = self._bridge.get_formatter(**kwargs)
try:
# MODIFIED: replaced by whitespace wrapped call
with whitespace(lexer) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
except ErrorToken:
# this is most probably not the selected language,
# so let it pass unhighlighted
# MODIFIED: replaced by whitespace wrapped call
with whitespace(sphinx.highlighting.lexers["none"]) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
if self._bridge.dest == 'html':
return hlsource
else:
if not isinstance(hlsource, text_type): # Py2 / Pygments < 1.6
hlsource = hlsource.decode()
return hlsource.translate(tex_hl_escape_map_new)
# MODIFIED: replaced by whitespace wrapped call
with whitespace(sphinx.highlighting.lexers["none"]) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
return hlsource
class whitespace_highlighter(object):
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
def __init__(self, translator, node):
self.translator = translator
self.node = node
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
self._orig_highlighter = self.translator.highlighter
def __init__(self, translator, node):
self.translator = translator
self.node = node
def __enter__(self):
whitespace = self.node["whitespace"] if "whitespace" in self.node else False
if whitespace:
self.translator.highlighter = PygmentsBridgeExt(self._orig_highlighter, whitespace)
return self.translator
self._orig_highlighter = self.translator.highlighter
def __exit__(self, exc_type, exc_val, exc_tb):
self.translator.highlighter = self._orig_highlighter
def __enter__(self):
whitespace = self.node["whitespace"] if "whitespace" in self.node else False
if whitespace:
self.translator.highlighter = PygmentsBridgeExt(
self._orig_highlighter, whitespace
)
return self.translator
def __exit__(self, exc_type, exc_val, exc_tb):
self.translator.highlighter = self._orig_highlighter
def visit_literal_block_ext(translator, node):
"""
When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the
visitor for regular literal blocks, then switch back again.
"""
with whitespace_highlighter(translator, node):
translator.visit_literal_block(node)
"""
When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the
visitor for regular literal blocks, then switch back again.
"""
with whitespace_highlighter(translator, node):
translator.visit_literal_block(node)
def depart_literal_block_ext(translator, node):
"""
Just call the depart function for regular literal blocks.
"""
with whitespace_highlighter(translator, node):
translator.depart_literal_block(node)
"""
Just call the depart function for regular literal blocks.
"""
with whitespace_highlighter(translator, node):
translator.depart_literal_block(node)
def setup(app):
# custom directive
app.add_directive("code-block-ext", CodeBlockExt)
# custom directive
app.add_directive("code-block-ext", CodeBlockExt)
# custom node type
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
# custom node type
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
return dict(version="0.1")
return {"version": "0.1"}
+90 -75
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__license__ = "The MIT License <http://opensource.org/licenses/MIT>"
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
@@ -10,103 +10,118 @@ import codecs
import requests
from contextlib import closing
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
nodes, parselinenos, logger, container_wrapper
from sphinx.directives.code import (
LiteralIncludeReader,
LiteralInclude,
dedent_lines,
nodes,
parselinenos,
logger,
container_wrapper,
)
from sphinx.util.nodes import set_source_info
if False:
# For type annotation
from typing import Any, List # NOQA
# For type annotation
from typing import Any, List # NOQA
cache = {}
cache = dict()
class OnlineIncludeReader(LiteralIncludeReader):
def read_file(self, filename, location=None):
# type: (unicode, Any) -> List[unicode]
def read_file(self, filename, location=None):
# type: (unicode, Any) -> List[unicode]
global cache
try:
if filename in cache:
lines = cache[filename]
else:
with closing(requests.get(filename, stream=True)) as r:
r.encoding = self.encoding
lines = r.text.splitlines(True)
cache[filename] = lines
global cache
try:
if filename in cache:
lines = cache[filename]
else:
with closing(requests.get(filename, stream=True)) as r:
r.encoding = self.encoding
lines = r.text.splitlines(True)
cache[filename] = lines
if "tab-width" in self.options:
lines = [line.expandtabs(self.options["tab-width"]) for line in lines]
if 'tab-width' in self.options:
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
return lines
except (IOError, OSError):
raise IOError('Include file %r not found or reading it failed' % filename)
except UnicodeError:
raise UnicodeError('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option' % (self.encoding, filename))
return lines
except (IOError, OSError):
raise IOError("Include file %r not found or reading it failed" % filename)
except UnicodeError:
raise UnicodeError(
"Encoding %r used for reading included file %r seems to "
"be wrong, try giving an :encoding: option" % (self.encoding, filename)
)
class OnlineIncludeDirective(LiteralInclude):
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
if not document.settings.file_insertion_enabled:
return [
document.reporter.warning("File insertion disabled", line=self.lineno)
]
# convert options['diff'] to absolute path
if "diff" in self.options:
_, path = self.env.relfn2path(self.options["diff"])
self.options["diff"] = path
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
if not document.settings.file_insertion_enabled:
return [document.reporter.warning('File insertion disabled',
line=self.lineno)]
# convert options['diff'] to absolute path
if 'diff' in self.options:
_, path = self.env.relfn2path(self.options['diff'])
self.options['diff'] = path
try:
location = self.state_machine.get_source_and_line(self.lineno)
url = self.arguments[0]
try:
location = self.state_machine.get_source_and_line(self.lineno)
url = self.arguments[0]
reader = OnlineIncludeReader(url, self.options, self.config)
text, lines = reader.read(location=location)
reader = OnlineIncludeReader(url, self.options, self.config)
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
if self.options.get("diff"): # if diff is set, set udiff
retnode["language"] = "udiff"
elif "language" in self.options:
retnode["language"] = self.options["language"]
retnode["linenos"] = (
"linenos" in self.options
or "lineno-start" in self.options
or "lineno-match" in self.options
)
retnode["classes"] += self.options.get("class", [])
extra_args = retnode["highlight_args"] = {}
if "emphasize-lines" in self.options:
hl_lines = parselinenos(self.options["emphasize-lines"], lines)
if any(i >= lines for i in hl_lines):
logger.warning(
"line number spec is out of range(1-%d): %r"
% (lines, self.options["emphasize-lines"]),
location=location,
)
extra_args["hl_lines"] = [x + 1 for x in hl_lines if x < lines]
extra_args["linenostart"] = reader.lineno_start
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
retnode['language'] = self.options['language']
retnode['linenos'] = ('linenos' in self.options or
'lineno-start' in self.options or
'lineno-match' in self.options)
retnode['classes'] += self.options.get('class', [])
extra_args = retnode['highlight_args'] = {}
if 'emphasize-lines' in self.options:
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
if any(i >= lines for i in hl_lines):
logger.warning('line number spec is out of range(1-%d): %r' %
(lines, self.options['emphasize-lines']),
location=location)
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
extra_args['linenostart'] = reader.lineno_start
if "caption" in self.options:
caption = self.options["caption"] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
if 'caption' in self.options:
caption = self.options['caption'] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
# retnode will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(retnode)
# retnode will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(retnode)
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
def visit_onlineinclude(translator, node):
translator.visit_literal_block(node)
translator.visit_literal_block(node)
def depart_onlineinclude(translator, node):
translator.depart_literal_block(node)
translator.depart_literal_block(node)
def setup(app):
app.add_directive("onlineinclude", OnlineIncludeDirective)
app.add_directive("onlineinclude", OnlineIncludeDirective)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
+6 -3
View File
@@ -10,17 +10,20 @@ basedir = os.path.dirname(os.path.realpath(__file__))
old = os.path.join(basedir, "octoprint")
if os.path.exists(old):
# rename left-overs from old file structure
print("""
print(
"""
Found left-overs from old file structure, renaming to
"octoprint.backup". Please remove this manually (I don't
dare to do so myself since you might have changes in there
I don't know anything about).
""")
"""
)
os.rename(old, os.path.join(basedir, "octoprint.backup"))
sys.path.insert(0, os.path.join(basedir, "src"))
import octoprint
import octoprint # noqa: E402
if len(sys.argv) == 1:
sys.argv.append("serve")
octoprint.main()
+17 -6
View File
@@ -14,11 +14,22 @@ parentdir_prefix =
lookupfile = .versioneer-lookup
[flake8]
ignore =
D
E
W
F401
F523
max-line-length = 90
extend-ignore = E203, E231, E265, E266, E402, E501, E731
select = B,C,E,F,W,T4,B9
exclude =
src/octoprint/vendor
[isort]
multi_line_output = 3
include_trailing_comma = True
force_grid_wrap = 0
use_parentheses = True
ensure_newline_before_comments = True
line_length = 90
skip =
src/octoprint/vendor
known_first_party =
octoprint
octoprint_setuptools
octoprint_client
+238 -225
View File
@@ -1,294 +1,307 @@
#!/usr/bin/env python2
# coding=utf-8
# -*- coding: utf-8 -*-
from distutils.command.build_py import build_py as _build_py
import os
import versioneer
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import octoprint_setuptools
import setuptools
from distutils.command.build_py import build_py as _build_py
#-----------------------------------------------------------------------------------------------------------------------
import versioneer # noqa: F401
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import setuptools # noqa: F401,E402
import octoprint_setuptools # noqa: F401,E402
# ----------------------------------------------------------------------------------------
# Supported python versions
# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported
PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
# Requirements for setup.py
SETUP_REQUIRES = [
"markdown>=3.1,<3.2" # newer versions require Python 3
]
SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3
# Requirements for our application
INSTALL_REQUIRES = [
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FirmwareCheck>=2020.06.22",
"OctoPrint-FileCheck>=2020.07.06",
# 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
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"rsa==4.0", # newer versions require Python 3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"flask>=1.1.2,<2",
"Jinja2>=2.11.2,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Babel>=1.0,<2",
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2",
"itsdangerous>=1.1.0,<2",
"cachelib>=0.1,<1",
"PyYAML>=5.3.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.7.19,<1",
"watchdog>=0.10.2,<1",
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"pylru>=1.2,<2",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"feedparser>=5.2.1,<6",
"future>=0.18.2,<1",
"websocket-client>=0.57,<1",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"frozendict>=1.2,<2",
"sentry-sdk>=0.15.1,<1",
"filetype>=1.0.7,<2",
# vendor bundle dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2" # dependency of flask_principal
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FirmwareCheck>=2020.09.23",
"OctoPrint-FileCheck>=2020.08.07",
# 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
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"rsa==4.0", # newer versions require Python 3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"flask>=1.1.2,<2",
"Jinja2>=2.11.2,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Babel>=1.0,<2",
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2",
"itsdangerous>=1.1.0,<2",
"cachelib>=0.1,<1",
"PyYAML>=5.3.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.7.19,<1",
"watchdog==0.10.4", # watchdog dropped Py>3.6 on 0.10.5 point release...
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"pylru>=1.2,<2",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"future>=0.18.2,<1",
"websocket-client>=0.57,<1",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"frozendict>=1.2,<2",
"sentry-sdk>=0.15.1,<1",
"filetype>=1.0.7,<2",
# vendor bundled dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2", # dependency of flask_principal
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"futures>=3.3,<4",
"monotonic>=1.5,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.7.4.1,<4"
"feedparser>=5.2.1,<6", # newer versions require Python 3
"futures>=3.3,<4",
"monotonic>=1.5,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.7.4.1,<4",
"enum34>=1.1.10,<1.2",
]
# Python 3 specific requirements
INSTALL_REQUIRES_PYTHON3 = ["feedparser>=6.0.2,<7", "zeroconf>=0.24,<0.25"]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.4",
"appdirs>=1.4.4",
]
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies - SEE ALSO tox.ini
"mock>=3.0.5,<4",
"pytest==4.6.10",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# linter
"flake8",
# profiler
"pyinstrument",
],
# Dependencies for developing OctoPrint plugins
plugins=[
"cookiecutter>=1.7.2,<1.8"
],
# Dependencies for building the documentation - Python 3 required!
docs=[
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext"
],
)
EXTRA_REQUIRES = {
"develop": [
# Testing dependencies
"mock>=3.0.5,<4",
"pytest==4.6.10",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# pre-commit
"pre-commit",
# profiler
"pyinstrument",
],
# Dependencies for developing OctoPrint plugins
"plugins": ["cookiecutter>=1.7.2,<1.8"],
# Dependencies for building the documentation - Python 3 required!
"docs": [
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext",
],
}
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
# adapted from https://hynek.me/articles/conditional-python-dependencies/
if int(setuptools.__version__.split(".", 1)[0]) < 18:
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
# would get lost there
assert "bdist_wheel" not in sys.argv
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
# would get lost there
assert "bdist_wheel" not in sys.argv
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
if sys.version_info[0] < 3:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
if sys.version_info[0] < 3:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
else:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3
if sys.platform == "darwin":
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
if sys.platform == "darwin":
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
else:
# environment markers supported
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
# environment markers supported
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
#-----------------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
here = os.path.abspath(os.path.dirname(__file__))
def read_file_contents(path):
import codecs
with codecs.open(path, encoding="utf-8") as f:
return f.read()
import codecs
with codecs.open(path, encoding="utf-8") as f:
return f.read()
def md_to_html_build_py_factory(files, baseclass):
class md_to_html_build_py(baseclass):
files = dict()
class md_to_html_build_py(baseclass):
files = {}
def run(self):
print("RUNNING md_to_html_build_py")
if not self.dry_run:
for directory, files in self.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
def run(self):
print("RUNNING md_to_html_build_py")
if not self.dry_run:
for directory, files in self.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry[0], os.path.join(target_dir, entry[1])
else:
source = entry
dest = os.path.join(target_dir, source + ".html")
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry[0], os.path.join(target_dir, entry[1])
else:
source = entry
dest = os.path.join(target_dir, source + ".html")
print("Rendering markdown from {} to {}".format(source, dest))
print("Rendering markdown from {} to {}".format(source, dest))
from markdown import markdownFromFile
markdownFromFile(input=source,
output=dest,
encoding="utf-8")
baseclass.run(self)
from markdown import markdownFromFile
markdownFromFile(input=source, output=dest, encoding="utf-8")
baseclass.run(self)
return type(md_to_html_build_py)(
md_to_html_build_py.__name__, (md_to_html_build_py,), {"files": files}
)
return type(md_to_html_build_py)(md_to_html_build_py.__name__,
(md_to_html_build_py,),
dict(files=files))
def get_cmdclass():
# make sure these are always available, even when run by dependabot
global versioneer, octoprint_setuptools, md_to_html_build_py_factory
# make sure these are always available, even when run by dependabot
global versioneer, octoprint_setuptools, md_to_html_build_py_factory
cmdclass = versioneer.get_cmdclass()
cmdclass = versioneer.get_cmdclass()
# add clean command
cmdclass.update(dict(clean=octoprint_setuptools.CleanCommand.for_options(source_folder="src", eggs=["OctoPrint*.egg-info"])))
# add clean command
cmdclass.update(
{
"clean": octoprint_setuptools.CleanCommand.for_options(
source_folder="src", eggs=["OctoPrint*.egg-info"]
)
}
)
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(
octoprint_setuptools.get_babel_commandclasses(
pot_file=pot_file,
output_dir=translation_dir,
pack_name_prefix="OctoPrint-i18n-",
pack_path_prefix="",
bundled_dir=bundled_dir,
)
)
cmdclass["build_py"] = md_to_html_build_py_factory({
"octoprint/templates/_data": [
"AUTHORS.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
}, cmdclass["build_py"] if "build_py" in cmdclass else _build_py)
cmdclass["build_py"] = md_to_html_build_py_factory(
{
"octoprint/templates/_data": [
"AUTHORS.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
},
cmdclass["build_py"] if "build_py" in cmdclass else _build_py,
)
return cmdclass
return cmdclass
def params():
# make sure these are always available, even when run by dependabot
global versioneer, get_cmdclass, read_file_contents, here, \
PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
# make sure these are always available, even when run by dependabot
global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
name = "OctoPrint"
version = versioneer.get_version()
cmdclass = get_cmdclass()
name = "OctoPrint"
version = versioneer.get_version()
cmdclass = get_cmdclass()
description = "The snappy web interface for your 3D printer"
long_description = read_file_contents(os.path.join(here, "README.md"))
long_description_content_type = "text/markdown"
description = "The snappy web interface for your 3D printer"
long_description = read_file_contents(os.path.join(here, "README.md"))
long_description_content_type = "text/markdown"
python_requires = PYTHON_REQUIRES
setup_requires = SETUP_REQUIRES
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
python_requires = PYTHON_REQUIRES
setup_requires = SETUP_REQUIRES
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
"Topic :: System :: Monitoring"
]
author = "Gina Häußge"
author_email = "gina@octoprint.org"
url = "https://octoprint.org"
license = "GNU Affero General Public License v3"
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
"Topic :: System :: Monitoring",
]
author = "Gina Häußge"
author_email = "gina@octoprint.org"
url = "https://octoprint.org"
license = "GNU Affero General Public License v3"
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
project_urls={
"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"
}
project_urls = {
"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",
}
packages = setuptools.find_packages(where="src")
package_dir = {
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint',
['static', 'templates', 'plugins', 'translations'])
+ ['util/piptestballoon/setup.py']
}
packages = setuptools.find_packages(where="src")
package_dir = {
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs(
"src/octoprint", ["static", "templates", "plugins", "translations"]
)
+ ["util/piptestballoon/setup.py"]
}
include_package_data = True
zip_safe = False
include_package_data = True
zip_safe = False
if os.environ.get('READTHEDOCS', None) == 'True':
# we can't tell read the docs to please perform a pip install -e .[docs], so we help
# it a bit here by explicitly adding the development dependencies, which include our
# documentation dependencies
install_requires = install_requires + extras_require['docs']
if os.environ.get("READTHEDOCS", None) == "True":
# we can't tell read the docs to please perform a pip install -e .[docs], so we help
# it a bit here by explicitly adding the development dependencies, which include our
# documentation dependencies
install_requires = install_requires + extras_require["docs"]
entry_points = {
"console_scripts": [
"octoprint = octoprint:main"
]
}
entry_points = {"console_scripts": ["octoprint = octoprint:main"]}
return locals()
return locals()
setuptools.setup(**params())
+791 -481
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -3,5 +3,6 @@
from __future__ import absolute_import, division, print_function, unicode_literals
if __name__ == "__main__":
import octoprint
octoprint.main()
import octoprint
octoprint.main()
+114 -82
View File
@@ -14,11 +14,11 @@ from __future__ import absolute_import, division, print_function, unicode_litera
import errno
import io
import logging
import os
import re
import subprocess
import sys
import logging
def get_keywords():
@@ -64,12 +64,14 @@ HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
@@ -81,9 +83,12 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
p = subprocess.Popen(
[c] + args,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr else None),
)
break
except EnvironmentError:
e = sys.exc_info()[1]
@@ -116,12 +121,17 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix))
print(
"guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix)
)
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None}
return {
"version": dirname[len(parentdir_prefix) :],
"full-revisionid": None,
"dirty": False,
"error": None,
}
@register_vcs_handler("git", "get_keywords")
@@ -159,11 +169,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 = {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 = {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
@@ -172,12 +182,15 @@ 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 = {r for r in refs if re.search(r"\d", r)}
if verbose:
print("discarding '%s', no digits" % ",".join(refs-tags))
print("discarding '%s', no digits" % ",".join(refs - tags))
branches = [r for r in refs if not r.startswith(TAG)
and r != "HEAD" and not r.startswith("refs/")]
branches = [
r
for r in refs
if not r.startswith(TAG) and r != "HEAD" and not r.startswith("refs/")
]
if verbose:
print("likely branches: %s" % ",".join(sorted(branches)))
branch = None
@@ -189,22 +202,28 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
r = ref[len(tag_prefix) :]
if verbose:
print("picking %s" % r)
result = {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None}
result = {
"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": None,
}
if branch is not None:
result["branch"] = branch
return result
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags"}
return {
"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
}
@register_vcs_handler("git", "pieces_from_vcs")
@@ -225,10 +244,19 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["git.cmd", "git.exe"]
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
describe_out = run_command(
GITS,
[
"describe",
"--tags",
"--dirty",
"--always",
"--long",
"--match",
"%s*" % tag_prefix,
],
cwd=root,
)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
@@ -251,12 +279,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
git_describe = git_describe[: git_describe.rindex("-dirty")]
# figure out our branch
abbrev_ref_out = run_command(GITS,
["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
abbrev_ref_out = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
if abbrev_ref_out is not None and abbrev_ref_out != "HEAD":
pieces["branch"] = abbrev_ref_out.strip()
@@ -264,11 +290,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
return pieces
# tag
@@ -277,10 +302,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
full_tag,
tag_prefix,
)
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
pieces["closest-tag"] = full_tag[len(tag_prefix) :]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
@@ -291,8 +318,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root)
pieces["distance"] = int(count_out) # total number of commits
return pieces
@@ -309,11 +335,12 @@ def git_parse_lookup_file(path):
return []
import re
lookup = []
with io.open(path, "rt", encoding="utf-8") as f:
for line in f:
if '#' in line:
line = line[:line.index("#")]
if "#" in line:
line = line[: line.index("#")]
line = line.strip()
if not line:
continue
@@ -353,8 +380,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
if stdout is None:
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
@@ -365,37 +391,33 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
for matcher, render, tag, ref_commit in lookup:
if matcher.match(current_branch):
if tag is None or ref_commit is None:
raise NotThisMethod("tag or ref_commit is unset for "
"this branch")
raise NotThisMethod("tag or ref_commit is unset for " "this branch")
stdout = run_command(GITS,
["rev-list", "%s..HEAD" % ref_commit,
"--count"],
cwd=root)
stdout = run_command(
GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root
)
if stdout is None:
raise NotThisMethod("git rev-list %s..HEAD "
"--count failed" % ref_commit)
raise NotThisMethod(
"git rev-list %s..HEAD " "--count failed" % ref_commit
)
try:
num_commits = int(stdout.strip())
except ValueError:
raise NotThisMethod("git rev-list %s..HEAD --count didn't "
"return a valid number" % ref_commit)
raise NotThisMethod(
"git rev-list %s..HEAD --count didn't "
"return a valid number" % ref_commit
)
stdout = run_command(GITS,
["rev-parse", "--short", "HEAD"],
cwd=root)
stdout = run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
if stdout is None:
raise NotThisMethod("git describe rev-parse "
"--short HEAD failed")
raise NotThisMethod("git describe rev-parse " "--short HEAD failed")
short_hash = stdout.strip()
stdout = run_command(GITS,
["describe", "--tags",
"--dirty", "--always"],
cwd=root)
stdout = run_command(
GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root
)
if stdout is None:
raise NotThisMethod("git describe --tags --dirty "
"--always failed")
raise NotThisMethod("git describe --tags --dirty " "--always failed")
dirty = stdout.strip().endswith("-dirty")
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
@@ -411,7 +433,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
"closest-tag": tag,
"distance": num_commits,
"error": None,
"render": render
"render": render,
}
raise NotThisMethod("no matching lookup definition found")
@@ -442,8 +464,7 @@ def render_pep440(pieces):
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
@@ -603,10 +624,12 @@ def render_git_describe_long(pieces):
def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
return {
"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
}
if "render" in pieces and pieces["render"] is not None:
style = pieces["render"]
@@ -633,8 +656,12 @@ def render(pieces, style):
else:
raise ValueError("unknown style '%s'" % style)
result = {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None}
result = {
"version": rendered,
"full-revisionid": pieces["long"],
"dirty": pieces["dirty"],
"error": None,
}
if "branch" in pieces and pieces["branch"] is not None:
result["branch"] = pieces["branch"]
return result
@@ -651,8 +678,7 @@ def get_versions():
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
except NotThisMethod:
pass
@@ -661,14 +687,17 @@ def get_versions():
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in cfg.versionfile_source.split('/'):
for _ in cfg.versionfile_source.split("/"):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree"}
return {
"version": "0+unknown",
"full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree",
}
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
lookuppath = os.path.join(root, lookupfile)
if os.path.exists(lookuppath):
try:
@@ -690,6 +719,9 @@ def get_versions():
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version"}
return {
"version": "0+unknown",
"full-revisionid": None,
"dirty": None,
"error": "unable to compute version",
}
File diff suppressed because it is too large. Load diff
+369 -294
View File
@@ -2,391 +2,466 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Marc Hannappel <salandora@gmail.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
from future.utils import with_metaclass
from flask import g, abort
from flask_babel import gettext
from octoprint.vendor.flask_principal import Permission, PermissionDenied, RoleNeed, Need
from functools import wraps
from collections import OrderedDict, defaultdict
from functools import wraps
from flask import abort, g
from flask_babel import gettext
from future.utils import with_metaclass
# noinspection PyCompatibility
from past.builtins import basestring
from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP
from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP
from octoprint.vendor.flask_principal import Need, Permission, PermissionDenied, RoleNeed
class OctoPrintPermission(Permission):
@classmethod
def convert_needs_to_dict(cls, needs):
ret_needs = defaultdict(list)
for need in needs:
if need.value not in ret_needs[need.method]:
ret_needs[need.method].append(need.value)
return ret_needs
@classmethod
def convert_needs_to_dict(cls, needs):
ret_needs = defaultdict(list)
for need in needs:
if need.value not in ret_needs[need.method]:
ret_needs[need.method].append(need.value)
return ret_needs
@classmethod
def convert_to_needs(cls, needs):
result = []
for need in needs:
# noinspection PyCompatibility
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
result.append(RoleNeed(need))
return result
@classmethod
def convert_to_needs(cls, needs):
result = []
for need in needs:
# noinspection PyCompatibility
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
result.append(RoleNeed(need))
return result
def __init__(self, name, description, *needs, **kwargs):
self._name = name
self._description = description
self._dangerous = kwargs.pop("dangerous", False)
self._default_groups = kwargs.pop("default_groups", [])
def __init__(self, name, description, *needs, **kwargs):
self._name = name
self._description = description
self._dangerous = kwargs.pop("dangerous", False)
self._default_groups = kwargs.pop("default_groups", [])
self._key = None
self._key = None
Permission.__init__(self, *self.convert_to_needs(needs))
Permission.__init__(self, *self.convert_to_needs(needs))
def as_dict(self):
return dict(
key=self.key,
name=self.get_name(),
dangerous=self._dangerous,
default_groups=self._default_groups,
description=self.get_description(),
needs=self.convert_needs_to_dict(self.needs)
)
def as_dict(self):
return {
"key": self.key,
"name": self.get_name(),
"dangerous": self._dangerous,
"default_groups": self._default_groups,
"description": self.get_description(),
"needs": self.convert_needs_to_dict(self.needs),
}
@property
def key(self):
return self._key
@property
def key(self):
return self._key
@key.setter
def key(self, value):
self._key = value
@key.setter
def key(self, value):
self._key = value
@property
def default_groups(self):
return self._default_groups
@property
def dangerous(self):
return self._dangerous
def get_name(self):
return self._name
@property
def default_groups(self):
return self._default_groups
def get_description(self):
return self._description
def get_name(self):
return self._name
def allows(self, identity):
"""Whether the identity can access this permission.
Overridden from Permission.allows to make sure the Identity provides ALL
required needs instead of ANY required need.
def get_description(self):
return self._description
:param identity: The identity
"""
if self.needs and len(self.needs.intersection(identity.provides)) != len(self.needs):
return False
def allows(self, identity):
"""Whether the identity can access this permission.
Overridden from Permission.allows to make sure the Identity provides ALL
required needs instead of ANY required need.
if self.excludes and self.excludes.intersection(identity.provides):
return False
:param identity: The identity
"""
if self.needs and len(self.needs.intersection(identity.provides)) != len(
self.needs
):
return False
return True
if self.excludes and self.excludes.intersection(identity.provides):
return False
return True
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
:param other: The other permission
"""
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
p.excludes.update(self.excludes.union(other.excludes))
return p
:param other: The other permission
"""
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
p.excludes.update(self.excludes.union(other.excludes))
return p
def difference(self, other):
"""Create a new OctoPrintPermission consisting of requirements in this
permission and not in the other.
"""
def difference(self, other):
"""Create a new OctoPrintPermission consisting of requirements in this
permission and not in the other.
"""
p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
p.excludes.update(self.excludes.difference(other.excludes))
return p
p = self.__class__(
self._name, self._description, *self.needs.difference(other.needs)
)
p.excludes.update(self.excludes.difference(other.excludes))
return p
def __repr__(self):
return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
self.get_name(),
self.get_description(),
', '.join(map(repr, self.needs)))
def __repr__(self):
return "{}({!r}, {!r}, {})".format(
self.__class__.__name__,
self.get_name(),
self.get_description(),
", ".join(map(repr, self.needs)),
)
def __hash__(self):
return self.get_name().__hash__()
def __hash__(self):
return self.get_name().__hash__()
def __eq__(self, other):
return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
def __eq__(self, other):
return (
isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
)
class PluginOctoPrintPermission(OctoPrintPermission):
def __init__(self, *args, **kwargs):
self.plugin = kwargs.pop("plugin", None)
OctoPrintPermission.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
self.plugin = kwargs.pop("plugin", None)
OctoPrintPermission.__init__(self, *args, **kwargs)
def as_dict(self):
result = OctoPrintPermission.as_dict(self)
result["plugin"] = self.plugin
return result
def as_dict(self):
result = OctoPrintPermission.as_dict(self)
result["plugin"] = self.plugin
return result
class PluginIdentityContext(object):
"""Identity context for not initialized Permissions
"""Identity context for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
Needed to support @Permissions.PLUGIN_X_Y.require()
Will search the permission when needed
"""
def __init__(self, key, http_exception=None):
self.key = key
self.http_exception = http_exception
"""The permission of this principal
"""
Will search the permission when needed
"""
@property
def identity(self):
"""The identity of this principal
"""
return g.identity
def __init__(self, key, http_exception=None):
self.key = key
self.http_exception = http_exception
"""The permission of this principal
"""
def can(self):
"""Whether the identity has access to the permission
"""
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
@property
def identity(self):
"""The identity of this principal"""
return g.identity
return permission.can()
def can(self):
"""Whether the identity has access to the permission"""
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
def __call__(self, f):
@wraps(f)
def _decorated(*args, **kw):
with self:
rv = f(*args, **kw)
return rv
return permission.can()
return _decorated
def __call__(self, f):
@wraps(f)
def _decorated(*args, **kw):
with self:
rv = f(*args, **kw)
return rv
def __enter__(self):
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
return _decorated
# check the permission here
if not permission.can():
if self.http_exception:
abort(self.http_exception, permission)
raise PermissionDenied(permission)
def __enter__(self):
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
def __exit__(self, *args):
return False
# check the permission here
if not permission.can():
if self.http_exception:
abort(self.http_exception, permission)
raise PermissionDenied(permission)
def __exit__(self, *args):
return False
class PluginPermissionDecorator(Permission):
"""Decorator Class for not initialized Permissions
"""Decorator Class for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
"""
def __init__(self, key):
self.key = key
Needed to support @Permissions.PLUGIN_X_Y.require()
"""
def require(self, http_exception=None):
return PluginIdentityContext(self.key, http_exception)
def __init__(self, key):
self.key = key
def require(self, http_exception=None):
return PluginIdentityContext(self.key, http_exception)
class PermissionsMetaClass(type):
permissions = OrderedDict()
permissions = OrderedDict()
def __new__(mcs, name, bases, args):
cls = type.__new__(mcs, name, bases, args)
def __new__(mcs, name, bases, args):
cls = type.__new__(mcs, name, bases, args)
for key, value in args.items():
if isinstance(value, OctoPrintPermission):
value.key = key
mcs.permissions[key] = value
delattr(cls, key)
for key, value in args.items():
if isinstance(value, OctoPrintPermission):
value.key = key
mcs.permissions[key] = value
delattr(cls, key)
return cls
return cls
def __setattr__(cls, key, value):
if isinstance(value, OctoPrintPermission):
if key in cls.permissions:
raise PermissionAlreadyExists(key)
value.key = key
cls.permissions[key] = value
def __setattr__(cls, key, value):
if isinstance(value, OctoPrintPermission):
if key in cls.permissions:
raise PermissionAlreadyExists(key)
value.key = key
cls.permissions[key] = value
def __getattr__(cls, key):
permission = cls.permissions.get(key)
def __getattr__(cls, key):
permission = cls.permissions.get(key)
if key.startswith("PLUGIN_") and permission is None:
return PluginPermissionDecorator(key)
if key.startswith("PLUGIN_") and permission is None:
return PluginPermissionDecorator(key)
return permission
return permission
def all(cls):
return list(cls.permissions.values())
def all(cls):
return list(cls.permissions.values())
def filter(cls, cb):
return list(filter(cb, cls.all()))
def filter(cls, cb):
return list(filter(cb, cls.all()))
def find(cls, p, filter=None):
key = None
if isinstance(p, OctoPrintPermission):
key = p.key
elif isinstance(p, dict):
key = p.get("key")
elif isinstance(p, basestring):
key = p
def find(cls, p, filter=None):
key = None
if isinstance(p, OctoPrintPermission):
key = p.key
elif isinstance(p, dict):
key = p.get("key")
elif isinstance(p, basestring):
key = p
if key is None:
return None
if key is None:
return None
return cls.match(lambda p: p.key == key, filter=filter)
return cls.match(lambda p: p.key == key, filter=filter)
def match(cls, match, filter=None):
if callable(filter):
permissions = cls.filter(filter)
else:
permissions = cls.all()
def match(cls, match, filter=None):
if callable(filter):
permissions = cls.filter(filter)
else:
permissions = cls.all()
for permission in permissions:
if match(permission):
return permission
for permission in permissions:
if match(permission):
return permission
return None
return None
class Permissions(with_metaclass(PermissionsMetaClass)):
# Special permission
ADMIN = OctoPrintPermission("Admin",
gettext("Admin is allowed to do everything"),
RoleNeed("admin"),
dangerous=True,
default_groups=[ADMIN_GROUP])
# Special permission
ADMIN = OctoPrintPermission(
"Admin",
gettext("Admin is allowed to do everything"),
RoleNeed("admin"),
dangerous=True,
default_groups=[ADMIN_GROUP],
)
STATUS = OctoPrintPermission("Status",
gettext("Allows to gather basic status information, e.g. job progress, "
"printer state, temperatures, ... Mandatory for the default UI "
"to work"),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP])
STATUS = OctoPrintPermission(
"Status",
gettext(
"Allows to gather basic status information, e.g. job progress, "
"printer state, temperatures, ... Mandatory for the default UI "
"to work"
),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
CONNECTION = OctoPrintPermission("Connection",
gettext("Allows to connect to and disconnect from a printer"),
RoleNeed("connection"),
default_groups=[USER_GROUP])
CONNECTION = OctoPrintPermission(
"Connection",
gettext("Allows to connect to and disconnect from a printer"),
RoleNeed("connection"),
default_groups=[USER_GROUP],
)
WEBCAM = OctoPrintPermission("Webcam",
gettext("Allows to watch the webcam stream"),
RoleNeed("webcam"),
default_groups=[USER_GROUP, READONLY_GROUP])
WEBCAM = OctoPrintPermission(
"Webcam",
gettext("Allows to watch the webcam stream"),
RoleNeed("webcam"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
SYSTEM = OctoPrintPermission("System",
gettext("Allows to run system commands, e.g. restart OctoPrint, "
"shutdown or reboot the system"),
RoleNeed("system"),
dangerous=True)
SYSTEM = OctoPrintPermission(
"System",
gettext(
"Allows to run system commands, e.g. restart OctoPrint, "
"shutdown or reboot the system, and to retrieve system and usage information"
),
RoleNeed("system"),
dangerous=True,
)
FILES_LIST = OctoPrintPermission("File List",
gettext("Allows to retrieve a list of all uploaded files and folders, including"
"their metadata (e.g. date, file size, analysis results, ...)"),
RoleNeed("files_list"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_UPLOAD = OctoPrintPermission("File Upload",
gettext("Allows users to upload new files, create new folders and copy existing ones. If "
"the File Delete permission is also set, File Upload also allows "
"moving files and folders."),
RoleNeed("files_upload"),
default_groups=[USER_GROUP])
FILES_DOWNLOAD = OctoPrintPermission("File Download",
gettext("Allows users to download files. The GCODE viewer is "
"affected by this as well."),
RoleNeed("files_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_DELETE = OctoPrintPermission("File Delete",
gettext("Allows users to delete files and folders. If the File Upload permission is "
"also set, File Delete also allows moving files and folders."),
RoleNeed("files_delete"),
default_groups=[USER_GROUP])
FILES_SELECT = OctoPrintPermission("File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"),
default_groups=[USER_GROUP])
FILES_LIST = OctoPrintPermission(
"File List",
gettext(
"Allows to retrieve a list of all uploaded files and folders, including"
"their metadata (e.g. date, file size, analysis results, ...)"
),
RoleNeed("files_list"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
FILES_UPLOAD = OctoPrintPermission(
"File Upload",
gettext(
"Allows users to upload new files, create new folders and copy existing ones. If "
"the File Delete permission is also set, File Upload also allows "
"moving files and folders."
),
RoleNeed("files_upload"),
default_groups=[USER_GROUP],
)
FILES_DOWNLOAD = OctoPrintPermission(
"File Download",
gettext(
"Allows users to download files. The GCODE viewer is "
"affected by this as well."
),
RoleNeed("files_download"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
FILES_DELETE = OctoPrintPermission(
"File Delete",
gettext(
"Allows users to delete files and folders. If the File Upload permission is "
"also set, File Delete also allows moving files and folders."
),
RoleNeed("files_delete"),
default_groups=[USER_GROUP],
)
FILES_SELECT = OctoPrintPermission(
"File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"),
default_groups=[USER_GROUP],
)
PRINT = OctoPrintPermission("Print",
gettext("Allows to start, pause and cancel a print job"),
RoleNeed("print"),
default_groups=[USER_GROUP])
PRINT = OctoPrintPermission(
"Print",
gettext("Allows to start, pause and cancel a print job"),
RoleNeed("print"),
default_groups=[USER_GROUP],
)
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
gettext("Allows access to the GCODE viewer if the \"File Download\""
"permission is also set."),
RoleNeed("gcodeviewer"),
default_groups=[USER_GROUP, READONLY_GROUP])
GCODE_VIEWER = OctoPrintPermission(
"GCODE viewer",
gettext(
'Allows access to the GCODE viewer if the "File Download"'
"permission is also set."
),
RoleNeed("gcodeviewer"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
gettext("Allows to watch the terminal tab but not to send commands "
"to the printer from it"),
RoleNeed("monitor_terminal"),
default_groups=[USER_GROUP, READONLY_GROUP])
MONITOR_TERMINAL = OctoPrintPermission(
"Terminal",
gettext(
"Allows to watch the terminal tab but not to send commands "
"to the printer from it"
),
RoleNeed("monitor_terminal"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
CONTROL = OctoPrintPermission("Control",
gettext("Allows to control of the printer by using the temperature controls,"
"the control tab or sending commands through the terminal."),
RoleNeed("control"),
default_groups=[USER_GROUP])
CONTROL = OctoPrintPermission(
"Control",
gettext(
"Allows to control of the printer by using the temperature controls,"
"the control tab or sending commands through the terminal."
),
RoleNeed("control"),
default_groups=[USER_GROUP],
)
SLICE = OctoPrintPermission("Slice",
gettext("Allows to slice files"),
RoleNeed("slice"),
default_groups=[USER_GROUP])
SLICE = OctoPrintPermission(
"Slice",
gettext("Allows to slice files"),
RoleNeed("slice"),
default_groups=[USER_GROUP],
)
TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
gettext("Allows to list timelapse videos"),
RoleNeed("timelapse_list"),
default_groups=[USER_GROUP, READONLY_GROUP])
TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
gettext("Allows to download timelapse videos"),
RoleNeed("timelapse_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
gettext("Allows to delete timelapse videos and unrendered timelapses"),
RoleNeed("timelapse_delete"),
default_groups=[USER_GROUP])
TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
gettext("Allows to change the timelapse settings and delete or "
"render unrendered timelapses. Includes the \"Timelapse List\","
"\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP])
SETTINGS_READ = OctoPrintPermission("Settings Access",
gettext("Allows to read non sensitive settings. Mandatory for the "
"default UI to work."),
RoleNeed("settings_read"),
default_groups=[USER_GROUP, READONLY_GROUP])
SETTINGS = OctoPrintPermission("Settings Admin",
gettext("Allows to manage settings and also to read sensitive settings"),
RoleNeed("settings"),
dangerous=True)
TIMELAPSE_LIST = OctoPrintPermission(
"Timelapse List",
gettext("Allows to list timelapse videos"),
RoleNeed("timelapse_list"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
TIMELAPSE_DOWNLOAD = OctoPrintPermission(
"Timelapse Download",
gettext("Allows to download timelapse videos"),
RoleNeed("timelapse_download"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
TIMELAPSE_DELETE = OctoPrintPermission(
"Timelapse Delete",
gettext("Allows to delete timelapse videos and unrendered timelapses"),
RoleNeed("timelapse_delete"),
default_groups=[USER_GROUP],
)
TIMELAPSE_ADMIN = OctoPrintPermission(
"Timelapse Admin",
gettext(
"Allows to change the timelapse settings and delete or "
'render unrendered timelapses. Includes the "Timelapse List",'
'"Timelapse Delete" and "Timelapse Download" permissions'
),
RoleNeed("timelapse_admin"),
TIMELAPSE_LIST,
TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP],
)
SETTINGS_READ = OctoPrintPermission(
"Settings Access",
gettext(
"Allows to read non sensitive settings. Mandatory for the "
"default UI to work."
),
RoleNeed("settings_read"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
SETTINGS = OctoPrintPermission(
"Settings Admin",
gettext("Allows to manage settings and also to read sensitive settings"),
RoleNeed("settings"),
dangerous=True,
)
class PermissionAlreadyExists(Exception):
def __init__(self, permission):
Exception.__init__(self, "Permission %s already exists" % permission)
def __init__(self, permission):
Exception.__init__(self, "Permission %s already exists" % permission)
class UnknownPermission(Exception):
def __init__(self, permissionname):
Exception.__init__(self, "Unknown permission: %s" % permissionname)
def __init__(self, permissionname):
Exception.__init__(self, "Unknown permission: %s" % permissionname)
+1297 -1135
View File
File diff suppressed because it is too large. Load diff
+281 -120
View File
@@ -1,177 +1,338 @@
# -*- 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'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import octoprint
import sys
#~~ click context
import click
import octoprint
click.disable_unicode_literals_warning = True
# ~~ click context
class OctoPrintContext(object):
"""Custom context wrapping the standard options."""
"""Custom context wrapping the standard options."""
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
self.safe_mode = safe_mode
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
self.safe_mode = safe_mode
pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True)
"""Decorator to pass in the :class:`OctoPrintContext` instance."""
#~~ Custom click option to hide from help
# ~~ Basic CLI initialization for plugins
def init_platform_for_cli(ctx):
"""
Performs a basic platform initialization for the CLI.
Plugin implementations will be initialized, but only with a subset of the usual
property injections:
* _identifier and everything else parsed from metadata
* _logger
* _connectivity_checker
* _environment_detector
* _event_bus
* _plugin_manager
* _settings
Returns: the same list of components as returned by ``init_platform``
"""
from octoprint import (
init_custom_events,
init_platform,
init_settings_plugin_config_migration_and_cleanup,
)
from octoprint import octoprint_plugin_inject_factory as opif
from octoprint import settings_plugin_inject_factory as spif
components = init_platform(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
safe_mode=True,
)
(
settings,
logger,
safe_mode,
event_manager,
connectivity_checker,
plugin_manager,
environment_detector,
) = components
init_custom_events(plugin_manager)
octoprint_plugin_inject_factory = opif(
settings,
{
"plugin_manager": plugin_manager,
"event_bus": event_manager,
"connectivity_checker": connectivity_checker,
"environment_detector": environment_detector,
},
)
settings_plugin_inject_factory = spif(settings)
plugin_manager.implementation_inject_factories = [
octoprint_plugin_inject_factory,
settings_plugin_inject_factory,
]
plugin_manager.initialize_implementations()
init_settings_plugin_config_migration_and_cleanup(plugin_manager)
return components
# ~~ Custom click option to hide from help
class HiddenOption(click.Option):
"""Custom option sub class with empty help."""
def get_help_record(self, ctx):
pass
"""Custom option sub class with empty help."""
def get_help_record(self, ctx):
pass
def hidden_option(*param_decls, **attrs):
"""Attaches a hidden option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`; all keyword
arguments are forwarded unchanged. This is equivalent to creating an
:class:`Option` instance manually and attaching it to the
:attr:`Command.params` list.
"""
"""Attaches a hidden option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`; all keyword
arguments are forwarded unchanged. This is equivalent to creating an
:class:`Option` instance manually and attaching it to the
:attr:`Command.params` list.
"""
import inspect
from click.decorators import _param_memo
import inspect
def decorator(f):
if 'help' in attrs:
attrs['help'] = inspect.cleandoc(attrs['help'])
_param_memo(f, HiddenOption(param_decls, **attrs))
return f
return decorator
from click.decorators import _param_memo
def decorator(f):
if "help" in attrs:
attrs["help"] = inspect.cleandoc(attrs["help"])
_param_memo(f, HiddenOption(param_decls, **attrs))
return f
return decorator
# ~~ helper for setting context options
#~~ helper for setting context options
def set_ctx_obj_option(ctx, param, value):
"""Helper for setting eager options on the context."""
if ctx.obj is None:
ctx.obj = OctoPrintContext()
if value != param.default:
setattr(ctx.obj, param.name, value)
elif param.default is not None:
setattr(ctx.obj, param.name, param.default)
"""Helper for setting eager options on the context."""
if ctx.obj is None:
ctx.obj = OctoPrintContext()
if value != param.default:
setattr(ctx.obj, param.name, value)
elif param.default is not None:
setattr(ctx.obj, param.name, param.default)
# ~~ helper for retrieving context options
#~~ helper for retrieving context options
def get_ctx_obj_option(ctx, key, default, include_parents=True):
if include_parents and hasattr(ctx, "parent") and ctx.parent:
fallback = get_ctx_obj_option(ctx.parent, key, default)
else:
fallback = default
return getattr(ctx.obj, key, fallback)
if include_parents and hasattr(ctx, "parent") and ctx.parent:
fallback = get_ctx_obj_option(ctx.parent, key, default)
else:
fallback = default
return getattr(ctx.obj, key, fallback)
# ~~ helper for setting a lot of bulk options
#~~ helper for setting a lot of bulk options
def bulk_options(options):
"""
Utility decorator to decorate a function with a list of click decorators.
"""
Utility decorator to decorate a function with a list of click decorators.
The provided list of ``options`` will be reversed to ensure correct
processing order (inverse from what would be intuitive).
"""
The provided list of ``options`` will be reversed to ensure correct
processing order (inverse from what would be intuitive).
"""
def decorator(f):
options.reverse()
for option in options:
option(f)
return f
return decorator
def decorator(f):
options.reverse()
for option in options:
option(f)
return f
return decorator
# ~~ helper for setting --basedir, --config and --verbose options
#~~ helper for setting --basedir, --config and --verbose options
def standard_options(hidden=False):
"""
Decorator to add the standard options shared among all "octoprint" commands.
"""
Decorator to add the standard options shared among all "octoprint" commands.
Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden``
is set to ``True``, the options will be available on the command but not
listed in its help page.
"""
Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden``
is set to ``True``, the options will be available on the command but not
listed in its help page.
"""
factory = click.option
if hidden:
factory = hidden_option
factory = click.option
if hidden:
factory = hidden_option
options = [
factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the basedir to use for configs, uploads, timelapses etc."),
factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the config file to use."),
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Increase logging verbosity."),
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Enable safe mode; disables all third party plugins.")
]
options = [
factory(
"--basedir",
"-b",
type=click.Path(),
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Specify the basedir to use for configs, uploads, timelapses etc.",
),
factory(
"--config",
"-c",
"configfile",
type=click.Path(),
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Specify the config file to use.",
),
factory(
"--verbose",
"-v",
"verbosity",
count=True,
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Increase logging verbosity.",
),
factory(
"--safe",
"safe_mode",
is_flag=True,
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Enable safe mode; disables all third party plugins.",
),
]
return bulk_options(options)
return bulk_options(options)
#~~ helper for settings legacy options we still have to support on "octoprint"
legacy_options = bulk_options([
hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option),
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option),
hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option),
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option),
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option),
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option),
hidden_option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option)
])
# ~~ helper for settings legacy options we still have to support on "octoprint"
legacy_options = bulk_options(
[
hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option),
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option),
hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option),
hidden_option(
"--daemon",
type=click.Choice(["start", "stop", "restart"]),
callback=set_ctx_obj_option,
),
hidden_option(
"--pid",
type=click.Path(),
default="/tmp/octoprint.pid",
callback=set_ctx_obj_option,
),
hidden_option(
"--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option
),
hidden_option(
"--ignore-blacklist",
"ignore_blacklist",
is_flag=True,
callback=set_ctx_obj_option,
),
]
)
"""Legacy options available directly on the "octoprint" command in earlier versions.
Kept available for reasons of backwards compatibility, but hidden from the
generated help pages."""
#~~ "octoprint" command, merges server_commands and plugin_commands groups
# ~~ "octoprint" command, merges server_commands and plugin_commands groups
from .server import server_commands
from .plugins import plugin_commands
from .dev import dev_commands
from .client import client_commands
from .config import config_commands
from .analysis import analysis_commands
from .user import user_commands
from .analysis import analysis_commands # noqa: E402
from .client import client_commands # noqa: E402
from .config import config_commands # noqa: E402
from .dev import dev_commands # noqa: E402
from .plugins import plugin_commands # noqa: E402
from .server import server_commands # noqa: E402
from .systeminfo import systeminfo_commands # noqa: E402
from .user import user_commands # noqa: E402
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands])
@click.group(
name="octoprint",
invoke_without_command=True,
cls=click.CommandCollection,
sources=[
server_commands,
plugin_commands,
dev_commands,
client_commands,
config_commands,
analysis_commands,
user_commands,
systeminfo_commands,
],
)
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
@click.pass_context
def octo(ctx, **kwargs):
if ctx.invoked_subcommand is None:
# We have to support calling the octoprint command without any
# sub commands to remain backwards compatible.
#
# But better print a message to inform people that they should
# use the sub commands instead.
if ctx.invoked_subcommand is None:
# We have to support calling the octoprint command without any
# sub commands to remain backwards compatible.
#
# But better print a message to inform people that they should
# use the sub commands instead.
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
daemon = get_value("daemon")
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
if daemon:
click.echo("Daemon operation via \"octoprint --daemon "
"start|stop|restart\" is deprecated, please use "
"\"octoprint daemon start|stop|restart\" from now on")
daemon = get_value("daemon")
if sys.platform == "win32" or sys.platform == "darwin":
click.echo("Sorry, daemon mode is not supported under your operating system right now")
else:
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo("Starting the server via \"octoprint\" is deprecated, "
"please use \"octoprint serve\" from now on.")
if daemon:
click.echo(
'Daemon operation via "octoprint --daemon '
'start|stop|restart" is deprecated, please use '
'"octoprint daemon start|stop|restart" from now on'
)
from octoprint.cli.server import serve_command
ctx.invoke(serve_command, **kwargs)
if sys.platform == "win32" or sys.platform == "darwin":
click.echo(
"Sorry, daemon mode is not supported under your operating system right now"
)
else:
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo(
'Starting the server via "octoprint" is deprecated, '
'please use "octoprint serve" from now on.'
)
from octoprint.cli.server import serve_command
ctx.invoke(serve_command, **kwargs)
+71 -42
View File
@@ -1,22 +1,25 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
#~~ "octoprint util" commands
# ~~ "octoprint util" commands
@click.group()
def analysis_commands():
pass
pass
@analysis_commands.group(name="analysis")
def util():
"""Analysis tools."""
pass
"""Analysis tools."""
pass
@util.command(name="gcode")
@@ -30,49 +33,75 @@ def util():
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
@click.option("--progress", "progress", is_flag=True)
@click.argument("path", type=click.Path())
def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
"""Runs a GCODE file analysis."""
def gcode_command(
path,
speedx,
speedy,
speedz,
offset,
maxt,
throttle,
throttle_lines,
g90_extruder,
progress,
):
"""Runs a GCODE file analysis."""
import time
import yaml
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
import time
throttle_callback = None
if throttle:
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
import yaml
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
start_time = monotonic_time()
throttle_callback = None
if throttle:
progress_callback = None
if progress:
def progress_callback(percentage):
click.echo("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
interpreter.load(path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder)
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = monotonic_time()
progress_callback = None
if progress:
def progress_callback(percentage):
click.echo("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
interpreter.load(
path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder,
)
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=4,
allow_unicode=True,
)
)
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=4, allow_unicode=True))
if __name__ == "__main__":
gcode_command()
gcode_command()
+207 -138
View File
@@ -1,107 +1,125 @@
# -*- 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'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import io
import json
import octoprint_client
from octoprint.cli import get_ctx_obj_option, bulk_options
from octoprint import init_settings, FatalStartupError
import click
from past.builtins import unicode
import octoprint_client
from octoprint import FatalStartupError, init_settings
from octoprint.cli import bulk_options, get_ctx_obj_option
click.disable_unicode_literals_warning = True
class JsonStringParamType(click.ParamType):
name = "json"
name = "json"
def convert(self, value, param, ctx):
try:
return json.loads(value)
except Exception:
self.fail("%s is not a valid json string" % value, param, ctx)
def convert(self, value, param, ctx):
try:
return json.loads(value)
except Exception:
self.fail("%s is not a valid json string" % value, param, ctx)
def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None):
assert(host is not None or settings is not None)
assert(port is not None or settings is not None)
assert(apikey is not None or settings is not None)
def create_client(
settings=None,
apikey=None,
host=None,
port=None,
httpuser=None,
httppass=None,
https=False,
prefix=None,
):
assert host is not None or settings is not None
assert port is not None or settings is not None
assert apikey is not None or settings is not None
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
if not apikey:
apikey = settings.get(["api", "key"])
if not apikey:
apikey = settings.get(["api", "key"])
baseurl = octoprint_client.build_base_url(https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix)
baseurl = octoprint_client.build_base_url(
https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix,
)
return octoprint_client.Client(baseurl, apikey)
return octoprint_client.Client(baseurl, apikey)
client_options = bulk_options([
click.option("--apikey", "-a", type=click.STRING),
click.option("--host", "-h", type=click.STRING),
click.option("--port", "-p", type=click.INT),
click.option("--httpuser", type=click.STRING),
click.option("--httppass", type=click.STRING),
click.option("--https", is_flag=True),
click.option("--prefix", type=click.STRING)
])
client_options = bulk_options(
[
click.option("--apikey", "-a", type=click.STRING),
click.option("--host", "-h", type=click.STRING),
click.option("--port", "-p", type=click.INT),
click.option("--httpuser", type=click.STRING),
click.option("--httppass", type=click.STRING),
click.option("--https", is_flag=True),
click.option("--prefix", type=click.STRING),
]
)
"""Common options to configure an API client."""
@click.group()
def client_commands():
pass
pass
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
@client_commands.group("client", context_settings={"ignore_unknown_options": True})
@client_options
@click.pass_context
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
try:
settings = None
if not host or not port or not apikey:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
"""Basic API client."""
try:
settings = None
if not host or not port or not apikey:
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
ctx.obj.client = create_client(settings=settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
ctx.obj.client = create_client(
settings=settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
ctx.exit(-1)
except FatalStartupError as e:
click.echo(str(e), err=True)
click.echo("There was a fatal error initializing the client.", err=True)
ctx.exit(-1)
def log_response(response, status_code=True, body=True, headers=False):
if status_code:
click.echo("Status Code: {}".format(response.status_code))
if headers:
for header, value in response.headers.items():
click.echo("{}: {}".format(header, value))
click.echo()
if body:
click.echo(response.text)
if status_code:
click.echo("Status Code: {}".format(response.status_code))
if headers:
for header, value in response.headers.items():
click.echo("{}: {}".format(header, value))
click.echo()
if body:
click.echo(response.text)
@client.command("get")
@@ -109,9 +127,9 @@ def log_response(response, status_code=True, body=True, headers=False):
@click.option("--timeout", type=float, default=None)
@click.pass_context
def get(ctx, path, timeout):
"""Performs a GET request against the specified server path."""
r = ctx.obj.client.get(path, timeout=timeout)
log_response(r)
"""Performs a GET request against the specified server path."""
r = ctx.obj.client.get(path, timeout=timeout)
log_response(r)
@client.command("post_json")
@@ -120,9 +138,9 @@ def get(ctx, path, timeout):
@click.option("--timeout", type=float, default=None)
@click.pass_context
def post_json(ctx, path, data, timeout):
"""POSTs JSON data to the specified server path."""
r = ctx.obj.client.post_json(path, data, timeout=timeout)
log_response(r)
"""POSTs JSON data to the specified server path."""
r = ctx.obj.client.post_json(path, data, timeout=timeout)
log_response(r)
@client.command("patch_json")
@@ -131,75 +149,118 @@ def post_json(ctx, path, data, timeout):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def patch_json(ctx, path, data, timeout):
"""PATCHes JSON data to the specified server path."""
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
log_response(r)
"""PATCHes JSON data to the specified server path."""
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
log_response(r)
@client.command("post_from_file")
@click.argument("path")
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.argument(
"file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)
)
@click.option("--json", is_flag=True)
@click.option("--yaml", is_flag=True)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with io.open(file_path, 'rt') as fp:
data = json.load(fp)
else:
import yaml
with io.open(file_path, 'rt') as fp:
data = yaml.safe_load(fp)
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with io.open(file_path, "rt") as fp:
data = json.load(fp)
else:
import yaml
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with io.open(file_path, 'rb') as fp:
data = fp.read()
with io.open(file_path, "rt") as fp:
data = yaml.safe_load(fp)
r = ctx.obj.client.post(path, data, timeout=timeout)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with io.open(file_path, "rb") as fp:
data = fp.read()
log_response(r)
r = ctx.obj.client.post(path, data, timeout=timeout)
log_response(r)
@client.command("command")
@click.argument("path")
@click.argument("command")
@click.option("--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
@click.option(
"--str",
"-s",
"str_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, unicode]),
)
@click.option(
"--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])
)
@click.option(
"--float",
"-f",
"float_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, float]),
)
@click.option(
"--bool",
"-b",
"bool_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, bool]),
)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
"""Sends a JSON command to the specified server path."""
data = dict()
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
log_response(r, body=False)
def command(
ctx, path, command, str_params, int_params, float_params, bool_params, timeout
):
"""Sends a JSON command to the specified server path."""
data = {}
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
log_response(r, body=False)
@client.command("upload")
@click.argument("path")
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
@click.argument(
"file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)
)
@click.option(
"--parameter",
"-P",
"params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, unicode]),
)
@click.option("--file-name", type=click.STRING)
@click.option("--content-type", type=click.STRING)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
"""Uploads the specified file to the specified server path."""
data = dict()
for param in params:
data[param[0]] = param[1]
"""Uploads the specified file to the specified server path."""
data = {}
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.upload(path, file_path,
additional=data, file_name=file_name, content_type=content_type, timeout=timeout)
log_response(r)
r = ctx.obj.client.upload(
path,
file_path,
additional=data,
file_name=file_name,
content_type=content_type,
timeout=timeout,
)
log_response(r)
@client.command("delete")
@@ -207,37 +268,45 @@ def upload(ctx, path, file_path, params, file_name, content_type, timeout):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def delete(ctx, path, timeout):
"""Sends a DELETE request to the specified server path."""
r = ctx.obj.client.delete(path, timeout=timeout)
log_response(r)
"""Sends a DELETE request to the specified server path."""
r = ctx.obj.client.delete(path, timeout=timeout)
log_response(r)
@client.command("listen")
@click.pass_context
def listen(ctx):
def on_connect(ws):
click.echo(">>> Connected!")
def on_connect(ws):
click.echo("--- Connected!")
def on_close(ws):
click.echo(">>> Connection closed!")
def on_close(ws):
click.echo("--- Connection closed!")
def on_error(ws, error):
click.echo("!!! Error: {}".format(error))
def on_error(ws, error):
click.echo("!!! Error: {}".format(error))
def on_heartbeat(ws):
click.echo("<3")
def on_sent(ws, data):
click.echo(">>> {}".format(json.dumps(data)))
def on_message(ws, message_type, message_payload):
click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload)))
def on_heartbeat(ws):
click.echo("<3")
socket = ctx.obj.client.create_socket(on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_heartbeat=on_heartbeat,
on_message=on_message)
def on_message(ws, message_type, message_payload):
click.echo(
"<<< {}, Payload: {}".format(message_type, json.dumps(message_payload))
)
click.echo(">>> Waiting for client to exit")
try:
socket.wait()
finally:
click.echo(">>> Goodbye...")
socket = ctx.obj.client.create_socket(
on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_sent=on_sent,
on_heartbeat=on_heartbeat,
on_message=on_message,
)
click.echo("--- Waiting for client to exit")
try:
socket.wait()
finally:
click.echo("--- Goodbye...")
+158 -147
View File
@@ -1,95 +1,104 @@
# -*- 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'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
from octoprint import init_settings, FatalStartupError
from octoprint.cli import standard_options, bulk_options, get_ctx_obj_option
import yaml
import json
import logging
import pprint
import click
import yaml
from octoprint import FatalStartupError, init_settings
from octoprint.cli import get_ctx_obj_option, standard_options
click.disable_unicode_literals_warning = True
def _to_settings_path(path):
if not isinstance(path, (list, tuple)):
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
return path
if not isinstance(path, (list, tuple)):
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
return path
def _set_helper(settings, path, value, data_type=None):
path = _to_settings_path(path)
path = _to_settings_path(path)
method = settings.set
if data_type is not None:
name = None
if data_type == bool:
name = "setBoolean"
elif data_type == float:
name = "setFloat"
elif data_type == int:
name = "setInt"
method = settings.set
if data_type is not None:
name = None
if data_type == bool:
name = "setBoolean"
elif data_type == float:
name = "setFloat"
elif data_type == int:
name = "setInt"
if name is not None:
method = getattr(settings, name)
if name is not None:
method = getattr(settings, name)
method(path, value)
settings.save()
method(path, value)
settings.save()
# ~~ "octoprint config" commands
#~~ "octoprint config" commands
@click.group()
def config_commands():
pass
pass
@config_commands.group(name="config")
@click.pass_context
def config(ctx):
"""Basic config manipulation."""
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
try:
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
"""Basic config manipulation."""
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
try:
ctx.obj.settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
except FatalStartupError as e:
click.echo(str(e), err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
@config.command(name="set")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--bool", "as_bool", is_flag=True,
help="Interpret value as bool")
@click.option("--float", "as_float", is_flag=True,
help="Interpret value as float")
@click.option("--int", "as_int", is_flag=True,
help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True,
help="Parse value from json")
@click.option("--bool", "as_bool", is_flag=True, help="Interpret value as bool")
@click.option("--float", "as_float", is_flag=True, help="Interpret value as float")
@click.option("--int", "as_int", is_flag=True, help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True, help="Parse value from json")
@click.pass_context
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
"""Sets a config path to the provided value."""
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
"""Sets a config path to the provided value."""
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(str(e), err=True)
ctx.exit(-1)
data_type = None
if as_bool:
data_type = bool
elif as_float:
data_type = float
elif as_int:
data_type = int
data_type = None
if as_bool:
data_type = bool
elif as_float:
data_type = float
elif as_int:
data_type = int
_set_helper(ctx.obj.settings, path, value, data_type=data_type)
_set_helper(ctx.obj.settings, path, value, data_type=data_type)
@config.command(name="remove")
@@ -97,8 +106,8 @@ def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
@click.argument("path", type=click.STRING)
@click.pass_context
def remove_command(ctx, path):
"""Removes a config path."""
_set_helper(ctx.obj.settings, path, None)
"""Removes a config path."""
_set_helper(ctx.obj.settings, path, None)
@config.command(name="append_value")
@@ -108,25 +117,25 @@ def remove_command(ctx, path):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def append_value_command(ctx, path, value, as_json=False):
"""Appends value to list behind config path."""
path = _to_settings_path(path)
"""Appends value to list behind config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(str(e), err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot append to non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot append to non-list value at given path", err=True)
ctx.exit(-1)
current.append(value)
_set_helper(ctx.obj.settings, path, current)
current.append(value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="insert_value")
@@ -137,25 +146,25 @@ def append_value_command(ctx, path, value, as_json=False):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def insert_value_command(ctx, path, index, value, as_json=False):
"""Inserts value at index of list behind config key."""
path = _to_settings_path(path)
"""Inserts value at index of list behind config key."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(str(e), err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot insert into non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot insert into non-list value at given path", err=True)
ctx.exit(-1)
current.insert(index, value)
_set_helper(ctx.obj.settings, path, current)
current.insert(index, value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="remove_value")
@@ -165,78 +174,80 @@ def insert_value_command(ctx, path, index, value, as_json=False):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def remove_value_command(ctx, path, value, as_json=False):
"""Removes value from list at config path."""
path = _to_settings_path(path)
"""Removes value from list at config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(str(e), err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
if not value in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
if value not in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
current.remove(value)
_set_helper(ctx.obj.settings, path, current)
current.remove(value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="get")
@click.argument("path", type=click.STRING)
@click.option("--json", "as_json", is_flag=True,
help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True,
help="Output value formatted as YAML")
@click.option("--raw", "as_raw", is_flag=True,
help="Output value as raw string representation")
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
@click.option(
"--raw", "as_raw", is_flag=True, help="Output value as raw string representation"
)
@standard_options(hidden=True)
@click.pass_context
def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
"""Retrieves value from config path."""
path = _to_settings_path(path)
value = ctx.obj.settings.get(path, merged=True)
"""Retrieves value from config path."""
path = _to_settings_path(path)
value = ctx.obj.settings.get(path, merged=True)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(
value, default_flow_style=False, indent=4, allow_unicode=True
)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
click.echo(output)
click.echo(output)
@config.command(name="effective")
@click.option("--json", "as_json", is_flag=True,
help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True,
help="Output value formatted as YAML")
@click.option("--raw", "as_raw", is_flag=True,
help="Output value as raw string representation")
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
@click.option(
"--raw", "as_raw", is_flag=True, help="Output value as raw string representation"
)
@standard_options(hidden=True)
@click.pass_context
def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
"""Retrieves the full effective config."""
value = ctx.obj.settings.effective
"""Retrieves the full effective config."""
value = ctx.obj.settings.effective
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(
value, default_flow_style=False, indent=4, allow_unicode=True
)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
click.echo(output)
click.echo(output)
+211 -180
View File
@@ -2,238 +2,269 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
from past.builtins import basestring
class OctoPrintDevelCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that provides commands relevant for (plugin) development
based on availability of development dependencies.
"""
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that provides commands relevant for (plugin) development
based on availability of development dependencies.
"""
sep = ":"
groups = ("plugin",)
sep = ":"
groups = ("plugin",)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
from octoprint.util.commandline import CommandlineCaller
from functools import partial
from functools import partial
def log_util(f):
def log(*lines):
for line in lines:
f(line)
return log
from octoprint.util.commandline import CommandlineCaller
self.command_caller = CommandlineCaller()
self.command_caller.on_log_call = log_util(lambda x: click.echo(">> {}".format(x)))
self.command_caller.on_log_stdout = log_util(click.echo)
self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True))
def log_util(f):
def log(*lines):
for line in lines:
f(line)
def _get_prefix_methods(self, method_prefix):
for name in [x for x in dir(self) if x.startswith(method_prefix)]:
method = getattr(self, name)
yield method
return log
def _get_commands_from_prefix_methods(self, method_prefix):
for method in self._get_prefix_methods(method_prefix):
result = method()
if result is not None and isinstance(result, click.Command):
yield result
self.command_caller = CommandlineCaller()
self.command_caller.on_log_call = log_util(
lambda x: click.echo(">> {}".format(x))
)
self.command_caller.on_log_stdout = log_util(click.echo)
self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True))
def _get_commands(self):
result = dict()
for group in self.groups:
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
result[group + self.sep + command.name] = command
return result
def _get_prefix_methods(self, method_prefix):
for name in [x for x in dir(self) if x.startswith(method_prefix)]:
method = getattr(self, name)
yield method
def list_commands(self, ctx):
result = [name for name in self._get_commands()]
result.sort()
return result
def _get_commands_from_prefix_methods(self, method_prefix):
for method in self._get_prefix_methods(method_prefix):
result = method()
if result is not None and isinstance(result, click.Command):
yield result
def get_command(self, ctx, cmd_name):
commands = self._get_commands()
return commands.get(cmd_name, None)
def _get_commands(self):
result = {}
for group in self.groups:
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
result[group + self.sep + command.name] = command
return result
def plugin_new(self):
try:
import cookiecutter.main
except ImportError:
return None
def list_commands(self, ctx):
result = [name for name in self._get_commands()]
result.sort()
return result
try:
# we depend on Cookiecutter >= 1.4
from cookiecutter.prompt import StrictEnvironment
except ImportError:
return None
def get_command(self, ctx, cmd_name):
commands = self._get_commands()
return commands.get(cmd_name, None)
import contextlib
def plugin_new(self):
try:
import cookiecutter.main
except ImportError:
return None
@contextlib.contextmanager
def custom_cookiecutter_config(config):
"""
Allows overriding cookiecutter's user config with a custom dict
with fallback to the original data.
"""
from octoprint.util import fallback_dict
try:
# we depend on Cookiecutter >= 1.4
from cookiecutter.prompt import StrictEnvironment
except ImportError:
return None
original_get_user_config = cookiecutter.main.get_user_config
try:
def f(*args, **kwargs):
original_config = original_get_user_config(*args, **kwargs)
return fallback_dict(config, original_config)
cookiecutter.main.get_user_config = f
yield
finally:
cookiecutter.main.get_user_config = original_get_user_config
import contextlib
@contextlib.contextmanager
def custom_cookiecutter_prompt(options):
"""
Custom cookiecutter prompter for the template config.
@contextlib.contextmanager
def custom_cookiecutter_config(config):
"""
Allows overriding cookiecutter's user config with a custom dict
with fallback to the original data.
"""
from octoprint.util import fallback_dict
If a setting is available in the provided options (read from the CLI)
that will be used, otherwise the user will be prompted for a value
via click.
"""
original_prompt_for_config = cookiecutter.main.prompt_for_config
original_get_user_config = cookiecutter.main.get_user_config
try:
def custom_prompt_for_config(context, no_input=False):
cookiecutter_dict = dict()
def f(*args, **kwargs):
original_config = original_get_user_config(*args, **kwargs)
return fallback_dict(config, original_config)
env = StrictEnvironment()
cookiecutter.main.get_user_config = f
yield
finally:
cookiecutter.main.get_user_config = original_get_user_config
for key, raw in context['cookiecutter'].items():
if key in options:
val = options[key]
else:
if not isinstance(raw, basestring):
raw = str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
@contextlib.contextmanager
def custom_cookiecutter_prompt(options):
"""
Custom cookiecutter prompter for the template config.
if not no_input:
val = click.prompt(key, default=val)
If a setting is available in the provided options (read from the CLI)
that will be used, otherwise the user will be prompted for a value
via click.
"""
original_prompt_for_config = cookiecutter.main.prompt_for_config
cookiecutter_dict[key] = val
return cookiecutter_dict
def custom_prompt_for_config(context, no_input=False):
cookiecutter_dict = {}
try:
cookiecutter.main.prompt_for_config = custom_prompt_for_config
yield
finally:
cookiecutter.main.prompt_for_config = original_prompt_for_config
env = StrictEnvironment()
@click.command("new")
@click.option("--name", "-n", help="The name of the plugin")
@click.option("--package", "-p", help="The plugin package")
@click.option("--author", "-a", help="The plugin author's name")
@click.option("--email", "-e", help="The plugin author's mail address")
@click.option("--license", "-l", help="The plugin's license")
@click.option("--description", "-d", help="The plugin's description")
@click.option("--homepage", help="The plugin's homepage URL")
@click.option("--source", "-s", help="The URL to the plugin's source")
@click.option("--installurl", "-i", help="The plugin's install URL")
@click.argument("identifier", required=False)
def command(name, package, author, email, description, license, homepage, source, installurl, identifier):
"""Creates a new plugin based on the OctoPrint Plugin cookiecutter template."""
from octoprint.util import tempdir
for key, raw in context["cookiecutter"].items():
if key in options:
val = options[key]
else:
if not isinstance(raw, basestring):
raw = str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
# deleting a git checkout folder might run into access errors due
# to write-protected sub folders, so we use a custom onerror handler
# that tries to fix such permissions
def onerror(func, path, exc_info):
"""Originally from http://stackoverflow.com/a/2656405/2028598"""
import stat
import os
if not no_input:
val = click.prompt(key, default=val)
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
cookiecutter_dict[key] = val
return cookiecutter_dict
with tempdir(onerror=onerror) as path:
custom = dict(cookiecutters_dir=path)
with custom_cookiecutter_config(custom):
raw_options = dict(
plugin_identifier=identifier,
plugin_package=package,
plugin_name=name,
full_name=author,
email=email,
plugin_description=description,
plugin_license=license,
plugin_homepage=homepage,
plugin_source=source,
plugin_installurl=installurl
)
options = dict((k, v) for k, v in raw_options.items() if v is not None)
try:
cookiecutter.main.prompt_for_config = custom_prompt_for_config
yield
finally:
cookiecutter.main.prompt_for_config = original_prompt_for_config
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin")
@click.command("new")
@click.option("--name", "-n", help="The name of the plugin")
@click.option("--package", "-p", help="The plugin package")
@click.option("--author", "-a", help="The plugin author's name")
@click.option("--email", "-e", help="The plugin author's mail address")
@click.option("--license", "-l", help="The plugin's license")
@click.option("--description", "-d", help="The plugin's description")
@click.option("--homepage", help="The plugin's homepage URL")
@click.option("--source", "-s", help="The URL to the plugin's source")
@click.option("--installurl", "-i", help="The plugin's install URL")
@click.argument("identifier", required=False)
def command(
name,
package,
author,
email,
description,
license,
homepage,
source,
installurl,
identifier,
):
"""Creates a new plugin based on the OctoPrint Plugin cookiecutter template."""
from octoprint.util import tempdir
return command
# deleting a git checkout folder might run into access errors due
# to write-protected sub folders, so we use a custom onerror handler
# that tries to fix such permissions
def onerror(func, path, exc_info):
"""Originally from http://stackoverflow.com/a/2656405/2028598"""
import os
import stat
def plugin_install(self):
@click.command("install")
@click.option("--path", help="Path of the local plugin development folder to install")
def command(path):
"""
Installs the local plugin in development mode.
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
Note: This can NOT be used to install plugins from remote locations
such as the plugin repository! It is strictly for local development
of plugins, to ensure the plugin is installed (editable) into the
same python environment that OctoPrint is installed under.
"""
with tempdir(onerror=onerror) as path:
custom = {"cookiecutters_dir": path}
with custom_cookiecutter_config(custom):
raw_options = {
"plugin_identifier": identifier,
"plugin_package": package,
"plugin_name": name,
"full_name": author,
"email": email,
"plugin_description": description,
"plugin_license": license,
"plugin_homepage": homepage,
"plugin_source": source,
"plugin_installurl": installurl,
}
options = dict(
(k, v) for k, v in raw_options.items() if v is not None
)
import os
import sys
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter(
"gh:OctoPrint/cookiecutter-octoprint-plugin"
)
if not path:
path = os.getcwd()
return command
# check if this really looks like a plugin
if not os.path.isfile(os.path.join(path, "setup.py")):
click.echo("This doesn't look like an OctoPrint plugin folder")
sys.exit(1)
def plugin_install(self):
@click.command("install")
@click.option(
"--path", help="Path of the local plugin development folder to install"
)
def command(path):
"""
Installs the local plugin in development mode.
self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path)
Note: This can NOT be used to install plugins from remote locations
such as the plugin repository! It is strictly for local development
of plugins, to ensure the plugin is installed (editable) into the
same python environment that OctoPrint is installed under.
"""
return command
import os
import sys
def plugin_uninstall(self):
@click.command("uninstall")
@click.argument("name")
def command(name):
"""Uninstalls the plugin with the given name."""
import sys
if not path:
path = os.getcwd()
lower_name = name.lower()
if not lower_name.startswith("octoprint_") and not lower_name.startswith("octoprint-"):
click.echo("This doesn't look like an OctoPrint plugin name")
sys.exit(1)
# check if this really looks like a plugin
if not os.path.isfile(os.path.join(path, "setup.py")):
click.echo("This doesn't look like an OctoPrint plugin folder")
sys.exit(1)
call = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
self.command_caller.call(call)
self.command_caller.call(
[sys.executable, "-m", "pip", "install", "-e", "."], cwd=path
)
return command
def plugin_uninstall(self):
@click.command("uninstall")
@click.argument("name")
def command(name):
"""Uninstalls the plugin with the given name."""
import sys
lower_name = name.lower()
if not lower_name.startswith("octoprint_") and not lower_name.startswith(
"octoprint-"
):
click.echo("This doesn't look like an OctoPrint plugin name")
sys.exit(1)
call = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
self.command_caller.call(call)
return command
return command
@click.group()
def dev_commands():
pass
pass
@dev_commands.group(name="dev", cls=OctoPrintDevelCommands)
def dev():
"""Additional commands for development tasks."""
pass
"""Additional commands for development tasks."""
pass
+109 -94
View File
@@ -1,137 +1,152 @@
# -*- 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'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
import logging.config
from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option
import click
from octoprint.cli import OctoPrintContext, get_ctx_obj_option, pass_octoprint_ctx
from octoprint.util import dict_merge
click.disable_unicode_literals_warning = True
LOGGING_CONFIG = {
"version": 1,
"formatters": {
"brief": {
"format": "%(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "brief",
"stream": "ext://sys.stdout"
}
},
"loggers": {
"octoprint.plugin.core": {
"level": logging.ERROR
}
},
"root": {
"level": logging.WARNING
}
"version": 1,
"formatters": {"brief": {"format": "%(message)s"}},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "brief",
"stream": "ext://sys.stdout",
}
},
"loggers": {"octoprint.plugin.core": {"level": logging.ERROR}},
"root": {"level": logging.WARNING},
}
#~~ "octoprint plugin:command" commands
# ~~ "octoprint plugin:command" commands
class OctoPrintPluginCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that collects commands from the plugin hook
:ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`.
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that collects commands from the plugin hook
:ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`.
.. attribute:: settings
.. attribute:: settings
The global :class:`~octoprint.settings.Settings` instance.
The global :class:`~octoprint.settings.Settings` instance.
.. attribute:: plugin_manager
.. attribute:: plugin_manager
The :class:`~octoprint.plugin.core.PluginManager` instance.
"""
The :class:`~octoprint.plugin.core.PluginManager` instance.
"""
sep = ":"
sep = ":"
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
self.settings = None
self.plugin_manager = None
self.hooks = dict()
self.settings = None
self.plugin_manager = None
self.hooks = {}
self._logger = logging.getLogger(__name__)
self._initialized = False
self._logger = logging.getLogger(__name__)
self._initialized = False
def _initialize(self, ctx):
if self._initialized:
return
def _initialize(self, ctx):
if self._initialized:
return
click.echo("Initializing settings & plugin subsystem...")
if ctx.obj is None:
ctx.obj = OctoPrintContext()
click.echo("Initializing settings & plugin subsystem...")
if ctx.obj is None:
ctx.obj = OctoPrintContext()
logging_config = dict_merge(LOGGING_CONFIG, dict(root=dict(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING)))
logging.config.dictConfig(logging_config)
logging_config = dict_merge(
LOGGING_CONFIG,
{
"root": {
"level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING
}
},
)
logging.config.dictConfig(logging_config)
# initialize settings and plugin manager based on provided
# context (basedir and configfile)
from octoprint import init_settings, init_pluginsystem, FatalStartupError
try:
self.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
self.plugin_manager = init_pluginsystem(self.settings,
safe_mode=get_ctx_obj_option(ctx, "safe_mode", False))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings or the plugin system.", err=True)
ctx.exit(-1)
# initialize settings and plugin manager based on provided
# context (basedir and configfile)
from octoprint import FatalStartupError, init_pluginsystem, init_settings
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
try:
self.settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
self.plugin_manager = init_pluginsystem(
self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False)
)
except FatalStartupError as e:
click.echo(str(e), err=True)
click.echo(
"There was a fatal error initializing the settings or the plugin system.",
err=True,
)
ctx.exit(-1)
self._initialized = True
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
def list_commands(self, ctx):
self._initialize(ctx)
result = [name for name in self._get_commands()]
result.sort()
return result
self._initialized = True
def get_command(self, ctx, cmd_name):
self._initialize(ctx)
commands = self._get_commands()
return commands.get(cmd_name, None)
def list_commands(self, ctx):
self._initialize(ctx)
result = [name for name in self._get_commands()]
result.sort()
return result
def _get_commands(self):
"""Fetch all commands from plugins providing any."""
def get_command(self, ctx, cmd_name):
self._initialize(ctx)
commands = self._get_commands()
return commands.get(cmd_name, None)
import collections
result = collections.OrderedDict()
def _get_commands(self):
"""Fetch all commands from plugins providing any."""
for name, hook in self.hooks.items():
try:
commands = hook(self, pass_octoprint_ctx)
for command in commands:
if not isinstance(command, click.Command):
self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
continue
result[name + self.sep + command.name] = command
except Exception:
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
extra=dict(plugin=name))
import collections
result = collections.OrderedDict()
for name, hook in self.hooks.items():
try:
commands = hook(self, pass_octoprint_ctx)
for command in commands:
if not isinstance(command, click.Command):
self._logger.warning(
"Plugin {} provided invalid CLI command, ignoring it: {!r}".format(
name, command
)
)
continue
result[name + self.sep + command.name] = command
except Exception:
self._logger.exception(
"Error while retrieving cli commands for plugin {}".format(name),
extra={"plugin": name},
)
return result
return result
@click.group()
@pass_octoprint_ctx
def plugin_commands(obj):
pass
pass
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
def plugins():
"""Additional commands provided by plugins."""
pass
"""Additional commands provided by plugins."""
pass
+360 -214
View File
@@ -1,178 +1,277 @@
# -*- 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'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
import sys
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
import click
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."""
from octoprint.cli import (
bulk_options,
get_ctx_obj_option,
set_ctx_obj_option,
standard_options,
)
from octoprint import init_platform, __display_version__, FatalStartupError
click.disable_unicode_literals_warning = True
def log_startup(recorder=None, safe_mode=None, **kwargs):
from octoprint.logging import get_divider_line
logger = logging.getLogger("octoprint.startup")
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."""
logger.info(get_divider_line("*"))
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))
from octoprint import FatalStartupError, __display_version__, init_platform
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
def log_startup(recorder=None, safe_mode=None, **kwargs):
from octoprint.logging import get_divider_line
from octoprint.logging.handlers import PluginTimingsLogHandler
from octoprint.logging.handlers import CombinedLogHandler
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
logger = logging.getLogger("octoprint.startup")
PluginTimingsLogHandler.arm_rollover()
logger.info(get_divider_line("-"))
logger.info(get_divider_line("*"))
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))
from octoprint import urllib3_ssl
if not urllib3_ssl:
logging.getLogger("octoprint.server")\
.warning("requests/urllib3 will run in an insecure SSL environment. "
"You might see corresponding warnings logged later "
"(\"InsecurePlatformWarning\"). It is recommended to either "
"update to a Python version >= 2.7.9 or alternatively "
"install PyOpenSSL plus its dependencies. For details see "
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
logger.info(get_divider_line("*"))
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs):
from octoprint.logging import get_handler, log_to_handler, get_divider_line
from octoprint.logging.handlers import OctoPrintLogHandler
from octoprint.logging.handlers import CombinedLogHandler
def rollover_callback():
handler = get_handler("file")
if handler is None:
return
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
logger = logging.getLogger("octoprint.server")
logger.info(get_divider_line("-"))
def _log(message, level=logging.INFO):
log_to_handler(logger, handler, level, message)
from octoprint import urllib3_ssl
_log(get_divider_line("-", "Log roll over detected"))
_log("OctoPrint {}".format(__display_version__))
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
environment_detector.log_detected_environment(only_to_handler=handler)
_log(get_divider_line("-"))
if not urllib3_ssl:
logging.getLogger("octoprint.server").warning(
"requests/urllib3 will run in an insecure SSL environment. "
"You might see corresponding warnings logged later "
'("InsecurePlatformWarning"). It is recommended to either '
"update to a Python version >= 2.7.9 or alternatively "
"install PyOpenSSL plus its dependencies. For details see "
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl"
)
logger.info(get_divider_line("*"))
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
def log_register_rollover(
safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs
):
from octoprint.logging import get_divider_line, get_handler, log_to_handler
from octoprint.logging.handlers import OctoPrintLogHandler
try:
components = init_platform(basedir, configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover)
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
def rollover_callback():
handler = get_handler("file")
if handler is None:
return
except FatalStartupError as e:
logger = logging.getLogger("octoprint.startup").fatal
echo = lambda x: click.echo(x, err=True)
logger = logging.getLogger("octoprint.server")
for method in logger, echo:
method(str(e))
method("There was a fatal error starting up OctoPrint.")
def _log(message, level=logging.INFO):
log_to_handler(logger, handler, level, message)
else:
from octoprint.server import Server
octoprint_server = Server(settings=settings,
plugin_manager=plugin_manager,
event_manager=event_manager,
connectivity_checker=connectivity_checker,
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
octoprint_daemon=octoprint_daemon)
octoprint_server.run()
_log(get_divider_line("-", "Log roll over detected"))
_log("OctoPrint {}".format(__display_version__))
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
environment_detector.log_detected_environment(only_to_handler=handler)
_log(get_divider_line("-"))
#~~ server options
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
server_options = bulk_options([
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
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,
help="Allow OctoPrint to run as user root."),
click.option("--debug", is_flag=True, callback=set_ctx_obj_option,
help="Enable debug mode."),
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
help="Disable processing of the plugin blacklist.")
])
try:
components = init_platform(
basedir,
configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover,
)
(
settings,
_,
safe_mode,
event_manager,
connectivity_checker,
plugin_manager,
environment_detector,
) = components
except FatalStartupError as e:
logger = logging.getLogger("octoprint.startup").fatal
echo = lambda x: click.echo(x, err=True)
for method in logger, echo:
method(str(e))
method("There was a fatal error starting up OctoPrint.")
else:
from octoprint.server import Server
octoprint_server = Server(
settings=settings,
plugin_manager=plugin_manager,
event_manager=event_manager,
connectivity_checker=connectivity_checker,
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
octoprint_daemon=octoprint_daemon,
)
octoprint_server.run()
# ~~ server options
server_options = bulk_options(
[
click.option(
"--host",
type=click.STRING,
callback=set_ctx_obj_option,
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,
help="Allow OctoPrint to run as user root.",
),
click.option(
"--debug",
is_flag=True,
callback=set_ctx_obj_option,
help="Enable debug mode.",
),
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``, ``-4``, ``-6``
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
daemon_options = bulk_options([
click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option,
help="Pidfile to use for daemonizing.")
])
daemon_options = bulk_options(
[
click.option(
"--pid",
type=click.Path(),
default="/tmp/octoprint.pid",
callback=set_ctx_obj_option,
help="Pidfile to use for daemonizing.",
)
]
)
"""Decorator to add the options for the daemon subcommand: ``--pid``."""
#~~ "octoprint serve" and "octoprint daemon" commands
# ~~ "octoprint serve" and "octoprint daemon" commands
@click.group()
def server_commands():
pass
pass
@server_commands.command(name="safemode")
@standard_options()
@click.pass_context
def enable_safemode(ctx, **kwargs):
"""Sets the safe mode flag for the next start."""
from octoprint import init_settings, FatalStartupError
"""Sets the safe mode flag for the next start."""
from octoprint import FatalStartupError, init_settings
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
try:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
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()
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
try:
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
except FatalStartupError as e:
click.echo(str(e), 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()
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")
@@ -180,109 +279,156 @@ def enable_safemode(ctx, **kwargs):
@server_options
@click.pass_context
def serve_command(ctx, **kwargs):
"""Starts the OctoPrint server."""
"""Starts the OctoPrint server."""
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
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")
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")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
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 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)
run_server(
basedir,
configfile,
host,
port,
v6,
debug,
allow_root,
logging,
verbosity,
safe_mode,
ignore_blacklist,
)
if sys.platform != "win32" and sys.platform != "darwin":
# we do not support daemon mode under windows or macosx
# we do not support daemon mode under windows or macosx
@server_commands.command(name="daemon")
@standard_options()
@server_options
@daemon_options
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status")
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
@server_commands.command(name="daemon")
@standard_options()
@server_options
@daemon_options
@click.argument(
"command",
type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status",
)
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
Please note that daemon mode is not supported under Windows and MacOSX right now.
"""
Please note that daemon mode is not supported under Windows and MacOSX right now.
"""
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
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")
pid = get_value("pid")
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")
pid = get_value("pid")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
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 v4 and not host:
host = "0.0.0.0"
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
sys.exit(1)
if pid is None:
click.echo("No path to a pidfile set", file=sys.stderr)
sys.exit(1)
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config,
verbosity, safe_mode, ignore_blacklist):
Daemon.__init__(self, pidfile)
from octoprint.daemon import Daemon
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
self._verbosity = verbosity
self._safe_mode = safe_mode
self._ignore_blacklist = ignore_blacklist
class OctoPrintDaemon(Daemon):
def __init__(
self,
pidfile,
basedir,
configfile,
host,
port,
v6_only,
debug,
allow_root,
logging_config,
verbosity,
safe_mode,
ignore_blacklist,
):
Daemon.__init__(self, pidfile)
def run(self):
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)
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
self._verbosity = verbosity
self._safe_mode = safe_mode
self._ignore_blacklist = 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()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
def run(self):
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,
v6,
debug,
allow_root,
logging,
verbosity,
safe_mode,
ignore_blacklist,
)
if command == "start":
octoprint_daemon.start()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
+66
View File
@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import click
from octoprint.cli import init_platform_for_cli, standard_options
click.disable_unicode_literals_warning = True
def get_systeminfo(environment_detector, connectivity_checker):
from octoprint import __version__
from octoprint.util import dict_flatten
environment_detector.run_detection(notify_plugins=False)
systeminfo = {
"octoprint": {"version": __version__},
"connectivity": connectivity_checker.as_dict(),
"env": environment_detector.environment,
}
# flatten and filter
flattened = dict_flatten(systeminfo)
flattened["env.python.virtualenv"] = "env.python.virtualenv" in flattened
return flattened
@click.group()
def systeminfo_commands():
pass
@systeminfo_commands.command(name="systeminfo")
@standard_options()
@click.pass_context
def systeminfo_command(ctx, **kwargs):
"""Retrieves and prints the system info."""
logging.disable(logging.ERROR)
try:
(
settings,
logger,
safe_mode,
event_manager,
connectivity_checker,
plugin_manager,
environment_detector,
) = init_platform_for_cli(ctx)
except Exception as e:
click.echo(str(e), err=True)
click.echo("There was a fatal error initializing the platform.", err=True)
ctx.exit(-1)
else:
systeminfo = get_systeminfo(environment_detector, connectivity_checker)
for k in sorted(systeminfo.keys()):
click.echo("{}: {}".format(k, systeminfo[k]))
ctx.exit(0)
+146 -107
View File
@@ -1,124 +1,157 @@
# coding=utf-8
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import logging
import click
from octoprint import init_settings
from octoprint.cli import get_ctx_obj_option
from octoprint.access.groups import FilebasedGroupManager
from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
from octoprint.access.users import (
CorruptUserStorage,
FilebasedUserManager,
UnknownUser,
UserAlreadyExists,
)
from octoprint.cli import get_ctx_obj_option
from octoprint.util import get_class, sv
click.disable_unicode_literals_warning = True
#~~ "octoprint user" commands
# ~~ "octoprint user" commands
@click.group()
def user_commands():
pass
pass
@user_commands.group(name="user")
@click.pass_context
def user(ctx):
"""
User management.
"""
User management.
Note that this currently only supports managing user accounts stored in the configured user manager, not any
user managers added through plugins and the "octoprint.users.factory" hook.
"""
try:
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
Note that this currently only supports managing user accounts stored in the configured user manager, not any
user managers added through plugins and the "octoprint.users.factory" hook.
"""
try:
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
group_manager_name = settings.get(["accessControl", "groupManager"])
try:
clazz = get_class(group_manager_name)
group_manager = clazz()
except AttributeError:
click.echo("Could not instantiate group manager {}, "
"falling back to FilebasedGroupManager!".format(group_manager_name), err=True)
group_manager = FilebasedGroupManager()
group_manager_name = settings.get(["accessControl", "groupManager"])
try:
clazz = get_class(group_manager_name)
group_manager = clazz()
except AttributeError:
click.echo(
"Could not instantiate group manager {}, "
"falling back to FilebasedGroupManager!".format(group_manager_name),
err=True,
)
group_manager = FilebasedGroupManager()
ctx.obj.group_manager = group_manager
ctx.obj.group_manager = group_manager
name = settings.get(["accessControl", "userManager"])
try:
clazz = get_class(name)
user_manager = clazz(group_manager=group_manager, settings=settings)
except Exception:
click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
user_manager = FilebasedUserManager(group_manager, settings=settings)
finally:
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
name = settings.get(["accessControl", "userManager"])
try:
clazz = get_class(name)
user_manager = clazz(group_manager=group_manager, settings=settings)
except CorruptUserStorage:
raise
except Exception:
click.echo(
"Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(
name
),
err=True,
)
user_manager = FilebasedUserManager(group_manager, settings=settings)
ctx.obj.user_manager = user_manager
ctx.obj.user_manager = user_manager
except Exception:
click.echo("Could not instantiate user manager", err=True)
return
except Exception:
click.echo("Could not instantiate user manager", err=True)
ctx.exit(-1)
@user.command(name="list")
@click.pass_context
def list_users_command(ctx):
"""Lists user information"""
users = ctx.obj.user_manager.get_all_users()
_print_list(users)
"""Lists user information"""
users = ctx.obj.user_manager.get_all_users()
_print_list(users)
@user.command(name="add")
@click.argument("username", type=click.STRING, required=True)
@click.password_option("--password", "password", help="Password for the user")
@click.option("-g", "--group", "groups", multiple=True,
help="Groups to set on the user")
@click.option("-p", "--permission", "permissions", multiple=True,
help="Individual permissions to set on the user")
@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
help="Adds user to admin group")
@click.option("-g", "--group", "groups", multiple=True, help="Groups to set on the user")
@click.option(
"-p",
"--permission",
"permissions",
multiple=True,
help="Individual permissions to set on the user",
)
@click.option(
"--admin",
"is_admin",
type=click.BOOL,
is_flag=True,
default=False,
help="Adds user to admin group",
)
@click.pass_context
def add_user_command(ctx, username, password, groups, permissions, is_admin):
"""Add a new user."""
if not groups:
groups = []
"""Add a new user."""
if not groups:
groups = []
if is_admin:
groups.append(ctx.obj.group_manager.admin_group)
if is_admin:
groups.append(ctx.obj.group_manager.admin_group)
try:
ctx.obj.user_manager.add_user(username,
password,
groups=groups,
permissions=permissions,
active=True)
try:
ctx.obj.user_manager.add_user(
username, password, groups=groups, permissions=permissions, active=True
)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo("A user with the name {} does already exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo(
"A user with the name {} does already exist!".format(username), err=True
)
@user.command(name="remove")
@click.argument("username", type=click.STRING)
@click.pass_context
def remove_user_command(ctx, username):
"""Remove an existing user."""
confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING)
"""Remove an existing user."""
confirm = click.prompt(
"This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING,
)
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
else:
click.echo("User {} not removed.".format(username))
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
else:
click.echo("User {} not removed.".format(username))
@user.command(name="password")
@@ -126,59 +159,65 @@ def remove_user_command(ctx, username):
@click.password_option("--password", "password", help="New password for user")
@click.pass_context
def change_password_command(ctx, username, password):
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="activate")
@click.argument("username", type=click.STRING)
@click.pass_context
def activate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="deactivate")
@click.argument("username", type=click.STRING)
@click.pass_context
def deactivate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
def _print_list(users):
click.echo("{} users registered in the system:".format(len(users)))
for user in sorted(map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))):
click.echo("\t{}".format(_user_to_line(user)))
click.echo("{} users registered in the system:".format(len(users)))
for user in sorted(
map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))
):
click.echo("\t{}".format(_user_to_line(user)))
def _user_to_line(user):
return "{name}" \
"\n\t\tactive: {active}" \
"\n\t\tgroups: {groups}" \
"\n\t\tpermissions: {permissions}".format(name=user.get("name"),
active=user.get("active", "False"),
groups=", ".join(user.get("groups", [])),
permissions=", ".join(user.get("permissions", [])))
return (
"{name}"
"\n\t\tactive: {active}"
"\n\t\tgroups: {groups}"
"\n\t\tpermissions: {permissions}".format(
name=user.get("name"),
active=user.get("active", "False"),
groups=", ".join(user.get("groups", [])),
permissions=", ".join(user.get("permissions", [])),
)
)
+147 -134
View File
@@ -7,170 +7,183 @@ Generic linux daemon base class
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
"""
import io, sys, os, time, signal
import io
import os
import signal
import sys
import time
class Daemon:
"""
A generic daemon class.
"""
A generic daemon class.
Usage: subclass the daemon class and override the run() method.
Usage: subclass the daemon class and override the run() method.
If you want to log the output to someplace different that stdout and stderr,
also override the echo() and error() methods.
"""
If you want to log the output to someplace different that stdout and stderr,
also override the echo() and error() methods.
"""
def __init__(self, pidfile):
self.pidfile = pidfile
def __init__(self, pidfile):
self.pidfile = pidfile
def _daemonize(self):
"""Daemonize class. UNIX double fork mechanism."""
def _daemonize(self):
"""Daemonize class. UNIX double fork mechanism."""
self._double_fork()
self._redirect_io()
self._double_fork()
self._redirect_io()
# write pidfile
pid = str(os.getpid())
self.set_pid(pid)
# write pidfile
pid = str(os.getpid())
self.set_pid(pid)
def _double_fork(self):
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
self.error("First fork failed: {}".format(str(err)))
sys.exit(1)
def _double_fork(self):
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
self.error("First fork failed: {}".format(str(err)))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(0o002)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0o002)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
self.error("Second fork failed: {}".format(str(err)))
sys.exit(1)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
self.error("Second fork failed: {}".format(str(err)))
sys.exit(1)
def _redirect_io(self):
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = io.open(os.devnull, 'rt', encoding='utf-8')
so = io.open(os.devnull, 'at+', encoding='utf-8')
se = io.open(os.devnull, 'at+', encoding='utf-8')
def _redirect_io(self):
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = io.open(os.devnull, "rt", encoding="utf-8")
so = io.open(os.devnull, "at+", encoding="utf-8")
se = io.open(os.devnull, "at+", encoding="utf-8")
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
def terminated(self):
self.remove_pidfile()
def terminated(self):
self.remove_pidfile()
def start(self):
"""Start the daemon."""
def start(self):
"""Start the daemon."""
# Check for a pidfile to see if the daemon already runs
pid = self.get_pid()
if pid:
self.error("pidfile {} already exist. Is the daemon already running?".format(self.pidfile))
sys.exit(1)
# Check for a pidfile to see if the daemon already runs
pid = self.get_pid()
if pid:
self.error(
"pidfile {} already exist. Is the daemon already running?".format(
self.pidfile
)
)
sys.exit(1)
self.echo("Starting daemon...")
self.echo("Starting daemon...")
# Start the daemon
self._daemonize()
self.run()
# Start the daemon
self._daemonize()
self.run()
def stop(self, check_running=True):
"""Stop the daemon."""
pid = self.get_pid()
if not pid:
if not check_running:
return
self.error("pidfile {} does not exist. Is the daemon really running?".format(self.pidfile))
sys.exit(1)
def stop(self, check_running=True):
"""Stop the daemon."""
pid = self.get_pid()
if not pid:
if not check_running:
return
self.error(
"pidfile {} does not exist. Is the daemon really running?".format(
self.pidfile
)
)
sys.exit(1)
self.echo("Stopping daemon...")
self.echo("Stopping daemon...")
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
self.remove_pidfile()
else:
self.error(e)
sys.exit(1)
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
self.remove_pidfile()
else:
self.error(e)
sys.exit(1)
def restart(self):
"""Restart the daemon."""
self.stop(check_running=False)
self.start()
def restart(self):
"""Restart the daemon."""
self.stop(check_running=False)
self.start()
def status(self):
"""Prints the daemon status."""
if self.is_running():
self.echo("Daemon is running")
else:
self.echo("Daemon is not running")
def status(self):
"""Prints the daemon status."""
if self.is_running():
self.echo("Daemon is running")
else:
self.echo("Daemon is not running")
def is_running(self):
"""Check if a process is running under the specified pid."""
pid = self.get_pid()
if pid is None:
return False
def is_running(self):
"""Check if a process is running under the specified pid."""
pid = self.get_pid()
if pid is None:
return False
try:
os.kill(pid, 0)
except OSError:
try:
self.remove_pidfile()
except Exception:
self.error("Daemon found not running, but could not remove stale pidfile")
return False
else:
return True
try:
os.kill(pid, 0)
except OSError:
try:
self.remove_pidfile()
except Exception:
self.error("Daemon found not running, but could not remove stale pidfile")
return False
else:
return True
def get_pid(self):
"""Get the pid from the pidfile."""
try:
with io.open(self.pidfile,'rt', encoding='utf-8') as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
pid = None
return pid
def get_pid(self):
"""Get the pid from the pidfile."""
try:
with io.open(self.pidfile, "rt", encoding="utf-8") as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
pid = None
return pid
def set_pid(self, pid):
"""Write the pid to the pidfile."""
with io.open(self.pidfile,'wt+', encoding='utf-8') as f:
f.write(str(pid) + '\n')
def set_pid(self, pid):
"""Write the pid to the pidfile."""
with io.open(self.pidfile, "wt+", encoding="utf-8") as f:
f.write(str(pid) + "\n")
def remove_pidfile(self):
"""Removes the pidfile."""
if os.path.isfile(self.pidfile):
os.remove(self.pidfile)
def remove_pidfile(self):
"""Removes the pidfile."""
if os.path.isfile(self.pidfile):
os.remove(self.pidfile)
def run(self):
"""You should override this method when you subclass Daemon.
def run(self):
"""You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart()."""
It will be called after the process has been daemonized by
start() or restart()."""
raise NotImplementedError()
raise NotImplementedError()
@classmethod
def echo(cls, line):
print(line)
@classmethod
def echo(cls, line):
print(line)
@classmethod
def error(cls, line):
print(line, file=sys.stderr)
@classmethod
def error(cls, line):
print(line, file=sys.stderr)
+151 -127
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
@@ -9,165 +9,189 @@ import logging
import os
import sys
import threading
import yaml
import psutil
import yaml
from octoprint.plugin import EnvironmentDetectionPlugin
from octoprint.util.platform import get_os
from octoprint.util.version import get_python_version_string
class EnvironmentDetector(object):
def __init__(self, plugin_manager):
self._plugin_manager = plugin_manager
def __init__(self, plugin_manager):
self._plugin_manager = plugin_manager
self._cache = None
self._cache_lock = threading.RLock()
self._cache = None
self._cache_lock = threading.RLock()
self._logger = logging.getLogger(__name__)
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 = []
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:
if self._cache is None:
self.run_detection()
return copy.deepcopy(self._cache)
@property
def environment(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
return copy.deepcopy(self._cache)
def run_detection(self, notify_plugins=True):
try:
environment = {}
environment["os"] = self._detect_os()
environment["python"] = self._detect_python()
environment["hardware"] = self._detect_hardware()
def run_detection(self, notify_plugins=True):
try:
environment = dict()
environment["os"] = self._detect_os()
environment["python"] = self._detect_python()
environment["hardware"] = self._detect_hardware()
plugin_result = self._detect_from_plugins()
if plugin_result:
environment["plugins"] = plugin_result
plugin_result = self._detect_from_plugins()
if plugin_result:
environment["plugins"] = plugin_result
with self._cache_lock:
self._cache = environment
with self._cache_lock:
self._cache = environment
if notify_plugins:
self.notify_plugins()
if notify_plugins:
self.notify_plugins()
return environment
except Exception:
self._logger.exception("Unexpected error while detecting environment")
with self._cache_lock:
self._cache = {}
return self._cache
return environment
except Exception:
self._logger.exception("Unexpected error while detecting environment")
with self._cache_lock:
self._cache = dict()
return self._cache
def _detect_os(self):
return {
"id": get_os(),
"platform": sys.platform,
"bits": 64 if sys.maxsize > 2 ** 32 else 32,
}
def _detect_os(self):
return dict(id=get_os(),
platform=sys.platform)
def _detect_python(self):
result = {"version": "unknown", "pip": "unknown"}
def _detect_python(self):
result = dict(version="unknown",
pip="unknown")
# determine python version
try:
result["version"] = get_python_version_string()
except Exception:
self._logger.exception("Error detecting python version")
# determine python version
try:
result["version"] = get_python_version_string()
except Exception:
self._logger.exception("Error detecting python version")
# determine if we are running from a virtual environment
try:
if hasattr(sys, "real_prefix") or (
hasattr(sys, "base_prefix")
and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)
):
result["virtualenv"] = sys.prefix
except Exception:
self._logger.exception(
"Error detecting whether we are running in a virtual environment"
)
# determine if we are running from a virtual environment
try:
if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
result["virtualenv"] = sys.prefix
except Exception:
self._logger.exception("Error detecting whether we are running in a virtual environment")
# try to find pip version
try:
import pkg_resources
# try to find pip version
try:
import pkg_resources
result["pip"] = pkg_resources.get_distribution("pip").version
except Exception:
self._logger.exception("Error detecting pip version")
result["pip"] = pkg_resources.get_distribution("pip").version
except Exception:
self._logger.exception("Error detecting pip version")
return result
return result
def _detect_hardware(self):
result = dict(cores="unknown",
freq="unknown",
ram="unknown")
def _detect_hardware(self):
result = {"cores": "unknown", "freq": "unknown", "ram": "unknown"}
try:
cores = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
ram = psutil.virtual_memory()
if cores:
result["cores"] = cores
if cpu_freq and hasattr(cpu_freq, "max"):
result["freq"] = cpu_freq.max
if ram and hasattr(ram, "total"):
result["ram"] = ram.total
except Exception:
self._logger.exception("Error while detecting hardware environment")
try:
cores = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
ram = psutil.virtual_memory()
if cores:
result["cores"] = cores
if cpu_freq and hasattr(cpu_freq, "max"):
result["freq"] = cpu_freq.max
if ram and hasattr(ram, "total"):
result["ram"] = ram.total
except Exception:
self._logger.exception("Error while detecting hardware environment")
return result
return result
def _detect_from_plugins(self):
result = dict()
def _detect_from_plugins(self):
result = {}
for implementation in self._environment_plugins:
try:
additional = implementation.get_additional_environment()
if additional is not None and isinstance(additional, dict) and len(additional):
result[implementation._identifier] = additional
except Exception:
self._logger.exception("Error while fetching additional "
"environment data from plugin {}".format(implementation._identifier),
extra=dict(plugin=implementation._identifier))
for implementation in self._environment_plugins:
try:
additional = implementation.get_additional_environment()
if (
additional is not None
and isinstance(additional, dict)
and len(additional)
):
result[implementation._identifier] = additional
except Exception:
self._logger.exception(
"Error while fetching additional "
"environment data from plugin {}".format(implementation._identifier),
extra={"plugin": implementation._identifier},
)
return result
return result
def log_detected_environment(self, only_to_handler=None):
def _log(message, level=logging.INFO):
if only_to_handler is not None:
import octoprint.logging
octoprint.logging.log_to_handler(self._logger, only_to_handler, level, message, [])
else:
self._logger.log(level, message)
def log_detected_environment(self, only_to_handler=None):
def _log(message, level=logging.INFO):
if only_to_handler is not None:
import octoprint.logging
try:
_log(self._format())
except Exception:
self._logger.exception("Error logging detected environment")
octoprint.logging.log_to_handler(
self._logger, only_to_handler, level, message, []
)
else:
self._logger.log(level, message)
def _format(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
environment = copy.deepcopy(self._cache)
try:
_log(self._format())
except Exception:
self._logger.exception("Error logging detected environment")
dumped_environment = yaml.safe_dump(environment,
default_flow_style=False,
indent=4,
allow_unicode=True).strip()
environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n")))
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
environment["os"]["id"].title(),
environment["os"]["platform"],
environment_lines)
def _format(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
environment = copy.deepcopy(self._cache)
def notify_plugins(self):
with self._cache_lock:
if self._cache is None:
self.run_detection(notify_plugins=False)
environment = copy.deepcopy(self._cache)
dumped_environment = yaml.safe_dump(
environment, default_flow_style=False, indent=4, allow_unicode=True
).strip()
environment_lines = "\n".join(
map(lambda l: "| {}".format(l), dumped_environment.split("\n"))
)
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(
environment["python"]["version"],
environment["os"]["id"].title(),
environment["os"]["platform"],
environment_lines,
)
for implementation in self._environment_plugins:
try:
implementation.on_environment_detected(environment)
except Exception:
self._logger.exception("Error while sending environment "
"detection result to plugin {}".format(implementation._identifier))
def notify_plugins(self):
with self._cache_lock:
if self._cache is None:
self.run_detection(notify_plugins=False)
environment = copy.deepcopy(self._cache)
for implementation in self._environment_plugins:
try:
implementation.on_environment_detected(environment)
except Exception:
self._logger.exception(
"Error while sending environment "
"detection result to plugin {}".format(implementation._identifier)
)
+428 -373
View File
@@ -2,487 +2,542 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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 datetime
import logging
import subprocess
try:
import queue
import queue
except ImportError:
import Queue as queue
import threading
import Queue as queue
import collections
import re
import threading
from octoprint.settings import settings
import octoprint.plugin
from octoprint.settings import settings
# singleton
_instance = None
def all_events():
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)]
return [
getattr(Events, name)
for name in Events.__dict__
if not name.startswith("_") and name not in ("register_event",)
]
class Events(object):
# server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# connect/disconnect to printer
CONNECTING = "Connecting"
CONNECTED = "Connected"
DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
# connect/disconnect to printer
CONNECTING = "Connecting"
CONNECTED = "Connected"
DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
PRINTER_RESET = "PrinterReset"
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
PRINTER_RESET = "PrinterReset"
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
CLIENT_AUTHED = "ClientAuthed"
CLIENT_DEAUTHED = "ClientDeauthed"
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
CLIENT_AUTHED = "ClientAuthed"
CLIENT_DEAUTHED = "ClientDeauthed"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# File management
UPLOAD = "Upload"
FILE_SELECTED = "FileSelected"
FILE_DESELECTED = "FileDeselected"
UPDATED_FILES = "UpdatedFiles"
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
# File management
UPLOAD = "Upload"
FILE_SELECTED = "FileSelected"
FILE_DESELECTED = "FileDeselected"
UPDATED_FILES = "UpdatedFiles"
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
FILE_ADDED = "FileAdded"
FILE_REMOVED = "FileRemoved"
FOLDER_ADDED = "FolderAdded"
FOLDER_REMOVED = "FolderRemoved"
FILE_ADDED = "FileAdded"
FILE_REMOVED = "FileRemoved"
FOLDER_ADDED = "FolderAdded"
FOLDER_REMOVED = "FolderRemoved"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
TRANSFER_DONE = "TransferDone"
TRANSFER_FAILED = "TransferFailed"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
TRANSFER_DONE = "TransferDone"
TRANSFER_FAILED = "TransferFailed"
# print job
PRINT_STARTED = "PrintStarted"
PRINT_DONE = "PrintDone"
PRINT_FAILED = "PrintFailed"
PRINT_CANCELLING = "PrintCancelling"
PRINT_CANCELLED = "PrintCancelled"
PRINT_PAUSED = "PrintPaused"
PRINT_RESUMED = "PrintResumed"
ERROR = "Error"
# print job
PRINT_STARTED = "PrintStarted"
PRINT_DONE = "PrintDone"
PRINT_FAILED = "PrintFailed"
PRINT_CANCELLING = "PrintCancelling"
PRINT_CANCELLED = "PrintCancelled"
PRINT_PAUSED = "PrintPaused"
PRINT_RESUMED = "PrintResumed"
ERROR = "Error"
# print/gcode events
POWER_ON = "PowerOn"
POWER_OFF = "PowerOff"
HOME = "Home"
Z_CHANGE = "ZChange"
WAITING = "Waiting"
DWELL = "Dwelling"
COOLING = "Cooling"
ALERT = "Alert"
CONVEYOR = "Conveyor"
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
FIRMWARE_DATA = "FirmwareData"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# print/gcode events
POWER_ON = "PowerOn"
POWER_OFF = "PowerOff"
HOME = "Home"
Z_CHANGE = "ZChange"
WAITING = "Waiting"
DWELL = "Dwelling"
COOLING = "Cooling"
ALERT = "Alert"
CONVEYOR = "Conveyor"
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
FIRMWARE_DATA = "FirmwareData"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
COMMAND_SUPPRESSED = "CommandSuppressed"
INVALID_TOOL_REPORTED = "InvalidToolReported"
# Timelapse
CAPTURE_START = "CaptureStart"
CAPTURE_DONE = "CaptureDone"
CAPTURE_FAILED = "CaptureFailed"
POSTROLL_START = "PostRollStart"
POSTROLL_END = "PostRollEnd"
MOVIE_RENDERING = "MovieRendering"
MOVIE_DONE = "MovieDone"
MOVIE_FAILED = "MovieFailed"
# Timelapse
CAPTURE_START = "CaptureStart"
CAPTURE_DONE = "CaptureDone"
CAPTURE_FAILED = "CaptureFailed"
POSTROLL_START = "PostRollStart"
POSTROLL_END = "PostRollEnd"
MOVIE_RENDERING = "MovieRendering"
MOVIE_DONE = "MovieDone"
MOVIE_FAILED = "MovieFailed"
# Slicing
SLICING_STARTED = "SlicingStarted"
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
# Slicing
SLICING_STARTED = "SlicingStarted"
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
# Printer Profiles
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
# Printer Profiles
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
# 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
@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])')
# 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()
@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
if _instance is None:
_instance = EventManager()
return _instance
global _instance
if _instance is None:
_instance = EventManager()
return _instance
class EventManager(object):
"""
Handles receiving events and dispatching them to subscribers
"""
"""
Handles receiving events and dispatching them to subscribers
"""
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
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
self._startup_signaled = False
self._shutdown_signaled = False
self._queue = queue.Queue()
self._held_back = queue.Queue()
self._queue = queue.Queue()
self._held_back = queue.Queue()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def _work(self):
try:
while not self._shutdown_signaled:
event, payload = self._queue.get(True)
if event == Events.SHUTDOWN:
# we've got the shutdown event here, stop event loop processing after this has been processed
self._logger.info("Processing shutdown event, this will be our last event")
self._shutdown_signaled = True
def _work(self):
try:
while not self._shutdown_signaled:
event, payload = self._queue.get(True)
if event == Events.SHUTDOWN:
# we've got the shutdown event here, stop event loop processing after this has been processed
self._logger.info(
"Processing shutdown event, this will be our last event"
)
self._shutdown_signaled = True
eventListeners = self._registeredListeners[event]
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
eventListeners = self._registeredListeners[event]
self._logger_fire.debug(
"Firing event: {} (Payload: {!r})".format(event, payload)
)
for listener in eventListeners:
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except Exception:
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
for listener in eventListeners:
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except Exception:
self._logger.exception(
"Got an exception while sending event {} (Payload: {!r}) to {}".format(
event, payload, listener
)
)
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=(event, payload))
self._logger.info("Event loop shut down")
except Exception:
self._logger.exception("Ooops, the event bus worker loop crashed")
octoprint.plugin.call_plugin(
octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=(event, payload),
)
self._logger.info("Event loop shut down")
except Exception:
self._logger.exception("Ooops, the event bus worker loop crashed")
def fire(self, event, payload=None):
"""
Fire an event to anyone subscribed to it
def fire(self, event, payload=None):
"""
Fire an event to anyone subscribed to it
Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but
case sensitive) and any extra payload data that may pertain to the event.
Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but
case sensitive) and any extra payload data that may pertain to the event.
Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and
payload being a payload object specific to the event.
"""
Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and
payload being a payload object specific to the event.
"""
send_held_back = False
if event == Events.STARTUP:
self._logger.info("Processing startup event, this is our first event")
self._startup_signaled = True
send_held_back = True
send_held_back = False
if event == Events.STARTUP:
self._logger.info("Processing startup event, this is our first event")
self._startup_signaled = True
send_held_back = True
self._enqueue(event, payload)
self._enqueue(event, payload)
if send_held_back:
self._logger.info("Adding {} events to queue that "
"were held back before startup event".format(self._held_back.qsize()))
while True:
try:
self._queue.put(self._held_back.get(block=False))
except queue.Empty:
break
if send_held_back:
self._logger.info(
"Adding {} events to queue that "
"were held back before startup event".format(self._held_back.qsize())
)
while True:
try:
self._queue.put(self._held_back.get(block=False))
except queue.Empty:
break
def _enqueue(self, event, payload):
if self._startup_signaled:
q = self._queue
else:
q = self._held_back
def _enqueue(self, event, payload):
if self._startup_signaled:
q = self._queue
else:
q = self._held_back
q.put((event, payload))
q.put((event, payload))
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
"""
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
"""
if callback in self._registeredListeners[event]:
# callback is already subscribed to the event
return
if callback in self._registeredListeners[event]:
# callback is already subscribed to the event
return
self._registeredListeners[event].append(callback)
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
self._registeredListeners[event].append(callback)
self._logger.debug(
"Subscribed listener {!r} for event {}".format(callback, event)
)
def unsubscribe (self, event, callback):
"""
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
def unsubscribe(self, event, callback):
"""
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
try:
self._registeredListeners[event].remove(callback)
except ValueError:
# not registered
pass
try:
self._registeredListeners[event].remove(callback)
except ValueError:
# not registered
pass
def join(self, timeout=None):
self._worker.join(timeout)
return self._worker.is_alive()
def join(self, timeout=None):
self._worker.join(timeout)
return self._worker.is_alive()
class GenericEventListener(object):
"""
The GenericEventListener can be subclassed to easily create custom event listeners.
"""
"""
The GenericEventListener can be subclassed to easily create custom event listeners.
"""
def __init__(self):
self._logger = logging.getLogger(__name__)
def __init__(self):
self._logger = logging.getLogger(__name__)
def subscribe(self, events):
"""
Subscribes the eventCallback method for all events in the given list.
"""
def subscribe(self, events):
"""
Subscribes the eventCallback method for all events in the given list.
"""
for event in events:
eventManager().subscribe(event, self.eventCallback)
for event in events:
eventManager().subscribe(event, self.eventCallback)
def unsubscribe(self, events):
"""
Unsubscribes the eventCallback method for all events in the given list
"""
def unsubscribe(self, events):
"""
Unsubscribes the eventCallback method for all events in the given list
"""
for event in events:
eventManager().unsubscribe(event, self.eventCallback)
for event in events:
eventManager().unsubscribe(event, self.eventCallback)
def eventCallback(self, event, payload):
"""
Actual event callback called with name of event and optional payload. Not implemented here, override in
child classes.
"""
pass
def eventCallback(self, event, payload):
"""
Actual event callback called with name of event and optional payload. Not implemented here, override in
child classes.
"""
pass
class DebugEventListener(GenericEventListener):
def __init__(self):
GenericEventListener.__init__(self)
def __init__(self):
GenericEventListener.__init__(self)
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
self.subscribe(events)
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
self.subscribe(events)
def eventCallback(self, event, payload):
GenericEventListener.eventCallback(self, event, payload)
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
def eventCallback(self, event, payload):
GenericEventListener.eventCallback(self, event, payload)
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
class CommandTrigger(GenericEventListener):
def __init__(self, printer):
GenericEventListener.__init__(self)
self._printer = printer
self._subscriptions = {}
def __init__(self, printer):
GenericEventListener.__init__(self)
self._printer = printer
self._subscriptions = {}
self._initSubscriptions()
self._initSubscriptions()
def _initSubscriptions(self):
"""
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
respective commands.
"""
if not settings().get(["events"]):
return
def _initSubscriptions(self):
"""
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
respective commands.
"""
if not settings().get(["events"]):
return
if not settings().getBoolean(["events", "enabled"]):
return
if not settings().getBoolean(["events", "enabled"]):
return
eventsToSubscribe = []
subscriptions = settings().get(["events", "subscriptions"])
for subscription in subscriptions:
if not isinstance(subscription, dict):
self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription))
continue
eventsToSubscribe = []
subscriptions = settings().get(["events", "subscriptions"])
for subscription in subscriptions:
if not isinstance(subscription, dict):
self._logger.info(
"Invalid subscription definition, not a dictionary: {!r}".format(
subscription
)
)
continue
if not "event" in subscription or not "command" in subscription \
or not "type" in subscription or not subscription["type"] in ["system", "gcode"]:
self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription))
continue
if (
"event" not in subscription
or "command" not in subscription
or "type" not in subscription
or subscription["type"] not in ["system", "gcode"]
):
self._logger.info(
"Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(
subscription
)
)
continue
if "enabled" in subscription and not subscription["enabled"]:
self._logger.info("Disabled command trigger: {!r}".format(subscription))
continue
if "enabled" in subscription and not subscription["enabled"]:
self._logger.info("Disabled command trigger: {!r}".format(subscription))
continue
events = subscription["event"]
command = subscription["command"]
commandType = subscription["type"]
debug = subscription["debug"] if "debug" in subscription else False
events = subscription["event"]
command = subscription["command"]
commandType = subscription["type"]
debug = subscription["debug"] if "debug" in subscription else False
# "event" in the configuration can be a string, or
# a list of strings. If it's the former, convert it
# into the latter.
if not isinstance(events, (tuple, list, set)):
events = [events]
# "event" in the configuration can be a string, or
# a list of strings. If it's the former, convert it
# into the latter.
if not isinstance(events, (tuple, list, set)):
events = [events]
for event in events:
if event not in self._subscriptions:
self._subscriptions[event] = []
self._subscriptions[event].append((command, commandType, debug))
for event in events:
if event not in self._subscriptions:
self._subscriptions[event] = []
self._subscriptions[event].append((command, commandType, debug))
if event not in eventsToSubscribe:
eventsToSubscribe.append(event)
if event not in eventsToSubscribe:
eventsToSubscribe.append(event)
self.subscribe(eventsToSubscribe)
self.subscribe(eventsToSubscribe)
def eventCallback(self, event, payload):
"""
Event callback, iterates over all subscribed commands for the given event, processes the command
string and then executes the command via the abstract executeCommand method.
"""
def eventCallback(self, event, payload):
"""
Event callback, iterates over all subscribed commands for the given event, processes the command
string and then executes the command via the abstract executeCommand method.
"""
GenericEventListener.eventCallback(self, event, payload)
GenericEventListener.eventCallback(self, event, payload)
if not event in self._subscriptions:
return
if event not in self._subscriptions:
return
for command, commandType, debug in self._subscriptions[event]:
try:
if isinstance(command, (tuple, list, set)):
processedCommand = []
for c in command:
processedCommand.append(self._processCommand(c, event, payload))
else:
processedCommand = self._processCommand(command, event, payload)
self.executeCommand(processedCommand, commandType, debug=debug)
except KeyError:
self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command)
for command, commandType, debug in self._subscriptions[event]:
try:
if isinstance(command, (tuple, list, set)):
processedCommand = []
for c in command:
processedCommand.append(self._processCommand(c, event, payload))
else:
processedCommand = self._processCommand(command, event, payload)
self.executeCommand(processedCommand, commandType, debug=debug)
except KeyError:
self._logger.warning(
"There was an error processing one or more placeholders in the following command: %s"
% command
)
def executeCommand(self, command, commandType, debug=False):
if commandType == "system":
self._executeSystemCommand(command, debug=debug)
elif commandType == "gcode":
self._executeGcodeCommand(command, debug=debug)
def executeCommand(self, command, commandType, debug=False):
if commandType == "system":
self._executeSystemCommand(command, debug=debug)
elif commandType == "gcode":
self._executeGcodeCommand(command, debug=debug)
def _executeSystemCommand(self, command, debug=False):
def commandExecutioner(cmd):
if debug:
self._logger.info("Executing system command: {}".format(cmd))
else:
self._logger.info("Executing a system command")
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
subprocess.check_call(cmd, shell=True)
def _executeSystemCommand(self, command, debug=False):
def commandExecutioner(cmd):
if debug:
self._logger.info("Executing system command: {}".format(cmd))
else:
self._logger.info("Executing a system command")
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
subprocess.check_call(cmd, shell=True)
def process():
try:
if isinstance(command, (list, tuple, set)):
for c in command:
commandExecutioner(c)
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
if debug:
self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e)))
else:
self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
except Exception:
self._logger.exception("Command failed")
def process():
try:
if isinstance(command, (list, tuple, set)):
for c in command:
commandExecutioner(c)
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
if debug:
self._logger.warning(
"Command failed with return code {}: {}".format(
e.returncode, str(e)
)
)
else:
self._logger.warning(
"Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(
e.returncode
)
)
except Exception:
self._logger.exception("Command failed")
t = threading.Thread(target=process)
t.daemon = True
t.start()
t = threading.Thread(target=process)
t.daemon = True
t.start()
def _executeGcodeCommand(self, command, debug=False):
commands = [command]
if isinstance(command, (list, tuple, set)):
commands = list(command)
if debug:
self._logger.info("Executing GCode commands: %r" % command)
self._printer.commands(commands)
def _executeGcodeCommand(self, command, debug=False):
commands = [command]
if isinstance(command, (list, tuple, set)):
commands = list(command)
if debug:
self._logger.info("Executing GCode commands: %r" % command)
self._printer.commands(commands)
def _processCommand(self, command, event, payload):
"""
Performs string substitutions in the command string based on a few current parameters.
def _processCommand(self, command, event, payload):
"""
Performs string substitutions in the command string based on a few current parameters.
The following substitutions are currently supported:
The following substitutions are currently supported:
- {__currentZ} : current Z position of the print head, or -1 if not available
- {__eventname} : the name of the event hook being triggered
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
- {__progress} : current print progress in percent, 0 if no print is in progress
- {__data} : the string representation of the event's payload
- {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization
- {__now} : ISO 8601 representation of the current date and time
- {__currentZ} : current Z position of the print head, or -1 if not available
- {__eventname} : the name of the event hook being triggered
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
- {__progress} : current print progress in percent, 0 if no print is in progress
- {__data} : the string representation of the event's payload
- {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization
- {__now} : ISO 8601 representation of the current date and time
Additionally, the keys of the event's payload can also be used as placeholder.
"""
Additionally, the keys of the event's payload can also be used as placeholder.
"""
json_string = "{}"
if payload:
import json
try:
json_string = json.dumps(payload)
except Exception:
self._logger.exception("JSON: Cannot dump %r", payload)
json_string = ""
json_string = "{}"
if payload:
import json
params = {
"__currentZ": "-1",
"__eventname": event,
"__filename": "NO FILE",
"__filepath": "NO PATH",
"__progress": "0",
"__data": str(payload),
"__json": json_string,
"__now": datetime.datetime.now().isoformat()
}
try:
json_string = json.dumps(payload)
except Exception:
self._logger.exception("JSON: Cannot dump %r", payload)
json_string = ""
currentData = self._printer.get_current_data()
params = {
"__currentZ": "-1",
"__eventname": event,
"__filename": "NO FILE",
"__filepath": "NO PATH",
"__progress": "0",
"__data": str(payload),
"__json": json_string,
"__now": datetime.datetime.now().isoformat(),
}
if "currentZ" in currentData and currentData["currentZ"] is not None:
params["__currentZ"] = str(currentData["currentZ"])
currentData = self._printer.get_current_data()
if "job" in currentData and "file" in currentData["job"] and "name" in currentData["job"]["file"] \
and currentData["job"]["file"]["name"] is not None:
params["__filename"] = currentData["job"]["file"]["name"]
params["__filepath"] = currentData["job"]["file"]["path"]
params["__fileorigin"] = currentData["job"]["file"]["origin"]
if "progress" in currentData and currentData["progress"] is not None \
and "completion" in currentData["progress"] and currentData["progress"]["completion"] is not None:
params["__progress"] = str(round(currentData["progress"]["completion"]))
if "currentZ" in currentData and currentData["currentZ"] is not None:
params["__currentZ"] = str(currentData["currentZ"])
# now add the payload keys as well
if isinstance(payload, dict):
params.update(payload)
if (
"job" in currentData
and "file" in currentData["job"]
and "name" in currentData["job"]["file"]
and currentData["job"]["file"]["name"] is not None
):
params["__filename"] = currentData["job"]["file"]["name"]
params["__filepath"] = currentData["job"]["file"]["path"]
params["__fileorigin"] = currentData["job"]["file"]["origin"]
if (
"progress" in currentData
and currentData["progress"] is not None
and "completion" in currentData["progress"]
and currentData["progress"]["completion"] is not None
):
params["__progress"] = str(round(currentData["progress"]["completion"]))
return command.format(**params)
# now add the payload keys as well
if isinstance(payload, dict):
params.update(payload)
return command.format(**params)
File diff suppressed because it is too large. Load diff
+407 -338
View File
@@ -2,438 +2,507 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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
try:
import queue
import queue
except ImportError:
import Queue as queue
import Queue as queue
import collections
import os
import threading
import collections
import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import dict_merge
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import monotonic_time
from octoprint.util import get_fully_qualified_classname as fqcn, dict_merge
from octoprint.util.platform import CLOSE_FDS
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
class QueueEntry(
collections.namedtuple(
"QueueEntry",
"name, path, type, location, absolute_path, printer_profile, analysis",
)
):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
Arguments:
name (str): Name of the file to analyze.
path (str): Storage location specific path to the file to analyze.
type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class.
At the moment, only ``gcode`` is supported here.
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
Arguments:
name (str): Name of the file to analyze.
path (str): Storage location specific path to the file to analyze.
type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class.
At the moment, only ``gcode`` is supported here.
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
class AnalysisAborted(Exception):
def __init__(self, reenqueue=True, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.reenqueue = reenqueue
def __init__(self, reenqueue=True, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.reenqueue = reenqueue
class AnalysisQueue(object):
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
:meth:`unregister_finish_callback`.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
:meth:`unregister_finish_callback`.
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
(no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the
entry will be enqueued with the type specific analysis queue.
"""
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
(no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the
entry will be enqueued with the type specific analysis queue.
"""
def __init__(self, queue_factories):
self._logger = logging.getLogger(__name__)
self._callbacks = []
def __init__(self, queue_factories):
self._logger = logging.getLogger(__name__)
self._callbacks = []
self._queues = dict()
for key, queue_factory in queue_factories.items():
self._queues[key] = queue_factory(self._analysis_finished)
self._queues = {}
for key, queue_factory in queue_factories.items():
self._queues[key] = queue_factory(self._analysis_finished)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
def unregister_finish_callback(self, callback):
self._callbacks.remove(callback)
def unregister_finish_callback(self, callback):
self._callbacks.remove(callback)
def enqueue(self, entry, high_priority=False):
if entry is None:
return False
def enqueue(self, entry, high_priority=False):
if entry is None:
return False
if not entry.type in self._queues:
return False
if entry.type not in self._queues:
return False
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
def dequeue(self, entry):
if entry is None:
return False
def dequeue(self, entry):
if entry is None:
return False
if not entry.type in self._queues:
return False
if entry.type not in self._queues:
return False
self._queues[entry.type].dequeue(entry.location, entry.path)
self._queues[entry.type].dequeue(entry.location, entry.path)
def dequeue_folder(self, destination, path):
for q in self._queues.values():
q.dequeue_folder(destination, path)
def dequeue_folder(self, destination, path):
for q in self._queues.values():
q.dequeue_folder(destination, path)
def pause(self):
for q in self._queues.values():
q.pause()
def pause(self):
for q in self._queues.values():
q.pause()
def resume(self):
for q in self._queues.values():
q.resume()
def resume(self):
for q in self._queues.values():
q.resume()
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
try:
callback(entry, result)
except Exception:
self._logger.exception(
"Error while pushing analysis data to callback {}".format(callback),
extra={"callback": fqcn(callback)},
)
eventManager().fire(
Events.METADATA_ANALYSIS_FINISHED,
{
"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result,
},
)
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
try:
callback(entry, result)
except:
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
extra=dict(callback=fqcn(callback)))
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result})
class AbstractAnalysisQueue(object):
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
processing.
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
processing.
Arguments:
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
The callback will be called with the analyzed entry as the first argument and the analysis result as
returned from the queue implementation as the second parameter.
Arguments:
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
The callback will be called with the analyzed entry as the first argument and the analysis result as
returned from the queue implementation as the second parameter.
.. automethod:: _do_analysis
.. automethod:: _do_analysis
.. automethod:: _do_abort
"""
.. automethod:: _do_abort
"""
LOW_PRIO = 100
LOW_PRIO_ABORTED = 75
HIGH_PRIO = 50
HIGH_PRIO_ABORTED = 0
LOW_PRIO = 100
LOW_PRIO_ABORTED = 75
HIGH_PRIO = 50
HIGH_PRIO_ABORTED = 0
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
self._finished_callback = finished_callback
self._finished_callback = finished_callback
self._active = threading.Event()
self._active.set()
self._active = threading.Event()
self._active.set()
self._done = threading.Event()
self._done.clear()
self._done = threading.Event()
self._done.clear()
self._currentFile = None
self._currentProgress = None
self._currentFile = None
self._currentProgress = None
self._queue = queue.PriorityQueue()
self._current = None
self._current_highprio = False
self._queue = queue.PriorityQueue()
self._current = None
self._current_highprio = False
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def enqueue(self, entry, high_priority=False):
"""
Enqueues an ``entry`` for analysis by the queue.
def enqueue(self, entry, high_priority=False):
"""
Enqueues an ``entry`` for analysis by the queue.
If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before
other entries in the queue with normal priority.
If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before
other entries in the queue with normal priority.
Arguments:
entry (QueueEntry): The :class:`QueueEntry` to analyze.
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
(False, default)
"""
Arguments:
entry (QueueEntry): The :class:`QueueEntry` to analyze.
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
(False, default)
"""
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
return
elif high_priority:
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
prio = self.__class__.HIGH_PRIO
else:
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
prio = self.__class__.LOW_PRIO
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug(
"Ignoring entry {entry} for analysis queue".format(entry=entry)
)
return
elif high_priority:
self._logger.debug(
"Adding entry {entry} to analysis queue with high priority".format(
entry=entry
)
)
prio = self.__class__.HIGH_PRIO
else:
self._logger.debug(
"Adding entry {entry} to analysis queue with low priority".format(
entry=entry
)
)
prio = self.__class__.LOW_PRIO
self._queue.put((prio, entry, high_priority))
if high_priority and self._current is not None and not self._current_highprio:
self._logger.debug("Aborting current analysis in favor of high priority one")
self._do_abort()
self._queue.put((prio, entry, high_priority))
if high_priority and self._current is not None and not self._current_highprio:
self._logger.debug("Aborting current analysis in favor of high priority one")
self._do_abort()
def dequeue(self, location, path):
if self._current is not None and self._current.location == location \
and self._current.path == path:
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue(self, location, path):
if (
self._current is not None
and self._current.location == location
and self._current.path == path
):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue_folder(self, location, path):
if self._current is not None and self._current.location == location \
and self._current.path.startswith(path + "/"):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue_folder(self, location, path):
if (
self._current is not None
and self._current.location == location
and self._current.path.startswith(path + "/")
):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def pause(self):
"""
Pauses processing of the queue, e.g. when a print is active.
"""
def pause(self):
"""
Pauses processing of the queue, e.g. when a print is active.
"""
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
self._logger.debug("Aborting running analysis, will restart when analyzer is resumed")
self._do_abort()
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
self._logger.debug(
"Aborting running analysis, will restart when analyzer is resumed"
)
self._do_abort()
def resume(self):
"""
Resumes processing of the queue, e.g. when a print has finished.
"""
def resume(self):
"""
Resumes processing of the queue, e.g. when a print has finished.
"""
self._logger.debug("Resuming analyzer")
self._active.set()
self._logger.debug("Resuming analyzer")
self._active.set()
def _work(self):
while True:
(priority, entry, high_priority) = self._queue.get()
self._logger.debug("Processing entry {} from queue (priority {})".format(entry, priority))
self._active.wait()
def _work(self):
while True:
(priority, entry, high_priority) = self._queue.get()
self._logger.debug(
"Processing entry {} from queue (priority {})".format(entry, priority)
)
self._active.wait()
try:
self._analyze(entry, high_priority=high_priority)
self._queue.task_done()
self._done.set()
except AnalysisAborted as ex:
if ex.reenqueue:
self._queue.put((self.__class__.HIGH_PRIO_ABORTED if high_priority else self.__class__.LOW_PRIO_ABORTED,
entry,
high_priority))
self._logger.debug("Running analysis of entry {} aborted".format(entry))
self._queue.task_done()
self._done.set()
else:
time.sleep(1.0)
try:
self._analyze(entry, high_priority=high_priority)
self._queue.task_done()
self._done.set()
except AnalysisAborted as ex:
if ex.reenqueue:
self._queue.put(
(
self.__class__.HIGH_PRIO_ABORTED
if high_priority
else self.__class__.LOW_PRIO_ABORTED,
entry,
high_priority,
)
)
self._logger.debug("Running analysis of entry {} aborted".format(entry))
self._queue.task_done()
self._done.set()
else:
time.sleep(1.0)
def _analyze(self, entry, high_priority=False):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
def _analyze(self, entry, high_priority=False):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
self._current = entry
self._current_highprio = high_priority
self._current_progress = 0
self._current = entry
self._current_highprio = high_priority
self._current_progress = 0
try:
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type})
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
self._finished_callback(self._current, result)
finally:
self._current = None
self._current_progress = None
try:
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(
Events.METADATA_ANALYSIS_STARTED,
{
"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type,
},
)
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info(
"Analysis of entry {} finished, needed {:.2f}s".format(
entry, monotonic_time() - start_time
)
)
self._finished_callback(self._current, result)
finally:
self._current = None
self._current_progress = None
def _do_analysis(self, high_priority=False):
"""
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
overridden by sub classes.
def _do_analysis(self, high_priority=False):
"""
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
overridden by sub classes.
Arguments:
high_priority (bool): Whether the current entry has high priority or not.
Arguments:
high_priority (bool): Whether the current entry has high priority or not.
Returns:
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
construction.
"""
return None
Returns:
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
construction.
"""
return None
def _do_abort(self, reenqueue=True):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
pass
def _do_abort(self, reenqueue=True):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
pass
class GcodeAnalysisQueue(AbstractAnalysisQueue):
"""
A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows:
"""
A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows:
.. list-table::
:widths: 25 70
.. list-table::
:widths: 25 70
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
- * ``filament.toolX.length``
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
- * ``printingArea``
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
- * ``printingArea.minX``
* Minimum X coordinate of the printed object
- * ``printingArea.maxX``
* Maximum X coordinate of the printed object
- * ``printingArea.minY``
* Minimum Y coordinate of the printed object
- * ``printingArea.maxY``
* Maximum Y coordinate of the printed object
- * ``printingArea.minZ``
* Minimum Z coordinate of the printed object
- * ``printingArea.maxZ``
* Maximum Z coordinate of the printed object
- * ``dimensions``
* Dimensions of the printed object in X, Y, Z
- * ``dimensions.width``
* Width of the printed model along the X axis, in mm
- * ``dimensions.depth``
* Depth of the printed model along the Y axis, in mm
- * ``dimensions.height``
* Height of the printed model along the Z axis, in mm
"""
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
- * ``filament.toolX.length``
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
- * ``printingArea``
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
- * ``printingArea.minX``
* Minimum X coordinate of the printed object
- * ``printingArea.maxX``
* Maximum X coordinate of the printed object
- * ``printingArea.minY``
* Minimum Y coordinate of the printed object
- * ``printingArea.maxY``
* Maximum Y coordinate of the printed object
- * ``printingArea.minZ``
* Minimum Z coordinate of the printed object
- * ``printingArea.maxZ``
* Maximum Z coordinate of the printed object
- * ``dimensions``
* Dimensions of the printed object in X, Y, Z
- * ``dimensions.width``
* Width of the printed model along the X axis, in mm
- * ``dimensions.depth``
* Depth of the printed model along the Y axis, in mm
- * ``dimensions.height``
* Height of the printed model along the Z axis, in mm
"""
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
self._aborted = False
self._reenqueue = False
self._aborted = False
self._reenqueue = False
def _do_analysis(self, high_priority=False):
import sarge
import sys
import yaml
def _do_analysis(self, high_priority=False):
import sys
if self._current.analysis and all(map(lambda x: x in self._current.analysis, ("printingArea",
"dimensions",
"estimatedPrintTime",
"filament"))):
return self._current.analysis
import sarge
import yaml
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
if self._current.analysis and all(
map(
lambda x: x in self._current.analysis,
("printingArea", "dimensions", "estimatedPrintTime", "filament"),
)
):
return self._current.analysis
command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
"--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines)]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
try:
throttle = (
settings().getFloat(["gcodeAnalysis", "throttle_highprio"])
if high_priority
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
)
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
command = [
sys.executable,
"-m",
"octoprint",
"analysis",
"gcode",
"--speed-x={}".format(speedx),
"--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders),
"--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines),
]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
self._aborted = False
p = sarge.run(command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture())
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
self._aborted = False
p = sarge.run(
command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture()
)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError("Error while trying to run command {}".format(" ".join(command)))
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
try:
# let's wait for stuff to finish
while p.returncode is None:
if self._aborted:
# oh, we shall abort, let's do so!
p.commands[0].terminate()
raise AnalysisAborted(reenqueue=self._reenqueue)
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError(
"Error while trying to run command {}".format(" ".join(command))
)
# else continue
p.commands[0].poll()
finally:
p.close()
try:
# let's wait for stuff to finish
while p.returncode is None:
if self._aborted:
# oh, we shall abort, let's do so!
p.commands[0].terminate()
raise AnalysisAborted(reenqueue=self._reenqueue)
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
# else continue
p.commands[0].poll()
finally:
p.close()
if not "RESULTS:" in output:
raise RuntimeError("No analysis result found")
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
_, output = output.split("RESULTS:")
analysis = yaml.safe_load(output)
if "RESULTS:" not in output:
raise RuntimeError("No analysis result found")
result = dict()
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = dict()
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i]
}
_, output = output.split("RESULTS:")
analysis = yaml.safe_load(output)
if self._current.analysis and isinstance(self._current.analysis, dict):
return dict_merge(result, self._current.analysis)
else:
return result
finally:
self._gcode = None
result = {}
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = {}
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i],
}
def _do_abort(self, reenqueue=True):
self._aborted = True
self._reenqueue = reenqueue
if self._current.analysis and isinstance(self._current.analysis, dict):
return dict_merge(result, self._current.analysis)
else:
return result
finally:
self._gcode = None
def _do_abort(self, reenqueue=True):
self._aborted = True
self._reenqueue = reenqueue
Loaded 100 of 577 files, more files were not shown because too many files have changed in this diff. Show more