Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e46e8fa17a | ||
|
|
12d6de51da | ||
|
|
424dc0a13d | ||
|
|
d9fef47e78 | ||
|
|
222b9997a1 | ||
|
|
3124c08927 | ||
|
|
2697bd7a42 | ||
|
|
a2d4fc08a5 | ||
|
|
bdeb765f75 | ||
|
|
84b61e01f4 | ||
|
|
38256815ef | ||
|
|
c111054fd6 | ||
|
|
82dd94d51b | ||
|
|
1536ed6da3 | ||
|
|
9f9d0fc788 | ||
|
|
a23daa7c81 | ||
|
|
82d308c9ac | ||
|
|
fe7437388a | ||
|
|
28a1c8bb4f | ||
|
|
f67c15a9a4 | ||
|
|
a74309d650 | ||
|
|
220979bf68 | ||
|
|
49cd9d3283 | ||
|
|
308ac450e7 | ||
|
|
d80a27a64a | ||
|
|
a4630df622 | ||
|
|
149161694d | ||
|
|
5e7ea35239 | ||
|
|
4768a7eb5a | ||
|
|
84fb97f82a | ||
|
|
c30673fac0 | ||
|
|
9f5781eff4 | ||
|
|
f2ed1ebc74 | ||
|
|
e7e731800b | ||
|
|
89f3edcb27 | ||
|
|
c44e90302d | ||
|
|
5b5163c812 | ||
|
|
d311fb18e0 | ||
|
|
ab5d19bf12 | ||
|
|
75796dafbc | ||
|
|
2670d16407 | ||
|
|
54f98a5ad1 | ||
|
|
1238edf1b9 | ||
|
|
5f2a95d154 | ||
|
|
8cd51103d9 | ||
|
|
b94424411a | ||
|
|
fabf331197 | ||
|
|
bed0f8d1c8 | ||
|
|
f55d7e29f7 | ||
|
|
33dbfd2b3b | ||
|
|
b7a45b79bf | ||
|
|
1b41ab8567 | ||
|
|
d857779d67 | ||
|
|
4166ef1556 | ||
|
|
6a695c851a | ||
|
|
84b41e70a6 | ||
|
|
fe6a865c13 | ||
|
|
e82eced346 | ||
|
|
959b8637db | ||
|
|
e5f893d2ba | ||
|
|
e94c248f23 | ||
|
|
7483a24efa | ||
|
|
1480dcf6e0 | ||
|
|
ca62d15aac | ||
|
|
b5ce6281d8 | ||
|
|
cb9e5b401f | ||
|
|
3bd7004733 | ||
|
|
4110287349 | ||
|
|
a5e18300ea | ||
|
|
ee63eea02f | ||
|
|
caa63017cf | ||
|
|
837b5a65ea | ||
|
|
0aa5be6709 | ||
|
|
7f4dcaa5f1 | ||
|
|
7bdda2e2a6 | ||
|
|
7d49f20571 | ||
|
|
95ddb184a0 | ||
|
|
eec43e31c2 | ||
|
|
ee4eb72014 | ||
|
|
a58e02940d | ||
|
|
d41feaec6d | ||
|
|
de29cdb7e5 | ||
|
|
18e4025c47 | ||
|
|
79f0b06150 | ||
|
|
189d3bbbdf | ||
|
|
60f14e1f99 | ||
|
|
d0ad6c6223 | ||
|
|
6c1eaad083 | ||
|
|
27ced65a4d | ||
|
|
1e0f549fb6 | ||
|
|
9fed67306e | ||
|
|
0267250af4 | ||
|
|
b12e5a6e00 | ||
|
|
60a40d55b6 | ||
|
|
8500584c02 | ||
|
|
5246ca85f0 | ||
|
|
900d7c36d2 | ||
|
|
dbc012fa4c | ||
|
|
f21653510f | ||
|
|
065b87d694 | ||
|
|
7986ba7072 | ||
|
|
8793495edd | ||
|
|
16161fdb0a | ||
|
|
a3dd2c6b34 | ||
|
|
c0c6dd7c7b | ||
|
|
fd319fc82f | ||
|
|
0d90bb9e8f | ||
|
|
3db176e77f | ||
|
|
6c18931153 | ||
|
|
688188777f | ||
|
|
83c411b308 | ||
|
|
2acf4764c2 | ||
|
|
021748e81a | ||
|
|
1d689d0b87 | ||
|
|
c20c9946f8 | ||
|
|
8294eae6d9 | ||
|
|
79814905fa | ||
|
|
4dea9f08ef | ||
|
|
9494db9568 | ||
|
|
4bafd14bef | ||
|
|
706210a483 | ||
|
|
69644593f7 | ||
|
|
c5051ddb30 | ||
|
|
e7d037d3d4 | ||
|
|
3478aa1305 | ||
|
|
8033692873 | ||
|
|
257deabbbe | ||
|
|
78f26de1d8 | ||
|
|
b96f7657e6 | ||
|
|
de81591b26 | ||
|
|
90130dcd7d | ||
|
|
4392ca7352 | ||
|
|
23b6bd1101 | ||
|
|
d62b9f00de | ||
|
|
f291fa898e | ||
|
|
1688d8f22a | ||
|
|
3c31d98c50 | ||
|
|
446e1b7ece | ||
|
|
bc785141e5 | ||
|
|
1e5d6786da | ||
|
|
d3cf2a8e35 | ||
|
|
aafbd62c2d | ||
|
|
29726b15d1 | ||
|
|
a653628acb | ||
|
|
6b44909f21 | ||
|
|
eb37b72dc1 | ||
|
|
9ab1a56935 | ||
|
|
8427383b31 | ||
|
|
7c4582a0fe | ||
|
|
86255c7bbe | ||
|
|
a788fc255d | ||
|
|
7599a09b0d | ||
|
|
b5be8f3eae | ||
|
|
6d6671c2a1 | ||
|
|
cae6730ea8 | ||
|
|
fbfb34df58 | ||
|
|
1f93b2355a | ||
|
|
60f45ffaf6 | ||
|
|
aba033ae63 | ||
|
|
986312b6ae | ||
|
|
af60fd6428 | ||
|
|
559c9b4e52 | ||
|
|
21c8095b8a | ||
|
|
8377b59217 | ||
|
|
d06e0c5e94 | ||
|
|
db0cf4082d | ||
|
|
0747a4d850 | ||
|
|
3b19d4b6fb | ||
|
|
8a3a4ff653 | ||
|
|
d652524cef | ||
|
|
3c1aaa24f5 | ||
|
|
26151b3c42 | ||
|
|
9a7712ed11 | ||
|
|
098e5f2516 | ||
|
|
687e6ad900 | ||
|
|
22ce8e4c24 | ||
|
|
24204efab6 | ||
|
|
9611172b88 | ||
|
|
a808c58091 | ||
|
|
d19ce0a67e | ||
|
|
3672f7bad7 | ||
|
|
855cdad612 | ||
|
|
b857fd1e24 | ||
|
|
9dce1e5291 | ||
|
|
126d370b34 | ||
|
|
37210a76fa | ||
|
|
e92e69b35b | ||
|
|
b218cbab92 | ||
|
|
6746e8777a | ||
|
|
81b295726f | ||
|
|
b7d749ec90 | ||
|
|
87102407c7 | ||
|
|
8668e5d66b | ||
|
|
0b9158f727 | ||
|
|
d98b793705 | ||
|
|
0d96f1b8ca | ||
|
|
290de2f15c | ||
|
|
d30b3a398f | ||
|
|
fc56327e79 | ||
|
|
03918703d9 | ||
|
|
8feb5b2ff9 | ||
|
|
cf16ce6e64 | ||
|
|
fb6248c624 | ||
|
|
10827e56aa | ||
|
|
107926dd7e | ||
|
|
c0495d22c9 | ||
|
|
030f9ac6d3 | ||
|
|
786e2f860f | ||
|
|
a6fc1e715a | ||
|
|
917dd262f9 | ||
|
|
d85d3f346e | ||
|
|
4b0ad7dc1f | ||
|
|
dd78fd3ed3 | ||
|
|
cac1e4b0bd | ||
|
|
b8294f2cb7 | ||
|
|
40c21acf38 | ||
|
|
250842e561 | ||
|
|
1cbc322904 | ||
|
|
30cfc57b03 | ||
|
|
5a9ef80f4c | ||
|
|
dee7f31e55 | ||
|
|
9a688ab1bd | ||
|
|
cb43f46b83 | ||
|
|
cfb9c93e65 | ||
|
|
e781e9c3e8 | ||
|
|
b51d5fecd1 | ||
|
|
64b57186da | ||
|
|
a5a3b9f8ee | ||
|
|
9e5d1e9ad6 | ||
|
|
6ea2caa770 | ||
|
|
0b92c63734 | ||
|
|
ef8903902c | ||
|
|
9f289a0e9c | ||
|
|
80f2ab86c1 | ||
|
|
ec4e2c7193 | ||
|
|
cdce9a6feb | ||
|
|
c1fa23d745 | ||
|
|
5f7c7ecfd8 | ||
|
|
b80826dd0c | ||
|
|
d320b1c7a3 | ||
|
|
7657544d74 | ||
|
|
44b5ce144c | ||
|
|
65eb45c56a | ||
|
|
0dd43d7bcc | ||
|
|
4cf2a673c8 | ||
|
|
e83e2a4467 | ||
|
|
497cf925ab | ||
|
|
1d09914f8c | ||
|
|
497af61712 | ||
|
|
e91fcd6387 | ||
|
|
b3bc1e75aa | ||
|
|
6132f481ce | ||
|
|
966c473507 | ||
|
|
f415010337 | ||
|
|
cbf1fe71a5 | ||
|
|
e72aab3448 | ||
|
|
98c7fc8197 | ||
|
|
105078f4b1 | ||
|
|
e57adfac08 | ||
|
|
bdb68ae28b | ||
|
|
b7fab60023 | ||
|
|
98a83e89d0 | ||
|
|
fadbe7bffe | ||
|
|
c4a807c090 | ||
|
|
513a7bf4b1 | ||
|
|
69247460a1 | ||
|
|
bd7ed94b4a | ||
|
|
8357f344af | ||
|
|
045d4b9856 | ||
|
|
ed3a775ad2 | ||
|
|
52b08b9959 | ||
|
|
16c8eb2689 | ||
|
|
89544ba9fb | ||
|
|
c7ef487f2b | ||
|
|
711aae9c85 | ||
|
|
b09c0d6819 | ||
|
|
6fed292ef1 | ||
|
|
3dc181e3fb | ||
|
|
c235b12201 | ||
|
|
5cd93e4e0f | ||
|
|
641f27af3c | ||
|
|
72eec66208 | ||
|
|
2fb60bd40f | ||
|
|
f79d217ffa | ||
|
|
ab016b5ccd | ||
|
|
a11c3895ef | ||
|
|
82754a5213 | ||
|
|
5ca20f741a | ||
|
|
4d82f2a4c6 | ||
|
|
0de671a1de | ||
|
|
1306c6f7be | ||
|
|
2a19480084 | ||
|
|
5df72729d1 | ||
|
|
4bf2896413 | ||
|
|
09c2800181 | ||
|
|
3111846ddc | ||
|
|
33d28e6226 | ||
|
|
8ea4adce56 | ||
|
|
5a33ecf63b | ||
|
|
abbbd926bc | ||
|
|
ad6230074a | ||
|
|
58fa6004bb | ||
|
|
1d55e488ae | ||
|
|
ffb2a0ed73 | ||
|
|
ac967499f3 | ||
|
|
e49d0b0c22 | ||
|
|
a846fd8f83 | ||
|
|
c9186edd34 | ||
|
|
e7e04271fd | ||
|
|
894178918b | ||
|
|
05cd917693 | ||
|
|
ffde393c66 | ||
|
|
252b9b7e41 | ||
|
|
b0247597f9 | ||
|
|
fb8fcb0685 | ||
|
|
cae900b1fb | ||
|
|
65937a9244 | ||
|
|
06637280e5 | ||
|
|
c57c2b5a2b | ||
|
|
462f90979d | ||
|
|
3b6be8b4b9 | ||
|
|
87cd0a88fb | ||
|
|
6165e5b0f0 | ||
|
|
d47ea73dfc | ||
|
|
f62addc5e8 | ||
|
|
8b939d89a5 | ||
|
|
b973b5fab2 | ||
|
|
c1bddcd594 | ||
|
|
b1e2121682 | ||
|
|
b3d094db02 | ||
|
|
bc015da547 | ||
|
|
a9ad2aa2fa | ||
|
|
232d5ce54f | ||
|
|
8f508067e6 | ||
|
|
dbd7f719f6 | ||
|
|
63135a4b2b | ||
|
|
003b80689e | ||
|
|
df66dd9abf | ||
|
|
b20c15f56d | ||
|
|
1b05e782bf | ||
|
|
d628f11388 | ||
|
|
6c891a3e29 | ||
|
|
7f6d2c9582 | ||
|
|
1746820d69 |
No files matched your search
+11
-7
@@ -8,19 +8,23 @@ end_of_line = lf
|
|||||||
charset = utf-8
|
charset = utf-8
|
||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
trim_trailing_whitespace = true
|
trim_trailing_whitespace = true
|
||||||
|
indent_style = space
|
||||||
|
max_line_length = 90
|
||||||
|
|
||||||
[**.py]
|
[**.py]
|
||||||
indent_style = tab
|
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
|
|
||||||
[src/octoprint/vendor/sockjs/**.py]
|
[**.yaml]
|
||||||
indent_style = space
|
indent_size = 2
|
||||||
indent_size = 4
|
|
||||||
|
|
||||||
[src/octoprint/static/js/app/**.js]
|
[src/octoprint/static/js/app/**.js]
|
||||||
indent_style = space
|
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
|
|
||||||
[.travis.yml]
|
[src/octoprint/static/js/login/**.js]
|
||||||
indent_style = space
|
indent_size = 4
|
||||||
|
|
||||||
|
[src/octoprint/static/js/recovery/**.js]
|
||||||
|
indent_size = 4
|
||||||
|
|
||||||
|
[src/octoprint/static/less/octoprint.less]
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -17,7 +17,7 @@ or request features within OctoPrint (not OctoPi, not any OctoPrint
|
|||||||
plugins and not unofficial OctoPrint versions).
|
plugins and not unofficial OctoPrint versions).
|
||||||
|
|
||||||
Do not seek support here ("I need help with ...", "I have a
|
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.
|
community.octoprint.org, NOT here.
|
||||||
|
|
||||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||||
@@ -37,7 +37,7 @@ Thank you!
|
|||||||
|
|
||||||
#### What were you doing?
|
#### What were you doing?
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
Please be as specific as possible here. The maintainers will need to
|
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
|
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.
|
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?
|
#### Did the same happen when running OctoPrint in safe mode?
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
Test if you can reproduce your problem in safe mode. You can find information
|
Test if you can reproduce your problem in safe mode. You can find information
|
||||||
on how to enable safe mode in the Contribution Guidelines.
|
on how to enable safe mode in the Contribution Guidelines.
|
||||||
|
|
||||||
|
|||||||
@@ -16,15 +16,15 @@ checklist:
|
|||||||
made sure your changes don't interfere with current development by
|
made sure your changes don't interfere with current development by
|
||||||
talking it through with the maintainers, e.g. through a
|
talking it through with the maintainers, e.g. through a
|
||||||
Brainstorming ticket
|
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
|
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)
|
against master or anything else please)
|
||||||
* [ ] Your PR was opened from a custom branch on your repository
|
* [ ] Your PR was opened from a custom branch on your repository
|
||||||
(no PRs from your version of master, maintenance or devel please),
|
(no PRs from your version of master, maintenance or devel please),
|
||||||
e.g. dev/my_new_feature or fix/my_bugfix
|
e.g. dev/my_new_feature or fix/my_bugfix
|
||||||
* [ ] Your PR only contains relevant changes: no unrelated files,
|
* [ ] 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!
|
if necessary!
|
||||||
* [ ] Your changes follow the existing coding style
|
* [ ] Your changes follow the existing coding style
|
||||||
* [ ] If your changes include style sheets: You have modified the
|
* [ ] If your changes include style sheets: You have modified the
|
||||||
@@ -37,7 +37,7 @@ checklist:
|
|||||||
* [ ] You have added yourself to the AUTHORS.md file :)
|
* [ ] 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!
|
details the better!
|
||||||
-->
|
-->
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
accessControl:
|
accessControl:
|
||||||
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
||||||
plugins:
|
plugins:
|
||||||
virtual_printer:
|
virtual_printer:
|
||||||
enabled: true
|
enabled: true
|
||||||
tracking:
|
tracking:
|
||||||
enabled: false
|
enabled: false
|
||||||
server:
|
server:
|
||||||
firstRun: false
|
firstRun: false
|
||||||
onlineCheck:
|
onlineCheck:
|
||||||
enabled: false
|
enabled: false
|
||||||
pluginBlacklist:
|
pluginBlacklist:
|
||||||
enabled: false
|
enabled: false
|
||||||
secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
|
secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
|
||||||
seenWizards:
|
seenWizards:
|
||||||
backup: null
|
backup: null
|
||||||
corewizard: 3
|
corewizard: 3
|
||||||
tracking: null
|
tracking: null
|
||||||
@@ -1,22 +1,22 @@
|
|||||||
admin:
|
admin:
|
||||||
active: true
|
active: true
|
||||||
apikey: null
|
apikey: null
|
||||||
groups:
|
groups:
|
||||||
- admins
|
- admins
|
||||||
- users
|
- users
|
||||||
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
|
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
|
||||||
permissions: []
|
permissions: []
|
||||||
roles:
|
roles:
|
||||||
- user
|
- user
|
||||||
- admin
|
- admin
|
||||||
settings: {}
|
settings: {}
|
||||||
user:
|
user:
|
||||||
active: true
|
active: true
|
||||||
apikey: null
|
apikey: null
|
||||||
groups:
|
groups:
|
||||||
- users
|
- users
|
||||||
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
|
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
|
||||||
permissions: []
|
permissions: []
|
||||||
roles:
|
roles:
|
||||||
- user
|
- user
|
||||||
settings: {}
|
settings: {}
|
||||||
+73
-18
@@ -1,8 +1,11 @@
|
|||||||
name: Build
|
name: Build
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, sychronize, reopened]
|
||||||
release:
|
release:
|
||||||
types: [published, prereleased]
|
types: [published, prereleased]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -28,6 +31,70 @@ jobs:
|
|||||||
name: dist
|
name: dist
|
||||||
path: 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:
|
test-unit:
|
||||||
name: 🧪 Unit tests
|
name: 🧪 Unit tests
|
||||||
strategy:
|
strategy:
|
||||||
@@ -47,22 +114,6 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
pytest
|
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:
|
test-install:
|
||||||
name: 🧪 Installation tests
|
name: 🧪 Installation tests
|
||||||
needs: build
|
needs: build
|
||||||
@@ -121,8 +172,8 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
working-directory: tests/cypress
|
working-directory: tests/cypress
|
||||||
browser: chrome
|
browser: chrome
|
||||||
start: 'octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000'
|
start: "octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000"
|
||||||
wait-on: 'http://127.0.0.1:5000/online.txt'
|
wait-on: "http://127.0.0.1:5000/online.txt"
|
||||||
|
|
||||||
- name: ⬆ Upload screenshots
|
- name: ⬆ Upload screenshots
|
||||||
uses: actions/upload-artifact@v1
|
uses: actions/upload-artifact@v1
|
||||||
@@ -141,6 +192,10 @@ jobs:
|
|||||||
name: 📦 Publish on TestPyPI
|
name: 📦 Publish on TestPyPI
|
||||||
if: github.event_name == 'release'
|
if: github.event_name == 'release'
|
||||||
needs:
|
needs:
|
||||||
|
- lint-black
|
||||||
|
- lint-prettier
|
||||||
|
- lint-isort
|
||||||
|
- lint-flake8
|
||||||
- test-unit
|
- test-unit
|
||||||
- test-install
|
- test-install
|
||||||
- test-e2e
|
- test-e2e
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
name: "Issue Labeler"
|
name: "Issue Labeler"
|
||||||
on:
|
on:
|
||||||
issues:
|
issues:
|
||||||
types: [opened, edited]
|
types: [opened, edited, closed, reopened]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
apply-label:
|
label-opened-and-edited:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/github-script@v2
|
- uses: actions/github-script@v2
|
||||||
@@ -12,19 +12,50 @@ jobs:
|
|||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
script: |
|
script: |
|
||||||
let labels = [];
|
let labels = [];
|
||||||
|
let setLabels = false;
|
||||||
|
context.payload.issue.labels.forEach(label => { labels.push(label.name) });
|
||||||
|
|
||||||
if (context.payload.issue.title.match(/\[request\]|feature request/i)) {
|
switch (context.payload.action) {
|
||||||
labels.push('type:request');
|
|
||||||
}
|
case 'opened':
|
||||||
if (context.payload.issue.title.match(/\[brainstorming\]/i)) {
|
case 'edited': {
|
||||||
labels.push('type:brainstorming');
|
if (context.payload.issue.title.match(/\[request\]|feature request/i)) {
|
||||||
}
|
labels.push('request');
|
||||||
if (context.payload.issue.title.match(/\[rc feedback\]/i)) {
|
labels = labels.filter(label => label !== 'triage');
|
||||||
labels.push('type:rc feedback');
|
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 (labels.length > 0) {
|
if (setLabels) {
|
||||||
github.issues.addLabels({
|
github.issues.setLabels({
|
||||||
issue_number: context.issue.number,
|
issue_number: context.issue.number,
|
||||||
owner: context.repo.owner,
|
owner: context.repo.owner,
|
||||||
repo: context.repo.repo,
|
repo: context.repo.repo,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
name: 'Lock outdated issues & PRs'
|
name: "Lock outdated issues & PRs"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '0 0 * * *'
|
- cron: "0 0 * * *"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lock:
|
lock:
|
||||||
@@ -12,5 +12,5 @@ jobs:
|
|||||||
uses: dessant/lock-threads@v2
|
uses: dessant/lock-threads@v2
|
||||||
with:
|
with:
|
||||||
github-token: ${{ github.token }}
|
github-token: ${{ github.token }}
|
||||||
issue-lock-comment: ''
|
issue-lock-comment: ""
|
||||||
pr-lock-comment: ''
|
pr-lock-comment: ""
|
||||||
@@ -6,7 +6,7 @@ on:
|
|||||||
- master
|
- master
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '0 */12 * * *'
|
- cron: "0 */12 * * *"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
install-branch:
|
install-branch:
|
||||||
@@ -35,14 +35,14 @@ jobs:
|
|||||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||||
uses: Ilshidur/action-discord@master
|
uses: Ilshidur/action-discord@master
|
||||||
with:
|
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
|
- name: 📧 Discord failure notification
|
||||||
if: failure()
|
if: failure()
|
||||||
env:
|
env:
|
||||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||||
uses: Ilshidur/action-discord@master
|
uses: Ilshidur/action-discord@master
|
||||||
with:
|
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:
|
install-latest:
|
||||||
name: Install latest release
|
name: Install latest release
|
||||||
@@ -69,11 +69,11 @@ jobs:
|
|||||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||||
uses: Ilshidur/action-discord@master
|
uses: Ilshidur/action-discord@master
|
||||||
with:
|
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
|
- name: 📧 Discord failure notification
|
||||||
if: failure()
|
if: failure()
|
||||||
env:
|
env:
|
||||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||||
uses: Ilshidur/action-discord@master
|
uses: Ilshidur/action-discord@master
|
||||||
with:
|
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"
|
||||||
@@ -4,15 +4,44 @@ on:
|
|||||||
types:
|
types:
|
||||||
- released
|
- released
|
||||||
- prereleased
|
- prereleased
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- maintenance
|
||||||
|
- devel
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
trigger:
|
dispatch_releases:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'push'
|
||||||
steps:
|
steps:
|
||||||
- name: 🚀 Repository Dispatch
|
- name: 🚀 Repository Dispatch
|
||||||
uses: peter-evans/repository-dispatch@v1
|
uses: peter-evans/repository-dispatch@v1
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
||||||
repository: OctoPrint/docker
|
repository: ${{ github.repository_owner }}/octoprint-docker
|
||||||
event-type: octoprint-release
|
event-type: ${{ github.event_name }}
|
||||||
client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}", "event-name": "${{ github.event_name }}", "event-type": "${{ github.event.action }}"}'
|
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,6 +2,7 @@ src/octoprint/templates/_data/AUTHORS.md
|
|||||||
src/octoprint/templates/_data/CHANGELOG.md
|
src/octoprint/templates/_data/CHANGELOG.md
|
||||||
src/octoprint/templates/_data/SUPPORTERS.md
|
src/octoprint/templates/_data/SUPPORTERS.md
|
||||||
src/octoprint/templates/_data/THIRDPARTYLICENSES.md
|
src/octoprint/templates/_data/THIRDPARTYLICENSES.md
|
||||||
|
src/octoprint/plugins/pi_support/.local_debug
|
||||||
docs/_build
|
docs/_build
|
||||||
|
|
||||||
devtools
|
devtools
|
||||||
@@ -35,6 +36,7 @@ pypy
|
|||||||
.eggs
|
.eggs
|
||||||
.mypy_cache
|
.mypy_cache
|
||||||
.pytest_cache
|
.pytest_cache
|
||||||
|
.python-version
|
||||||
.tox
|
.tox
|
||||||
|
|
||||||
venv*
|
venv*
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -5,4 +5,3 @@ host = https://www.transifex.com
|
|||||||
file_filter = translations/<lang>/LC_MESSAGES/messages.po
|
file_filter = translations/<lang>/LC_MESSAGES/messages.po
|
||||||
source_file = translations/messages.pot
|
source_file = translations/messages.pot
|
||||||
source_lang = en
|
source_lang = en
|
||||||
|
|
||||||
+9
-9
@@ -18,19 +18,19 @@ prerelease
|
|||||||
HEAD
|
HEAD
|
||||||
\(detached.*
|
\(detached.*
|
||||||
|
|
||||||
# maintenance is currently the branch for preparation of maintenance release 1.4.3
|
# maintenance is currently the branch for preparation of maintenance release 1.5.0
|
||||||
# so are any fix/... and improve/... branches
|
# so are any fix/... and improve/... branches
|
||||||
maintenance 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
maintenance 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev
|
||||||
fix/.* 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
fix/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev
|
||||||
improve/.* 1.4.3 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
improve/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev
|
||||||
|
|
||||||
# staging/hotfix is the branch for preparation of the 1.4.2 hotfix release
|
# staging/hotfix is the branch for preparation of the 1.5.2 hotfix release
|
||||||
staging/hotfix 1.4.2 3ab84ed7e4c3aaaf71fe0f184b465f25d689f929 pep440-dev
|
staging/hotfix 1.5.2 38256815ef6d6dd602e0fac949a17fbf8f30f838 pep440-dev
|
||||||
|
|
||||||
# staging/maintenance is currently the branch for preparation of 1.4.1rc5
|
# staging/maintenance is currently the branch for preparation of 1.5.0rc4
|
||||||
# so is regressionfix/...
|
# so is regressionfix/...
|
||||||
staging/maintenance 1.4.1rc5 458ab91f915307857941f839a1b743430b8786a4 pep440-dev
|
staging/maintenance 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev
|
||||||
regressionfix/.* 1.4.1rc5 458ab91f915307857941f839a1b743430b8786a4 pep440-dev
|
regressionfix/.* 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev
|
||||||
|
|
||||||
# staging/devel is currently inactive (but has the 1.4.1rc4 namespace)
|
# staging/devel is currently inactive (but has the 1.4.1rc4 namespace)
|
||||||
staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev
|
staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev
|
||||||
|
|||||||
@@ -121,7 +121,15 @@ date of first contribution):
|
|||||||
* [Josh Friend](https://github.com/joshfriend)
|
* [Josh Friend](https://github.com/joshfriend)
|
||||||
* [Lachlan Cresswell](https://github.com/lachyc)
|
* [Lachlan Cresswell](https://github.com/lachyc)
|
||||||
* [Khoi Pham](https://github.com/osubuu)
|
* [Khoi Pham](https://github.com/osubuu)
|
||||||
|
* [Timofei Korostelev](https://github.com/chudsaviet)
|
||||||
* [Federico Nembrini](https://github.com/FedericoNembrini)
|
* [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
|
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
|
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
OctoPrint's Code of Conduct can be found at [octoprint.org/conduct/](https://octoprint.org/conduct/).
|
||||||
+62
-117
@@ -39,7 +39,7 @@ nothing but ticket management.
|
|||||||
[community forum at community.octoprint.org](https://community.octoprint.org) for
|
[community forum at community.octoprint.org](https://community.octoprint.org) for
|
||||||
such support issues.
|
such support issues.
|
||||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
- 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).
|
[community forum at community.octoprint.org](https://community.octoprint.org/c/development).
|
||||||
- If you need **support**, have a **question** or some **other reason** that
|
- 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.
|
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.
|
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||||
|
|
||||||
> 👉 **Note**
|
> 👉 **Note**
|
||||||
>
|
>
|
||||||
> A bot is in place that monitors new tickets, automatically
|
> A bot is in place that monitors new tickets, automatically
|
||||||
> categorizes them and checks new bug reports for usage of the provided template.
|
> 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
|
> 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
|
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
|
of the official version of OctoPrint, which is the 3D print server and
|
||||||
corresponding web interface itself.
|
corresponding web interface itself.
|
||||||
|
|
||||||
**OctoPrint doesn't manage your network connection or your webcam nor
|
**OctoPrint doesn't manage your network connection or your webcam nor
|
||||||
can it fix your printer not getting detected as a serial interface** -
|
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
|
if you have any kinds of problems with that, get in touch on the
|
||||||
[community forum](https://community.octoprint.org).
|
[community forum](https://community.octoprint.org).
|
||||||
|
|
||||||
**This is not the bug tracker of OctoPi**, which is the preconfigured
|
**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
|
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
|
[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
|
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
|
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
|
||||||
very diligent here!
|
very diligent here!
|
||||||
|
|
||||||
If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org)
|
If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org)
|
||||||
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
|
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
|
||||||
there.
|
there.
|
||||||
|
|
||||||
### What should I include in a bug report?
|
### What should I include in a bug report?
|
||||||
|
|
||||||
First of all make sure your use **a descriptive title**. "It doesn't work"
|
First of all make sure your use **a descriptive title**. "It doesn't work"
|
||||||
and similar unspecific complaints are NOT descriptive titles.
|
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**:
|
existing ticket**:
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -152,7 +152,7 @@ or request features within OctoPrint (not OctoPi, not any OctoPrint
|
|||||||
plugins and not unofficial OctoPrint versions).
|
plugins and not unofficial OctoPrint versions).
|
||||||
|
|
||||||
Do not seek support here ("I need help with ...", "I have a
|
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.
|
community.octoprint.org, NOT here.
|
||||||
|
|
||||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||||
@@ -172,7 +172,7 @@ Thank you!
|
|||||||
|
|
||||||
#### What were you doing?
|
#### What were you doing?
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
Please be as specific as possible here. The maintainers will need to
|
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
|
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.
|
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?
|
#### Did the same happen when running OctoPrint in safe mode?
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
Test if you can reproduce your problem in safe mode. You can find information
|
Test if you can reproduce your problem in safe mode. You can find information
|
||||||
on how to enable safe mode in the Contribution Guidelines.
|
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
|
## 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).
|
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
|
This also includes information on how to run the test suite and how to build
|
||||||
the documentation.
|
the documentation, the bundled virtual printer plugin and OctoPrint's versioning
|
||||||
|
and branching strategy.
|
||||||
|
|
||||||
## Pull requests
|
## Pull requests
|
||||||
|
|
||||||
@@ -297,11 +298,12 @@ the documentation.
|
|||||||
consider if it wouldn't be better suited for a plugin.** As a general rule
|
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
|
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
|
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
|
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 :)
|
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
|
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
|
[forums](https://community.octoprint.org/c/development)** first so
|
||||||
that we can determine if it's a good time for your specific pull
|
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
|
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
|
just cause unnecessary work and frustration for everyone or
|
||||||
possibly get the PR rejected.
|
possibly get the PR rejected.
|
||||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
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**:
|
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
|
* 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
|
*small* backwards compatible new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
|
||||||
* otherwise: `devel` 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**.
|
5. Create **one pull request per feature/bug fix**.
|
||||||
6. Make sure there are **only relevant changes** included in your PR. No
|
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.
|
changes to unrelated files, no additional files that don't belong (e.g.
|
||||||
commits of your full virtual environment). Make sure your PR consists
|
commits of your full virtual environment). Make sure your PR consists
|
||||||
**ideally of only one commit** (use git's rebase and squash functionality).
|
**ideally of only one commit** (use git's rebase and squash functionality).
|
||||||
7. Make sure you **follow the current coding style**. This means:
|
7. Make sure you **follow the current coding style**. This means:
|
||||||
* Tabs instead of spaces in the Python files[2]
|
* Spaces for indenting and alignment, indentation width 4.
|
||||||
* Spaces instead of tabs in the JavaScript sources
|
|
||||||
* English language (code, variables, comments, ...)
|
* English language (code, variables, comments, ...)
|
||||||
* Comments where necessary: Tell *why* the code does something like it does
|
* Comments where necessary: Tell *why* the code does something like it does
|
||||||
it, structure your code
|
it, structure your code
|
||||||
@@ -333,29 +336,41 @@ the documentation.
|
|||||||
from experiments).
|
from experiments).
|
||||||
8. Ensure your changes **pass the existing unit tests**. PRs that break
|
8. Ensure your changes **pass the existing unit tests**. PRs that break
|
||||||
those cannot be accepted. You can run the unit tests locally (after
|
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
|
by running
|
||||||
|
|
||||||
```
|
```
|
||||||
nosetests --with-doctest
|
pytest
|
||||||
```
|
```
|
||||||
|
|
||||||
in the OctoPrint checkout folder. A [travis build](https://travis-ci.org/foosel/OctoPrint)
|
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
|
is also setup so that if the tests should fail, your PR will be marked
|
||||||
accordingly.
|
accordingly.
|
||||||
9. **Test your changes thoroughly**. That also means testing with usage
|
9. Run the **pre-commit check suite** against your changes. You can run that (after
|
||||||
scenarios you don't normally use, e.g. if you only use access control, test
|
[initial development environment setup with "develop" dependencies](https://docs.octoprint.org/en/master/development/environment.html))
|
||||||
without and vice versa. If you only test with your printer, test with the
|
by running
|
||||||
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
|
pre-commit run --hook-stage manual --all-files
|
||||||
with a test suite helps a lot!
|
```
|
||||||
10. In your pull request's description, **state what your pull request does**,
|
|
||||||
|
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
|
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
|
thoroughly you explain your intent behind the PR here, the higher the
|
||||||
chances it will get merged fast. There is a template provided below
|
chances it will get merged fast. There is a template provided below
|
||||||
that can help you here.
|
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** :)
|
file** :)
|
||||||
|
|
||||||
Template to use for Pull Request descriptions:
|
Template to use for Pull Request descriptions:
|
||||||
@@ -374,81 +389,13 @@ Template to use for Pull Request descriptions:
|
|||||||
#### Further notes
|
#### 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?
|
## What do the branches mean?
|
||||||
|
|
||||||
There are three main branches in OctoPrint:
|
See [the corresponding chapter in the documentation](https://docs.octoprint.org/en/master/development/branches.html).
|
||||||
|
|
||||||
* `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.
|
|
||||||
|
|
||||||
## History
|
## 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-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
|
* 2018-10-18: Allow PRs against `maintenance` branch for improvements and small
|
||||||
new features, suggest getting in touch on the forum for larger changes
|
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
|
## Footnotes
|
||||||
* [1] - If you are wondering why, the problem is that anything that you add
|
* [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
|
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 from your version of `devel` chances are high you'll add changes to the
|
||||||
PR that do not belong to the PR.
|
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).
|
|
||||||
@@ -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>
|
||||||
|
|
||||||

|
<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"/>
|
||||||
[](https://community.octoprint.org)
|
<img src="https://img.shields.io/github/workflow/status/OctoPrint/OctoPrint/Build" alt="Build status"/>
|
||||||
[](https://discord.octoprint.org)
|
<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>
|
||||||
[](https://twitter.com/OctoPrint3d)
|
<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
|
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).
|
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).
|
**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!**
|
If you enjoy OctoPrint, please consider becoming a regular supporter!**
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
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
|
(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
|
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).
|
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.
|
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||||
|
|
||||||
The generic steps that should basically be done regardless of operating system
|
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`.
|
parameter, e.g. `virtualenv --python=python3 venv`.
|
||||||
2. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install OctoPrint`
|
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)
|
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
|
||||||
for details.
|
for details.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -6,6 +6,6 @@ Always update to the latest version of OctoPrint to keep up with security patche
|
|||||||
|
|
||||||
## Reporting a Vulnerability
|
## 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.
|
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
|
||||||
+11
-4
@@ -18,48 +18,55 @@ thanks to everyone who contributed!
|
|||||||
* D Brian Kimmel
|
* D Brian Kimmel
|
||||||
* DeltaMaker 3D Printers
|
* DeltaMaker 3D Printers
|
||||||
* Dennis Breining
|
* Dennis Breining
|
||||||
|
* Eric Berry
|
||||||
* Eric Betts
|
* Eric Betts
|
||||||
* Ernesto Martinez
|
* Ernesto Martinez
|
||||||
* Franziska Kunsmann
|
* Franziska Kunsmann
|
||||||
* GadgetAngel
|
|
||||||
* George Robles
|
* George Robles
|
||||||
* Greg Holloway
|
* Greg Holloway
|
||||||
* Hog Duske
|
* Hog Duske
|
||||||
|
* Hopewell Medical Acupuncture Center
|
||||||
* Hugh Blemings
|
* Hugh Blemings
|
||||||
* jean-claude migneault
|
* jean-claude migneault
|
||||||
|
* Jefferson Hunt
|
||||||
* Jeremy Cole
|
* Jeremy Cole
|
||||||
* Joe Pasqua
|
* Joe Pasqua
|
||||||
* John Robinson
|
* John Gregory Robinson
|
||||||
* Joshua Wills
|
* Joshua Wills
|
||||||
* Justin Kaufman
|
* Justin Kaufman
|
||||||
* Kaile Riser
|
* Kaile Riser
|
||||||
* Kale Stedman
|
* Kale Stedman
|
||||||
* Kazuhiro Ogura
|
* Kazuhiro Ogura
|
||||||
|
* Kelly C McNiece
|
||||||
* Kenneth Jiang
|
* Kenneth Jiang
|
||||||
* Kurt Wubbels
|
* Kurt Wubbels
|
||||||
* Kyle Menigoz
|
* Kyle Menigoz
|
||||||
* LA 3D Printer Repair
|
* LA 3D Printer Repair
|
||||||
* Lee Dohm
|
* Lee Dohm
|
||||||
|
* Loyal Moses
|
||||||
* Makespace Madrid
|
* Makespace Madrid
|
||||||
* Mark Walker
|
* Mark Walker
|
||||||
* Michael Aumock
|
* Michael Aumock
|
||||||
|
* Michael Begala
|
||||||
* Miles Flavel
|
* Miles Flavel
|
||||||
* Mosaic Manufacturing
|
* Mosaic Manufacturing
|
||||||
* Neil R. Goldberg
|
* Neil R. Goldberg
|
||||||
|
* Patrick Glyré
|
||||||
* Patrick McGinnis
|
* Patrick McGinnis
|
||||||
* Prof Yuh Wen Chen
|
* Prof Yuh Wen Chen
|
||||||
* Raise3D
|
* Raise3D
|
||||||
* Randy C. Will
|
* Randy C. Will
|
||||||
* Ranjib Dey
|
* Ranjib Dey
|
||||||
|
* Richard McGuire
|
||||||
* Richard Michaud
|
* Richard Michaud
|
||||||
|
* Rigid3D
|
||||||
* Robert Gusek
|
* Robert Gusek
|
||||||
* Ronald Griehsler
|
* Ronald Griehsler
|
||||||
* Sacha Telgenhof
|
* Sacha Telgenhof
|
||||||
* Sebastien Andrivet
|
* Sebastien Andrivet
|
||||||
* Stefan Krister
|
* Stefan Krister
|
||||||
* Steve Thompson
|
* Steve Thompson
|
||||||
* Stewart Danos
|
|
||||||
* Sven Mueller
|
* Sven Mueller
|
||||||
* Ulrich Kempken
|
* Ulrich Kempken
|
||||||
|
|
||||||
and 1943 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)!
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
* [css-element-queries](https://github.com/marcj/css-element-queries): MIT
|
* [css-element-queries](https://github.com/marcj/css-element-queries): MIT
|
||||||
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
|
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
|
||||||
* [Flot](http://www.flotcharts.org/): MIT
|
* [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
|
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
|
||||||
* [JQuery](http://jquery.com/): MIT
|
* [JQuery](http://jquery.com/): MIT
|
||||||
* [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
|
* [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
|
||||||
|
|||||||
+21
@@ -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
|
||||||
|
)
|
||||||
|
'''
|
||||||
@@ -145,6 +145,31 @@ Temperature offset
|
|||||||
- Number
|
- Number
|
||||||
- Temperature offset for the printer's heated bed.
|
- 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:
|
.. _sec-api-datamodel-jobs:
|
||||||
|
|
||||||
|
|||||||
+7
-3
@@ -319,7 +319,8 @@ Upload file or create folder
|
|||||||
Upload a file to the selected ``location`` or create a new empty folder on it.
|
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
|
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
|
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.
|
contents and file name of the file to upload.
|
||||||
@@ -341,6 +342,7 @@ Upload file or create folder
|
|||||||
Host: example.com
|
Host: example.com
|
||||||
X-Api-Key: abcdef...
|
X-Api-Key: abcdef...
|
||||||
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||||
|
Content-Length: 430
|
||||||
|
|
||||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||||
Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode"
|
Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode"
|
||||||
@@ -350,7 +352,7 @@ Upload file or create folder
|
|||||||
T0
|
T0
|
||||||
G21
|
G21
|
||||||
G90
|
G90
|
||||||
...
|
|
||||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||||
Content-Disposition: form-data; name="select"
|
Content-Disposition: form-data; name="select"
|
||||||
|
|
||||||
@@ -400,6 +402,7 @@ Upload file or create folder
|
|||||||
Host: example.com
|
Host: example.com
|
||||||
X-Api-Key: abcdef...
|
X-Api-Key: abcdef...
|
||||||
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||||
|
Content-Length: 263
|
||||||
|
|
||||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||||
Content-Disposition: form-data; name="file"; filename*=utf-8''20mm-%C3%BCml%C3%A4ut-b%C3%B6x.gcode
|
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
|
T0
|
||||||
G21
|
G21
|
||||||
G90
|
G90
|
||||||
...
|
|
||||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC--
|
------WebKitFormBoundaryDeC2E3iWbTv1PwMC--
|
||||||
|
|
||||||
.. sourcecode:: http
|
.. sourcecode:: http
|
||||||
@@ -440,6 +443,7 @@ Upload file or create folder
|
|||||||
Host: example.com
|
Host: example.com
|
||||||
X-Api-Key: abcdef...
|
X-Api-Key: abcdef...
|
||||||
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMD
|
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMD
|
||||||
|
Content-Length: 246
|
||||||
|
|
||||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMD
|
------WebKitFormBoundaryDeC2E3iWbTv1PwMD
|
||||||
Content-Disposition: form-data; name="foldername"
|
Content-Disposition: form-data; name="foldername"
|
||||||
|
|||||||
@@ -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
|
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.
|
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
|
.. 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
|
Host: example.com
|
||||||
X-Api-Key: abcdef...
|
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.
|
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||||
|
|
||||||
.. sourcecode:: http
|
.. sourcecode:: http
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ REST API
|
|||||||
|
|
||||||
general.rst
|
general.rst
|
||||||
version.rst
|
version.rst
|
||||||
|
server.rst
|
||||||
connection.rst
|
connection.rst
|
||||||
files.rst
|
files.rst
|
||||||
job.rst
|
job.rst
|
||||||
|
|||||||
+4
-2
@@ -205,8 +205,10 @@ Retrieve information about the current job
|
|||||||
},
|
},
|
||||||
"estimatedPrintTime": 8811,
|
"estimatedPrintTime": 8811,
|
||||||
"filament": {
|
"filament": {
|
||||||
"length": 810,
|
"tool0": {
|
||||||
"volume": 5.36
|
"length": 810,
|
||||||
|
"volume": 5.36
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"progress": {
|
"progress": {
|
||||||
|
|||||||
@@ -177,6 +177,15 @@ Data model
|
|||||||
- 0..*
|
- 0..*
|
||||||
- List of String
|
- List of String
|
||||||
- Lines for the serial communication log (special messages)
|
- 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:
|
.. _sec-api-push-datamodel-event:
|
||||||
|
|
||||||
|
|||||||
@@ -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
@@ -354,84 +354,22 @@ Data model
|
|||||||
==========
|
==========
|
||||||
|
|
||||||
The data model on the settings API mostly reflects the contents of
|
The data model on the settings API mostly reflects the contents of
|
||||||
:ref:`config.yaml <sec-configuration-config_yaml>`. The settings tree
|
:ref:`config.yaml <sec-configuration-config_yaml>`, which are directly
|
||||||
returned by the API contains the following fields, which are directly
|
mapped, with the following exceptions:
|
||||||
mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
|
||||||
|
|
||||||
.. list-table::
|
.. list-table::
|
||||||
:header-rows: 1
|
:header-rows: 1
|
||||||
|
|
||||||
* - Field
|
* - Field
|
||||||
- Notes
|
- 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``
|
* - ``feature.gcodeViewer``
|
||||||
- Maps to ``gcodeViewer.enabled`` in ``config.yaml``
|
- Maps to ``gcodeViewer.enabled`` in ``config.yaml``
|
||||||
* - ``feature.sizeThreshold``
|
* - ``feature.sizeThreshold``
|
||||||
- Maps to ``gcodeViewer.sizeThreshold`` in ``config.yaml``
|
- Maps to ``gcodeViewer.sizeThreshold`` in ``config.yaml``
|
||||||
* - ``feature.mobileSizeThreshold``
|
* - ``feature.mobileSizeThreshold``
|
||||||
- Maps to ``gcodeViewer.mobileSizeThreshold`` in ``config.yaml``
|
- 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``
|
* - ``folder.timelapseTmp``
|
||||||
- Maps to ``folder.timelapse_tmp`` in ``config.yaml``
|
- Maps to ``folder.timelapse_tmp`` in ``config.yaml``
|
||||||
* - ``folder.logs``
|
|
||||||
-
|
|
||||||
* - ``folder.watched``
|
|
||||||
-
|
|
||||||
* - ``plugins``
|
* - ``plugins``
|
||||||
- Plugin settings as available from ``config.yaml`` and :class:`~octoprint.plugin.SettingsPlugin` implementations
|
- Plugin settings as available from ``config.yaml`` and :class:`~octoprint.plugin.SettingsPlugin` implementations
|
||||||
* - ``printer.defaultExtrusionLength``
|
* - ``printer.defaultExtrusionLength``
|
||||||
@@ -446,8 +384,6 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
|||||||
- Available serial ports
|
- Available serial ports
|
||||||
* - ``serial.baudrateOptions``
|
* - ``serial.baudrateOptions``
|
||||||
- Available serial baudrates
|
- Available serial baudrates
|
||||||
* - ``serial.autoconnect``
|
|
||||||
-
|
|
||||||
* - ``serial.timeoutConnection``
|
* - ``serial.timeoutConnection``
|
||||||
- Maps to ``serial.timeout.connection`` in ``config.yaml``
|
- Maps to ``serial.timeout.connection`` in ``config.yaml``
|
||||||
* - ``serial.timeoutDetection``
|
* - ``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``
|
- Maps to ``serial.timeout.temperatureTargetSet`` in ``config.yaml``
|
||||||
* - ``serial.timeoutSdStatus``
|
* - ``serial.timeoutSdStatus``
|
||||||
- Maps to ``serial.timeout.sdStatus`` in ``config.yaml``
|
- 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``
|
* - ``serial.maxTimeoutsIdle``
|
||||||
- Maps to ``serial.maxCommunicationTimeouts.idle`` in ``config.yaml``
|
- Maps to ``serial.maxCommunicationTimeouts.idle`` in ``config.yaml``
|
||||||
* - ``serial.maxTimeoutsPrinting``
|
* - ``serial.maxTimeoutsPrinting``
|
||||||
- Maps to ``serial.maxCommunicationTimeouts.printing`` in ``config.yaml``
|
- Maps to ``serial.maxCommunicationTimeouts.printing`` in ``config.yaml``
|
||||||
* - ``serial.maxTimeoutsLong``
|
* - ``serial.maxTimeoutsLong``
|
||||||
- Maps to ``serial.maxCommunicationTimeouts.long`` in ``config.yaml``
|
- 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``
|
* - ``system.actions``
|
||||||
- Whole subtree taken from ``config.yaml``
|
- Whole subtree taken from ``config.yaml``
|
||||||
* - ``system.events``
|
* - ``system.events``
|
||||||
- Whole subtree taken from ``config.yaml``
|
- Whole subtree taken from ``config.yaml``
|
||||||
* - ``temperature.profiles``
|
* - ``temperature.profiles``
|
||||||
- Whole subtree taken from ``config.yaml``
|
- Whole subtree taken from ``config.yaml``
|
||||||
* - ``temperature.cutoff``
|
|
||||||
-
|
|
||||||
* - ``terminalFilters``
|
* - ``terminalFilters``
|
||||||
- Whole subtree taken from ``config.yaml``
|
- Whole subtree taken from ``config.yaml``
|
||||||
* - ``webcam.streamUrl``
|
* - ``webcam.streamUrl``
|
||||||
@@ -512,17 +416,3 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
|||||||
- Maps to ``webcam.snapshot`` in ``config.yaml``
|
- Maps to ``webcam.snapshot`` in ``config.yaml``
|
||||||
* - ``webcam.ffmpegPath``
|
* - ``webcam.ffmpegPath``
|
||||||
- Maps to ``webcam.ffmpeg`` in ``config.yaml``
|
- Maps to ``webcam.ffmpeg`` in ``config.yaml``
|
||||||
* - ``webcam.bitrate``
|
|
||||||
-
|
|
||||||
* - ``webcam.ffmpegThreads``
|
|
||||||
-
|
|
||||||
* - ``webcam.ffmpegVideoCodec``
|
|
||||||
-
|
|
||||||
* - ``webcam.watermark``
|
|
||||||
-
|
|
||||||
* - ``webcam.flipH``
|
|
||||||
-
|
|
||||||
* - ``webcam.flipV``
|
|
||||||
-
|
|
||||||
* - ``webcam.rotate90``
|
|
||||||
-
|
|
||||||
+90
-2
@@ -6,8 +6,8 @@ Util
|
|||||||
|
|
||||||
.. _sec-api-util-test:
|
.. _sec-api-util-test:
|
||||||
|
|
||||||
Test paths or URLs
|
Various tests
|
||||||
==================
|
=============
|
||||||
|
|
||||||
.. http:post:: /api/util/test
|
.. 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>`
|
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!
|
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.
|
Requires the ``ADMIN`` permission.
|
||||||
|
|
||||||
**Example 1**
|
**Example 1**
|
||||||
@@ -320,6 +329,58 @@ Test paths or URLs
|
|||||||
"result": true
|
"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 command: The command to execute, currently either ``path`` or ``url``
|
||||||
:json path: ``path`` command only: the path to test
|
: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``
|
: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 port: ``server`` command only: the port to test
|
||||||
:json protocol: ``server`` command only: the protocol to test
|
:json protocol: ``server`` command only: the protocol to test
|
||||||
:json name: ``resolution`` command only: the host name 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
|
:statuscode 200: No error occurred
|
||||||
|
|
||||||
.. _sec-api-util-datamodel:
|
.. _sec-api-util-datamodel:
|
||||||
@@ -466,3 +528,29 @@ Resolution test result
|
|||||||
- 1
|
- 1
|
||||||
- bool
|
- bool
|
||||||
- ``true`` if the check passed.
|
- ``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.
|
||||||
@@ -6,7 +6,7 @@ Version information
|
|||||||
|
|
||||||
.. http:get:: /api/version
|
.. 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 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).
|
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
Action Command Notification support
|
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
|
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
|
using :ref:`action commands <sec-features-action_commands>` about relevant events. These notifications will be shown
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
Action Command Prompt support
|
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
|
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
|
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_choice Filament swapped
|
||||||
//action:prompt_show
|
//action:prompt_show
|
||||||
|
|
||||||
If the user clicks the button, assuming a ``selection_command`` of ``M876 S{choice}`` is configured, OctoPrint
|
If the user clicks the button, OctoPrint will send back ``M876 S0`` (0-based index).
|
||||||
will send back ``M876 S0`` (0-based index).
|
|
||||||
|
|
||||||
A more complicated example with three options would be the following:
|
A more complicated example with three options would be the following:
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
Announcement Plugin
|
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
|
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
|
plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
Application Keys Plugin
|
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
|
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
|
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
|
- Multiplicity
|
||||||
- Type
|
- Type
|
||||||
- Description
|
- Description
|
||||||
* - ``apikey``
|
* - ``api_key``
|
||||||
- 1
|
- 1
|
||||||
- str
|
- str
|
||||||
- the API key generated for the application
|
- the API key generated for the application
|
||||||
|
|||||||
@@ -3,9 +3,11 @@
|
|||||||
Backup Plugin
|
Backup Plugin
|
||||||
=============
|
=============
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.10
|
||||||
|
|
||||||
The OctoPrint Backup Plugin comes bundled with OctoPrint (starting with 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
|
This allows easy migration
|
||||||
to newly setup instances as well as making regular backups to prevent data loss.
|
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 -
|
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!
|
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:
|
.. _sec-bundledplugins-backup-cli:
|
||||||
|
|
||||||
Command line usage
|
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.
|
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:
|
.. _sec-bundledplugins-backup-sourcecode:
|
||||||
|
|
||||||
Source code
|
Source code
|
||||||
@@ -65,6 +185,8 @@ Source code
|
|||||||
The source of the Backup plugin is bundled with OctoPrint and can be found in
|
The source of the Backup plugin is bundled with OctoPrint and can be found in
|
||||||
its source repository under ``src/octoprint/plugins/backup``.
|
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>`_
|
.. [#1] Note that restore is currently unavailable on OctoPrint servers running on Windows. Additionally they may be
|
||||||
can be automatically restored. If you have plugins installed that are not available on there you'll get their
|
disabled through a config flag or an environment variable as documented :ref:`here <sec-bundledplugins-backup-configuration>`.
|
||||||
names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them.
|
.. [#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.
|
||||||
@@ -3,11 +3,12 @@
|
|||||||
Discovery Plugin
|
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
|
The OctoPrint Discovery Plugin comes bundled with OctoPrint.
|
||||||
`pybonjour <https://pypi.python.org/pypi/pybonjour>`_ is installed OctoPrint
|
|
||||||
will additionally support discovery via ZeroConf, also known as Bonjour or Avahi.
|
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
|
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
|
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
|
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:
|
.. _sec-bundledplugins-discovery-configuration:
|
||||||
|
|
||||||
Configuring the plugin
|
Configuring the plugin
|
||||||
@@ -74,6 +36,10 @@ Configuring the plugin
|
|||||||
|
|
||||||
The plugin supports the following configuration keys:
|
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,
|
* ``publicPort``: Public port number OctoPrint is reachable under,
|
||||||
optional, if not set the port OctoPrint itself was started under will be used
|
optional, if not set the port OctoPrint itself was started under will be used
|
||||||
* ``pathPrefix``: Path prefix OctoPrint is running under, optional, if not
|
* ``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:
|
plugins:
|
||||||
discovery:
|
discovery:
|
||||||
|
interfaces:
|
||||||
|
- eth0
|
||||||
publicPort: 443
|
publicPort: 443
|
||||||
useSsl: true
|
useSsl: true
|
||||||
zeroConf:
|
zeroConf:
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
Error Tracking Plugin
|
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
|
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/>`_.
|
OctoPrint's `Sentry instance <https://sentry.io/>`_.
|
||||||
|
|
||||||
|
|||||||
@@ -3,5 +3,7 @@
|
|||||||
File Check
|
File Check
|
||||||
==========
|
==========
|
||||||
|
|
||||||
|
.. versionadded:: 1.4.1
|
||||||
|
|
||||||
The file check plugin - while considered bundled with OctoPrint - is a separate project on its own release
|
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>`_.
|
cycle and documented on `its Github repository <https://github.com/OctoPrint/OctoPrint-FileCheck>`_.
|
||||||
@@ -3,5 +3,9 @@
|
|||||||
Firmware Check
|
Firmware Check
|
||||||
==============
|
==============
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.7
|
||||||
|
|
||||||
The firmware check plugin - while considered bundled with OctoPrint - is a separate project on its own release
|
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>`_.
|
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.
|
||||||
@@ -3,6 +3,8 @@
|
|||||||
GCode Viewer Plugin
|
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>`_.
|
The GCode Viewer plugin provides a GCode viewer based on `Alex Ustyantsev's work <https://github.com/hudbrog/gCodeViewer>`_.
|
||||||
|
|
||||||
.. _fig-bundledplugins-gcodeviewer-example:
|
.. _fig-bundledplugins-gcodeviewer-example:
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ Bundled Plugins
|
|||||||
firmware_check.rst
|
firmware_check.rst
|
||||||
gcodeviewer.rst
|
gcodeviewer.rst
|
||||||
logging.rst
|
logging.rst
|
||||||
loginui.rst
|
|
||||||
pluginmanager.rst
|
pluginmanager.rst
|
||||||
printer_safety_check.rst
|
printer_safety_check.rst
|
||||||
softwareupdate.rst
|
softwareupdate.rst
|
||||||
|
|||||||
@@ -3,9 +3,9 @@
|
|||||||
Logging
|
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.
|
configure logging levels for sub modules through the included settings dialog.
|
||||||
|
|
||||||
.. _fig-bundledplugins-logging-settings:
|
.. _fig-bundledplugins-logging-settings:
|
||||||
|
|||||||
@@ -3,64 +3,4 @@
|
|||||||
Login UI
|
Login UI
|
||||||
========
|
========
|
||||||
|
|
||||||
The Login UI plugin has been bundled since OctoPrint 1.4.0 and replaces the ForceLogin plugin bundled with prior
|
The Login UI plugin's functionality has been merged into OctoPrint's core as of OctoPrint 1.4.2.
|
||||||
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``.
|
|
||||||
@@ -3,8 +3,9 @@
|
|||||||
Plugin Manager
|
Plugin Manager
|
||||||
==============
|
==============
|
||||||
|
|
||||||
The OctoPrint Plugin Manager comes bundled with OctoPrint starting with
|
.. versionadded:: 1.2.0
|
||||||
version 1.2.0.
|
|
||||||
|
The OctoPrint Plugin Manager comes bundled with OctoPrint.
|
||||||
|
|
||||||
It allows management of installed plugins (listing, enabling, disabling
|
It allows management of installed plugins (listing, enabling, disabling
|
||||||
and uninstalling) and installing new plugins from the official
|
and uninstalling) and installing new plugins from the official
|
||||||
|
|||||||
@@ -3,10 +3,14 @@
|
|||||||
Software Update Plugin
|
Software Update Plugin
|
||||||
======================
|
======================
|
||||||
|
|
||||||
|
.. versionadded:: 1.2.0
|
||||||
|
|
||||||
The Software Update Plugin allows receiving notifications about new releases
|
The Software Update Plugin allows receiving notifications about new releases
|
||||||
of OctoPrint or installed plugins which registered with it and -- if properly
|
of OctoPrint or installed plugins which registered with it and -- if properly
|
||||||
configured -- also applying the found updates.
|
configured -- also applying the found updates.
|
||||||
|
|
||||||
|
It comes bundled with OctoPrint.
|
||||||
|
|
||||||
.. _sec-bundledplugins-softwareupdate-firststeps:
|
.. _sec-bundledplugins-softwareupdate-firststeps:
|
||||||
|
|
||||||
First Steps
|
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.
|
wrench icon in the upper right corner.
|
||||||
|
|
||||||
.. _fig-bundledplugins-softwareupdate-plugin-configuration:
|
.. _fig-bundledplugins-softwareupdate-plugin-configuration:
|
||||||
.. figure:: ../images/bundledplugins-softwareupdate-plugin-configuration.png
|
.. figure:: ../images/bundledplugins-softwareupdate-configuration.png
|
||||||
:align: center
|
:align: center
|
||||||
:alt: Software Update plugin configuration dialog
|
: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
|
* **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.
|
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,
|
* **Tracked branch** (if tracking is set to "Github Commit"): The branch that will be tracked if you set version tracking to "Github Commit".
|
||||||
select "Stable" here which is also the default. "Maintenance RCs" will also allow you to update to maintenance release
|
* **OctoPrint ``pip`` target** (if tracking is set to "Release" or "Github Commit"): The argument that will be provided to ``pip`` when updating OctoPrint.
|
||||||
candidates, "Devel RCs" will also allow you to update to development release candidates. If in doubt, leave it at
|
Usually you don't want to change this from its default value of ``https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip``.
|
||||||
"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 is set to "Local checkout"): This must be the path to OctoPrint's git checkout folder
|
||||||
* **OctoPrint checkout folder** (if tracking git commits): 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/>`_).
|
(``/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
|
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.
|
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
|
* **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
|
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.
|
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>`.
|
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:
|
.. _sec-bundledplugins-softwareupdate-cli:
|
||||||
|
|
||||||
@@ -119,9 +127,6 @@ Configuring the Plugin
|
|||||||
|
|
||||||
plugins:
|
plugins:
|
||||||
softwareupdate:
|
softwareupdate:
|
||||||
# the time-to-live of the version cache, in minutes
|
|
||||||
cache_ttl: 60
|
|
||||||
|
|
||||||
# configured version check and update methods
|
# configured version check and update methods
|
||||||
checks:
|
checks:
|
||||||
# "octoprint" is reserved for OctoPrint
|
# "octoprint" is reserved for OctoPrint
|
||||||
@@ -141,6 +146,41 @@ Configuring the Plugin
|
|||||||
# used - should normally NOT be necessary and hence set
|
# used - should normally NOT be necessary and hence set
|
||||||
pip_command: /path/to/pip
|
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:
|
.. _sec-bundledplugins-softwareupdate-configuration-versionchecks:
|
||||||
|
|
||||||
Version checks
|
Version checks
|
||||||
@@ -156,10 +196,28 @@ types are currently recognized:
|
|||||||
* ``repo``: (mandatory) Github repository to check
|
* ``repo``: (mandatory) Github repository to check
|
||||||
* ``prerelease``: ``True`` or ``False``, default ``False``, set to
|
* ``prerelease``: ``True`` or ``False``, default ``False``, set to
|
||||||
``True`` to also include releases on Github marked as prerelease.
|
``True`` to also include releases on Github marked as prerelease.
|
||||||
* ``release_branch``: Branch name to check against ``target_comittish``
|
* ``prerelease_branches``: Prerelease channel definitions, optional. List of:
|
||||||
field in Github release data - release will only be included if the
|
* ``branch``: Branch associated with the channel, acts as ID
|
||||||
values match. Defaults to being unset, in which case no match will
|
* ``name``: Human readable name of the release channel
|
||||||
be performed.
|
* ``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
|
* ``release_compare``: Method to use to compare between current version
|
||||||
information and release versions on Github. One of ``python`` (version
|
information and release versions on Github. One of ``python`` (version
|
||||||
comparison using ``pkg_resources.parse_version``, newer version detected
|
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
|
``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.
|
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
|
* ``git_commit``: Checks a local git repository for new commits on its
|
||||||
configured remote. Additional config parameters:
|
configured remote. Additional config parameters:
|
||||||
|
|
||||||
@@ -204,6 +264,8 @@ types are currently recognized:
|
|||||||
|
|
||||||
* ``package``: (mandatory) Name of the package which to check.
|
* ``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
|
* ``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
|
against things like ``ETag`` or ``Last-Modified`` headers. Additional
|
||||||
config parameters:
|
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``
|
* ``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.
|
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
|
* ``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
|
property ``version``, which should contain the latest version, e.g. ``{"version":"1.2.3"}``. Additional
|
||||||
config parameters:
|
config parameters:
|
||||||
|
|
||||||
* ``jsondata``: (mandatory) URL from which to fetch the JSON data
|
* ``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
|
* ``command_line``: Uses a provided script to determine whether an update
|
||||||
is available. Additional config parameters:
|
is available. Additional config parameters:
|
||||||
|
|
||||||
@@ -243,12 +309,16 @@ types are currently recognized:
|
|||||||
|
|
||||||
* ``current_version``: Version to report for both local and remote version.
|
* ``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
|
* ``never_current``: Always reports that an update is necessary. Useful for debugging
|
||||||
software update mechanisms during development. Additional config parameters:
|
software update mechanisms during development. Additional config parameters:
|
||||||
|
|
||||||
* ``local_version``: Current local version. Defaults to ``1.0.0``.
|
* ``local_version``: Current local version. Defaults to ``1.0.0``.
|
||||||
* ``remote_version``: Remote version to offer update to. Defaults to ``1.0.1``.
|
* ``remote_version``: Remote version to offer update to. Defaults to ``1.0.1``.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.7
|
||||||
|
|
||||||
.. _sec-bundledplugins-softwareupdate-configuration-updatemethods:
|
.. _sec-bundledplugins-softwareupdate-configuration-updatemethods:
|
||||||
|
|
||||||
Update methods
|
Update methods
|
||||||
@@ -294,6 +364,8 @@ supported:
|
|||||||
a countdown in the meantime. Useful for debugging software update mechanisms
|
a countdown in the meantime. Useful for debugging software update mechanisms
|
||||||
during development.
|
during development.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.7
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
To allow default configurations for multiple update methods, if more than one of
|
To allow default configurations for multiple update methods, if more than one of
|
||||||
@@ -357,7 +429,69 @@ tracked:
|
|||||||
repo: OctoPrint-SomePlugin
|
repo: OctoPrint-SomePlugin
|
||||||
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
|
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):
|
"bleeding edge" updates):
|
||||||
|
|
||||||
.. code-block:: yaml
|
.. 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
|
``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.
|
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:
|
.. _sec-bundledplugins-softwareupdate-events:
|
||||||
|
|
||||||
Events
|
Events
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
Anonymous Usage Tracking Plugin
|
Anonymous Usage Tracking Plugin
|
||||||
===============================
|
===============================
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.10
|
||||||
|
|
||||||
The Anonymous Usage Tracking plugin provides valuable insights into how many instances running what versions of
|
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.
|
OctoPrint are out there, whether they are successfully completing print jobs and various other metrics.
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
Virtual Printer
|
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
|
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
|
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>`.
|
:ref:`the development documentation on details and usage <sec-development-virtual-printer>`.
|
||||||
|
|||||||
+89
-69
@@ -18,8 +18,8 @@ import sys, os
|
|||||||
# If extensions (or modules to document with autodoc) are in another directory,
|
# 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
|
# 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.
|
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||||
sys.path.insert(0, os.path.abspath('../src/'))
|
sys.path.insert(0, os.path.abspath("../src/"))
|
||||||
sys.path.append(os.path.abspath('sphinxext'))
|
sys.path.append(os.path.abspath("sphinxext"))
|
||||||
|
|
||||||
import octoprint._version
|
import octoprint._version
|
||||||
from datetime import date
|
from datetime import date
|
||||||
@@ -30,32 +30,46 @@ year_current = date.today().year
|
|||||||
# -- General configuration -----------------------------------------------------
|
# -- General configuration -----------------------------------------------------
|
||||||
|
|
||||||
# If your documentation needs a minimal Sphinx version, state it here.
|
# 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
|
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||||
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
|
extensions = [
|
||||||
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid', 'sphinx.ext.intersphinx']
|
"codeblockext",
|
||||||
|
"onlineinclude",
|
||||||
|
"sphinx.ext.todo",
|
||||||
|
"sphinx.ext.autodoc",
|
||||||
|
"sphinxcontrib.httpdomain",
|
||||||
|
"sphinx.ext.napoleon",
|
||||||
|
"sphinxcontrib.mermaid",
|
||||||
|
"sphinx.ext.intersphinx",
|
||||||
|
]
|
||||||
todo_include_todos = True
|
todo_include_todos = True
|
||||||
intersphinx_mapping = {'python': ('https://docs.python.org/3', None),
|
intersphinx_mapping = {
|
||||||
'python2': ('https://docs.python.org/2', None),
|
"python": ("https://docs.python.org/3", None),
|
||||||
'pyserial': ('https://pythonhosted.org/pyserial', 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.
|
# Add any paths that contain templates here, relative to this directory.
|
||||||
templates_path = ['_templates']
|
templates_path = ["_templates"]
|
||||||
|
|
||||||
# The suffix of source filenames.
|
# The suffix of source filenames.
|
||||||
source_suffix = '.rst'
|
source_suffix = ".rst"
|
||||||
|
|
||||||
# The encoding of source files.
|
# The encoding of source files.
|
||||||
#source_encoding = 'utf-8-sig'
|
# source_encoding = 'utf-8-sig'
|
||||||
|
|
||||||
# The master toctree document.
|
# The master toctree document.
|
||||||
master_doc = 'index'
|
master_doc = "index"
|
||||||
|
|
||||||
# General information about the project.
|
# General information about the project.
|
||||||
project = 'OctoPrint'
|
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
|
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
|
# The version info for the project you're documenting, acts as replacement for
|
||||||
# |version| and |release|, also used in various other places throughout the
|
# |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
|
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||||
# for a list of supported languages.
|
# for a list of supported languages.
|
||||||
#language = None
|
# language = None
|
||||||
|
|
||||||
# There are two options for replacing |today|: either, you set today to some
|
# There are two options for replacing |today|: either, you set today to some
|
||||||
# non-false value, then it is used:
|
# non-false value, then it is used:
|
||||||
#today = ''
|
# today = ''
|
||||||
# Else, today_fmt is used as the format for a strftime call.
|
# 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
|
# List of patterns, relative to source directory, that match files and
|
||||||
# directories to ignore when looking for source files.
|
# 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.
|
# 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.
|
# 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
|
# If true, the current module name will be prepended to all description
|
||||||
# unit titles (such as .. function::).
|
# unit titles (such as .. function::).
|
||||||
#add_module_names = True
|
# add_module_names = True
|
||||||
|
|
||||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||||
# output. They are ignored by default.
|
# output. They are ignored by default.
|
||||||
#show_authors = False
|
# show_authors = False
|
||||||
|
|
||||||
# The name of the Pygments (syntax highlighting) style to use.
|
# 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.
|
# 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.
|
# If true, keep warnings as "system message" paragraphs in the built documents.
|
||||||
#keep_warnings = False
|
# keep_warnings = False
|
||||||
|
|
||||||
numfig = True
|
numfig = True
|
||||||
|
|
||||||
# -- Options for HTML output ---------------------------------------------------
|
# -- Options for HTML output ---------------------------------------------------
|
||||||
|
|
||||||
import sphinx_rtd_theme
|
import sphinx_rtd_theme
|
||||||
html_theme = 'sphinx_rtd_theme'
|
|
||||||
|
html_theme = "sphinx_rtd_theme"
|
||||||
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||||
|
|
||||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||||
# a list of built-in themes.
|
# 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
|
# 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
|
# further. For a list of options available for each theme, see the
|
||||||
# documentation.
|
# documentation.
|
||||||
#html_theme_options = {}
|
# html_theme_options = {}
|
||||||
|
|
||||||
# Add any paths that contain custom themes here, relative to this directory.
|
# 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
|
# The name for this set of Sphinx documents. If None, it defaults to
|
||||||
# "<project> v<release> documentation".
|
# "<project> v<release> documentation".
|
||||||
#html_title = None
|
# html_title = None
|
||||||
|
|
||||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
# 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
|
# The name of an image file (relative to this directory) to place at the top
|
||||||
# of the sidebar.
|
# 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
|
# 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
|
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||||
# pixels large.
|
# pixels large.
|
||||||
#html_favicon = None
|
# html_favicon = None
|
||||||
|
|
||||||
# Add any paths that contain custom static files (such as style sheets) here,
|
# 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,
|
# 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".
|
# so a file named "default.css" will overwrite the built-in "default.css".
|
||||||
html_static_path = ['_static']
|
html_static_path = ["_static"]
|
||||||
|
|
||||||
|
|
||||||
def setup(app):
|
def setup(app):
|
||||||
app.add_css_file("theme_overrides.css")
|
app.add_css_file("theme_overrides.css")
|
||||||
|
|
||||||
|
|
||||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||||
# using the given strftime format.
|
# 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
|
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||||
# typographically correct entities.
|
# typographically correct entities.
|
||||||
#html_use_smartypants = True
|
# html_use_smartypants = True
|
||||||
|
|
||||||
# Custom sidebar templates, maps document names to template names.
|
# 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
|
# Additional templates that should be rendered to pages, maps page names to
|
||||||
# template names.
|
# template names.
|
||||||
#html_additional_pages = {}
|
# html_additional_pages = {}
|
||||||
|
|
||||||
# If false, no module index is generated.
|
# If false, no module index is generated.
|
||||||
#html_domain_indices = True
|
# html_domain_indices = True
|
||||||
|
|
||||||
# If false, no index is generated.
|
# 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.
|
# 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.
|
# 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.
|
# 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.
|
# 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
|
# 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
|
# contain a <link> tag referring to it. The value of this option must be the
|
||||||
# base URL from which the finished HTML is served.
|
# 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").
|
# 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.
|
# Output file base name for HTML help builder.
|
||||||
htmlhelp_basename = 'OctoPrintDoc'
|
htmlhelp_basename = "OctoPrintDoc"
|
||||||
|
|
||||||
|
|
||||||
# -- Options for LaTeX output --------------------------------------------------
|
# -- Options for LaTeX output --------------------------------------------------
|
||||||
|
|
||||||
#latex_elements = {
|
# latex_elements = {
|
||||||
# The paper size ('letterpaper' or 'a4paper').
|
# The paper size ('letterpaper' or 'a4paper').
|
||||||
#'papersize': 'letterpaper',
|
#'papersize': 'letterpaper',
|
||||||
|
|
||||||
@@ -203,47 +220,44 @@ htmlhelp_basename = 'OctoPrintDoc'
|
|||||||
|
|
||||||
# Additional stuff for the LaTeX preamble.
|
# Additional stuff for the LaTeX preamble.
|
||||||
#'preamble': '',
|
#'preamble': '',
|
||||||
#}
|
# }
|
||||||
|
|
||||||
# Grouping the document tree into LaTeX files. List of tuples
|
# Grouping the document tree into LaTeX files. List of tuples
|
||||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||||
#latex_documents = [
|
# latex_documents = [
|
||||||
# ('index', 'OctoPrint.tex', 'OctoPrint Documentation',
|
# ('index', 'OctoPrint.tex', 'OctoPrint Documentation',
|
||||||
# 'Gina Häußge', 'manual'),
|
# 'Gina Häußge', 'manual'),
|
||||||
#]
|
# ]
|
||||||
|
|
||||||
# The name of an image file (relative to this directory) to place at the top of
|
# The name of an image file (relative to this directory) to place at the top of
|
||||||
# the title page.
|
# the title page.
|
||||||
#latex_logo = None
|
# latex_logo = None
|
||||||
|
|
||||||
# For "manual" documents, if this is true, then top-level headings are parts,
|
# For "manual" documents, if this is true, then top-level headings are parts,
|
||||||
# not chapters.
|
# not chapters.
|
||||||
#latex_use_parts = False
|
# latex_use_parts = False
|
||||||
|
|
||||||
# If true, show page references after internal links.
|
# If true, show page references after internal links.
|
||||||
#latex_show_pagerefs = False
|
# latex_show_pagerefs = False
|
||||||
|
|
||||||
# If true, show URL addresses after external links.
|
# 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.
|
# Documents to append as an appendix to all manuals.
|
||||||
#latex_appendices = []
|
# latex_appendices = []
|
||||||
|
|
||||||
# If false, no module index is generated.
|
# If false, no module index is generated.
|
||||||
#latex_domain_indices = True
|
# latex_domain_indices = True
|
||||||
|
|
||||||
|
|
||||||
# -- Options for manual page output --------------------------------------------
|
# -- Options for manual page output --------------------------------------------
|
||||||
|
|
||||||
# One entry per manual page. List of tuples
|
# One entry per manual page. List of tuples
|
||||||
# (source start file, name, description, authors, manual section).
|
# (source start file, name, description, authors, manual section).
|
||||||
man_pages = [
|
man_pages = [("index", "octoprint", "OctoPrint Documentation", ["Gina Häußge"], 1)]
|
||||||
('index', 'octoprint', 'OctoPrint Documentation',
|
|
||||||
['Gina Häußge'], 1)
|
|
||||||
]
|
|
||||||
|
|
||||||
# If true, show URL addresses after external links.
|
# If true, show URL addresses after external links.
|
||||||
#man_show_urls = False
|
# man_show_urls = False
|
||||||
|
|
||||||
|
|
||||||
# -- Options for Texinfo output ------------------------------------------------
|
# -- Options for Texinfo output ------------------------------------------------
|
||||||
@@ -252,19 +266,25 @@ man_pages = [
|
|||||||
# (source start file, target name, title, author,
|
# (source start file, target name, title, author,
|
||||||
# dir menu entry, description, category)
|
# dir menu entry, description, category)
|
||||||
texinfo_documents = [
|
texinfo_documents = [
|
||||||
('index', 'OctoPrint', 'OctoPrint Documentation',
|
(
|
||||||
'Gina Häußge', 'OctoPrint', 'One line description of project.',
|
"index",
|
||||||
'Miscellaneous'),
|
"OctoPrint",
|
||||||
|
"OctoPrint Documentation",
|
||||||
|
"Gina Häußge",
|
||||||
|
"OctoPrint",
|
||||||
|
"One line description of project.",
|
||||||
|
"Miscellaneous",
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
# Documents to append as an appendix to all manuals.
|
# Documents to append as an appendix to all manuals.
|
||||||
#texinfo_appendices = []
|
# texinfo_appendices = []
|
||||||
|
|
||||||
# If false, no module index is generated.
|
# If false, no module index is generated.
|
||||||
#texinfo_domain_indices = True
|
# texinfo_domain_indices = True
|
||||||
|
|
||||||
# How to display URL addresses: 'footnote', 'no', or 'inline'.
|
# 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.
|
# If true, do not generate a @detailmenu in the "Top" node's menu.
|
||||||
#texinfo_no_detailmenu = False
|
# texinfo_no_detailmenu = False
|
||||||
@@ -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.
|
||||||
@@ -10,6 +10,7 @@ you can just create it - it will only get created by OctoPrint once you save set
|
|||||||
settings.
|
settings.
|
||||||
|
|
||||||
Note that many of these settings are available from the "Settings" menu in OctoPrint itself.
|
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::
|
.. contents::
|
||||||
|
|
||||||
@@ -23,9 +24,6 @@ Use the following settings to enable access control:
|
|||||||
.. code-block:: yaml
|
.. code-block:: yaml
|
||||||
|
|
||||||
accessControl:
|
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
|
# 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
|
# user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml
|
||||||
# in the default configuration folder, see below)
|
# 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.
|
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
|
||||||
addRemoteUsers: false
|
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:
|
.. _sec-configuration-config_yaml-api:
|
||||||
|
|
||||||
API
|
API
|
||||||
@@ -123,6 +125,10 @@ appearance or to modify the order and presence of the various UI components:
|
|||||||
# acrylic for its frame ;)
|
# acrylic for its frame ;)
|
||||||
colorTransparent: false
|
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
|
# Configures the order and availability of the UI components
|
||||||
components:
|
components:
|
||||||
|
|
||||||
@@ -146,10 +152,14 @@ appearance or to modify the order and presence of the various UI components:
|
|||||||
navbar:
|
navbar:
|
||||||
- settings
|
- settings
|
||||||
- systemmenu
|
- systemmenu
|
||||||
|
- plugin_announcements
|
||||||
|
- plugin_logging
|
||||||
|
- plugin_pi_support
|
||||||
- login
|
- login
|
||||||
|
|
||||||
# order of sidebar items
|
# order of sidebar items
|
||||||
sidebar:
|
sidebar:
|
||||||
|
- plugin_firmware_check
|
||||||
- connection
|
- connection
|
||||||
- state
|
- state
|
||||||
- files
|
- files
|
||||||
@@ -158,7 +168,7 @@ appearance or to modify the order and presence of the various UI components:
|
|||||||
tab:
|
tab:
|
||||||
- temperature
|
- temperature
|
||||||
- control
|
- control
|
||||||
- gcodeviewer
|
- plugin_gcodeviewer
|
||||||
- terminal
|
- terminal
|
||||||
- timelapse
|
- timelapse
|
||||||
|
|
||||||
@@ -175,17 +185,40 @@ appearance or to modify the order and presence of the various UI components:
|
|||||||
- features
|
- features
|
||||||
- webcam
|
- webcam
|
||||||
- accesscontrol
|
- accesscontrol
|
||||||
|
- plugin_gcodeviewer
|
||||||
- api
|
- api
|
||||||
|
- plugin_appkeys
|
||||||
- section_octoprint
|
- section_octoprint
|
||||||
- folders
|
- folders
|
||||||
- appearance
|
- appearance
|
||||||
- logs
|
- plugin_logging
|
||||||
|
- plugin_pluginmanager
|
||||||
|
- plugin_softwareupdate
|
||||||
|
- plugin_announcements
|
||||||
|
- plugin_backup
|
||||||
|
- plugin_tracking
|
||||||
|
- plugin_errortracking
|
||||||
|
|
||||||
# order of user settings
|
# order of user settings
|
||||||
usersettings:
|
usersettings:
|
||||||
- access
|
- access
|
||||||
- interface
|
- 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
|
# order of generic templates
|
||||||
generic: []
|
generic: []
|
||||||
|
|
||||||
@@ -222,7 +255,7 @@ appearance or to modify the order and presence of the various UI components:
|
|||||||
tab:
|
tab:
|
||||||
- plugin_helloworld
|
- 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.
|
``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)
|
# the response skips on the ok)
|
||||||
triggerOkForM29: true
|
triggerOkForM29: true
|
||||||
|
|
||||||
|
# Percentage of resend requests among all sent lines that should be considered critical
|
||||||
|
resendRatioThreshold: 10
|
||||||
|
|
||||||
capabilities:
|
capabilities:
|
||||||
|
|
||||||
# Whether to enable temperature autoreport in the firmware if its support is detected
|
# 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
|
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||||
systemShutdownCommand: sudo shutdown -h now
|
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
|
# Configuration of the regular online connectivity check
|
||||||
onlineCheck:
|
onlineCheck:
|
||||||
# whether the online check is enabled, defaults to false due to valid privacy concerns
|
# 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)'
|
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
|
||||||
- name: Suppress wait responses
|
- name: Suppress wait responses
|
||||||
regex: 'Recv: wait'
|
regex: 'Recv: wait'
|
||||||
|
- name: Suppress processing responses
|
||||||
|
regex: 'Recv: (echo:\s*)?busy:\s*processing'
|
||||||
|
|
||||||
.. _sec-configuration-config_yaml-webcam:
|
.. _sec-configuration-config_yaml-webcam:
|
||||||
|
|
||||||
|
|||||||
@@ -10,3 +10,4 @@ Configuration
|
|||||||
yaml.rst
|
yaml.rst
|
||||||
config_yaml.rst
|
config_yaml.rst
|
||||||
logging_yaml.rst
|
logging_yaml.rst
|
||||||
|
cli.rst
|
||||||
@@ -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.
|
||||||
@@ -13,8 +13,8 @@ below.
|
|||||||
|
|
||||||
* Prerequisites:
|
* Prerequisites:
|
||||||
|
|
||||||
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
|
||||||
* `Python 3.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>`_
|
* `Git <https://git-scm.com>`_
|
||||||
|
|
||||||
* Checkout the OctoPrint sources from their Git repository:
|
* 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
|
installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning
|
||||||
issues for the dependencies with system wide installed instances:
|
issues for the dependencies with system wide installed instances:
|
||||||
|
|
||||||
* PY2: ``virtualenv --python=python2 venv2``
|
|
||||||
* PY3: ``virtualenv --python=python3 venv3``
|
* PY3: ``virtualenv --python=python3 venv3``
|
||||||
|
* PY2: ``virtualenv --python=python2 venv2``
|
||||||
|
|
||||||
.. note::
|
.. 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,
|
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``
|
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)
|
* 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:
|
* Update ``pip`` in the virtual environment:
|
||||||
|
|
||||||
@@ -49,10 +50,20 @@ below.
|
|||||||
|
|
||||||
* ``pip install -e '.[develop,plugins]'``
|
* ``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:
|
When the virtual environment is activated you can then:
|
||||||
|
|
||||||
* run the OctoPrint server via ``octoprint serve``
|
* run the OctoPrint server via ``octoprint serve``
|
||||||
* run the test suite from the checked out source folder via ``pytest``
|
* 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.
|
To switch the activated virtual environment, simply activate the new environment as described above.
|
||||||
|
|
||||||
@@ -106,6 +117,8 @@ Then:
|
|||||||
source ./venv3/bin/activate
|
source ./venv3/bin/activate
|
||||||
pip install --upgrade pip
|
pip install --upgrade pip
|
||||||
pip install -e .[develop,plugins,docs]
|
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.
|
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
|
source ./venv3/Scripts/activate
|
||||||
pip install --upgrade pip
|
pip install --upgrade pip
|
||||||
pip install -e .[develop,plugins,docs]
|
pip install -e .[develop,plugins,docs]
|
||||||
|
pre-commit install
|
||||||
|
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||||
|
|
||||||
.. _sec-development-environment-mac:
|
.. _sec-development-environment-mac:
|
||||||
|
|
||||||
@@ -198,6 +213,8 @@ You'll need a user account with administrator privileges.
|
|||||||
source venv/bin/activate
|
source venv/bin/activate
|
||||||
pip install --upgrade pip
|
pip install --upgrade pip
|
||||||
pip install -e .[develop,plugins]
|
pip install -e .[develop,plugins]
|
||||||
|
pre-commit install
|
||||||
|
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||||
|
|
||||||
.. _sec-development-environment-ides:
|
.. _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
|
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]``.
|
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
|
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.
|
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.
|
Otherwise go through Settings.
|
||||||
|
|||||||
@@ -7,6 +7,11 @@ Development
|
|||||||
.. toctree::
|
.. toctree::
|
||||||
:maxdepth: 3
|
:maxdepth: 3
|
||||||
|
|
||||||
|
versioning.rst
|
||||||
|
branches.rst
|
||||||
environment.rst
|
environment.rst
|
||||||
virtual_printer.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>`_!
|
||||||
@@ -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.
|
||||||
@@ -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
|
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
|
||||||
smoothieTemperatureReporting: false
|
smoothieTemperatureReporting: false
|
||||||
|
|
||||||
# Whether M20 responses will include filesize or not
|
# Settings related to the SD file list output
|
||||||
#
|
sdFiles:
|
||||||
# True: <filename> <filesize in bytes>
|
# Whether M20 responses will include filesize or not
|
||||||
# False: <filename>
|
#
|
||||||
extendedSdFileList: false
|
# 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
|
# Forced pause for retrieving from the outgoing buffer
|
||||||
throttle: 0.01
|
throttle: 0.01
|
||||||
@@ -192,6 +200,31 @@ There many configuration options via ``config.yaml`` for the virtual printer tha
|
|||||||
|
|
||||||
# Simulated ambient temperature in °C
|
# Simulated ambient temperature in °C
|
||||||
ambientTemperature: 21.3
|
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:
|
.. _sec-development-virtual-printer-log:
|
||||||
|
|
||||||
|
|||||||
@@ -109,6 +109,9 @@ ClientOpened
|
|||||||
|
|
||||||
**Note:** Name changed in version 1.1.0
|
**Note:** Name changed in version 1.1.0
|
||||||
|
|
||||||
|
.. versionchanged:: 1.1.0
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
ClientAuthed
|
ClientAuthed
|
||||||
A client has authenticated a user session on the push socket.
|
A client has authenticated a user session on the push socket.
|
||||||
|
|
||||||
@@ -118,6 +121,8 @@ ClientAuthed
|
|||||||
valid login session.
|
valid login session.
|
||||||
* ``username``: the name of the user who authed. On the push socket only available with a valid login session.
|
* ``username``: the name of the user who authed. On the push socket only available with a valid login session.
|
||||||
|
|
||||||
|
.. versionadded:: 1.4.0
|
||||||
|
|
||||||
ClientClosed
|
ClientClosed
|
||||||
A client has disconnected from the push socket.
|
A client has disconnected from the push socket.
|
||||||
|
|
||||||
@@ -133,12 +138,16 @@ UserLoggedIn
|
|||||||
|
|
||||||
* ``username``: the name of the user who logged in
|
* ``username``: the name of the user who logged in
|
||||||
|
|
||||||
|
.. versionadded:: 1.4.0
|
||||||
|
|
||||||
UserLoggedOut
|
UserLoggedOut
|
||||||
A user logged out. On the push socket only available with a valid login session with admin rights.
|
A user logged out. On the push socket only available with a valid login session with admin rights.
|
||||||
|
|
||||||
Payload:
|
Payload:
|
||||||
* ``username``: the name of the user who logged out
|
* ``username``: the name of the user who logged out
|
||||||
|
|
||||||
|
.. versionadded:: 1.4.0
|
||||||
|
|
||||||
ConnectivityChanged
|
ConnectivityChanged
|
||||||
The server's internet connectivity changed
|
The server's internet connectivity changed
|
||||||
|
|
||||||
@@ -147,6 +156,8 @@ ConnectivityChanged
|
|||||||
* ``old``: Old connectivity value (true for online, false for offline)
|
* ``old``: Old connectivity value (true for online, false for offline)
|
||||||
* ``new``: New 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:
|
.. _sec-events-available_events-printer_commmunication:
|
||||||
|
|
||||||
Printer communication
|
Printer communication
|
||||||
@@ -155,6 +166,8 @@ Printer communication
|
|||||||
Connecting
|
Connecting
|
||||||
The server is attempting to connect to the printer.
|
The server is attempting to connect to the printer.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.0
|
||||||
|
|
||||||
Connected
|
Connected
|
||||||
The server has connected to the printer.
|
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
|
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.
|
from each other. Do not depend on this for critical life cycle management.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.0
|
||||||
|
|
||||||
Disconnected
|
Disconnected
|
||||||
The server has disconnected from the printer
|
The server has disconnected from the printer
|
||||||
|
|
||||||
@@ -191,6 +206,8 @@ PrinterStateChanged
|
|||||||
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
|
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
|
||||||
* ``state_string``: Text representation of the new state.
|
* ``state_string``: Text representation of the new state.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.0
|
||||||
|
|
||||||
.. _sec-events-available_events-file_handling:
|
.. _sec-events-available_events-file_handling:
|
||||||
|
|
||||||
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.
|
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
FileAdded
|
FileAdded
|
||||||
A file has been added to a storage.
|
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
|
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.
|
path and then ``FileAdded`` for the new one.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.3
|
||||||
|
|
||||||
FileRemoved
|
FileRemoved
|
||||||
A file has been removed from a storage.
|
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.
|
A moved file first triggers ``FileRemoved`` for its original path and then ``FileAdded`` for the new one.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.3
|
||||||
|
|
||||||
FolderAdded
|
FolderAdded
|
||||||
A folder has been added to a storage.
|
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
|
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.
|
path and then ``FolderAdded`` for the new one.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.3
|
||||||
|
|
||||||
FolderRemoved
|
FolderRemoved
|
||||||
A folder has been removed from a storage.
|
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.
|
A moved folder first triggers ``FolderRemoved`` for its original path and then ``FolderAdded`` for the new one.
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.3
|
||||||
|
|
||||||
UpdatedFiles
|
UpdatedFiles
|
||||||
A file list was modified.
|
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
|
reasons of backwards compatibility and will also be sent on modification of ``printables``. It will however
|
||||||
be removed with 1.4.0.
|
be removed with 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
MetadataAnalysisStarted
|
MetadataAnalysisStarted
|
||||||
The metadata analysis of a file has started.
|
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.
|
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
MetadataAnalysisFinished
|
MetadataAnalysisFinished
|
||||||
The metadata analysis of a file has finished.
|
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.
|
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
FileSelected
|
FileSelected
|
||||||
A file has been selected for printing.
|
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.
|
* ``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.
|
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
FileDeselected
|
FileDeselected
|
||||||
No file is selected any more for printing.
|
No file is selected any more for printing.
|
||||||
|
|
||||||
@@ -334,6 +368,8 @@ TransferStarted
|
|||||||
|
|
||||||
**Note:** Name changed in version 1.1.0
|
**Note:** Name changed in version 1.1.0
|
||||||
|
|
||||||
|
.. versionchanged:: 1.1.0
|
||||||
|
|
||||||
TransferDone
|
TransferDone
|
||||||
A file transfer to the printer's SD has finished.
|
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.
|
* ``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.
|
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
PrintFailed
|
PrintFailed
|
||||||
A print failed.
|
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.
|
* ``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.
|
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
PrintDone
|
PrintDone
|
||||||
A print completed successfully.
|
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.
|
* ``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.
|
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
PrintCancelling
|
PrintCancelling
|
||||||
The print is about to be cancelled.
|
The print is about to be cancelled.
|
||||||
|
|
||||||
@@ -413,6 +455,8 @@ PrintCancelling
|
|||||||
* ``user``: the user who cancelled the print job (if available)
|
* ``user``: the user who cancelled the print job (if available)
|
||||||
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
|
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.7
|
||||||
|
|
||||||
PrintCancelled
|
PrintCancelled
|
||||||
The print has been cancelled.
|
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.
|
* ``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.
|
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
PrintPaused
|
PrintPaused
|
||||||
The print has been paused.
|
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.
|
* ``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.
|
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
PrintResumed
|
PrintResumed
|
||||||
The print has been resumed.
|
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.
|
* ``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.
|
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
.. _sec-events-available_events-gcode_processing:
|
.. _sec-events-available_events-gcode_processing:
|
||||||
|
|
||||||
GCODE processing
|
GCODE processing
|
||||||
@@ -543,6 +593,8 @@ PositionUpdate
|
|||||||
* ``t``: last tool selected *through OctoPrint*
|
* ``t``: last tool selected *through OctoPrint*
|
||||||
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
|
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.0
|
||||||
|
|
||||||
ToolChange
|
ToolChange
|
||||||
A tool change command was sent to the printer. The payload contains the former current tool index and the
|
A tool change command was sent to the printer. The payload contains the former current tool index and the
|
||||||
new current tool index.
|
new current tool index.
|
||||||
@@ -552,6 +604,34 @@ ToolChange
|
|||||||
* ``old``: old tool index
|
* ``old``: old tool index
|
||||||
* ``new``: new 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:
|
.. _sec-events-available_events-timelapses:
|
||||||
|
|
||||||
Timelapses
|
Timelapses
|
||||||
@@ -577,6 +657,8 @@ CaptureFailed
|
|||||||
* ``file``: the name of the image file that should have been saved
|
* ``file``: the name of the image file that should have been saved
|
||||||
* ``error``: the error that was caught
|
* ``error``: the error that was caught
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.0
|
||||||
|
|
||||||
MovieRendering
|
MovieRendering
|
||||||
The timelapse movie has started rendering.
|
The timelapse movie has started rendering.
|
||||||
|
|
||||||
@@ -669,6 +751,8 @@ SlicingProfileAdded
|
|||||||
* ``slicer``: the slicer for which the profile was added
|
* ``slicer``: the slicer for which the profile was added
|
||||||
* ``profile``: the profile that was added
|
* ``profile``: the profile that was added
|
||||||
|
|
||||||
|
.. versionadded:: 1.2.12
|
||||||
|
|
||||||
SlicingProfileModified
|
SlicingProfileModified
|
||||||
A slicing profile was modified.
|
A slicing profile was modified.
|
||||||
|
|
||||||
@@ -677,6 +761,8 @@ SlicingProfileModified
|
|||||||
* ``slicer``: the slicer for which the profile was modified
|
* ``slicer``: the slicer for which the profile was modified
|
||||||
* ``profile``: the profile that was modified
|
* ``profile``: the profile that was modified
|
||||||
|
|
||||||
|
.. versionadded:: 1.2.12
|
||||||
|
|
||||||
SlicingProfileDeleted
|
SlicingProfileDeleted
|
||||||
A slicing profile was deleted.
|
A slicing profile was deleted.
|
||||||
|
|
||||||
@@ -685,6 +771,8 @@ SlicingProfileDeleted
|
|||||||
* ``slicer``: the slicer for which the profile was deleted
|
* ``slicer``: the slicer for which the profile was deleted
|
||||||
* ``profile``: the profile that was deleted
|
* ``profile``: the profile that was deleted
|
||||||
|
|
||||||
|
.. versionadded:: 1.2.12
|
||||||
|
|
||||||
.. _sec-events-available_events-settings:
|
.. _sec-events-available_events-settings:
|
||||||
|
|
||||||
Settings
|
Settings
|
||||||
@@ -696,6 +784,8 @@ SettingsUpdated
|
|||||||
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
|
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``.
|
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
|
||||||
|
|
||||||
|
.. versionadded:: 1.2.0
|
||||||
|
|
||||||
.. _sec-events-available_events-printer_profile:
|
.. _sec-events-available_events-printer_profile:
|
||||||
|
|
||||||
Printer Profile
|
Printer Profile
|
||||||
@@ -707,3 +797,6 @@ PrinterProfileModified
|
|||||||
Payload:
|
Payload:
|
||||||
|
|
||||||
* ``identifier``: the identifier of the modified printer profile
|
* ``identifier``: the identifier of the modified printer profile
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.12
|
||||||
|
|
||||||
@@ -3,6 +3,8 @@
|
|||||||
Access Control
|
Access Control
|
||||||
==============
|
==============
|
||||||
|
|
||||||
|
.. versionchanged:: 1.4.0
|
||||||
|
|
||||||
OctoPrint's bundled access control feature allows granular permission control
|
OctoPrint's bundled access control feature allows granular permission control
|
||||||
over which users or user groups are allowed to access which parts of OctoPrint.
|
over which users or user groups are allowed to access which parts of OctoPrint.
|
||||||
|
|
||||||
|
|||||||
@@ -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:
|
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
|
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.
|
"Cancel" button had been clicked.
|
||||||
|
|
||||||
pause
|
pause
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
@ Commands
|
@ Commands
|
||||||
==========
|
==========
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.7
|
||||||
|
|
||||||
@ commands (also known as host commands elsewhere) are special commands you may include in GCODE files streamed
|
@ 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.
|
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.
|
Contrary to other commands they will never be sent to the printer but instead trigger functions inside OctoPrint.
|
||||||
|
|||||||
@@ -172,9 +172,10 @@ Controls
|
|||||||
turn the button red.
|
turn the button red.
|
||||||
* - ``enabled``
|
* - ``enabled``
|
||||||
- (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control
|
- (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
|
should be enabled or not. This allows to override the default logic for the enable state
|
||||||
or currently printing). The JavaScript snippet is ``eval``'d and processed in a context where the control
|
of the control (disabled if printer is offline). The JavaScript snippet is ``eval``'d and processed
|
||||||
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
|
in a context where the control it is part of is provided as local variable ``data`` and the
|
||||||
|
``ControlViewModel`` is available as ``self``.
|
||||||
* - ``input``
|
* - ``input``
|
||||||
- (Optional) A list of definitions of input parameters for a ``command`` or ``commands``, to be rendered as
|
- (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
|
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
|
- (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
|
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.
|
with ``template`` this allows rendition of received data from the printer within the UI.
|
||||||
|
|
||||||
|
**Please also read the note below**.
|
||||||
* - ``template``
|
* - ``template``
|
||||||
- (Optional) A template to use for rendering the match of ``regex``. May contain placeholders in
|
- (Optional) A template to use for rendering the match of ``regex``. May contain placeholders in
|
||||||
:ref:`Python Format String Syntax <formatstrings>` for either named
|
: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*)``)
|
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
|
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.]+)``).
|
``X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)``).
|
||||||
|
|
||||||
|
**Please also read the note below**.
|
||||||
* - ``confirm``
|
* - ``confirm``
|
||||||
- (Optional) A text to display to the user to confirm his button press. Can be used with sensitive custom controls
|
- (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
|
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`.
|
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:
|
.. _fig-configuration-customcontrols-confirm:
|
||||||
.. figure:: ../images/features-custom_controls-confirm.png
|
.. figure:: ../images/features-custom_controls-confirm.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|||||||
@@ -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
|
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
|
``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
|
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.
|
to the persisted pause position on resume, making sure to also reset the extruder and feedrate.
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
Plugins
|
Plugins
|
||||||
*******
|
*******
|
||||||
|
|
||||||
|
.. versionadded:: 1.2.0
|
||||||
|
|
||||||
Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually
|
Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually
|
||||||
extend OctoPrint's functionality.
|
extend OctoPrint's functionality.
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,9 @@
|
|||||||
Safe mode
|
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
|
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
|
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language
|
||||||
packs instead of OctoPrint itself.
|
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
@@ -207,6 +207,8 @@ octoprint.access.permissions
|
|||||||
|
|
||||||
.. py:function:: additional_permissions_hook(*args, **kwargs)
|
.. 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
|
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
|
to add granular permissions to your plugin which can be configured for users and user groups in the general
|
||||||
access control settings of OctoPrint.
|
access control settings of OctoPrint.
|
||||||
@@ -261,6 +263,8 @@ octoprint.access.users.factory
|
|||||||
|
|
||||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
.. 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
|
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.
|
be called only once during initial server startup.
|
||||||
|
|
||||||
@@ -295,6 +299,8 @@ octoprint.accesscontrol.keyvalidator
|
|||||||
|
|
||||||
.. py:function:: acl_keyvalidator_hook(apikey, *args, **kwargs)
|
.. 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.
|
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.
|
``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)
|
.. 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).
|
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
|
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)
|
.. 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``.
|
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
|
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)
|
.. 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.
|
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
|
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
|
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.
|
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 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 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``
|
``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:
|
.. _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)
|
.. 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``
|
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
|
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.
|
detailed description of each of these phases.
|
||||||
@@ -588,7 +608,7 @@ This describes actually two hooks:
|
|||||||
octoprint.comm.protocol.gcode.<phase>
|
octoprint.comm.protocol.gcode.<phase>
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
This describes actually four hooks:
|
This actually describes four hooks:
|
||||||
|
|
||||||
* ``octoprint.comm.protocol.gcode.queuing``
|
* ``octoprint.comm.protocol.gcode.queuing``
|
||||||
* ``octoprint.comm.protocol.gcode.queued``
|
* ``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)
|
.. 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
|
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
|
||||||
are the following:
|
are the following:
|
||||||
|
|
||||||
@@ -750,6 +772,8 @@ octoprint.comm.protocol.gcode.received
|
|||||||
|
|
||||||
.. py:function:: gcode_received_hook(comm_instance, line, *args, **kwargs)
|
.. 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
|
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
|
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
|
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)
|
.. 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
|
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
|
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
|
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)
|
.. 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
|
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
|
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.
|
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)
|
.. 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
|
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.
|
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)
|
.. 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
|
Return additional port names (not glob patterns!) to use as a serial connection to the printer. Expected to be
|
||||||
``list`` of ``string``s.
|
``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)
|
.. 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
|
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``.
|
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)
|
.. 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.
|
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
|
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)
|
.. py:function:: analysis_queue_factory_hook(*args, **kwargs)
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.9
|
||||||
|
|
||||||
Return additional (or replacement) analysis queue factories used for analysing uploaded files.
|
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
|
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)
|
.. 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.
|
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
|
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)
|
.. 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`.
|
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
|
``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.
|
:return: The `file_object` as passed in or None, or a replaced version to use instead for further processing.
|
||||||
:rtype: AbstractFileWrapper or None
|
: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:
|
.. _sec-plugins-hook-plugin-loginui-theming:
|
||||||
|
|
||||||
octoprint.plugin.loginui.theming
|
octoprint.plugin.loginui.theming
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
.. versionadded:: 1.4.0
|
||||||
|
|
||||||
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
|
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
|
||||||
|
|
||||||
.. _sec-plugins-hook-plugin-pluginmanager-reconnect:
|
.. _sec-plugins-hook-plugin-pluginmanager-reconnect:
|
||||||
@@ -1133,6 +1187,8 @@ See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
|
|||||||
octoprint.plugin.pluginmanager.reconnect_hooks
|
octoprint.plugin.pluginmanager.reconnect_hooks
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
.. versionadded:: 1.4.0
|
||||||
|
|
||||||
See :ref:`here <sec-bundledplugins-pluginmanager-hooks-reconnect_hooks>`.
|
See :ref:`here <sec-bundledplugins-pluginmanager-hooks-reconnect_hooks>`.
|
||||||
|
|
||||||
.. _sec-plugins-hook-plugin-softwareupdate-check_config:
|
.. _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
|
octoprint.plugin.softwareupdate.check_config
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
.. versionadded:: 1.2.0
|
||||||
|
|
||||||
See :ref:`here <sec-bundledplugins-softwareupdate-hooks-check_config>`.
|
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:
|
.. _sec-plugins-hook-printer-factory:
|
||||||
|
|
||||||
octoprint.printer.factory
|
octoprint.printer.factory
|
||||||
@@ -1149,6 +1236,8 @@ octoprint.printer.factory
|
|||||||
|
|
||||||
.. py:function:: printer_factory_hook(components, *args, **kwargs)
|
.. 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
|
Return a :class:`~octoprint.printer.PrinterInstance` instance to use as global printer object. This will
|
||||||
be called only once during initial server startup.
|
be called only once during initial server startup.
|
||||||
|
|
||||||
@@ -1180,6 +1269,8 @@ octoprint.printer.estimation.factory
|
|||||||
|
|
||||||
.. py:function:: print_time_estimator_factory(*args, **kwargs)
|
.. 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
|
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``
|
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,
|
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)
|
.. 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.
|
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``
|
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)
|
.. 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.
|
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.
|
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)
|
.. 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.
|
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.
|
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)
|
.. py:function:: access_validator_hook(request, *args, **kwargs)
|
||||||
|
|
||||||
|
.. versionadded:: 1.3.10
|
||||||
|
|
||||||
Allows adding additional access validators to the default tornado routers.
|
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.
|
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)
|
.. 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
|
Allows extending the list of custom maximum body sizes on the web server per path and HTTP method with custom entries
|
||||||
from plugins.
|
from plugins.
|
||||||
|
|
||||||
@@ -1398,6 +1499,8 @@ octoprint.server.http.routes
|
|||||||
|
|
||||||
.. py:function:: server_route_hook(server_routes, *args, **kwargs)
|
.. py:function:: server_route_hook(server_routes, *args, **kwargs)
|
||||||
|
|
||||||
|
.. versionadded:: 1.2.0
|
||||||
|
|
||||||
Allows extending the list of routes registered on the web server.
|
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
|
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):
|
.. 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).
|
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
|
: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):
|
.. 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.
|
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``
|
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):
|
.. 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>`.
|
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.
|
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)
|
.. 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
|
Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of
|
||||||
additional file extensions.
|
additional file extensions.
|
||||||
|
|
||||||
@@ -1542,6 +1653,8 @@ octoprint.ui.web.templatetypes
|
|||||||
|
|
||||||
.. py:function:: templatetype_hook(template_sorting, template_rules, *args, **kwargs)
|
.. 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
|
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
|
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.
|
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)
|
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||||
:rtype: list
|
: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:
|
.. _sec-plugins-hook-timelapse-capture-pre:
|
||||||
|
|
||||||
octoprint.timelapse.capture.pre
|
octoprint.timelapse.capture.pre
|
||||||
@@ -1655,6 +1804,8 @@ octoprint.timelapse.capture.pre
|
|||||||
|
|
||||||
.. py:function:: capture_pre_hook(filename)
|
.. py:function:: capture_pre_hook(filename)
|
||||||
|
|
||||||
|
.. versionadded:: 1.4.0
|
||||||
|
|
||||||
Perform specific actions prior to capturing a timelapse frame.
|
Perform specific actions prior to capturing a timelapse frame.
|
||||||
|
|
||||||
``filename`` will be the future path of the frame to be saved.
|
``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)
|
.. py:function:: capture_post_hook(filename, success)
|
||||||
|
|
||||||
|
.. versionadded:: 1.4.0
|
||||||
|
|
||||||
Perform specific actions after capturing a timelapse frame.
|
Perform specific actions after capturing a timelapse frame.
|
||||||
|
|
||||||
``filename`` will be the path of the frame that should have been saved.
|
``filename`` will be the path of the frame that should have been saved.
|
||||||
|
|||||||
@@ -238,6 +238,11 @@ getAdditionalControls()
|
|||||||
Your view model may return additional custom control definitions for inclusion on the "Control" tab of OctoPrint's
|
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>`.
|
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()
|
onSettingsShown()
|
||||||
Called when the settings dialog is shown.
|
Called when the settings dialog is shown.
|
||||||
|
|
||||||
|
|||||||
+213
-193
@@ -2,15 +2,13 @@
|
|||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||||
|
|
||||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
__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"
|
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
|
||||||
|
|
||||||
from sphinx.directives.code import CodeBlock
|
from sphinx.directives.code import CodeBlock
|
||||||
|
|
||||||
import sphinx.highlighting
|
import sphinx.highlighting
|
||||||
from sphinx.highlighting import PygmentsBridge
|
|
||||||
from sphinx.ext import doctest
|
from sphinx.ext import doctest
|
||||||
from sphinx.util.texescape import tex_hl_escape_map_new
|
|
||||||
|
|
||||||
from docutils import nodes
|
from docutils import nodes
|
||||||
from docutils.parsers.rst import directives
|
from docutils.parsers.rst import directives
|
||||||
@@ -23,241 +21,263 @@ from pygments.lexers.python import PythonConsoleLexer
|
|||||||
from pygments.util import ClassNotFound
|
from pygments.util import ClassNotFound
|
||||||
|
|
||||||
if False:
|
if False:
|
||||||
# For type annotation
|
# For type annotation
|
||||||
from typing import Any, Dict, List, Tuple # NOQA
|
from typing import Any, Dict, List, Tuple # NOQA
|
||||||
|
|
||||||
|
|
||||||
def _merge_dict(a, b):
|
def _merge_dict(a, b):
|
||||||
"""
|
"""
|
||||||
Little helper to merge two dicts a and b on the fly.
|
Little helper to merge two dicts a and b on the fly.
|
||||||
"""
|
"""
|
||||||
result = dict(a)
|
result = dict(a)
|
||||||
result.update(b)
|
result.update(b)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
class literal_block_ext(nodes.General, nodes.FixedTextElement):
|
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
|
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.
|
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):
|
class CodeBlockExt(CodeBlock):
|
||||||
"""
|
"""
|
||||||
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
|
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
|
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
|
||||||
code blocks.
|
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):
|
def run(self):
|
||||||
# type: () -> List[nodes.Node]
|
# type: () -> List[nodes.Node]
|
||||||
# get result from parent implementation
|
# get result from parent implementation
|
||||||
code_block = CodeBlock.run(self)
|
code_block = CodeBlock.run(self)
|
||||||
|
|
||||||
def find_and_wrap_literal_block(node):
|
def find_and_wrap_literal_block(node):
|
||||||
"""
|
"""
|
||||||
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
|
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if isinstance(node, nodes.container):
|
if isinstance(node, nodes.container):
|
||||||
# container node => handle all children
|
# container node => handle all children
|
||||||
children = []
|
children = []
|
||||||
for child in node.children:
|
for child in node.children:
|
||||||
children.append(find_and_wrap_literal_block(child))
|
children.append(find_and_wrap_literal_block(child))
|
||||||
node.children = children
|
node.children = children
|
||||||
return node
|
return node
|
||||||
|
|
||||||
elif isinstance(node, nodes.literal_block):
|
elif isinstance(node, nodes.literal_block):
|
||||||
# literal block => replace it
|
# literal block => replace it
|
||||||
return self._wrap_literal_block(node)
|
return self._wrap_literal_block(node)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# no idea what that is => leave it alone
|
# no idea what that is => leave it alone
|
||||||
return node
|
return node
|
||||||
|
|
||||||
# replace all created literal_blocks with literal_block_ext instances
|
# replace all created literal_blocks with literal_block_ext instances
|
||||||
return list(map(find_and_wrap_literal_block, code_block))
|
return list(map(find_and_wrap_literal_block, code_block))
|
||||||
|
|
||||||
|
def _wrap_literal_block(self, node):
|
||||||
|
literal = literal_block_ext.from_literal_block(node)
|
||||||
|
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):
|
class PygmentsBridgeExt(object):
|
||||||
"""
|
"""
|
||||||
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
|
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
|
||||||
which calls the parent implementation for lexer selection, then
|
which calls the parent implementation for lexer selection, then
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, bridge, whitespace):
|
def __init__(self, bridge, whitespace):
|
||||||
self._bridge = bridge
|
self._bridge = bridge
|
||||||
self._whitespace = whitespace
|
self._whitespace = whitespace
|
||||||
|
|
||||||
def __getattr__(self, item):
|
def __getattr__(self, item):
|
||||||
return getattr(self._bridge, item)
|
return getattr(self._bridge, item)
|
||||||
|
|
||||||
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
|
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
|
||||||
if not self._whitespace:
|
if not self._whitespace:
|
||||||
return self._bridge.highlight_block(source, lang, opts=opts, warn=warn, force=force, **kwargs)
|
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
|
# 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
|
# 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.
|
# 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
|
# 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.
|
# include the whitespace filter.
|
||||||
|
|
||||||
class whitespace(object):
|
class whitespace(object):
|
||||||
def __init__(self, lexer):
|
def __init__(self, lexer):
|
||||||
self._lexer = lexer
|
self._lexer = lexer
|
||||||
self._orig_filters = lexer.filters
|
self._orig_filters = lexer.filters
|
||||||
self._orig_tabsize = lexer.tabsize
|
self._orig_tabsize = lexer.tabsize
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
new_filters = list(self._orig_filters)
|
new_filters = list(self._orig_filters)
|
||||||
new_filters.append(VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize))
|
new_filters.append(
|
||||||
self._lexer.filters = new_filters
|
VisibleWhitespaceFilter(
|
||||||
self._lexer.tabsize = 0
|
spaces=True, tabs=True, tabsize=self._lexer.tabsize
|
||||||
return self._lexer
|
)
|
||||||
|
)
|
||||||
|
self._lexer.filters = new_filters
|
||||||
|
self._lexer.tabsize = 0
|
||||||
|
return self._lexer
|
||||||
|
|
||||||
def __exit__(self, type, value, traceback):
|
def __exit__(self, type, value, traceback):
|
||||||
self._lexer.filters = self._orig_filters
|
self._lexer.filters = self._orig_filters
|
||||||
self._lexer.tabsize = self._orig_tabsize
|
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
|
# 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
|
# 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.
|
# "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
|
# 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
|
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
|
||||||
# lies with the respective authors.
|
# lies with the respective authors.
|
||||||
|
|
||||||
if not isinstance(source, text_type):
|
if not isinstance(source, text_type):
|
||||||
source = source.decode()
|
source = source.decode()
|
||||||
|
|
||||||
# find out which lexer to use
|
# find out which lexer to use
|
||||||
if lang in ('py', 'python'):
|
if lang in ("py", "python"):
|
||||||
if source.startswith('>>>'):
|
if source.startswith(">>>"):
|
||||||
# interactive session
|
# interactive session
|
||||||
lexer = sphinx.highlighting.lexers['pycon']
|
lexer = sphinx.highlighting.lexers["pycon"]
|
||||||
elif not force:
|
elif not force:
|
||||||
# maybe Python -- try parsing it
|
# maybe Python -- try parsing it
|
||||||
if self.try_parse(source):
|
if self.try_parse(source):
|
||||||
lexer = sphinx.highlighting.lexers['python']
|
lexer = sphinx.highlighting.lexers["python"]
|
||||||
else:
|
else:
|
||||||
lexer = sphinx.highlighting.lexers['none']
|
lexer = sphinx.highlighting.lexers["none"]
|
||||||
else:
|
else:
|
||||||
lexer = sphinx.highlighting.lexers['python']
|
lexer = sphinx.highlighting.lexers["python"]
|
||||||
elif lang in ('python3', 'py3') and source.startswith('>>>'):
|
elif lang in ("python3", "py3") and source.startswith(">>>"):
|
||||||
# for py3, recognize interactive sessions, but do not try parsing...
|
# for py3, recognize interactive sessions, but do not try parsing...
|
||||||
lexer = sphinx.highlighting.lexers['pycon3']
|
lexer = sphinx.highlighting.lexers["pycon3"]
|
||||||
elif lang == 'guess':
|
elif lang == "guess":
|
||||||
# try:
|
# try:
|
||||||
lexer = sphinx.highlighting.guess_lexer(source)
|
lexer = sphinx.highlighting.guess_lexer(source)
|
||||||
# except Exception:
|
# except Exception:
|
||||||
# lexer = sphinx.highlighting.lexers['none']
|
# lexer = sphinx.highlighting.lexers['none']
|
||||||
else:
|
else:
|
||||||
if lang in sphinx.highlighting.lexers:
|
if lang in sphinx.highlighting.lexers:
|
||||||
lexer = sphinx.highlighting.lexers[lang]
|
lexer = sphinx.highlighting.lexers[lang]
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
lexer = sphinx.highlighting.lexers[lang] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
|
lexer = sphinx.highlighting.lexers[
|
||||||
except ClassNotFound:
|
lang
|
||||||
if warn:
|
] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
|
||||||
warn('Pygments lexer name %r is not known' % lang)
|
except ClassNotFound:
|
||||||
lexer = sphinx.highlighting.lexers['none']
|
if warn:
|
||||||
else:
|
warn("Pygments lexer name %r is not known" % lang)
|
||||||
raise
|
lexer = sphinx.highlighting.lexers["none"]
|
||||||
else:
|
else:
|
||||||
lexer.add_filter('raiseonerror')
|
raise
|
||||||
|
else:
|
||||||
|
lexer.add_filter("raiseonerror")
|
||||||
|
|
||||||
if not isinstance(source, text_type):
|
if not isinstance(source, text_type):
|
||||||
source = source.decode()
|
source = source.decode()
|
||||||
|
|
||||||
# trim doctest options if wanted
|
# trim doctest options if wanted
|
||||||
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
|
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
|
||||||
source = doctest.blankline_re.sub('', source)
|
source = doctest.blankline_re.sub("", source)
|
||||||
source = doctest.doctestopt_re.sub('', source)
|
source = doctest.doctestopt_re.sub("", source)
|
||||||
|
|
||||||
# highlight via Pygments
|
# highlight via Pygments
|
||||||
formatter = self._bridge.get_formatter(**kwargs)
|
formatter = self._bridge.get_formatter(**kwargs)
|
||||||
try:
|
try:
|
||||||
# MODIFIED: replaced by whitespace wrapped call
|
# MODIFIED: replaced by whitespace wrapped call
|
||||||
with whitespace(lexer) as l:
|
with whitespace(lexer) as l:
|
||||||
hlsource = highlight(source, l, formatter)
|
hlsource = highlight(source, l, formatter)
|
||||||
# /MODIFIED
|
# /MODIFIED
|
||||||
except ErrorToken:
|
except ErrorToken:
|
||||||
# this is most probably not the selected language,
|
# this is most probably not the selected language,
|
||||||
# so let it pass unhighlighted
|
# so let it pass unhighlighted
|
||||||
|
|
||||||
# MODIFIED: replaced by whitespace wrapped call
|
# MODIFIED: replaced by whitespace wrapped call
|
||||||
with whitespace(sphinx.highlighting.lexers["none"]) as l:
|
with whitespace(sphinx.highlighting.lexers["none"]) as l:
|
||||||
hlsource = highlight(source, l, formatter)
|
hlsource = highlight(source, l, formatter)
|
||||||
# /MODIFIED
|
# /MODIFIED
|
||||||
if self._bridge.dest == 'html':
|
return hlsource
|
||||||
return hlsource
|
|
||||||
else:
|
|
||||||
if not isinstance(hlsource, text_type): # Py2 / Pygments < 1.6
|
|
||||||
hlsource = hlsource.decode()
|
|
||||||
return hlsource.translate(tex_hl_escape_map_new)
|
|
||||||
|
|
||||||
|
|
||||||
class whitespace_highlighter(object):
|
class whitespace_highlighter(object):
|
||||||
"""
|
"""
|
||||||
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
|
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
|
|
||||||
|
|
||||||
self._orig_highlighter = self.translator.highlighter
|
def __init__(self, translator, node):
|
||||||
|
self.translator = translator
|
||||||
|
self.node = node
|
||||||
|
|
||||||
def __enter__(self):
|
self._orig_highlighter = self.translator.highlighter
|
||||||
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):
|
def __enter__(self):
|
||||||
self.translator.highlighter = self._orig_highlighter
|
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):
|
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
|
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.
|
visitor for regular literal blocks, then switch back again.
|
||||||
"""
|
"""
|
||||||
with whitespace_highlighter(translator, node):
|
with whitespace_highlighter(translator, node):
|
||||||
translator.visit_literal_block(node)
|
translator.visit_literal_block(node)
|
||||||
|
|
||||||
|
|
||||||
def depart_literal_block_ext(translator, node):
|
def depart_literal_block_ext(translator, node):
|
||||||
"""
|
"""
|
||||||
Just call the depart function for regular literal blocks.
|
Just call the depart function for regular literal blocks.
|
||||||
"""
|
"""
|
||||||
with whitespace_highlighter(translator, node):
|
with whitespace_highlighter(translator, node):
|
||||||
translator.depart_literal_block(node)
|
translator.depart_literal_block(node)
|
||||||
|
|
||||||
|
|
||||||
def setup(app):
|
def setup(app):
|
||||||
# custom directive
|
# custom directive
|
||||||
app.add_directive("code-block-ext", CodeBlockExt)
|
app.add_directive("code-block-ext", CodeBlockExt)
|
||||||
|
|
||||||
# custom node type
|
# custom node type
|
||||||
handler = (visit_literal_block_ext, depart_literal_block_ext)
|
handler = (visit_literal_block_ext, depart_literal_block_ext)
|
||||||
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
|
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
|
||||||
|
|
||||||
return dict(version="0.1")
|
return {"version": "0.1"}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||||
|
|
||||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
__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"
|
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
|
||||||
|
|
||||||
|
|
||||||
@@ -10,103 +10,118 @@ import codecs
|
|||||||
import requests
|
import requests
|
||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
|
|
||||||
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
|
from sphinx.directives.code import (
|
||||||
nodes, parselinenos, logger, container_wrapper
|
LiteralIncludeReader,
|
||||||
|
LiteralInclude,
|
||||||
|
dedent_lines,
|
||||||
|
nodes,
|
||||||
|
parselinenos,
|
||||||
|
logger,
|
||||||
|
container_wrapper,
|
||||||
|
)
|
||||||
from sphinx.util.nodes import set_source_info
|
from sphinx.util.nodes import set_source_info
|
||||||
|
|
||||||
if False:
|
if False:
|
||||||
# For type annotation
|
# For type annotation
|
||||||
from typing import Any, List # NOQA
|
from typing import Any, List # NOQA
|
||||||
|
|
||||||
|
cache = {}
|
||||||
|
|
||||||
cache = dict()
|
|
||||||
|
|
||||||
class OnlineIncludeReader(LiteralIncludeReader):
|
class OnlineIncludeReader(LiteralIncludeReader):
|
||||||
|
def read_file(self, filename, location=None):
|
||||||
|
# type: (unicode, Any) -> List[unicode]
|
||||||
|
|
||||||
def read_file(self, filename, location=None):
|
global cache
|
||||||
# type: (unicode, Any) -> List[unicode]
|
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
|
if "tab-width" in self.options:
|
||||||
try:
|
lines = [line.expandtabs(self.options["tab-width"]) for line in lines]
|
||||||
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:
|
return lines
|
||||||
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
|
except (IOError, OSError):
|
||||||
|
raise IOError("Include file %r not found or reading it failed" % filename)
|
||||||
return lines
|
except UnicodeError:
|
||||||
except (IOError, OSError):
|
raise UnicodeError(
|
||||||
raise IOError('Include file %r not found or reading it failed' % filename)
|
"Encoding %r used for reading included file %r seems to "
|
||||||
except UnicodeError:
|
"be wrong, try giving an :encoding: option" % (self.encoding, filename)
|
||||||
raise UnicodeError('Encoding %r used for reading included file %r seems to '
|
)
|
||||||
'be wrong, try giving an :encoding: option' % (self.encoding, filename))
|
|
||||||
|
|
||||||
|
|
||||||
class OnlineIncludeDirective(LiteralInclude):
|
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):
|
try:
|
||||||
# type: () -> List[nodes.Node]
|
location = self.state_machine.get_source_and_line(self.lineno)
|
||||||
document = self.state.document
|
url = self.arguments[0]
|
||||||
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:
|
reader = OnlineIncludeReader(url, self.options, self.config)
|
||||||
location = self.state_machine.get_source_and_line(self.lineno)
|
text, lines = reader.read(location=location)
|
||||||
url = self.arguments[0]
|
|
||||||
|
|
||||||
reader = OnlineIncludeReader(url, self.options, self.config)
|
retnode = nodes.literal_block(text, text, source=url)
|
||||||
text, lines = reader.read(location=location)
|
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)
|
if "caption" in self.options:
|
||||||
set_source_info(self, retnode)
|
caption = self.options["caption"] or self.arguments[0]
|
||||||
if self.options.get('diff'): # if diff is set, set udiff
|
retnode = container_wrapper(self, retnode, caption)
|
||||||
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:
|
# retnode will be note_implicit_target that is linked from caption and numref.
|
||||||
caption = self.options['caption'] or self.arguments[0]
|
# when options['name'] is provided, it should be primary ID.
|
||||||
retnode = container_wrapper(self, retnode, caption)
|
self.add_name(retnode)
|
||||||
|
|
||||||
# retnode will be note_implicit_target that is linked from caption and numref.
|
return [retnode]
|
||||||
# when options['name'] is provided, it should be primary ID.
|
except Exception as exc:
|
||||||
self.add_name(retnode)
|
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):
|
def visit_onlineinclude(translator, node):
|
||||||
translator.visit_literal_block(node)
|
translator.visit_literal_block(node)
|
||||||
|
|
||||||
|
|
||||||
def depart_onlineinclude(translator, node):
|
def depart_onlineinclude(translator, node):
|
||||||
translator.depart_literal_block(node)
|
translator.depart_literal_block(node)
|
||||||
|
|
||||||
|
|
||||||
def setup(app):
|
def setup(app):
|
||||||
app.add_directive("onlineinclude", OnlineIncludeDirective)
|
app.add_directive("onlineinclude", OnlineIncludeDirective)
|
||||||
|
|
||||||
handler = (visit_onlineinclude, depart_onlineinclude)
|
handler = (visit_onlineinclude, depart_onlineinclude)
|
||||||
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
|
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
|
||||||
@@ -10,17 +10,20 @@ basedir = os.path.dirname(os.path.realpath(__file__))
|
|||||||
old = os.path.join(basedir, "octoprint")
|
old = os.path.join(basedir, "octoprint")
|
||||||
if os.path.exists(old):
|
if os.path.exists(old):
|
||||||
# rename left-overs from old file structure
|
# rename left-overs from old file structure
|
||||||
print("""
|
print(
|
||||||
|
"""
|
||||||
Found left-overs from old file structure, renaming to
|
Found left-overs from old file structure, renaming to
|
||||||
"octoprint.backup". Please remove this manually (I don't
|
"octoprint.backup". Please remove this manually (I don't
|
||||||
dare to do so myself since you might have changes in there
|
dare to do so myself since you might have changes in there
|
||||||
I don't know anything about).
|
I don't know anything about).
|
||||||
""")
|
"""
|
||||||
|
)
|
||||||
os.rename(old, os.path.join(basedir, "octoprint.backup"))
|
os.rename(old, os.path.join(basedir, "octoprint.backup"))
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(basedir, "src"))
|
sys.path.insert(0, os.path.join(basedir, "src"))
|
||||||
|
|
||||||
import octoprint
|
import octoprint # noqa: E402
|
||||||
|
|
||||||
if len(sys.argv) == 1:
|
if len(sys.argv) == 1:
|
||||||
sys.argv.append("serve")
|
sys.argv.append("serve")
|
||||||
octoprint.main()
|
octoprint.main()
|
||||||
@@ -14,11 +14,22 @@ parentdir_prefix =
|
|||||||
lookupfile = .versioneer-lookup
|
lookupfile = .versioneer-lookup
|
||||||
|
|
||||||
[flake8]
|
[flake8]
|
||||||
ignore =
|
max-line-length = 90
|
||||||
D
|
extend-ignore = E203, E231, E265, E266, E402, E501, E731
|
||||||
E
|
select = B,C,E,F,W,T4,B9
|
||||||
W
|
|
||||||
F401
|
|
||||||
F523
|
|
||||||
exclude =
|
exclude =
|
||||||
src/octoprint/vendor
|
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
|
||||||
@@ -1,294 +1,307 @@
|
|||||||
#!/usr/bin/env python2
|
#!/usr/bin/env python2
|
||||||
# coding=utf-8
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
from distutils.command.build_py import build_py as _build_py
|
|
||||||
import os
|
import os
|
||||||
import versioneer
|
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
|
from distutils.command.build_py import build_py as _build_py
|
||||||
import octoprint_setuptools
|
|
||||||
import setuptools
|
|
||||||
|
|
||||||
#-----------------------------------------------------------------------------------------------------------------------
|
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
|
# Supported python versions
|
||||||
# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported
|
# 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"
|
PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
|
||||||
|
|
||||||
# Requirements for setup.py
|
# Requirements for setup.py
|
||||||
SETUP_REQUIRES = [
|
SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3
|
||||||
"markdown>=3.1,<3.2" # newer versions require Python 3
|
|
||||||
]
|
|
||||||
|
|
||||||
# Requirements for our application
|
# Requirements for our application
|
||||||
INSTALL_REQUIRES = [
|
INSTALL_REQUIRES = [
|
||||||
# additional OctoPrint plugins that are maintained on a different release cycle
|
# additional OctoPrint plugins that are maintained on a different release cycle
|
||||||
"OctoPrint-FirmwareCheck>=2020.06.22",
|
"OctoPrint-FirmwareCheck>=2020.09.23",
|
||||||
"OctoPrint-FileCheck>=2020.07.06",
|
"OctoPrint-FileCheck>=2020.08.07",
|
||||||
|
# the following dependencies are non trivial to update since later versions
|
||||||
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
|
# introduce backwards incompatible changes that might affect plugins, or due to
|
||||||
# changes that might affect plugins, or due to other observed problems
|
# other observed problems
|
||||||
|
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
|
||||||
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
|
"tornado==5.1.1", # newer versions require Python 3
|
||||||
"tornado==5.1.1", # newer versions require Python 3
|
"markdown>=3.1,<3.2", # newer versions require Python 3
|
||||||
"markdown>=3.1,<3.2", # newer versions require Python 3
|
"rsa==4.0", # newer versions require Python 3
|
||||||
"rsa==4.0", # newer versions require Python 3
|
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
# anything below this should be checked on releases for new versions
|
||||||
|
"flask>=1.1.2,<2",
|
||||||
# anything below this should be checked on releases for new versions
|
"Jinja2>=2.11.2,<3",
|
||||||
|
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
|
||||||
"flask>=1.1.2,<2",
|
"Flask-Babel>=1.0,<2",
|
||||||
"Jinja2>=2.11.2,<3",
|
"Flask-Assets>=2.0,<3",
|
||||||
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
|
"werkzeug>=1.0.1,<2",
|
||||||
"Flask-Babel>=1.0,<2",
|
"itsdangerous>=1.1.0,<2",
|
||||||
"Flask-Assets>=2.0,<3",
|
"cachelib>=0.1,<1",
|
||||||
"werkzeug>=1.0.1,<2",
|
"PyYAML>=5.3.1,<6",
|
||||||
"itsdangerous>=1.1.0,<2",
|
"pyserial>=3.4,<4",
|
||||||
"cachelib>=0.1,<1",
|
"netaddr>=0.7.19,<1",
|
||||||
"PyYAML>=5.3.1,<6",
|
"watchdog==0.10.4", # watchdog dropped Py>3.6 on 0.10.5 point release...
|
||||||
"pyserial>=3.4,<4",
|
"sarge==0.1.5post0",
|
||||||
"netaddr>=0.7.19,<1",
|
"netifaces>=0.10.9,<1",
|
||||||
"watchdog>=0.10.2,<1",
|
"pylru>=1.2,<2",
|
||||||
"sarge==0.1.5post0",
|
"pkginfo>=1.5.0.1,<2",
|
||||||
"netifaces>=0.10.9,<1",
|
"requests>=2.23.0,<3",
|
||||||
"pylru>=1.2,<2",
|
"semantic_version>=2.8.5,<3",
|
||||||
"pkginfo>=1.5.0.1,<2",
|
"psutil>=5.7,<6",
|
||||||
"requests>=2.23.0,<3",
|
"Click>=7.1.2,<8",
|
||||||
"semantic_version>=2.8.5,<3",
|
"future>=0.18.2,<1",
|
||||||
"psutil>=5.7,<6",
|
"websocket-client>=0.57,<1",
|
||||||
"Click>=7.1.2,<8",
|
"wrapt>=1.12.1,<2",
|
||||||
"feedparser>=5.2.1,<6",
|
"emoji>=0.5.4,<1",
|
||||||
"future>=0.18.2,<1",
|
"frozendict>=1.2,<2",
|
||||||
"websocket-client>=0.57,<1",
|
"sentry-sdk>=0.15.1,<1",
|
||||||
"wrapt>=1.12.1,<2",
|
"filetype>=1.0.7,<2",
|
||||||
"emoji>=0.5.4,<1",
|
# vendor bundled dependencies
|
||||||
"frozendict>=1.2,<2",
|
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
|
||||||
"sentry-sdk>=0.15.1,<1",
|
"blinker>=1.4,<2", # dependency of flask_principal
|
||||||
"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
|
|
||||||
]
|
]
|
||||||
|
|
||||||
# Python 2 specific requirements
|
# Python 2 specific requirements
|
||||||
INSTALL_REQUIRES_PYTHON2 = [
|
INSTALL_REQUIRES_PYTHON2 = [
|
||||||
"futures>=3.3,<4",
|
"feedparser>=5.2.1,<6", # newer versions require Python 3
|
||||||
"monotonic>=1.5,<2",
|
"futures>=3.3,<4",
|
||||||
"scandir>=1.10,<2",
|
"monotonic>=1.5,<2",
|
||||||
"chainmap>=1.0.3,<2",
|
"scandir>=1.10,<2",
|
||||||
"typing>=3.7.4.1,<4"
|
"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
|
# OSX specific requirements
|
||||||
INSTALL_REQUIRES_OSX = [
|
INSTALL_REQUIRES_OSX = [
|
||||||
"appdirs>=1.4.4",
|
"appdirs>=1.4.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
# Additional requirements for optional install options
|
# Additional requirements for optional install options
|
||||||
EXTRA_REQUIRES = dict(
|
EXTRA_REQUIRES = {
|
||||||
# Dependencies for developing OctoPrint
|
"develop": [
|
||||||
develop=[
|
# Testing dependencies
|
||||||
# Testing dependencies - SEE ALSO tox.ini
|
"mock>=3.0.5,<4",
|
||||||
"mock>=3.0.5,<4",
|
"pytest==4.6.10",
|
||||||
"pytest==4.6.10",
|
"pytest-doctest-custom>=1.0.0,<2",
|
||||||
"pytest-doctest-custom>=1.0.0,<2",
|
"ddt",
|
||||||
"ddt",
|
# pre-commit
|
||||||
|
"pre-commit",
|
||||||
# linter
|
# profiler
|
||||||
"flake8",
|
"pyinstrument",
|
||||||
|
],
|
||||||
# profiler
|
# Dependencies for developing OctoPrint plugins
|
||||||
"pyinstrument",
|
"plugins": ["cookiecutter>=1.7.2,<1.8"],
|
||||||
],
|
# Dependencies for building the documentation - Python 3 required!
|
||||||
|
"docs": [
|
||||||
# Dependencies for developing OctoPrint plugins
|
"sphinx>=3,<4",
|
||||||
plugins=[
|
"sphinxcontrib-httpdomain",
|
||||||
"cookiecutter>=1.7.2,<1.8"
|
"sphinxcontrib-mermaid",
|
||||||
],
|
"sphinx_rtd_theme",
|
||||||
|
"readthedocs-sphinx-ext",
|
||||||
# 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 for any of the aforementioned dependencies
|
||||||
DEPENDENCY_LINKS = []
|
DEPENDENCY_LINKS = []
|
||||||
|
|
||||||
# adapted from https://hynek.me/articles/conditional-python-dependencies/
|
# adapted from https://hynek.me/articles/conditional-python-dependencies/
|
||||||
if int(setuptools.__version__.split(".", 1)[0]) < 18:
|
if int(setuptools.__version__.split(".", 1)[0]) < 18:
|
||||||
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
|
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
|
||||||
# would get lost there
|
# would get lost there
|
||||||
assert "bdist_wheel" not in sys.argv
|
assert "bdist_wheel" not in sys.argv
|
||||||
|
|
||||||
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
|
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
|
||||||
if sys.version_info[0] < 3:
|
if sys.version_info[0] < 3:
|
||||||
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
|
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
|
||||||
|
else:
|
||||||
|
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3
|
||||||
|
|
||||||
if sys.platform == "darwin":
|
if sys.platform == "darwin":
|
||||||
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
|
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
|
||||||
else:
|
else:
|
||||||
# environment markers supported
|
# environment markers supported
|
||||||
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
|
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
|
||||||
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
|
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
|
# Anything below here is just command setup and general setup configuration
|
||||||
|
|
||||||
here = os.path.abspath(os.path.dirname(__file__))
|
here = os.path.abspath(os.path.dirname(__file__))
|
||||||
|
|
||||||
|
|
||||||
def read_file_contents(path):
|
def read_file_contents(path):
|
||||||
import codecs
|
import codecs
|
||||||
with codecs.open(path, encoding="utf-8") as f:
|
|
||||||
return f.read()
|
with codecs.open(path, encoding="utf-8") as f:
|
||||||
|
return f.read()
|
||||||
|
|
||||||
|
|
||||||
def md_to_html_build_py_factory(files, baseclass):
|
def md_to_html_build_py_factory(files, baseclass):
|
||||||
class md_to_html_build_py(baseclass):
|
class md_to_html_build_py(baseclass):
|
||||||
files = dict()
|
files = {}
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
print("RUNNING md_to_html_build_py")
|
print("RUNNING md_to_html_build_py")
|
||||||
if not self.dry_run:
|
if not self.dry_run:
|
||||||
for directory, files in self.files.items():
|
for directory, files in self.files.items():
|
||||||
target_dir = os.path.join(self.build_lib, directory)
|
target_dir = os.path.join(self.build_lib, directory)
|
||||||
self.mkpath(target_dir)
|
self.mkpath(target_dir)
|
||||||
|
|
||||||
for entry in files:
|
for entry in files:
|
||||||
if isinstance(entry, tuple):
|
if isinstance(entry, tuple):
|
||||||
if len(entry) != 2:
|
if len(entry) != 2:
|
||||||
continue
|
continue
|
||||||
source, dest = entry[0], os.path.join(target_dir, entry[1])
|
source, dest = entry[0], os.path.join(target_dir, entry[1])
|
||||||
else:
|
else:
|
||||||
source = entry
|
source = entry
|
||||||
dest = os.path.join(target_dir, source + ".html")
|
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
|
from markdown import markdownFromFile
|
||||||
markdownFromFile(input=source,
|
|
||||||
output=dest,
|
markdownFromFile(input=source, output=dest, encoding="utf-8")
|
||||||
encoding="utf-8")
|
baseclass.run(self)
|
||||||
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():
|
def get_cmdclass():
|
||||||
# make sure these are always available, even when run by dependabot
|
# make sure these are always available, even when run by dependabot
|
||||||
global versioneer, octoprint_setuptools, md_to_html_build_py_factory
|
global versioneer, octoprint_setuptools, md_to_html_build_py_factory
|
||||||
|
|
||||||
cmdclass = versioneer.get_cmdclass()
|
cmdclass = versioneer.get_cmdclass()
|
||||||
|
|
||||||
# add clean command
|
# add clean command
|
||||||
cmdclass.update(dict(clean=octoprint_setuptools.CleanCommand.for_options(source_folder="src", eggs=["OctoPrint*.egg-info"])))
|
cmdclass.update(
|
||||||
|
{
|
||||||
|
"clean": octoprint_setuptools.CleanCommand.for_options(
|
||||||
|
source_folder="src", eggs=["OctoPrint*.egg-info"]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
# add translation commands
|
# add translation commands
|
||||||
translation_dir = "translations"
|
translation_dir = "translations"
|
||||||
pot_file = os.path.join(translation_dir, "messages.pot")
|
pot_file = os.path.join(translation_dir, "messages.pot")
|
||||||
bundled_dir = os.path.join("src", "octoprint", "translations")
|
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.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({
|
cmdclass["build_py"] = md_to_html_build_py_factory(
|
||||||
"octoprint/templates/_data": [
|
{
|
||||||
"AUTHORS.md",
|
"octoprint/templates/_data": [
|
||||||
"SUPPORTERS.md",
|
"AUTHORS.md",
|
||||||
"THIRDPARTYLICENSES.md",
|
"SUPPORTERS.md",
|
||||||
]
|
"THIRDPARTYLICENSES.md",
|
||||||
}, cmdclass["build_py"] if "build_py" in cmdclass else _build_py)
|
]
|
||||||
|
},
|
||||||
|
cmdclass["build_py"] if "build_py" in cmdclass else _build_py,
|
||||||
|
)
|
||||||
|
|
||||||
return cmdclass
|
return cmdclass
|
||||||
|
|
||||||
|
|
||||||
def params():
|
def params():
|
||||||
# make sure these are always available, even when run by dependabot
|
# make sure these are always available, even when run by dependabot
|
||||||
global versioneer, get_cmdclass, read_file_contents, here, \
|
global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
|
||||||
PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
|
|
||||||
|
|
||||||
name = "OctoPrint"
|
name = "OctoPrint"
|
||||||
version = versioneer.get_version()
|
version = versioneer.get_version()
|
||||||
cmdclass = get_cmdclass()
|
cmdclass = get_cmdclass()
|
||||||
|
|
||||||
description = "The snappy web interface for your 3D printer"
|
description = "The snappy web interface for your 3D printer"
|
||||||
long_description = read_file_contents(os.path.join(here, "README.md"))
|
long_description = read_file_contents(os.path.join(here, "README.md"))
|
||||||
long_description_content_type = "text/markdown"
|
long_description_content_type = "text/markdown"
|
||||||
|
|
||||||
python_requires = PYTHON_REQUIRES
|
python_requires = PYTHON_REQUIRES
|
||||||
setup_requires = SETUP_REQUIRES
|
setup_requires = SETUP_REQUIRES
|
||||||
install_requires = INSTALL_REQUIRES
|
install_requires = INSTALL_REQUIRES
|
||||||
extras_require = EXTRA_REQUIRES
|
extras_require = EXTRA_REQUIRES
|
||||||
dependency_links = DEPENDENCY_LINKS
|
dependency_links = DEPENDENCY_LINKS
|
||||||
|
|
||||||
classifiers = [
|
classifiers = [
|
||||||
"Development Status :: 5 - Production/Stable",
|
"Development Status :: 5 - Production/Stable",
|
||||||
"Environment :: Web Environment",
|
"Environment :: Web Environment",
|
||||||
"Framework :: Flask",
|
"Framework :: Flask",
|
||||||
"Intended Audience :: Developers",
|
"Intended Audience :: Developers",
|
||||||
"Intended Audience :: Education",
|
"Intended Audience :: Education",
|
||||||
"Intended Audience :: End Users/Desktop",
|
"Intended Audience :: End Users/Desktop",
|
||||||
"Intended Audience :: Manufacturing",
|
"Intended Audience :: Manufacturing",
|
||||||
"Intended Audience :: Other Audience",
|
"Intended Audience :: Other Audience",
|
||||||
"Intended Audience :: Science/Research",
|
"Intended Audience :: Science/Research",
|
||||||
"License :: OSI Approved :: GNU Affero General Public License v3",
|
"License :: OSI Approved :: GNU Affero General Public License v3",
|
||||||
"Natural Language :: English",
|
"Natural Language :: English",
|
||||||
"Natural Language :: German",
|
"Natural Language :: German",
|
||||||
"Operating System :: OS Independent",
|
"Operating System :: OS Independent",
|
||||||
"Programming Language :: Python",
|
"Programming Language :: Python",
|
||||||
"Programming Language :: Python :: 2",
|
"Programming Language :: Python :: 2",
|
||||||
"Programming Language :: Python :: 2.7",
|
"Programming Language :: Python :: 2.7",
|
||||||
"Programming Language :: Python :: 3",
|
"Programming Language :: Python :: 3",
|
||||||
"Programming Language :: Python :: 3.6",
|
"Programming Language :: Python :: 3.6",
|
||||||
"Programming Language :: Python :: 3.7",
|
"Programming Language :: Python :: 3.7",
|
||||||
"Programming Language :: Python :: 3.8",
|
"Programming Language :: Python :: 3.8",
|
||||||
"Programming Language :: Python :: Implementation :: CPython",
|
"Programming Language :: Python :: Implementation :: CPython",
|
||||||
"Programming Language :: JavaScript",
|
"Programming Language :: JavaScript",
|
||||||
"Topic :: Printing",
|
"Topic :: Printing",
|
||||||
"Topic :: System :: Monitoring"
|
"Topic :: System :: Monitoring",
|
||||||
]
|
]
|
||||||
author = "Gina Häußge"
|
author = "Gina Häußge"
|
||||||
author_email = "gina@octoprint.org"
|
author_email = "gina@octoprint.org"
|
||||||
url = "https://octoprint.org"
|
url = "https://octoprint.org"
|
||||||
license = "GNU Affero General Public License v3"
|
license = "GNU Affero General Public License v3"
|
||||||
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
|
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
|
||||||
|
|
||||||
project_urls={
|
project_urls = {
|
||||||
"Community Forum": "https://community.octoprint.org",
|
"Community Forum": "https://community.octoprint.org",
|
||||||
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
|
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
|
||||||
"Source": "https://github.com/foosel/OctoPrint",
|
"Source": "https://github.com/foosel/OctoPrint",
|
||||||
"Funding": "https://donate.octoprint.org"
|
"Funding": "https://donate.octoprint.org",
|
||||||
}
|
}
|
||||||
|
|
||||||
packages = setuptools.find_packages(where="src")
|
packages = setuptools.find_packages(where="src")
|
||||||
package_dir = {
|
package_dir = {
|
||||||
"": "src",
|
"": "src",
|
||||||
}
|
}
|
||||||
package_data = {
|
package_data = {
|
||||||
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint',
|
"octoprint": octoprint_setuptools.package_data_dirs(
|
||||||
['static', 'templates', 'plugins', 'translations'])
|
"src/octoprint", ["static", "templates", "plugins", "translations"]
|
||||||
+ ['util/piptestballoon/setup.py']
|
)
|
||||||
}
|
+ ["util/piptestballoon/setup.py"]
|
||||||
|
}
|
||||||
|
|
||||||
include_package_data = True
|
include_package_data = True
|
||||||
zip_safe = False
|
zip_safe = False
|
||||||
|
|
||||||
if os.environ.get('READTHEDOCS', None) == 'True':
|
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
|
# 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
|
# it a bit here by explicitly adding the development dependencies, which include our
|
||||||
# documentation dependencies
|
# documentation dependencies
|
||||||
install_requires = install_requires + extras_require['docs']
|
install_requires = install_requires + extras_require["docs"]
|
||||||
|
|
||||||
entry_points = {
|
entry_points = {"console_scripts": ["octoprint = octoprint:main"]}
|
||||||
"console_scripts": [
|
|
||||||
"octoprint = octoprint:main"
|
return locals()
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
return locals()
|
|
||||||
|
|
||||||
setuptools.setup(**params())
|
setuptools.setup(**params())
|
||||||
+791
-481
File diff suppressed because it is too large.
Load diff
@@ -3,5 +3,6 @@
|
|||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import octoprint
|
import octoprint
|
||||||
octoprint.main()
|
|
||||||
|
octoprint.main()
|
||||||
+114
-82
@@ -14,11 +14,11 @@ from __future__ import absolute_import, division, print_function, unicode_litera
|
|||||||
|
|
||||||
import errno
|
import errno
|
||||||
import io
|
import io
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import logging
|
|
||||||
|
|
||||||
|
|
||||||
def get_keywords():
|
def get_keywords():
|
||||||
@@ -64,12 +64,14 @@ HANDLERS = {}
|
|||||||
|
|
||||||
def register_vcs_handler(vcs, method): # decorator
|
def register_vcs_handler(vcs, method): # decorator
|
||||||
"""Decorator to mark a method as the handler for a particular VCS."""
|
"""Decorator to mark a method as the handler for a particular VCS."""
|
||||||
|
|
||||||
def decorate(f):
|
def decorate(f):
|
||||||
"""Store f in HANDLERS[vcs][method]."""
|
"""Store f in HANDLERS[vcs][method]."""
|
||||||
if vcs not in HANDLERS:
|
if vcs not in HANDLERS:
|
||||||
HANDLERS[vcs] = {}
|
HANDLERS[vcs] = {}
|
||||||
HANDLERS[vcs][method] = f
|
HANDLERS[vcs][method] = f
|
||||||
return f
|
return f
|
||||||
|
|
||||||
return decorate
|
return decorate
|
||||||
|
|
||||||
|
|
||||||
@@ -81,9 +83,12 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
|||||||
try:
|
try:
|
||||||
dispcmd = str([c] + args)
|
dispcmd = str([c] + args)
|
||||||
# remember shell=False, so use git.cmd on windows, not just git
|
# remember shell=False, so use git.cmd on windows, not just git
|
||||||
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
|
p = subprocess.Popen(
|
||||||
stderr=(subprocess.PIPE if hide_stderr
|
[c] + args,
|
||||||
else None))
|
cwd=cwd,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=(subprocess.PIPE if hide_stderr else None),
|
||||||
|
)
|
||||||
break
|
break
|
||||||
except EnvironmentError:
|
except EnvironmentError:
|
||||||
e = sys.exc_info()[1]
|
e = sys.exc_info()[1]
|
||||||
@@ -116,12 +121,17 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
|
|||||||
dirname = os.path.basename(root)
|
dirname = os.path.basename(root)
|
||||||
if not dirname.startswith(parentdir_prefix):
|
if not dirname.startswith(parentdir_prefix):
|
||||||
if verbose:
|
if verbose:
|
||||||
print("guessing rootdir is '%s', but '%s' doesn't start with "
|
print(
|
||||||
"prefix '%s'" % (root, dirname, parentdir_prefix))
|
"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")
|
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
|
||||||
return {"version": dirname[len(parentdir_prefix):],
|
return {
|
||||||
"full-revisionid": None,
|
"version": dirname[len(parentdir_prefix) :],
|
||||||
"dirty": False, "error": None}
|
"full-revisionid": None,
|
||||||
|
"dirty": False,
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@register_vcs_handler("git", "get_keywords")
|
@register_vcs_handler("git", "get_keywords")
|
||||||
@@ -159,11 +169,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
|||||||
if verbose:
|
if verbose:
|
||||||
print("keywords are unexpanded, not using")
|
print("keywords are unexpanded, not using")
|
||||||
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
|
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
|
# 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.
|
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
|
||||||
TAG = "tag: "
|
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:
|
if not tags:
|
||||||
# Either we're using git < 1.8.3, or there really are no tags. We use
|
# 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
|
# 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
|
# between branches and tags. By ignoring refnames without digits, we
|
||||||
# filter out many common branch names like "release" and
|
# filter out many common branch names like "release" and
|
||||||
# "stabilization", as well as "HEAD" and "master".
|
# "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:
|
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)
|
branches = [
|
||||||
and r != "HEAD" and not r.startswith("refs/")]
|
r
|
||||||
|
for r in refs
|
||||||
|
if not r.startswith(TAG) and r != "HEAD" and not r.startswith("refs/")
|
||||||
|
]
|
||||||
if verbose:
|
if verbose:
|
||||||
print("likely branches: %s" % ",".join(sorted(branches)))
|
print("likely branches: %s" % ",".join(sorted(branches)))
|
||||||
branch = None
|
branch = None
|
||||||
@@ -189,22 +202,28 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
|||||||
for ref in sorted(tags):
|
for ref in sorted(tags):
|
||||||
# sorting will prefer e.g. "2.0" over "2.0rc1"
|
# sorting will prefer e.g. "2.0" over "2.0rc1"
|
||||||
if ref.startswith(tag_prefix):
|
if ref.startswith(tag_prefix):
|
||||||
r = ref[len(tag_prefix):]
|
r = ref[len(tag_prefix) :]
|
||||||
if verbose:
|
if verbose:
|
||||||
print("picking %s" % r)
|
print("picking %s" % r)
|
||||||
|
|
||||||
result = {"version": r,
|
result = {
|
||||||
"full-revisionid": keywords["full"].strip(),
|
"version": r,
|
||||||
"dirty": False, "error": None}
|
"full-revisionid": keywords["full"].strip(),
|
||||||
|
"dirty": False,
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
if branch is not None:
|
if branch is not None:
|
||||||
result["branch"] = branch
|
result["branch"] = branch
|
||||||
return result
|
return result
|
||||||
# no suitable tags, so version is "0+unknown", but full hex is still there
|
# no suitable tags, so version is "0+unknown", but full hex is still there
|
||||||
if verbose:
|
if verbose:
|
||||||
print("no suitable tags, using unknown + full revision id")
|
print("no suitable tags, using unknown + full revision id")
|
||||||
return {"version": "0+unknown",
|
return {
|
||||||
"full-revisionid": keywords["full"].strip(),
|
"version": "0+unknown",
|
||||||
"dirty": False, "error": "no suitable tags"}
|
"full-revisionid": keywords["full"].strip(),
|
||||||
|
"dirty": False,
|
||||||
|
"error": "no suitable tags",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@register_vcs_handler("git", "pieces_from_vcs")
|
@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"]
|
GITS = ["git.cmd", "git.exe"]
|
||||||
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
|
# 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)
|
# if there isn't one, this yields HEX[-dirty] (no NUM)
|
||||||
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
|
describe_out = run_command(
|
||||||
"--always", "--long",
|
GITS,
|
||||||
"--match", "%s*" % tag_prefix],
|
[
|
||||||
cwd=root)
|
"describe",
|
||||||
|
"--tags",
|
||||||
|
"--dirty",
|
||||||
|
"--always",
|
||||||
|
"--long",
|
||||||
|
"--match",
|
||||||
|
"%s*" % tag_prefix,
|
||||||
|
],
|
||||||
|
cwd=root,
|
||||||
|
)
|
||||||
# --long was added in git-1.5.5
|
# --long was added in git-1.5.5
|
||||||
if describe_out is None:
|
if describe_out is None:
|
||||||
raise NotThisMethod("'git describe' failed")
|
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")
|
dirty = git_describe.endswith("-dirty")
|
||||||
pieces["dirty"] = dirty
|
pieces["dirty"] = dirty
|
||||||
if dirty:
|
if dirty:
|
||||||
git_describe = git_describe[:git_describe.rindex("-dirty")]
|
git_describe = git_describe[: git_describe.rindex("-dirty")]
|
||||||
|
|
||||||
# figure out our branch
|
# figure out our branch
|
||||||
abbrev_ref_out = run_command(GITS,
|
abbrev_ref_out = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
|
||||||
["rev-parse", "--abbrev-ref", "HEAD"],
|
|
||||||
cwd=root)
|
|
||||||
if abbrev_ref_out is not None and abbrev_ref_out != "HEAD":
|
if abbrev_ref_out is not None and abbrev_ref_out != "HEAD":
|
||||||
pieces["branch"] = abbrev_ref_out.strip()
|
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:
|
if "-" in git_describe:
|
||||||
# TAG-NUM-gHEX
|
# 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:
|
if not mo:
|
||||||
# unparseable. Maybe git-describe is misbehaving?
|
# unparseable. Maybe git-describe is misbehaving?
|
||||||
pieces["error"] = ("unable to parse git-describe output: '%s'"
|
pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
|
||||||
% describe_out)
|
|
||||||
return pieces
|
return pieces
|
||||||
|
|
||||||
# tag
|
# tag
|
||||||
@@ -277,10 +302,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
|||||||
if verbose:
|
if verbose:
|
||||||
fmt = "tag '%s' doesn't start with prefix '%s'"
|
fmt = "tag '%s' doesn't start with prefix '%s'"
|
||||||
print(fmt % (full_tag, tag_prefix))
|
print(fmt % (full_tag, tag_prefix))
|
||||||
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
|
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
|
||||||
% (full_tag, tag_prefix))
|
full_tag,
|
||||||
|
tag_prefix,
|
||||||
|
)
|
||||||
return pieces
|
return pieces
|
||||||
pieces["closest-tag"] = full_tag[len(tag_prefix):]
|
pieces["closest-tag"] = full_tag[len(tag_prefix) :]
|
||||||
|
|
||||||
# distance: number of commits since tag
|
# distance: number of commits since tag
|
||||||
pieces["distance"] = int(mo.group(2))
|
pieces["distance"] = int(mo.group(2))
|
||||||
@@ -291,8 +318,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
|||||||
else:
|
else:
|
||||||
# HEX: no tags
|
# HEX: no tags
|
||||||
pieces["closest-tag"] = None
|
pieces["closest-tag"] = None
|
||||||
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
|
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root)
|
||||||
cwd=root)
|
|
||||||
pieces["distance"] = int(count_out) # total number of commits
|
pieces["distance"] = int(count_out) # total number of commits
|
||||||
|
|
||||||
return pieces
|
return pieces
|
||||||
@@ -309,11 +335,12 @@ def git_parse_lookup_file(path):
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
lookup = []
|
lookup = []
|
||||||
with io.open(path, "rt", encoding="utf-8") as f:
|
with io.open(path, "rt", encoding="utf-8") as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
if '#' in line:
|
if "#" in line:
|
||||||
line = line[:line.index("#")]
|
line = line[: line.index("#")]
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if not line:
|
if not line:
|
||||||
continue
|
continue
|
||||||
@@ -353,8 +380,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
|
|||||||
if sys.platform == "win32":
|
if sys.platform == "win32":
|
||||||
GITS = ["git.cmd", "git.exe"]
|
GITS = ["git.cmd", "git.exe"]
|
||||||
|
|
||||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
|
||||||
cwd=root)
|
|
||||||
if stdout is None:
|
if stdout is None:
|
||||||
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
|
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:
|
for matcher, render, tag, ref_commit in lookup:
|
||||||
if matcher.match(current_branch):
|
if matcher.match(current_branch):
|
||||||
if tag is None or ref_commit is None:
|
if tag is None or ref_commit is None:
|
||||||
raise NotThisMethod("tag or ref_commit is unset for "
|
raise NotThisMethod("tag or ref_commit is unset for " "this branch")
|
||||||
"this branch")
|
|
||||||
|
|
||||||
stdout = run_command(GITS,
|
stdout = run_command(
|
||||||
["rev-list", "%s..HEAD" % ref_commit,
|
GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root
|
||||||
"--count"],
|
)
|
||||||
cwd=root)
|
|
||||||
if stdout is None:
|
if stdout is None:
|
||||||
raise NotThisMethod("git rev-list %s..HEAD "
|
raise NotThisMethod(
|
||||||
"--count failed" % ref_commit)
|
"git rev-list %s..HEAD " "--count failed" % ref_commit
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
num_commits = int(stdout.strip())
|
num_commits = int(stdout.strip())
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise NotThisMethod("git rev-list %s..HEAD --count didn't "
|
raise NotThisMethod(
|
||||||
"return a valid number" % ref_commit)
|
"git rev-list %s..HEAD --count didn't "
|
||||||
|
"return a valid number" % ref_commit
|
||||||
|
)
|
||||||
|
|
||||||
stdout = run_command(GITS,
|
stdout = run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
|
||||||
["rev-parse", "--short", "HEAD"],
|
|
||||||
cwd=root)
|
|
||||||
if stdout is None:
|
if stdout is None:
|
||||||
raise NotThisMethod("git describe rev-parse "
|
raise NotThisMethod("git describe rev-parse " "--short HEAD failed")
|
||||||
"--short HEAD failed")
|
|
||||||
short_hash = stdout.strip()
|
short_hash = stdout.strip()
|
||||||
|
|
||||||
stdout = run_command(GITS,
|
stdout = run_command(
|
||||||
["describe", "--tags",
|
GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root
|
||||||
"--dirty", "--always"],
|
)
|
||||||
cwd=root)
|
|
||||||
if stdout is None:
|
if stdout is None:
|
||||||
raise NotThisMethod("git describe --tags --dirty "
|
raise NotThisMethod("git describe --tags --dirty " "--always failed")
|
||||||
"--always failed")
|
|
||||||
dirty = stdout.strip().endswith("-dirty")
|
dirty = stdout.strip().endswith("-dirty")
|
||||||
|
|
||||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
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,
|
"closest-tag": tag,
|
||||||
"distance": num_commits,
|
"distance": num_commits,
|
||||||
"error": None,
|
"error": None,
|
||||||
"render": render
|
"render": render,
|
||||||
}
|
}
|
||||||
|
|
||||||
raise NotThisMethod("no matching lookup definition found")
|
raise NotThisMethod("no matching lookup definition found")
|
||||||
@@ -442,8 +464,7 @@ def render_pep440(pieces):
|
|||||||
rendered += ".dirty"
|
rendered += ".dirty"
|
||||||
else:
|
else:
|
||||||
# exception #1
|
# exception #1
|
||||||
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
|
rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
|
||||||
pieces["short"])
|
|
||||||
if pieces["dirty"]:
|
if pieces["dirty"]:
|
||||||
rendered += ".dirty"
|
rendered += ".dirty"
|
||||||
return rendered
|
return rendered
|
||||||
@@ -603,10 +624,12 @@ def render_git_describe_long(pieces):
|
|||||||
def render(pieces, style):
|
def render(pieces, style):
|
||||||
"""Render the given version pieces into the requested style."""
|
"""Render the given version pieces into the requested style."""
|
||||||
if pieces["error"]:
|
if pieces["error"]:
|
||||||
return {"version": "unknown",
|
return {
|
||||||
"full-revisionid": pieces.get("long"),
|
"version": "unknown",
|
||||||
"dirty": None,
|
"full-revisionid": pieces.get("long"),
|
||||||
"error": pieces["error"]}
|
"dirty": None,
|
||||||
|
"error": pieces["error"],
|
||||||
|
}
|
||||||
|
|
||||||
if "render" in pieces and pieces["render"] is not None:
|
if "render" in pieces and pieces["render"] is not None:
|
||||||
style = pieces["render"]
|
style = pieces["render"]
|
||||||
@@ -633,8 +656,12 @@ def render(pieces, style):
|
|||||||
else:
|
else:
|
||||||
raise ValueError("unknown style '%s'" % style)
|
raise ValueError("unknown style '%s'" % style)
|
||||||
|
|
||||||
result = {"version": rendered, "full-revisionid": pieces["long"],
|
result = {
|
||||||
"dirty": pieces["dirty"], "error": None}
|
"version": rendered,
|
||||||
|
"full-revisionid": pieces["long"],
|
||||||
|
"dirty": pieces["dirty"],
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
if "branch" in pieces and pieces["branch"] is not None:
|
if "branch" in pieces and pieces["branch"] is not None:
|
||||||
result["branch"] = pieces["branch"]
|
result["branch"] = pieces["branch"]
|
||||||
return result
|
return result
|
||||||
@@ -651,8 +678,7 @@ def get_versions():
|
|||||||
verbose = cfg.verbose
|
verbose = cfg.verbose
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
|
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
|
||||||
verbose)
|
|
||||||
except NotThisMethod:
|
except NotThisMethod:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -661,14 +687,17 @@ def get_versions():
|
|||||||
# versionfile_source is the relative path from the top of the source
|
# versionfile_source is the relative path from the top of the source
|
||||||
# tree (where the .git directory might live) to this file. Invert
|
# tree (where the .git directory might live) to this file. Invert
|
||||||
# this to find the root from __file__.
|
# 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)
|
root = os.path.dirname(root)
|
||||||
except NameError:
|
except NameError:
|
||||||
return {"version": "0+unknown", "full-revisionid": None,
|
return {
|
||||||
"dirty": None,
|
"version": "0+unknown",
|
||||||
"error": "unable to find root of source tree"}
|
"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)
|
lookuppath = os.path.join(root, lookupfile)
|
||||||
if os.path.exists(lookuppath):
|
if os.path.exists(lookuppath):
|
||||||
try:
|
try:
|
||||||
@@ -690,6 +719,9 @@ def get_versions():
|
|||||||
except NotThisMethod:
|
except NotThisMethod:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
return {"version": "0+unknown", "full-revisionid": None,
|
return {
|
||||||
"dirty": None,
|
"version": "0+unknown",
|
||||||
"error": "unable to compute version"}
|
"full-revisionid": None,
|
||||||
|
"dirty": None,
|
||||||
|
"error": "unable to compute version",
|
||||||
|
}
|
||||||
+591
-453
File diff suppressed because it is too large.
Load diff
+369
-294
@@ -2,391 +2,466 @@
|
|||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||||
|
|
||||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
__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"
|
__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 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
|
# noinspection PyCompatibility
|
||||||
from past.builtins import basestring
|
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):
|
class OctoPrintPermission(Permission):
|
||||||
@classmethod
|
@classmethod
|
||||||
def convert_needs_to_dict(cls, needs):
|
def convert_needs_to_dict(cls, needs):
|
||||||
ret_needs = defaultdict(list)
|
ret_needs = defaultdict(list)
|
||||||
for need in needs:
|
for need in needs:
|
||||||
if need.value not in ret_needs[need.method]:
|
if need.value not in ret_needs[need.method]:
|
||||||
ret_needs[need.method].append(need.value)
|
ret_needs[need.method].append(need.value)
|
||||||
return ret_needs
|
return ret_needs
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def convert_to_needs(cls, needs):
|
def convert_to_needs(cls, needs):
|
||||||
result = []
|
result = []
|
||||||
for need in needs:
|
for need in needs:
|
||||||
# noinspection PyCompatibility
|
# noinspection PyCompatibility
|
||||||
if isinstance(need, Need):
|
if isinstance(need, Need):
|
||||||
result.append(need)
|
result.append(need)
|
||||||
elif isinstance(need, Permission):
|
elif isinstance(need, Permission):
|
||||||
result += need.needs
|
result += need.needs
|
||||||
elif isinstance(need, basestring):
|
elif isinstance(need, basestring):
|
||||||
result.append(RoleNeed(need))
|
result.append(RoleNeed(need))
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def __init__(self, name, description, *needs, **kwargs):
|
def __init__(self, name, description, *needs, **kwargs):
|
||||||
self._name = name
|
self._name = name
|
||||||
self._description = description
|
self._description = description
|
||||||
self._dangerous = kwargs.pop("dangerous", False)
|
self._dangerous = kwargs.pop("dangerous", False)
|
||||||
self._default_groups = kwargs.pop("default_groups", [])
|
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):
|
def as_dict(self):
|
||||||
return dict(
|
return {
|
||||||
key=self.key,
|
"key": self.key,
|
||||||
name=self.get_name(),
|
"name": self.get_name(),
|
||||||
dangerous=self._dangerous,
|
"dangerous": self._dangerous,
|
||||||
default_groups=self._default_groups,
|
"default_groups": self._default_groups,
|
||||||
description=self.get_description(),
|
"description": self.get_description(),
|
||||||
needs=self.convert_needs_to_dict(self.needs)
|
"needs": self.convert_needs_to_dict(self.needs),
|
||||||
)
|
}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def key(self):
|
def key(self):
|
||||||
return self._key
|
return self._key
|
||||||
|
|
||||||
@key.setter
|
@key.setter
|
||||||
def key(self, value):
|
def key(self, value):
|
||||||
self._key = value
|
self._key = value
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def default_groups(self):
|
def dangerous(self):
|
||||||
return self._default_groups
|
return self._dangerous
|
||||||
|
|
||||||
def get_name(self):
|
@property
|
||||||
return self._name
|
def default_groups(self):
|
||||||
|
return self._default_groups
|
||||||
|
|
||||||
def get_description(self):
|
def get_name(self):
|
||||||
return self._description
|
return self._name
|
||||||
|
|
||||||
def allows(self, identity):
|
def get_description(self):
|
||||||
"""Whether the identity can access this permission.
|
return self._description
|
||||||
Overridden from Permission.allows to make sure the Identity provides ALL
|
|
||||||
required needs instead of ANY required need.
|
|
||||||
|
|
||||||
:param identity: The identity
|
def allows(self, identity):
|
||||||
"""
|
"""Whether the identity can access this permission.
|
||||||
if self.needs and len(self.needs.intersection(identity.provides)) != len(self.needs):
|
Overridden from Permission.allows to make sure the Identity provides ALL
|
||||||
return False
|
required needs instead of ANY required need.
|
||||||
|
|
||||||
if self.excludes and self.excludes.intersection(identity.provides):
|
:param identity: The identity
|
||||||
return False
|
"""
|
||||||
|
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):
|
def union(self, other):
|
||||||
"""Create a new OctoPrintPermission with the requirements of the union of this
|
"""Create a new OctoPrintPermission with the requirements of the union of this
|
||||||
and other.
|
and other.
|
||||||
|
|
||||||
:param other: The other permission
|
:param other: The other permission
|
||||||
"""
|
"""
|
||||||
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
|
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
|
||||||
p.excludes.update(self.excludes.union(other.excludes))
|
p.excludes.update(self.excludes.union(other.excludes))
|
||||||
return p
|
return p
|
||||||
|
|
||||||
def difference(self, other):
|
def difference(self, other):
|
||||||
"""Create a new OctoPrintPermission consisting of requirements in this
|
"""Create a new OctoPrintPermission consisting of requirements in this
|
||||||
permission and not in the other.
|
permission and not in the other.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
|
p = self.__class__(
|
||||||
p.excludes.update(self.excludes.difference(other.excludes))
|
self._name, self._description, *self.needs.difference(other.needs)
|
||||||
return p
|
)
|
||||||
|
p.excludes.update(self.excludes.difference(other.excludes))
|
||||||
|
return p
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
|
return "{}({!r}, {!r}, {})".format(
|
||||||
self.get_name(),
|
self.__class__.__name__,
|
||||||
self.get_description(),
|
self.get_name(),
|
||||||
', '.join(map(repr, self.needs)))
|
self.get_description(),
|
||||||
|
", ".join(map(repr, self.needs)),
|
||||||
|
)
|
||||||
|
|
||||||
def __hash__(self):
|
def __hash__(self):
|
||||||
return self.get_name().__hash__()
|
return self.get_name().__hash__()
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
|
return (
|
||||||
|
isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class PluginOctoPrintPermission(OctoPrintPermission):
|
class PluginOctoPrintPermission(OctoPrintPermission):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.plugin = kwargs.pop("plugin", None)
|
||||||
|
OctoPrintPermission.__init__(self, *args, **kwargs)
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def as_dict(self):
|
||||||
self.plugin = kwargs.pop("plugin", None)
|
result = OctoPrintPermission.as_dict(self)
|
||||||
OctoPrintPermission.__init__(self, *args, **kwargs)
|
result["plugin"] = self.plugin
|
||||||
|
return result
|
||||||
def as_dict(self):
|
|
||||||
result = OctoPrintPermission.as_dict(self)
|
|
||||||
result["plugin"] = self.plugin
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
class PluginIdentityContext(object):
|
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
|
Will search the permission when needed
|
||||||
"""
|
"""
|
||||||
def __init__(self, key, http_exception=None):
|
|
||||||
self.key = key
|
|
||||||
self.http_exception = http_exception
|
|
||||||
"""The permission of this principal
|
|
||||||
"""
|
|
||||||
|
|
||||||
@property
|
def __init__(self, key, http_exception=None):
|
||||||
def identity(self):
|
self.key = key
|
||||||
"""The identity of this principal
|
self.http_exception = http_exception
|
||||||
"""
|
"""The permission of this principal
|
||||||
return g.identity
|
"""
|
||||||
|
|
||||||
def can(self):
|
@property
|
||||||
"""Whether the identity has access to the permission
|
def identity(self):
|
||||||
"""
|
"""The identity of this principal"""
|
||||||
permission = getattr(Permissions, self.key)
|
return g.identity
|
||||||
if permission is None or isinstance(permission, PluginPermissionDecorator):
|
|
||||||
raise UnknownPermission(self.key)
|
|
||||||
|
|
||||||
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):
|
return permission.can()
|
||||||
@wraps(f)
|
|
||||||
def _decorated(*args, **kw):
|
|
||||||
with self:
|
|
||||||
rv = f(*args, **kw)
|
|
||||||
return rv
|
|
||||||
|
|
||||||
return _decorated
|
def __call__(self, f):
|
||||||
|
@wraps(f)
|
||||||
|
def _decorated(*args, **kw):
|
||||||
|
with self:
|
||||||
|
rv = f(*args, **kw)
|
||||||
|
return rv
|
||||||
|
|
||||||
def __enter__(self):
|
return _decorated
|
||||||
permission = getattr(Permissions, self.key)
|
|
||||||
if permission is None or isinstance(permission, PluginPermissionDecorator):
|
|
||||||
raise UnknownPermission(self.key)
|
|
||||||
|
|
||||||
# check the permission here
|
def __enter__(self):
|
||||||
if not permission.can():
|
permission = getattr(Permissions, self.key)
|
||||||
if self.http_exception:
|
if permission is None or isinstance(permission, PluginPermissionDecorator):
|
||||||
abort(self.http_exception, permission)
|
raise UnknownPermission(self.key)
|
||||||
raise PermissionDenied(permission)
|
|
||||||
|
|
||||||
def __exit__(self, *args):
|
# check the permission here
|
||||||
return False
|
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):
|
class PluginPermissionDecorator(Permission):
|
||||||
"""Decorator Class for not initialized Permissions
|
"""Decorator Class for not initialized Permissions
|
||||||
|
|
||||||
Needed to support @Permissions.PLUGIN_X_Y.require()
|
Needed to support @Permissions.PLUGIN_X_Y.require()
|
||||||
"""
|
"""
|
||||||
def __init__(self, key):
|
|
||||||
self.key = key
|
|
||||||
|
|
||||||
def require(self, http_exception=None):
|
def __init__(self, key):
|
||||||
return PluginIdentityContext(self.key, http_exception)
|
self.key = key
|
||||||
|
|
||||||
|
def require(self, http_exception=None):
|
||||||
|
return PluginIdentityContext(self.key, http_exception)
|
||||||
|
|
||||||
|
|
||||||
class PermissionsMetaClass(type):
|
class PermissionsMetaClass(type):
|
||||||
permissions = OrderedDict()
|
permissions = OrderedDict()
|
||||||
|
|
||||||
def __new__(mcs, name, bases, args):
|
def __new__(mcs, name, bases, args):
|
||||||
cls = type.__new__(mcs, name, bases, args)
|
cls = type.__new__(mcs, name, bases, args)
|
||||||
|
|
||||||
for key, value in args.items():
|
for key, value in args.items():
|
||||||
if isinstance(value, OctoPrintPermission):
|
if isinstance(value, OctoPrintPermission):
|
||||||
value.key = key
|
value.key = key
|
||||||
mcs.permissions[key] = value
|
mcs.permissions[key] = value
|
||||||
delattr(cls, key)
|
delattr(cls, key)
|
||||||
|
|
||||||
return cls
|
return cls
|
||||||
|
|
||||||
def __setattr__(cls, key, value):
|
def __setattr__(cls, key, value):
|
||||||
if isinstance(value, OctoPrintPermission):
|
if isinstance(value, OctoPrintPermission):
|
||||||
if key in cls.permissions:
|
if key in cls.permissions:
|
||||||
raise PermissionAlreadyExists(key)
|
raise PermissionAlreadyExists(key)
|
||||||
value.key = key
|
value.key = key
|
||||||
cls.permissions[key] = value
|
cls.permissions[key] = value
|
||||||
|
|
||||||
def __getattr__(cls, key):
|
def __getattr__(cls, key):
|
||||||
permission = cls.permissions.get(key)
|
permission = cls.permissions.get(key)
|
||||||
|
|
||||||
if key.startswith("PLUGIN_") and permission is None:
|
if key.startswith("PLUGIN_") and permission is None:
|
||||||
return PluginPermissionDecorator(key)
|
return PluginPermissionDecorator(key)
|
||||||
|
|
||||||
return permission
|
return permission
|
||||||
|
|
||||||
def all(cls):
|
def all(cls):
|
||||||
return list(cls.permissions.values())
|
return list(cls.permissions.values())
|
||||||
|
|
||||||
def filter(cls, cb):
|
def filter(cls, cb):
|
||||||
return list(filter(cb, cls.all()))
|
return list(filter(cb, cls.all()))
|
||||||
|
|
||||||
def find(cls, p, filter=None):
|
def find(cls, p, filter=None):
|
||||||
key = None
|
key = None
|
||||||
if isinstance(p, OctoPrintPermission):
|
if isinstance(p, OctoPrintPermission):
|
||||||
key = p.key
|
key = p.key
|
||||||
elif isinstance(p, dict):
|
elif isinstance(p, dict):
|
||||||
key = p.get("key")
|
key = p.get("key")
|
||||||
elif isinstance(p, basestring):
|
elif isinstance(p, basestring):
|
||||||
key = p
|
key = p
|
||||||
|
|
||||||
if key is None:
|
if key is None:
|
||||||
return 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):
|
def match(cls, match, filter=None):
|
||||||
if callable(filter):
|
if callable(filter):
|
||||||
permissions = cls.filter(filter)
|
permissions = cls.filter(filter)
|
||||||
else:
|
else:
|
||||||
permissions = cls.all()
|
permissions = cls.all()
|
||||||
|
|
||||||
for permission in permissions:
|
for permission in permissions:
|
||||||
if match(permission):
|
if match(permission):
|
||||||
return permission
|
return permission
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
class Permissions(with_metaclass(PermissionsMetaClass)):
|
class Permissions(with_metaclass(PermissionsMetaClass)):
|
||||||
|
|
||||||
# Special permission
|
# Special permission
|
||||||
ADMIN = OctoPrintPermission("Admin",
|
ADMIN = OctoPrintPermission(
|
||||||
gettext("Admin is allowed to do everything"),
|
"Admin",
|
||||||
RoleNeed("admin"),
|
gettext("Admin is allowed to do everything"),
|
||||||
dangerous=True,
|
RoleNeed("admin"),
|
||||||
default_groups=[ADMIN_GROUP])
|
dangerous=True,
|
||||||
|
default_groups=[ADMIN_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
STATUS = OctoPrintPermission("Status",
|
STATUS = OctoPrintPermission(
|
||||||
gettext("Allows to gather basic status information, e.g. job progress, "
|
"Status",
|
||||||
"printer state, temperatures, ... Mandatory for the default UI "
|
gettext(
|
||||||
"to work"),
|
"Allows to gather basic status information, e.g. job progress, "
|
||||||
RoleNeed("status"),
|
"printer state, temperatures, ... Mandatory for the default UI "
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
"to work"
|
||||||
|
),
|
||||||
|
RoleNeed("status"),
|
||||||
|
default_groups=[USER_GROUP, READONLY_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
CONNECTION = OctoPrintPermission("Connection",
|
CONNECTION = OctoPrintPermission(
|
||||||
gettext("Allows to connect to and disconnect from a printer"),
|
"Connection",
|
||||||
RoleNeed("connection"),
|
gettext("Allows to connect to and disconnect from a printer"),
|
||||||
default_groups=[USER_GROUP])
|
RoleNeed("connection"),
|
||||||
|
default_groups=[USER_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
WEBCAM = OctoPrintPermission("Webcam",
|
WEBCAM = OctoPrintPermission(
|
||||||
gettext("Allows to watch the webcam stream"),
|
"Webcam",
|
||||||
RoleNeed("webcam"),
|
gettext("Allows to watch the webcam stream"),
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
RoleNeed("webcam"),
|
||||||
|
default_groups=[USER_GROUP, READONLY_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
SYSTEM = OctoPrintPermission("System",
|
SYSTEM = OctoPrintPermission(
|
||||||
gettext("Allows to run system commands, e.g. restart OctoPrint, "
|
"System",
|
||||||
"shutdown or reboot the system"),
|
gettext(
|
||||||
RoleNeed("system"),
|
"Allows to run system commands, e.g. restart OctoPrint, "
|
||||||
dangerous=True)
|
"shutdown or reboot the system, and to retrieve system and usage information"
|
||||||
|
),
|
||||||
|
RoleNeed("system"),
|
||||||
|
dangerous=True,
|
||||||
|
)
|
||||||
|
|
||||||
FILES_LIST = OctoPrintPermission("File List",
|
FILES_LIST = OctoPrintPermission(
|
||||||
gettext("Allows to retrieve a list of all uploaded files and folders, including"
|
"File List",
|
||||||
"their metadata (e.g. date, file size, analysis results, ...)"),
|
gettext(
|
||||||
RoleNeed("files_list"),
|
"Allows to retrieve a list of all uploaded files and folders, including"
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
"their metadata (e.g. date, file size, analysis results, ...)"
|
||||||
FILES_UPLOAD = OctoPrintPermission("File Upload",
|
),
|
||||||
gettext("Allows users to upload new files, create new folders and copy existing ones. If "
|
RoleNeed("files_list"),
|
||||||
"the File Delete permission is also set, File Upload also allows "
|
default_groups=[USER_GROUP, READONLY_GROUP],
|
||||||
"moving files and folders."),
|
)
|
||||||
RoleNeed("files_upload"),
|
FILES_UPLOAD = OctoPrintPermission(
|
||||||
default_groups=[USER_GROUP])
|
"File Upload",
|
||||||
FILES_DOWNLOAD = OctoPrintPermission("File Download",
|
gettext(
|
||||||
gettext("Allows users to download files. The GCODE viewer is "
|
"Allows users to upload new files, create new folders and copy existing ones. If "
|
||||||
"affected by this as well."),
|
"the File Delete permission is also set, File Upload also allows "
|
||||||
RoleNeed("files_download"),
|
"moving files and folders."
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
),
|
||||||
FILES_DELETE = OctoPrintPermission("File Delete",
|
RoleNeed("files_upload"),
|
||||||
gettext("Allows users to delete files and folders. If the File Upload permission is "
|
default_groups=[USER_GROUP],
|
||||||
"also set, File Delete also allows moving files and folders."),
|
)
|
||||||
RoleNeed("files_delete"),
|
FILES_DOWNLOAD = OctoPrintPermission(
|
||||||
default_groups=[USER_GROUP])
|
"File Download",
|
||||||
FILES_SELECT = OctoPrintPermission("File Select",
|
gettext(
|
||||||
gettext("Allows to select a file for printing"),
|
"Allows users to download files. The GCODE viewer is "
|
||||||
RoleNeed("files_select"),
|
"affected by this as well."
|
||||||
default_groups=[USER_GROUP])
|
),
|
||||||
|
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",
|
PRINT = OctoPrintPermission(
|
||||||
gettext("Allows to start, pause and cancel a print job"),
|
"Print",
|
||||||
RoleNeed("print"),
|
gettext("Allows to start, pause and cancel a print job"),
|
||||||
default_groups=[USER_GROUP])
|
RoleNeed("print"),
|
||||||
|
default_groups=[USER_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
|
GCODE_VIEWER = OctoPrintPermission(
|
||||||
gettext("Allows access to the GCODE viewer if the \"File Download\""
|
"GCODE viewer",
|
||||||
"permission is also set."),
|
gettext(
|
||||||
RoleNeed("gcodeviewer"),
|
'Allows access to the GCODE viewer if the "File Download"'
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
"permission is also set."
|
||||||
|
),
|
||||||
|
RoleNeed("gcodeviewer"),
|
||||||
|
default_groups=[USER_GROUP, READONLY_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
|
MONITOR_TERMINAL = OctoPrintPermission(
|
||||||
gettext("Allows to watch the terminal tab but not to send commands "
|
"Terminal",
|
||||||
"to the printer from it"),
|
gettext(
|
||||||
RoleNeed("monitor_terminal"),
|
"Allows to watch the terminal tab but not to send commands "
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
"to the printer from it"
|
||||||
|
),
|
||||||
|
RoleNeed("monitor_terminal"),
|
||||||
|
default_groups=[USER_GROUP, READONLY_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
CONTROL = OctoPrintPermission("Control",
|
CONTROL = OctoPrintPermission(
|
||||||
gettext("Allows to control of the printer by using the temperature controls,"
|
"Control",
|
||||||
"the control tab or sending commands through the terminal."),
|
gettext(
|
||||||
RoleNeed("control"),
|
"Allows to control of the printer by using the temperature controls,"
|
||||||
default_groups=[USER_GROUP])
|
"the control tab or sending commands through the terminal."
|
||||||
|
),
|
||||||
|
RoleNeed("control"),
|
||||||
|
default_groups=[USER_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
SLICE = OctoPrintPermission("Slice",
|
SLICE = OctoPrintPermission(
|
||||||
gettext("Allows to slice files"),
|
"Slice",
|
||||||
RoleNeed("slice"),
|
gettext("Allows to slice files"),
|
||||||
default_groups=[USER_GROUP])
|
RoleNeed("slice"),
|
||||||
|
default_groups=[USER_GROUP],
|
||||||
|
)
|
||||||
|
|
||||||
TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
|
TIMELAPSE_LIST = OctoPrintPermission(
|
||||||
gettext("Allows to list timelapse videos"),
|
"Timelapse List",
|
||||||
RoleNeed("timelapse_list"),
|
gettext("Allows to list timelapse videos"),
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
RoleNeed("timelapse_list"),
|
||||||
TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
|
default_groups=[USER_GROUP, READONLY_GROUP],
|
||||||
gettext("Allows to download timelapse videos"),
|
)
|
||||||
RoleNeed("timelapse_download"),
|
TIMELAPSE_DOWNLOAD = OctoPrintPermission(
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
"Timelapse Download",
|
||||||
TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
|
gettext("Allows to download timelapse videos"),
|
||||||
gettext("Allows to delete timelapse videos and unrendered timelapses"),
|
RoleNeed("timelapse_download"),
|
||||||
RoleNeed("timelapse_delete"),
|
default_groups=[USER_GROUP, READONLY_GROUP],
|
||||||
default_groups=[USER_GROUP])
|
)
|
||||||
TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
|
TIMELAPSE_DELETE = OctoPrintPermission(
|
||||||
gettext("Allows to change the timelapse settings and delete or "
|
"Timelapse Delete",
|
||||||
"render unrendered timelapses. Includes the \"Timelapse List\","
|
gettext("Allows to delete timelapse videos and unrendered timelapses"),
|
||||||
"\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
|
RoleNeed("timelapse_delete"),
|
||||||
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
|
default_groups=[USER_GROUP],
|
||||||
default_groups=[USER_GROUP])
|
)
|
||||||
|
TIMELAPSE_ADMIN = OctoPrintPermission(
|
||||||
SETTINGS_READ = OctoPrintPermission("Settings Access",
|
"Timelapse Admin",
|
||||||
gettext("Allows to read non sensitive settings. Mandatory for the "
|
gettext(
|
||||||
"default UI to work."),
|
"Allows to change the timelapse settings and delete or "
|
||||||
RoleNeed("settings_read"),
|
'render unrendered timelapses. Includes the "Timelapse List",'
|
||||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
'"Timelapse Delete" and "Timelapse Download" permissions'
|
||||||
SETTINGS = OctoPrintPermission("Settings Admin",
|
),
|
||||||
gettext("Allows to manage settings and also to read sensitive settings"),
|
RoleNeed("timelapse_admin"),
|
||||||
RoleNeed("settings"),
|
TIMELAPSE_LIST,
|
||||||
dangerous=True)
|
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):
|
class PermissionAlreadyExists(Exception):
|
||||||
def __init__(self, permission):
|
def __init__(self, permission):
|
||||||
Exception.__init__(self, "Permission %s already exists" % permission)
|
Exception.__init__(self, "Permission %s already exists" % permission)
|
||||||
|
|
||||||
|
|
||||||
class UnknownPermission(Exception):
|
class UnknownPermission(Exception):
|
||||||
def __init__(self, permissionname):
|
def __init__(self, permissionname):
|
||||||
Exception.__init__(self, "Unknown permission: %s" % permissionname)
|
Exception.__init__(self, "Unknown permission: %s" % permissionname)
|
||||||
+1297
-1135
File diff suppressed because it is too large.
Load diff
+281
-120
@@ -1,177 +1,338 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
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"
|
__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
|
import sys
|
||||||
|
|
||||||
#~~ click context
|
import click
|
||||||
|
|
||||||
|
import octoprint
|
||||||
|
|
||||||
|
click.disable_unicode_literals_warning = True
|
||||||
|
|
||||||
|
|
||||||
|
# ~~ click context
|
||||||
|
|
||||||
|
|
||||||
class OctoPrintContext(object):
|
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)
|
pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True)
|
||||||
"""Decorator to pass in the :class:`OctoPrintContext` instance."""
|
"""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):
|
class HiddenOption(click.Option):
|
||||||
"""Custom option sub class with empty help."""
|
"""Custom option sub class with empty help."""
|
||||||
def get_help_record(self, ctx):
|
|
||||||
pass
|
def get_help_record(self, ctx):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def hidden_option(*param_decls, **attrs):
|
def hidden_option(*param_decls, **attrs):
|
||||||
"""Attaches a hidden option to the command. All positional arguments are
|
"""Attaches a hidden option to the command. All positional arguments are
|
||||||
passed as parameter declarations to :class:`Option`; all keyword
|
passed as parameter declarations to :class:`Option`; all keyword
|
||||||
arguments are forwarded unchanged. This is equivalent to creating an
|
arguments are forwarded unchanged. This is equivalent to creating an
|
||||||
:class:`Option` instance manually and attaching it to the
|
:class:`Option` instance manually and attaching it to the
|
||||||
:attr:`Command.params` list.
|
:attr:`Command.params` list.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import inspect
|
import inspect
|
||||||
from click.decorators import _param_memo
|
|
||||||
|
|
||||||
def decorator(f):
|
from click.decorators import _param_memo
|
||||||
if 'help' in attrs:
|
|
||||||
attrs['help'] = inspect.cleandoc(attrs['help'])
|
def decorator(f):
|
||||||
_param_memo(f, HiddenOption(param_decls, **attrs))
|
if "help" in attrs:
|
||||||
return f
|
attrs["help"] = inspect.cleandoc(attrs["help"])
|
||||||
return decorator
|
_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):
|
def set_ctx_obj_option(ctx, param, value):
|
||||||
"""Helper for setting eager options on the context."""
|
"""Helper for setting eager options on the context."""
|
||||||
if ctx.obj is None:
|
if ctx.obj is None:
|
||||||
ctx.obj = OctoPrintContext()
|
ctx.obj = OctoPrintContext()
|
||||||
if value != param.default:
|
if value != param.default:
|
||||||
setattr(ctx.obj, param.name, value)
|
setattr(ctx.obj, param.name, value)
|
||||||
elif param.default is not None:
|
elif param.default is not None:
|
||||||
setattr(ctx.obj, param.name, param.default)
|
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):
|
def get_ctx_obj_option(ctx, key, default, include_parents=True):
|
||||||
if include_parents and hasattr(ctx, "parent") and ctx.parent:
|
if include_parents and hasattr(ctx, "parent") and ctx.parent:
|
||||||
fallback = get_ctx_obj_option(ctx.parent, key, default)
|
fallback = get_ctx_obj_option(ctx.parent, key, default)
|
||||||
else:
|
else:
|
||||||
fallback = default
|
fallback = default
|
||||||
return getattr(ctx.obj, key, fallback)
|
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):
|
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
|
The provided list of ``options`` will be reversed to ensure correct
|
||||||
processing order (inverse from what would be intuitive).
|
processing order (inverse from what would be intuitive).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def decorator(f):
|
def decorator(f):
|
||||||
options.reverse()
|
options.reverse()
|
||||||
for option in options:
|
for option in options:
|
||||||
option(f)
|
option(f)
|
||||||
return f
|
return f
|
||||||
return decorator
|
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
|
# ~~ helper for setting --basedir, --config and --verbose options
|
||||||
|
|
||||||
#~~ helper for setting --basedir, --config and --verbose options
|
|
||||||
|
|
||||||
def standard_options(hidden=False):
|
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``
|
Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden``
|
||||||
is set to ``True``, the options will be available on the command but not
|
is set to ``True``, the options will be available on the command but not
|
||||||
listed in its help page.
|
listed in its help page.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
factory = click.option
|
factory = click.option
|
||||||
if hidden:
|
if hidden:
|
||||||
factory = hidden_option
|
factory = hidden_option
|
||||||
|
|
||||||
options = [
|
options = [
|
||||||
factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
factory(
|
||||||
help="Specify the basedir to use for configs, uploads, timelapses etc."),
|
"--basedir",
|
||||||
factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
"-b",
|
||||||
help="Specify the config file to use."),
|
type=click.Path(),
|
||||||
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
callback=set_ctx_obj_option,
|
||||||
help="Increase logging verbosity."),
|
is_eager=True,
|
||||||
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
expose_value=False,
|
||||||
help="Enable safe mode; disables all third party plugins.")
|
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([
|
# ~~ helper for settings legacy options we still have to support on "octoprint"
|
||||||
hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option),
|
|
||||||
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
|
legacy_options = bulk_options(
|
||||||
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("--host", type=click.STRING, callback=set_ctx_obj_option),
|
||||||
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option),
|
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
|
||||||
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option),
|
hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option),
|
||||||
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option),
|
hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option),
|
||||||
hidden_option("--ignore-blacklist", "ignore_blacklist", 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.
|
"""Legacy options available directly on the "octoprint" command in earlier versions.
|
||||||
Kept available for reasons of backwards compatibility, but hidden from the
|
Kept available for reasons of backwards compatibility, but hidden from the
|
||||||
generated help pages."""
|
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 .analysis import analysis_commands # noqa: E402
|
||||||
from .plugins import plugin_commands
|
from .client import client_commands # noqa: E402
|
||||||
from .dev import dev_commands
|
from .config import config_commands # noqa: E402
|
||||||
from .client import client_commands
|
from .dev import dev_commands # noqa: E402
|
||||||
from .config import config_commands
|
from .plugins import plugin_commands # noqa: E402
|
||||||
from .analysis import analysis_commands
|
from .server import server_commands # noqa: E402
|
||||||
from .user import user_commands
|
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()
|
@standard_options()
|
||||||
@legacy_options
|
@legacy_options
|
||||||
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
|
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def octo(ctx, **kwargs):
|
def octo(ctx, **kwargs):
|
||||||
|
|
||||||
if ctx.invoked_subcommand is None:
|
if ctx.invoked_subcommand is None:
|
||||||
# We have to support calling the octoprint command without any
|
# We have to support calling the octoprint command without any
|
||||||
# sub commands to remain backwards compatible.
|
# sub commands to remain backwards compatible.
|
||||||
#
|
#
|
||||||
# But better print a message to inform people that they should
|
# But better print a message to inform people that they should
|
||||||
# use the sub commands instead.
|
# use the sub commands instead.
|
||||||
|
|
||||||
def get_value(key):
|
def get_value(key):
|
||||||
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
||||||
daemon = get_value("daemon")
|
|
||||||
|
|
||||||
if daemon:
|
daemon = get_value("daemon")
|
||||||
click.echo("Daemon operation via \"octoprint --daemon "
|
|
||||||
"start|stop|restart\" is deprecated, please use "
|
|
||||||
"\"octoprint daemon start|stop|restart\" from now on")
|
|
||||||
|
|
||||||
if sys.platform == "win32" or sys.platform == "darwin":
|
if daemon:
|
||||||
click.echo("Sorry, daemon mode is not supported under your operating system right now")
|
click.echo(
|
||||||
else:
|
'Daemon operation via "octoprint --daemon '
|
||||||
from octoprint.cli.server import daemon_command
|
'start|stop|restart" is deprecated, please use '
|
||||||
ctx.invoke(daemon_command, command=daemon, **kwargs)
|
'"octoprint daemon start|stop|restart" from now on'
|
||||||
else:
|
)
|
||||||
click.echo("Starting the server via \"octoprint\" is deprecated, "
|
|
||||||
"please use \"octoprint serve\" from now on.")
|
|
||||||
|
|
||||||
from octoprint.cli.server import serve_command
|
if sys.platform == "win32" or sys.platform == "darwin":
|
||||||
ctx.invoke(serve_command, **kwargs)
|
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)
|
||||||
@@ -1,22 +1,25 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
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"
|
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
import click
|
import click
|
||||||
|
|
||||||
click.disable_unicode_literals_warning = True
|
click.disable_unicode_literals_warning = True
|
||||||
|
|
||||||
#~~ "octoprint util" commands
|
# ~~ "octoprint util" commands
|
||||||
|
|
||||||
|
|
||||||
@click.group()
|
@click.group()
|
||||||
def analysis_commands():
|
def analysis_commands():
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@analysis_commands.group(name="analysis")
|
@analysis_commands.group(name="analysis")
|
||||||
def util():
|
def util():
|
||||||
"""Analysis tools."""
|
"""Analysis tools."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@util.command(name="gcode")
|
@util.command(name="gcode")
|
||||||
@@ -30,49 +33,75 @@ def util():
|
|||||||
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
|
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
|
||||||
@click.option("--progress", "progress", is_flag=True)
|
@click.option("--progress", "progress", is_flag=True)
|
||||||
@click.argument("path", type=click.Path())
|
@click.argument("path", type=click.Path())
|
||||||
def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
|
def gcode_command(
|
||||||
"""Runs a GCODE file analysis."""
|
path,
|
||||||
|
speedx,
|
||||||
|
speedy,
|
||||||
|
speedz,
|
||||||
|
offset,
|
||||||
|
maxt,
|
||||||
|
throttle,
|
||||||
|
throttle_lines,
|
||||||
|
g90_extruder,
|
||||||
|
progress,
|
||||||
|
):
|
||||||
|
"""Runs a GCODE file analysis."""
|
||||||
|
|
||||||
import time
|
import time
|
||||||
import yaml
|
|
||||||
from octoprint.util import monotonic_time
|
|
||||||
from octoprint.util.gcodeInterpreter import gcode
|
|
||||||
|
|
||||||
throttle_callback = None
|
import yaml
|
||||||
if throttle:
|
|
||||||
def throttle_callback(filePos, readBytes):
|
|
||||||
if filePos % throttle_lines == 0:
|
|
||||||
# only apply throttle every $throttle_lines lines
|
|
||||||
time.sleep(throttle)
|
|
||||||
|
|
||||||
offsets = offset
|
from octoprint.util import monotonic_time
|
||||||
if offsets is None:
|
from octoprint.util.gcodeInterpreter import gcode
|
||||||
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()
|
throttle_callback = None
|
||||||
|
if throttle:
|
||||||
|
|
||||||
progress_callback = None
|
def throttle_callback(filePos, readBytes):
|
||||||
if progress:
|
if filePos % throttle_lines == 0:
|
||||||
def progress_callback(percentage):
|
# only apply throttle every $throttle_lines lines
|
||||||
click.echo("PROGRESS:{}".format(percentage))
|
time.sleep(throttle)
|
||||||
interpreter = gcode(progress_callback=progress_callback)
|
|
||||||
|
|
||||||
interpreter.load(path,
|
offsets = offset
|
||||||
speedx=speedx,
|
if offsets is None:
|
||||||
speedy=speedy,
|
offsets = []
|
||||||
offsets=offsets,
|
elif isinstance(offset, tuple):
|
||||||
throttle=throttle_callback,
|
offsets = list(offsets)
|
||||||
max_extruders=maxt,
|
offsets = [(0, 0)] + offsets
|
||||||
g90_extruder=g90_extruder)
|
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__":
|
if __name__ == "__main__":
|
||||||
gcode_command()
|
gcode_command()
|
||||||
+207
-138
@@ -1,107 +1,125 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
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"
|
__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 io
|
||||||
import json
|
import json
|
||||||
|
|
||||||
import octoprint_client
|
import click
|
||||||
|
|
||||||
from octoprint.cli import get_ctx_obj_option, bulk_options
|
|
||||||
from octoprint import init_settings, FatalStartupError
|
|
||||||
|
|
||||||
from past.builtins import unicode
|
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):
|
class JsonStringParamType(click.ParamType):
|
||||||
name = "json"
|
name = "json"
|
||||||
|
|
||||||
def convert(self, value, param, ctx):
|
def convert(self, value, param, ctx):
|
||||||
try:
|
try:
|
||||||
return json.loads(value)
|
return json.loads(value)
|
||||||
except Exception:
|
except Exception:
|
||||||
self.fail("%s is not a valid json string" % value, param, ctx)
|
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):
|
def create_client(
|
||||||
assert(host is not None or settings is not None)
|
settings=None,
|
||||||
assert(port is not None or settings is not None)
|
apikey=None,
|
||||||
assert(apikey is not None or settings is not 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:
|
if not host:
|
||||||
host = settings.get(["server", "host"])
|
host = settings.get(["server", "host"])
|
||||||
host = host if host != "0.0.0.0" else "127.0.0.1"
|
host = host if host != "0.0.0.0" else "127.0.0.1"
|
||||||
if not port:
|
if not port:
|
||||||
port = settings.getInt(["server", "port"])
|
port = settings.getInt(["server", "port"])
|
||||||
|
|
||||||
if not apikey:
|
if not apikey:
|
||||||
apikey = settings.get(["api", "key"])
|
apikey = settings.get(["api", "key"])
|
||||||
|
|
||||||
baseurl = octoprint_client.build_base_url(https=https,
|
baseurl = octoprint_client.build_base_url(
|
||||||
httpuser=httpuser,
|
https=https,
|
||||||
httppass=httppass,
|
httpuser=httpuser,
|
||||||
host=host,
|
httppass=httppass,
|
||||||
port=port,
|
host=host,
|
||||||
prefix=prefix)
|
port=port,
|
||||||
|
prefix=prefix,
|
||||||
|
)
|
||||||
|
|
||||||
return octoprint_client.Client(baseurl, apikey)
|
return octoprint_client.Client(baseurl, apikey)
|
||||||
|
|
||||||
|
|
||||||
client_options = bulk_options([
|
client_options = bulk_options(
|
||||||
click.option("--apikey", "-a", type=click.STRING),
|
[
|
||||||
click.option("--host", "-h", type=click.STRING),
|
click.option("--apikey", "-a", type=click.STRING),
|
||||||
click.option("--port", "-p", type=click.INT),
|
click.option("--host", "-h", type=click.STRING),
|
||||||
click.option("--httpuser", type=click.STRING),
|
click.option("--port", "-p", type=click.INT),
|
||||||
click.option("--httppass", type=click.STRING),
|
click.option("--httpuser", type=click.STRING),
|
||||||
click.option("--https", is_flag=True),
|
click.option("--httppass", type=click.STRING),
|
||||||
click.option("--prefix", type=click.STRING)
|
click.option("--https", is_flag=True),
|
||||||
])
|
click.option("--prefix", type=click.STRING),
|
||||||
|
]
|
||||||
|
)
|
||||||
"""Common options to configure an API client."""
|
"""Common options to configure an API client."""
|
||||||
|
|
||||||
|
|
||||||
@click.group()
|
@click.group()
|
||||||
def client_commands():
|
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
|
@client_options
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||||
"""Basic API client."""
|
"""Basic API client."""
|
||||||
try:
|
try:
|
||||||
settings = None
|
settings = None
|
||||||
if not host or not port or not apikey:
|
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))
|
settings = init_settings(
|
||||||
|
get_ctx_obj_option(ctx, "basedir", None),
|
||||||
|
get_ctx_obj_option(ctx, "configfile", None),
|
||||||
|
)
|
||||||
|
|
||||||
ctx.obj.client = create_client(settings=settings,
|
ctx.obj.client = create_client(
|
||||||
apikey=apikey,
|
settings=settings,
|
||||||
host=host,
|
apikey=apikey,
|
||||||
port=port,
|
host=host,
|
||||||
httpuser=httpuser,
|
port=port,
|
||||||
httppass=httppass,
|
httpuser=httpuser,
|
||||||
https=https,
|
httppass=httppass,
|
||||||
prefix=prefix)
|
https=https,
|
||||||
|
prefix=prefix,
|
||||||
|
)
|
||||||
|
|
||||||
except FatalStartupError as e:
|
except FatalStartupError as e:
|
||||||
click.echo(e.message, err=True)
|
click.echo(str(e), err=True)
|
||||||
click.echo("There was a fatal error initializing the client.", err=True)
|
click.echo("There was a fatal error initializing the client.", err=True)
|
||||||
ctx.exit(-1)
|
ctx.exit(-1)
|
||||||
|
|
||||||
|
|
||||||
def log_response(response, status_code=True, body=True, headers=False):
|
def log_response(response, status_code=True, body=True, headers=False):
|
||||||
if status_code:
|
if status_code:
|
||||||
click.echo("Status Code: {}".format(response.status_code))
|
click.echo("Status Code: {}".format(response.status_code))
|
||||||
if headers:
|
if headers:
|
||||||
for header, value in response.headers.items():
|
for header, value in response.headers.items():
|
||||||
click.echo("{}: {}".format(header, value))
|
click.echo("{}: {}".format(header, value))
|
||||||
click.echo()
|
click.echo()
|
||||||
if body:
|
if body:
|
||||||
click.echo(response.text)
|
click.echo(response.text)
|
||||||
|
|
||||||
|
|
||||||
@client.command("get")
|
@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.option("--timeout", type=float, default=None)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def get(ctx, path, timeout):
|
def get(ctx, path, timeout):
|
||||||
"""Performs a GET request against the specified server path."""
|
"""Performs a GET request against the specified server path."""
|
||||||
r = ctx.obj.client.get(path, timeout=timeout)
|
r = ctx.obj.client.get(path, timeout=timeout)
|
||||||
log_response(r)
|
log_response(r)
|
||||||
|
|
||||||
|
|
||||||
@client.command("post_json")
|
@client.command("post_json")
|
||||||
@@ -120,9 +138,9 @@ def get(ctx, path, timeout):
|
|||||||
@click.option("--timeout", type=float, default=None)
|
@click.option("--timeout", type=float, default=None)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def post_json(ctx, path, data, timeout):
|
def post_json(ctx, path, data, timeout):
|
||||||
"""POSTs JSON data to the specified server path."""
|
"""POSTs JSON data to the specified server path."""
|
||||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||||
log_response(r)
|
log_response(r)
|
||||||
|
|
||||||
|
|
||||||
@client.command("patch_json")
|
@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.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def patch_json(ctx, path, data, timeout):
|
def patch_json(ctx, path, data, timeout):
|
||||||
"""PATCHes JSON data to the specified server path."""
|
"""PATCHes JSON data to the specified server path."""
|
||||||
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
|
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
|
||||||
log_response(r)
|
log_response(r)
|
||||||
|
|
||||||
|
|
||||||
@client.command("post_from_file")
|
@client.command("post_from_file")
|
||||||
@click.argument("path")
|
@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("--json", is_flag=True)
|
||||||
@click.option("--yaml", is_flag=True)
|
@click.option("--yaml", is_flag=True)
|
||||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
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."""
|
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
|
||||||
if json_flag or yaml_flag:
|
if json_flag or yaml_flag:
|
||||||
if json_flag:
|
if json_flag:
|
||||||
with io.open(file_path, 'rt') as fp:
|
with io.open(file_path, "rt") as fp:
|
||||||
data = json.load(fp)
|
data = json.load(fp)
|
||||||
else:
|
else:
|
||||||
import yaml
|
import yaml
|
||||||
with io.open(file_path, 'rt') as fp:
|
|
||||||
data = yaml.safe_load(fp)
|
|
||||||
|
|
||||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
with io.open(file_path, "rt") as fp:
|
||||||
else:
|
data = yaml.safe_load(fp)
|
||||||
with io.open(file_path, 'rb') as fp:
|
|
||||||
data = fp.read()
|
|
||||||
|
|
||||||
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")
|
@client.command("command")
|
||||||
@click.argument("path")
|
@click.argument("path")
|
||||||
@click.argument("command")
|
@click.argument("command")
|
||||||
@click.option("--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
|
@click.option(
|
||||||
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
|
"--str",
|
||||||
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
|
"-s",
|
||||||
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
|
"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.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
|
def command(
|
||||||
"""Sends a JSON command to the specified server path."""
|
ctx, path, command, str_params, int_params, float_params, bool_params, timeout
|
||||||
data = dict()
|
):
|
||||||
params = str_params + int_params + float_params + bool_params
|
"""Sends a JSON command to the specified server path."""
|
||||||
for param in params:
|
data = {}
|
||||||
data[param[0]] = param[1]
|
params = str_params + int_params + float_params + bool_params
|
||||||
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
|
for param in params:
|
||||||
log_response(r, body=False)
|
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")
|
@client.command("upload")
|
||||||
@click.argument("path")
|
@click.argument("path")
|
||||||
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
|
@click.argument(
|
||||||
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
|
"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("--file-name", type=click.STRING)
|
||||||
@click.option("--content-type", type=click.STRING)
|
@click.option("--content-type", type=click.STRING)
|
||||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
|
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
|
||||||
"""Uploads the specified file to the specified server path."""
|
"""Uploads the specified file to the specified server path."""
|
||||||
data = dict()
|
data = {}
|
||||||
for param in params:
|
for param in params:
|
||||||
data[param[0]] = param[1]
|
data[param[0]] = param[1]
|
||||||
|
|
||||||
r = ctx.obj.client.upload(path, file_path,
|
r = ctx.obj.client.upload(
|
||||||
additional=data, file_name=file_name, content_type=content_type, timeout=timeout)
|
path,
|
||||||
log_response(r)
|
file_path,
|
||||||
|
additional=data,
|
||||||
|
file_name=file_name,
|
||||||
|
content_type=content_type,
|
||||||
|
timeout=timeout,
|
||||||
|
)
|
||||||
|
log_response(r)
|
||||||
|
|
||||||
|
|
||||||
@client.command("delete")
|
@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.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def delete(ctx, path, timeout):
|
def delete(ctx, path, timeout):
|
||||||
"""Sends a DELETE request to the specified server path."""
|
"""Sends a DELETE request to the specified server path."""
|
||||||
r = ctx.obj.client.delete(path, timeout=timeout)
|
r = ctx.obj.client.delete(path, timeout=timeout)
|
||||||
log_response(r)
|
log_response(r)
|
||||||
|
|
||||||
|
|
||||||
@client.command("listen")
|
@client.command("listen")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def listen(ctx):
|
def listen(ctx):
|
||||||
def on_connect(ws):
|
def on_connect(ws):
|
||||||
click.echo(">>> Connected!")
|
click.echo("--- Connected!")
|
||||||
|
|
||||||
def on_close(ws):
|
def on_close(ws):
|
||||||
click.echo(">>> Connection closed!")
|
click.echo("--- Connection closed!")
|
||||||
|
|
||||||
def on_error(ws, error):
|
def on_error(ws, error):
|
||||||
click.echo("!!! Error: {}".format(error))
|
click.echo("!!! Error: {}".format(error))
|
||||||
|
|
||||||
def on_heartbeat(ws):
|
def on_sent(ws, data):
|
||||||
click.echo("<3")
|
click.echo(">>> {}".format(json.dumps(data)))
|
||||||
|
|
||||||
def on_message(ws, message_type, message_payload):
|
def on_heartbeat(ws):
|
||||||
click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload)))
|
click.echo("<3")
|
||||||
|
|
||||||
socket = ctx.obj.client.create_socket(on_connect=on_connect,
|
def on_message(ws, message_type, message_payload):
|
||||||
on_close=on_close,
|
click.echo(
|
||||||
on_error=on_error,
|
"<<< {}, Payload: {}".format(message_type, json.dumps(message_payload))
|
||||||
on_heartbeat=on_heartbeat,
|
)
|
||||||
on_message=on_message)
|
|
||||||
|
|
||||||
click.echo(">>> Waiting for client to exit")
|
socket = ctx.obj.client.create_socket(
|
||||||
try:
|
on_connect=on_connect,
|
||||||
socket.wait()
|
on_close=on_close,
|
||||||
finally:
|
on_error=on_error,
|
||||||
click.echo(">>> Goodbye...")
|
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
@@ -1,95 +1,104 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
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"
|
__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 json
|
||||||
|
import logging
|
||||||
import pprint
|
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):
|
def _to_settings_path(path):
|
||||||
if not isinstance(path, (list, tuple)):
|
if not isinstance(path, (list, tuple)):
|
||||||
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
|
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
|
||||||
return path
|
return path
|
||||||
|
|
||||||
|
|
||||||
def _set_helper(settings, path, value, data_type=None):
|
def _set_helper(settings, path, value, data_type=None):
|
||||||
path = _to_settings_path(path)
|
path = _to_settings_path(path)
|
||||||
|
|
||||||
method = settings.set
|
method = settings.set
|
||||||
if data_type is not None:
|
if data_type is not None:
|
||||||
name = None
|
name = None
|
||||||
if data_type == bool:
|
if data_type == bool:
|
||||||
name = "setBoolean"
|
name = "setBoolean"
|
||||||
elif data_type == float:
|
elif data_type == float:
|
||||||
name = "setFloat"
|
name = "setFloat"
|
||||||
elif data_type == int:
|
elif data_type == int:
|
||||||
name = "setInt"
|
name = "setInt"
|
||||||
|
|
||||||
if name is not None:
|
if name is not None:
|
||||||
method = getattr(settings, name)
|
method = getattr(settings, name)
|
||||||
|
|
||||||
method(path, value)
|
method(path, value)
|
||||||
settings.save()
|
settings.save()
|
||||||
|
|
||||||
|
|
||||||
|
# ~~ "octoprint config" commands
|
||||||
|
|
||||||
#~~ "octoprint config" commands
|
|
||||||
|
|
||||||
@click.group()
|
@click.group()
|
||||||
def config_commands():
|
def config_commands():
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@config_commands.group(name="config")
|
@config_commands.group(name="config")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def config(ctx):
|
def config(ctx):
|
||||||
"""Basic config manipulation."""
|
"""Basic config manipulation."""
|
||||||
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
|
logging.basicConfig(
|
||||||
try:
|
level=logging.DEBUG
|
||||||
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
|
||||||
except FatalStartupError as e:
|
else logging.WARN
|
||||||
click.echo(e.message, err=True)
|
)
|
||||||
click.echo("There was a fatal error initializing the settings manager.", err=True)
|
try:
|
||||||
ctx.exit(-1)
|
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")
|
@config.command(name="set")
|
||||||
@standard_options(hidden=True)
|
@standard_options(hidden=True)
|
||||||
@click.argument("path", type=click.STRING)
|
@click.argument("path", type=click.STRING)
|
||||||
@click.argument("value", type=click.STRING)
|
@click.argument("value", type=click.STRING)
|
||||||
@click.option("--bool", "as_bool", is_flag=True,
|
@click.option("--bool", "as_bool", is_flag=True, help="Interpret value as bool")
|
||||||
help="Interpret value as bool")
|
@click.option("--float", "as_float", is_flag=True, help="Interpret value as float")
|
||||||
@click.option("--float", "as_float", is_flag=True,
|
@click.option("--int", "as_int", is_flag=True, help="Interpret value as int")
|
||||||
help="Interpret value as float")
|
@click.option("--json", "as_json", is_flag=True, help="Parse value from json")
|
||||||
@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
|
@click.pass_context
|
||||||
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
|
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
|
||||||
"""Sets a config path to the provided value."""
|
"""Sets a config path to the provided value."""
|
||||||
if as_json:
|
if as_json:
|
||||||
try:
|
try:
|
||||||
value = json.loads(value)
|
value = json.loads(value)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
click.echo(e.message, err=True)
|
click.echo(str(e), err=True)
|
||||||
ctx.exit(-1)
|
ctx.exit(-1)
|
||||||
|
|
||||||
data_type = None
|
data_type = None
|
||||||
if as_bool:
|
if as_bool:
|
||||||
data_type = bool
|
data_type = bool
|
||||||
elif as_float:
|
elif as_float:
|
||||||
data_type = float
|
data_type = float
|
||||||
elif as_int:
|
elif as_int:
|
||||||
data_type = 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")
|
@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.argument("path", type=click.STRING)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def remove_command(ctx, path):
|
def remove_command(ctx, path):
|
||||||
"""Removes a config path."""
|
"""Removes a config path."""
|
||||||
_set_helper(ctx.obj.settings, path, None)
|
_set_helper(ctx.obj.settings, path, None)
|
||||||
|
|
||||||
|
|
||||||
@config.command(name="append_value")
|
@config.command(name="append_value")
|
||||||
@@ -108,25 +117,25 @@ def remove_command(ctx, path):
|
|||||||
@click.option("--json", "as_json", is_flag=True)
|
@click.option("--json", "as_json", is_flag=True)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def append_value_command(ctx, path, value, as_json=False):
|
def append_value_command(ctx, path, value, as_json=False):
|
||||||
"""Appends value to list behind config path."""
|
"""Appends value to list behind config path."""
|
||||||
path = _to_settings_path(path)
|
path = _to_settings_path(path)
|
||||||
|
|
||||||
if as_json:
|
if as_json:
|
||||||
try:
|
try:
|
||||||
value = json.loads(value)
|
value = json.loads(value)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
click.echo(e.message, err=True)
|
click.echo(str(e), err=True)
|
||||||
ctx.exit(-1)
|
ctx.exit(-1)
|
||||||
|
|
||||||
current = ctx.obj.settings.get(path)
|
current = ctx.obj.settings.get(path)
|
||||||
if current is None:
|
if current is None:
|
||||||
current = []
|
current = []
|
||||||
if not isinstance(current, list):
|
if not isinstance(current, list):
|
||||||
click.echo("Cannot append to non-list value at given path", err=True)
|
click.echo("Cannot append to non-list value at given path", err=True)
|
||||||
ctx.exit(-1)
|
ctx.exit(-1)
|
||||||
|
|
||||||
current.append(value)
|
current.append(value)
|
||||||
_set_helper(ctx.obj.settings, path, current)
|
_set_helper(ctx.obj.settings, path, current)
|
||||||
|
|
||||||
|
|
||||||
@config.command(name="insert_value")
|
@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.option("--json", "as_json", is_flag=True)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def insert_value_command(ctx, path, index, value, as_json=False):
|
def insert_value_command(ctx, path, index, value, as_json=False):
|
||||||
"""Inserts value at index of list behind config key."""
|
"""Inserts value at index of list behind config key."""
|
||||||
path = _to_settings_path(path)
|
path = _to_settings_path(path)
|
||||||
|
|
||||||
if as_json:
|
if as_json:
|
||||||
try:
|
try:
|
||||||
value = json.loads(value)
|
value = json.loads(value)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
click.echo(e.message, err=True)
|
click.echo(str(e), err=True)
|
||||||
ctx.exit(-1)
|
ctx.exit(-1)
|
||||||
|
|
||||||
current = ctx.obj.settings.get(path)
|
current = ctx.obj.settings.get(path)
|
||||||
if current is None:
|
if current is None:
|
||||||
current = []
|
current = []
|
||||||
if not isinstance(current, list):
|
if not isinstance(current, list):
|
||||||
click.echo("Cannot insert into non-list value at given path", err=True)
|
click.echo("Cannot insert into non-list value at given path", err=True)
|
||||||
ctx.exit(-1)
|
ctx.exit(-1)
|
||||||
|
|
||||||
current.insert(index, value)
|
current.insert(index, value)
|
||||||
_set_helper(ctx.obj.settings, path, current)
|
_set_helper(ctx.obj.settings, path, current)
|
||||||
|
|
||||||
|
|
||||||
@config.command(name="remove_value")
|
@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.option("--json", "as_json", is_flag=True)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def remove_value_command(ctx, path, value, as_json=False):
|
def remove_value_command(ctx, path, value, as_json=False):
|
||||||
"""Removes value from list at config path."""
|
"""Removes value from list at config path."""
|
||||||
path = _to_settings_path(path)
|
path = _to_settings_path(path)
|
||||||
|
|
||||||
if as_json:
|
if as_json:
|
||||||
try:
|
try:
|
||||||
value = json.loads(value)
|
value = json.loads(value)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
click.echo(e.message, err=True)
|
click.echo(str(e), err=True)
|
||||||
ctx.exit(-1)
|
ctx.exit(-1)
|
||||||
|
|
||||||
current = ctx.obj.settings.get(path)
|
current = ctx.obj.settings.get(path)
|
||||||
if current is None:
|
if current is None:
|
||||||
current = []
|
current = []
|
||||||
if not isinstance(current, list):
|
if not isinstance(current, list):
|
||||||
click.echo("Cannot remove value from non-list value at given path", err=True)
|
click.echo("Cannot remove value from non-list value at given path", err=True)
|
||||||
ctx.exit(-1)
|
ctx.exit(-1)
|
||||||
|
|
||||||
if not value in current:
|
if value not in current:
|
||||||
click.echo("Value is not contained in list at given path")
|
click.echo("Value is not contained in list at given path")
|
||||||
ctx.exit()
|
ctx.exit()
|
||||||
|
|
||||||
current.remove(value)
|
current.remove(value)
|
||||||
_set_helper(ctx.obj.settings, path, current)
|
_set_helper(ctx.obj.settings, path, current)
|
||||||
|
|
||||||
|
|
||||||
@config.command(name="get")
|
@config.command(name="get")
|
||||||
@click.argument("path", type=click.STRING)
|
@click.argument("path", type=click.STRING)
|
||||||
@click.option("--json", "as_json", is_flag=True,
|
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
|
||||||
help="Output value formatted as JSON")
|
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
|
||||||
@click.option("--yaml", "as_yaml", is_flag=True,
|
@click.option(
|
||||||
help="Output value formatted as YAML")
|
"--raw", "as_raw", is_flag=True, help="Output value as raw string representation"
|
||||||
@click.option("--raw", "as_raw", is_flag=True,
|
)
|
||||||
help="Output value as raw string representation")
|
|
||||||
@standard_options(hidden=True)
|
@standard_options(hidden=True)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
||||||
"""Retrieves value from config path."""
|
"""Retrieves value from config path."""
|
||||||
path = _to_settings_path(path)
|
path = _to_settings_path(path)
|
||||||
value = ctx.obj.settings.get(path, merged=True)
|
value = ctx.obj.settings.get(path, merged=True)
|
||||||
|
|
||||||
if as_json:
|
if as_json:
|
||||||
output = json.dumps(value)
|
output = json.dumps(value)
|
||||||
elif as_yaml:
|
elif as_yaml:
|
||||||
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
|
output = yaml.safe_dump(
|
||||||
elif as_raw:
|
value, default_flow_style=False, indent=4, allow_unicode=True
|
||||||
output = value
|
)
|
||||||
else:
|
elif as_raw:
|
||||||
output = pprint.pformat(value)
|
output = value
|
||||||
|
else:
|
||||||
|
output = pprint.pformat(value)
|
||||||
|
|
||||||
click.echo(output)
|
click.echo(output)
|
||||||
|
|
||||||
|
|
||||||
@config.command(name="effective")
|
@config.command(name="effective")
|
||||||
@click.option("--json", "as_json", is_flag=True,
|
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
|
||||||
help="Output value formatted as JSON")
|
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
|
||||||
@click.option("--yaml", "as_yaml", is_flag=True,
|
@click.option(
|
||||||
help="Output value formatted as YAML")
|
"--raw", "as_raw", is_flag=True, help="Output value as raw string representation"
|
||||||
@click.option("--raw", "as_raw", is_flag=True,
|
)
|
||||||
help="Output value as raw string representation")
|
|
||||||
@standard_options(hidden=True)
|
@standard_options(hidden=True)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
|
def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
|
||||||
"""Retrieves the full effective config."""
|
"""Retrieves the full effective config."""
|
||||||
value = ctx.obj.settings.effective
|
value = ctx.obj.settings.effective
|
||||||
|
|
||||||
if as_json:
|
if as_json:
|
||||||
output = json.dumps(value)
|
output = json.dumps(value)
|
||||||
elif as_yaml:
|
elif as_yaml:
|
||||||
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
|
output = yaml.safe_dump(
|
||||||
elif as_raw:
|
value, default_flow_style=False, indent=4, allow_unicode=True
|
||||||
output = value
|
)
|
||||||
else:
|
elif as_raw:
|
||||||
output = pprint.pformat(value)
|
output = value
|
||||||
|
else:
|
||||||
|
output = pprint.pformat(value)
|
||||||
|
|
||||||
click.echo(output)
|
click.echo(output)
|
||||||
+211
-180
@@ -2,238 +2,269 @@
|
|||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||||
|
|
||||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
__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"
|
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
|
|
||||||
import click
|
import click
|
||||||
|
|
||||||
click.disable_unicode_literals_warning = True
|
click.disable_unicode_literals_warning = True
|
||||||
|
|
||||||
from past.builtins import basestring
|
from past.builtins import basestring
|
||||||
|
|
||||||
|
|
||||||
class OctoPrintDevelCommands(click.MultiCommand):
|
class OctoPrintDevelCommands(click.MultiCommand):
|
||||||
"""
|
"""
|
||||||
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
|
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
|
||||||
implementation that provides commands relevant for (plugin) development
|
implementation that provides commands relevant for (plugin) development
|
||||||
based on availability of development dependencies.
|
based on availability of development dependencies.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sep = ":"
|
sep = ":"
|
||||||
groups = ("plugin",)
|
groups = ("plugin",)
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
click.MultiCommand.__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):
|
from octoprint.util.commandline import CommandlineCaller
|
||||||
def log(*lines):
|
|
||||||
for line in lines:
|
|
||||||
f(line)
|
|
||||||
return log
|
|
||||||
|
|
||||||
self.command_caller = CommandlineCaller()
|
def log_util(f):
|
||||||
self.command_caller.on_log_call = log_util(lambda x: click.echo(">> {}".format(x)))
|
def log(*lines):
|
||||||
self.command_caller.on_log_stdout = log_util(click.echo)
|
for line in lines:
|
||||||
self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True))
|
f(line)
|
||||||
|
|
||||||
def _get_prefix_methods(self, method_prefix):
|
return log
|
||||||
for name in [x for x in dir(self) if x.startswith(method_prefix)]:
|
|
||||||
method = getattr(self, name)
|
|
||||||
yield method
|
|
||||||
|
|
||||||
def _get_commands_from_prefix_methods(self, method_prefix):
|
self.command_caller = CommandlineCaller()
|
||||||
for method in self._get_prefix_methods(method_prefix):
|
self.command_caller.on_log_call = log_util(
|
||||||
result = method()
|
lambda x: click.echo(">> {}".format(x))
|
||||||
if result is not None and isinstance(result, click.Command):
|
)
|
||||||
yield result
|
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):
|
def _get_prefix_methods(self, method_prefix):
|
||||||
result = dict()
|
for name in [x for x in dir(self) if x.startswith(method_prefix)]:
|
||||||
for group in self.groups:
|
method = getattr(self, name)
|
||||||
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
|
yield method
|
||||||
result[group + self.sep + command.name] = command
|
|
||||||
return result
|
|
||||||
|
|
||||||
def list_commands(self, ctx):
|
def _get_commands_from_prefix_methods(self, method_prefix):
|
||||||
result = [name for name in self._get_commands()]
|
for method in self._get_prefix_methods(method_prefix):
|
||||||
result.sort()
|
result = method()
|
||||||
return result
|
if result is not None and isinstance(result, click.Command):
|
||||||
|
yield result
|
||||||
|
|
||||||
def get_command(self, ctx, cmd_name):
|
def _get_commands(self):
|
||||||
commands = self._get_commands()
|
result = {}
|
||||||
return commands.get(cmd_name, None)
|
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):
|
def list_commands(self, ctx):
|
||||||
try:
|
result = [name for name in self._get_commands()]
|
||||||
import cookiecutter.main
|
result.sort()
|
||||||
except ImportError:
|
return result
|
||||||
return None
|
|
||||||
|
|
||||||
try:
|
def get_command(self, ctx, cmd_name):
|
||||||
# we depend on Cookiecutter >= 1.4
|
commands = self._get_commands()
|
||||||
from cookiecutter.prompt import StrictEnvironment
|
return commands.get(cmd_name, None)
|
||||||
except ImportError:
|
|
||||||
return None
|
|
||||||
|
|
||||||
import contextlib
|
def plugin_new(self):
|
||||||
|
try:
|
||||||
|
import cookiecutter.main
|
||||||
|
except ImportError:
|
||||||
|
return None
|
||||||
|
|
||||||
@contextlib.contextmanager
|
try:
|
||||||
def custom_cookiecutter_config(config):
|
# we depend on Cookiecutter >= 1.4
|
||||||
"""
|
from cookiecutter.prompt import StrictEnvironment
|
||||||
Allows overriding cookiecutter's user config with a custom dict
|
except ImportError:
|
||||||
with fallback to the original data.
|
return None
|
||||||
"""
|
|
||||||
from octoprint.util import fallback_dict
|
|
||||||
|
|
||||||
original_get_user_config = cookiecutter.main.get_user_config
|
import contextlib
|
||||||
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
|
|
||||||
|
|
||||||
@contextlib.contextmanager
|
@contextlib.contextmanager
|
||||||
def custom_cookiecutter_prompt(options):
|
def custom_cookiecutter_config(config):
|
||||||
"""
|
"""
|
||||||
Custom cookiecutter prompter for the template 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)
|
original_get_user_config = cookiecutter.main.get_user_config
|
||||||
that will be used, otherwise the user will be prompted for a value
|
try:
|
||||||
via click.
|
|
||||||
"""
|
|
||||||
original_prompt_for_config = cookiecutter.main.prompt_for_config
|
|
||||||
|
|
||||||
def custom_prompt_for_config(context, no_input=False):
|
def f(*args, **kwargs):
|
||||||
cookiecutter_dict = dict()
|
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():
|
@contextlib.contextmanager
|
||||||
if key in options:
|
def custom_cookiecutter_prompt(options):
|
||||||
val = options[key]
|
"""
|
||||||
else:
|
Custom cookiecutter prompter for the template config.
|
||||||
if not isinstance(raw, basestring):
|
|
||||||
raw = str(raw)
|
|
||||||
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
|
|
||||||
|
|
||||||
if not no_input:
|
If a setting is available in the provided options (read from the CLI)
|
||||||
val = click.prompt(key, default=val)
|
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
|
def custom_prompt_for_config(context, no_input=False):
|
||||||
return cookiecutter_dict
|
cookiecutter_dict = {}
|
||||||
|
|
||||||
try:
|
env = StrictEnvironment()
|
||||||
cookiecutter.main.prompt_for_config = custom_prompt_for_config
|
|
||||||
yield
|
|
||||||
finally:
|
|
||||||
cookiecutter.main.prompt_for_config = original_prompt_for_config
|
|
||||||
|
|
||||||
@click.command("new")
|
for key, raw in context["cookiecutter"].items():
|
||||||
@click.option("--name", "-n", help="The name of the plugin")
|
if key in options:
|
||||||
@click.option("--package", "-p", help="The plugin package")
|
val = options[key]
|
||||||
@click.option("--author", "-a", help="The plugin author's name")
|
else:
|
||||||
@click.option("--email", "-e", help="The plugin author's mail address")
|
if not isinstance(raw, basestring):
|
||||||
@click.option("--license", "-l", help="The plugin's license")
|
raw = str(raw)
|
||||||
@click.option("--description", "-d", help="The plugin's description")
|
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
|
||||||
@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
|
|
||||||
|
|
||||||
# deleting a git checkout folder might run into access errors due
|
if not no_input:
|
||||||
# to write-protected sub folders, so we use a custom onerror handler
|
val = click.prompt(key, default=val)
|
||||||
# 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 os.access(path, os.W_OK):
|
cookiecutter_dict[key] = val
|
||||||
os.chmod(path, stat.S_IWUSR)
|
return cookiecutter_dict
|
||||||
func(path)
|
|
||||||
else:
|
|
||||||
raise
|
|
||||||
|
|
||||||
with tempdir(onerror=onerror) as path:
|
try:
|
||||||
custom = dict(cookiecutters_dir=path)
|
cookiecutter.main.prompt_for_config = custom_prompt_for_config
|
||||||
with custom_cookiecutter_config(custom):
|
yield
|
||||||
raw_options = dict(
|
finally:
|
||||||
plugin_identifier=identifier,
|
cookiecutter.main.prompt_for_config = original_prompt_for_config
|
||||||
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)
|
|
||||||
|
|
||||||
with custom_cookiecutter_prompt(options):
|
@click.command("new")
|
||||||
cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin")
|
@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):
|
if not os.access(path, os.W_OK):
|
||||||
@click.command("install")
|
os.chmod(path, stat.S_IWUSR)
|
||||||
@click.option("--path", help="Path of the local plugin development folder to install")
|
func(path)
|
||||||
def command(path):
|
else:
|
||||||
"""
|
raise
|
||||||
Installs the local plugin in development mode.
|
|
||||||
|
|
||||||
Note: This can NOT be used to install plugins from remote locations
|
with tempdir(onerror=onerror) as path:
|
||||||
such as the plugin repository! It is strictly for local development
|
custom = {"cookiecutters_dir": path}
|
||||||
of plugins, to ensure the plugin is installed (editable) into the
|
with custom_cookiecutter_config(custom):
|
||||||
same python environment that OctoPrint is installed under.
|
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
|
with custom_cookiecutter_prompt(options):
|
||||||
import sys
|
cookiecutter.main.cookiecutter(
|
||||||
|
"gh:OctoPrint/cookiecutter-octoprint-plugin"
|
||||||
|
)
|
||||||
|
|
||||||
if not path:
|
return command
|
||||||
path = os.getcwd()
|
|
||||||
|
|
||||||
# check if this really looks like a plugin
|
def plugin_install(self):
|
||||||
if not os.path.isfile(os.path.join(path, "setup.py")):
|
@click.command("install")
|
||||||
click.echo("This doesn't look like an OctoPrint plugin folder")
|
@click.option(
|
||||||
sys.exit(1)
|
"--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):
|
if not path:
|
||||||
@click.command("uninstall")
|
path = os.getcwd()
|
||||||
@click.argument("name")
|
|
||||||
def command(name):
|
|
||||||
"""Uninstalls the plugin with the given name."""
|
|
||||||
import sys
|
|
||||||
|
|
||||||
lower_name = name.lower()
|
# check if this really looks like a plugin
|
||||||
if not lower_name.startswith("octoprint_") and not lower_name.startswith("octoprint-"):
|
if not os.path.isfile(os.path.join(path, "setup.py")):
|
||||||
click.echo("This doesn't look like an OctoPrint plugin name")
|
click.echo("This doesn't look like an OctoPrint plugin folder")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
call = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
|
self.command_caller.call(
|
||||||
self.command_caller.call(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()
|
@click.group()
|
||||||
def dev_commands():
|
def dev_commands():
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@dev_commands.group(name="dev", cls=OctoPrintDevelCommands)
|
@dev_commands.group(name="dev", cls=OctoPrintDevelCommands)
|
||||||
def dev():
|
def dev():
|
||||||
"""Additional commands for development tasks."""
|
"""Additional commands for development tasks."""
|
||||||
pass
|
pass
|
||||||
+109
-94
@@ -1,137 +1,152 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
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"
|
__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
|
||||||
import logging.config
|
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
|
from octoprint.util import dict_merge
|
||||||
|
|
||||||
|
click.disable_unicode_literals_warning = True
|
||||||
LOGGING_CONFIG = {
|
LOGGING_CONFIG = {
|
||||||
"version": 1,
|
"version": 1,
|
||||||
"formatters": {
|
"formatters": {"brief": {"format": "%(message)s"}},
|
||||||
"brief": {
|
"handlers": {
|
||||||
"format": "%(message)s"
|
"console": {
|
||||||
}
|
"class": "logging.StreamHandler",
|
||||||
},
|
"formatter": "brief",
|
||||||
"handlers": {
|
"stream": "ext://sys.stdout",
|
||||||
"console": {
|
}
|
||||||
"class": "logging.StreamHandler",
|
},
|
||||||
"formatter": "brief",
|
"loggers": {"octoprint.plugin.core": {"level": logging.ERROR}},
|
||||||
"stream": "ext://sys.stdout"
|
"root": {"level": logging.WARNING},
|
||||||
}
|
|
||||||
},
|
|
||||||
"loggers": {
|
|
||||||
"octoprint.plugin.core": {
|
|
||||||
"level": logging.ERROR
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"root": {
|
|
||||||
"level": logging.WARNING
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#~~ "octoprint plugin:command" commands
|
# ~~ "octoprint plugin:command" commands
|
||||||
|
|
||||||
|
|
||||||
class OctoPrintPluginCommands(click.MultiCommand):
|
class OctoPrintPluginCommands(click.MultiCommand):
|
||||||
"""
|
"""
|
||||||
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
|
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
|
||||||
implementation that collects commands from the plugin hook
|
implementation that collects commands from the plugin hook
|
||||||
:ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`.
|
: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):
|
def __init__(self, *args, **kwargs):
|
||||||
click.MultiCommand.__init__(self, *args, **kwargs)
|
click.MultiCommand.__init__(self, *args, **kwargs)
|
||||||
|
|
||||||
self.settings = None
|
self.settings = None
|
||||||
self.plugin_manager = None
|
self.plugin_manager = None
|
||||||
self.hooks = dict()
|
self.hooks = {}
|
||||||
|
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
self._initialized = False
|
self._initialized = False
|
||||||
|
|
||||||
def _initialize(self, ctx):
|
def _initialize(self, ctx):
|
||||||
if self._initialized:
|
if self._initialized:
|
||||||
return
|
return
|
||||||
|
|
||||||
click.echo("Initializing settings & plugin subsystem...")
|
click.echo("Initializing settings & plugin subsystem...")
|
||||||
if ctx.obj is None:
|
if ctx.obj is None:
|
||||||
ctx.obj = OctoPrintContext()
|
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 = dict_merge(
|
||||||
logging.config.dictConfig(logging_config)
|
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
|
# initialize settings and plugin manager based on provided
|
||||||
# context (basedir and configfile)
|
# context (basedir and configfile)
|
||||||
from octoprint import init_settings, init_pluginsystem, FatalStartupError
|
from octoprint import FatalStartupError, init_pluginsystem, init_settings
|
||||||
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)
|
|
||||||
|
|
||||||
# fetch registered hooks
|
try:
|
||||||
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
|
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._initialized = True
|
||||||
self._initialize(ctx)
|
|
||||||
result = [name for name in self._get_commands()]
|
|
||||||
result.sort()
|
|
||||||
return result
|
|
||||||
|
|
||||||
def get_command(self, ctx, cmd_name):
|
def list_commands(self, ctx):
|
||||||
self._initialize(ctx)
|
self._initialize(ctx)
|
||||||
commands = self._get_commands()
|
result = [name for name in self._get_commands()]
|
||||||
return commands.get(cmd_name, None)
|
result.sort()
|
||||||
|
return result
|
||||||
|
|
||||||
def _get_commands(self):
|
def get_command(self, ctx, cmd_name):
|
||||||
"""Fetch all commands from plugins providing any."""
|
self._initialize(ctx)
|
||||||
|
commands = self._get_commands()
|
||||||
|
return commands.get(cmd_name, None)
|
||||||
|
|
||||||
import collections
|
def _get_commands(self):
|
||||||
result = collections.OrderedDict()
|
"""Fetch all commands from plugins providing any."""
|
||||||
|
|
||||||
for name, hook in self.hooks.items():
|
import collections
|
||||||
try:
|
|
||||||
commands = hook(self, pass_octoprint_ctx)
|
result = collections.OrderedDict()
|
||||||
for command in commands:
|
|
||||||
if not isinstance(command, click.Command):
|
for name, hook in self.hooks.items():
|
||||||
self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
|
try:
|
||||||
continue
|
commands = hook(self, pass_octoprint_ctx)
|
||||||
result[name + self.sep + command.name] = command
|
for command in commands:
|
||||||
except Exception:
|
if not isinstance(command, click.Command):
|
||||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
|
self._logger.warning(
|
||||||
extra=dict(plugin=name))
|
"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()
|
@click.group()
|
||||||
@pass_octoprint_ctx
|
@pass_octoprint_ctx
|
||||||
def plugin_commands(obj):
|
def plugin_commands(obj):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
|
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
|
||||||
def plugins():
|
def plugins():
|
||||||
"""Additional commands provided by plugins."""
|
"""Additional commands provided by plugins."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
+360
-214
@@ -1,178 +1,277 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
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"
|
__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
|
||||||
import sys
|
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,
|
from octoprint.cli import (
|
||||||
ignore_blacklist, octoprint_daemon=None):
|
bulk_options,
|
||||||
"""Initializes the environment and starts up the server."""
|
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("*"))
|
from octoprint import FatalStartupError, __display_version__, init_platform
|
||||||
logger.info("Starting OctoPrint {}".format(__display_version__))
|
|
||||||
if safe_mode:
|
|
||||||
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
|
|
||||||
if safe_mode == "flag":
|
|
||||||
reason = "command line flag"
|
|
||||||
elif safe_mode == "settings":
|
|
||||||
reason = "setting in config.yaml"
|
|
||||||
elif safe_mode == "incomplete_startup":
|
|
||||||
reason = "problem during last startup"
|
|
||||||
else:
|
|
||||||
reason = "unknown"
|
|
||||||
logger.info("Reason for safe mode: {}".format(reason))
|
|
||||||
|
|
||||||
if recorder and len(recorder):
|
def log_startup(recorder=None, safe_mode=None, **kwargs):
|
||||||
logger.info(get_divider_line("-", "Logged during platform initialization:"))
|
from octoprint.logging import get_divider_line
|
||||||
|
from octoprint.logging.handlers import PluginTimingsLogHandler
|
||||||
|
|
||||||
from octoprint.logging.handlers import CombinedLogHandler
|
logger = logging.getLogger("octoprint.startup")
|
||||||
handler = CombinedLogHandler(*logging.getLogger().handlers)
|
PluginTimingsLogHandler.arm_rollover()
|
||||||
recorder.setTarget(handler)
|
|
||||||
recorder.flush()
|
|
||||||
|
|
||||||
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 recorder and len(recorder):
|
||||||
if not urllib3_ssl:
|
logger.info(get_divider_line("-", "Logged during platform initialization:"))
|
||||||
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("*"))
|
|
||||||
|
|
||||||
def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs):
|
from octoprint.logging.handlers import CombinedLogHandler
|
||||||
from octoprint.logging import get_handler, log_to_handler, get_divider_line
|
|
||||||
from octoprint.logging.handlers import OctoPrintLogHandler
|
|
||||||
|
|
||||||
def rollover_callback():
|
handler = CombinedLogHandler(*logging.getLogger().handlers)
|
||||||
handler = get_handler("file")
|
recorder.setTarget(handler)
|
||||||
if handler is None:
|
recorder.flush()
|
||||||
return
|
|
||||||
|
|
||||||
logger = logging.getLogger("octoprint.server")
|
logger.info(get_divider_line("-"))
|
||||||
|
|
||||||
def _log(message, level=logging.INFO):
|
from octoprint import urllib3_ssl
|
||||||
log_to_handler(logger, handler, level, message)
|
|
||||||
|
|
||||||
_log(get_divider_line("-", "Log roll over detected"))
|
if not urllib3_ssl:
|
||||||
_log("OctoPrint {}".format(__display_version__))
|
logging.getLogger("octoprint.server").warning(
|
||||||
if safe_mode:
|
"requests/urllib3 will run in an insecure SSL environment. "
|
||||||
_log("SAFE MODE is active. Third party plugins are disabled!")
|
"You might see corresponding warnings logged later "
|
||||||
plugin_manager.log_all_plugins(only_to_handler=handler)
|
'("InsecurePlatformWarning"). It is recommended to either '
|
||||||
environment_detector.log_detected_environment(only_to_handler=handler)
|
"update to a Python version >= 2.7.9 or alternatively "
|
||||||
_log(get_divider_line("-"))
|
"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:
|
def rollover_callback():
|
||||||
components = init_platform(basedir, configfile,
|
handler = get_handler("file")
|
||||||
logging_file=logging_config,
|
if handler is None:
|
||||||
debug=debug,
|
return
|
||||||
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.server")
|
||||||
logger = logging.getLogger("octoprint.startup").fatal
|
|
||||||
echo = lambda x: click.echo(x, err=True)
|
|
||||||
|
|
||||||
for method in logger, echo:
|
def _log(message, level=logging.INFO):
|
||||||
method(str(e))
|
log_to_handler(logger, handler, level, message)
|
||||||
method("There was a fatal error starting up OctoPrint.")
|
|
||||||
|
|
||||||
else:
|
_log(get_divider_line("-", "Log roll over detected"))
|
||||||
from octoprint.server import Server
|
_log("OctoPrint {}".format(__display_version__))
|
||||||
octoprint_server = Server(settings=settings,
|
if safe_mode:
|
||||||
plugin_manager=plugin_manager,
|
_log("SAFE MODE is active. Third party plugins are disabled!")
|
||||||
event_manager=event_manager,
|
plugin_manager.log_all_plugins(only_to_handler=handler)
|
||||||
connectivity_checker=connectivity_checker,
|
environment_detector.log_detected_environment(only_to_handler=handler)
|
||||||
environment_detector=environment_detector,
|
_log(get_divider_line("-"))
|
||||||
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
|
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
|
||||||
|
|
||||||
server_options = bulk_options([
|
try:
|
||||||
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
|
components = init_platform(
|
||||||
help="Specify the host address on which to bind the server."),
|
basedir,
|
||||||
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
|
configfile,
|
||||||
help="Specify the port on which to bind the server."),
|
logging_file=logging_config,
|
||||||
click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option,
|
debug=debug,
|
||||||
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."),
|
verbosity=verbosity,
|
||||||
click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option,
|
uncaught_logger=__name__,
|
||||||
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."),
|
safe_mode=safe_mode,
|
||||||
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
|
ignore_blacklist=ignore_blacklist,
|
||||||
help="Specify the config file to use for configuring logging."),
|
after_safe_mode=log_startup,
|
||||||
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
|
after_environment_detector=log_register_rollover,
|
||||||
help="Allow OctoPrint to run as user root."),
|
)
|
||||||
click.option("--debug", is_flag=True, callback=set_ctx_obj_option,
|
(
|
||||||
help="Enable debug mode."),
|
settings,
|
||||||
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
|
_,
|
||||||
help="Disable processing of the plugin blacklist.")
|
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``
|
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6``
|
||||||
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
|
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
|
||||||
|
|
||||||
daemon_options = bulk_options([
|
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.")
|
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``."""
|
"""Decorator to add the options for the daemon subcommand: ``--pid``."""
|
||||||
|
|
||||||
#~~ "octoprint serve" and "octoprint daemon" commands
|
# ~~ "octoprint serve" and "octoprint daemon" commands
|
||||||
|
|
||||||
|
|
||||||
@click.group()
|
@click.group()
|
||||||
def server_commands():
|
def server_commands():
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@server_commands.command(name="safemode")
|
@server_commands.command(name="safemode")
|
||||||
@standard_options()
|
@standard_options()
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def enable_safemode(ctx, **kwargs):
|
def enable_safemode(ctx, **kwargs):
|
||||||
"""Sets the safe mode flag for the next start."""
|
"""Sets the safe mode flag for the next start."""
|
||||||
from octoprint import init_settings, FatalStartupError
|
from octoprint import FatalStartupError, init_settings
|
||||||
|
|
||||||
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
|
logging.basicConfig(
|
||||||
try:
|
level=logging.DEBUG
|
||||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
|
||||||
except FatalStartupError as e:
|
else logging.WARN
|
||||||
click.echo(e.message, err=True)
|
)
|
||||||
click.echo("There was a fatal error initializing the settings manager.", err=True)
|
try:
|
||||||
ctx.exit(-1)
|
settings = init_settings(
|
||||||
else:
|
get_ctx_obj_option(ctx, "basedir", None),
|
||||||
settings.setBoolean(["server", "startOnceInSafeMode"], True)
|
get_ctx_obj_option(ctx, "configfile", None),
|
||||||
settings.save()
|
)
|
||||||
|
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")
|
@server_commands.command(name="serve")
|
||||||
@@ -180,109 +279,156 @@ def enable_safemode(ctx, **kwargs):
|
|||||||
@server_options
|
@server_options
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def serve_command(ctx, **kwargs):
|
def serve_command(ctx, **kwargs):
|
||||||
"""Starts the OctoPrint server."""
|
"""Starts the OctoPrint server."""
|
||||||
|
|
||||||
def get_value(key):
|
def get_value(key):
|
||||||
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
||||||
|
|
||||||
host = get_value("host")
|
host = get_value("host")
|
||||||
port = get_value("port")
|
port = get_value("port")
|
||||||
v4 = get_value("v4")
|
v4 = get_value("v4")
|
||||||
v6 = get_value("v6")
|
v6 = get_value("v6")
|
||||||
logging = get_value("logging")
|
logging = get_value("logging")
|
||||||
allow_root = get_value("allow_root")
|
allow_root = get_value("allow_root")
|
||||||
debug = get_value("debug")
|
debug = get_value("debug")
|
||||||
|
|
||||||
basedir = get_value("basedir")
|
basedir = get_value("basedir")
|
||||||
configfile = get_value("configfile")
|
configfile = get_value("configfile")
|
||||||
verbosity = get_value("verbosity")
|
verbosity = get_value("verbosity")
|
||||||
safe_mode = "flag" if get_value("safe_mode") else None
|
safe_mode = "flag" if get_value("safe_mode") else None
|
||||||
ignore_blacklist = get_value("ignore_blacklist")
|
ignore_blacklist = get_value("ignore_blacklist")
|
||||||
|
|
||||||
if v4 and not host:
|
if v4 and not host:
|
||||||
host = "0.0.0.0"
|
host = "0.0.0.0"
|
||||||
|
|
||||||
run_server(basedir, configfile, host, port, v6, debug,
|
run_server(
|
||||||
allow_root, logging, verbosity, safe_mode,
|
basedir,
|
||||||
ignore_blacklist)
|
configfile,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
v6,
|
||||||
|
debug,
|
||||||
|
allow_root,
|
||||||
|
logging,
|
||||||
|
verbosity,
|
||||||
|
safe_mode,
|
||||||
|
ignore_blacklist,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
if sys.platform != "win32" and sys.platform != "darwin":
|
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")
|
@server_commands.command(name="daemon")
|
||||||
@standard_options()
|
@standard_options()
|
||||||
@server_options
|
@server_options
|
||||||
@daemon_options
|
@daemon_options
|
||||||
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
|
@click.argument(
|
||||||
metavar="start|stop|restart|status")
|
"command",
|
||||||
@click.pass_context
|
type=click.Choice(["start", "stop", "restart", "status"]),
|
||||||
def daemon_command(ctx, command, **kwargs):
|
metavar="start|stop|restart|status",
|
||||||
"""
|
)
|
||||||
Starts, stops or restarts in daemon mode.
|
@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):
|
def get_value(key):
|
||||||
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
||||||
|
|
||||||
host = get_value("host")
|
host = get_value("host")
|
||||||
port = get_value("port")
|
port = get_value("port")
|
||||||
v4 = get_value("v4")
|
v4 = get_value("v4")
|
||||||
v6 = get_value("v6")
|
v6 = get_value("v6")
|
||||||
logging = get_value("logging")
|
logging = get_value("logging")
|
||||||
allow_root = get_value("allow_root")
|
allow_root = get_value("allow_root")
|
||||||
debug = get_value("debug")
|
debug = get_value("debug")
|
||||||
pid = get_value("pid")
|
pid = get_value("pid")
|
||||||
|
|
||||||
basedir = get_value("basedir")
|
basedir = get_value("basedir")
|
||||||
configfile = get_value("configfile")
|
configfile = get_value("configfile")
|
||||||
verbosity = get_value("verbosity")
|
verbosity = get_value("verbosity")
|
||||||
safe_mode = "flag" if get_value("safe_mode") else None
|
safe_mode = "flag" if get_value("safe_mode") else None
|
||||||
ignore_blacklist = get_value("ignore_blacklist")
|
ignore_blacklist = get_value("ignore_blacklist")
|
||||||
|
|
||||||
if v4 and not host:
|
if v4 and not host:
|
||||||
host = "0.0.0.0"
|
host = "0.0.0.0"
|
||||||
|
|
||||||
if pid is None:
|
if pid is None:
|
||||||
click.echo("No path to a pidfile set",
|
click.echo("No path to a pidfile set", file=sys.stderr)
|
||||||
file=sys.stderr)
|
sys.exit(1)
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
from octoprint.daemon import Daemon
|
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)
|
|
||||||
|
|
||||||
self._basedir = basedir
|
class OctoPrintDaemon(Daemon):
|
||||||
self._configfile = configfile
|
def __init__(
|
||||||
self._host = host
|
self,
|
||||||
self._port = port
|
pidfile,
|
||||||
self._v6_only = v6_only
|
basedir,
|
||||||
self._debug = debug
|
configfile,
|
||||||
self._allow_root = allow_root
|
host,
|
||||||
self._logging_config = logging_config
|
port,
|
||||||
self._verbosity = verbosity
|
v6_only,
|
||||||
self._safe_mode = safe_mode
|
debug,
|
||||||
self._ignore_blacklist = ignore_blacklist
|
allow_root,
|
||||||
|
logging_config,
|
||||||
|
verbosity,
|
||||||
|
safe_mode,
|
||||||
|
ignore_blacklist,
|
||||||
|
):
|
||||||
|
Daemon.__init__(self, pidfile)
|
||||||
|
|
||||||
def run(self):
|
self._basedir = basedir
|
||||||
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
|
self._configfile = configfile
|
||||||
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
|
self._host = host
|
||||||
self._ignore_blacklist, octoprint_daemon=self)
|
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,
|
def run(self):
|
||||||
verbosity, safe_mode, ignore_blacklist)
|
run_server(
|
||||||
|
self._basedir,
|
||||||
if command == "start":
|
self._configfile,
|
||||||
octoprint_daemon.start()
|
self._host,
|
||||||
elif command == "stop":
|
self._port,
|
||||||
octoprint_daemon.stop()
|
self._v6_only,
|
||||||
elif command == "restart":
|
self._debug,
|
||||||
octoprint_daemon.restart()
|
self._allow_root,
|
||||||
elif command == "status":
|
self._logging_config,
|
||||||
octoprint_daemon.status()
|
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()
|
||||||
@@ -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
@@ -1,124 +1,157 @@
|
|||||||
# coding=utf-8
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
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"
|
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
|
|
||||||
import click
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
import click
|
||||||
|
|
||||||
from octoprint import init_settings
|
from octoprint import init_settings
|
||||||
from octoprint.cli import get_ctx_obj_option
|
|
||||||
from octoprint.access.groups import FilebasedGroupManager
|
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
|
from octoprint.util import get_class, sv
|
||||||
|
|
||||||
click.disable_unicode_literals_warning = True
|
click.disable_unicode_literals_warning = True
|
||||||
|
|
||||||
#~~ "octoprint user" commands
|
# ~~ "octoprint user" commands
|
||||||
|
|
||||||
|
|
||||||
@click.group()
|
@click.group()
|
||||||
def user_commands():
|
def user_commands():
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@user_commands.group(name="user")
|
@user_commands.group(name="user")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def user(ctx):
|
def user(ctx):
|
||||||
"""
|
"""
|
||||||
User management.
|
User management.
|
||||||
|
|
||||||
Note that this currently only supports managing user accounts stored in the configured user manager, not any
|
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.
|
user managers added through plugins and the "octoprint.users.factory" hook.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
|
logging.basicConfig(
|
||||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
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"])
|
group_manager_name = settings.get(["accessControl", "groupManager"])
|
||||||
try:
|
try:
|
||||||
clazz = get_class(group_manager_name)
|
clazz = get_class(group_manager_name)
|
||||||
group_manager = clazz()
|
group_manager = clazz()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
click.echo("Could not instantiate group manager {}, "
|
click.echo(
|
||||||
"falling back to FilebasedGroupManager!".format(group_manager_name), err=True)
|
"Could not instantiate group manager {}, "
|
||||||
group_manager = FilebasedGroupManager()
|
"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"])
|
name = settings.get(["accessControl", "userManager"])
|
||||||
try:
|
try:
|
||||||
clazz = get_class(name)
|
clazz = get_class(name)
|
||||||
user_manager = clazz(group_manager=group_manager, settings=settings)
|
user_manager = clazz(group_manager=group_manager, settings=settings)
|
||||||
except Exception:
|
except CorruptUserStorage:
|
||||||
click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
|
raise
|
||||||
user_manager = FilebasedUserManager(group_manager, settings=settings)
|
except Exception:
|
||||||
finally:
|
click.echo(
|
||||||
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
|
"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:
|
except Exception:
|
||||||
click.echo("Could not instantiate user manager", err=True)
|
click.echo("Could not instantiate user manager", err=True)
|
||||||
return
|
ctx.exit(-1)
|
||||||
|
|
||||||
|
|
||||||
@user.command(name="list")
|
@user.command(name="list")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def list_users_command(ctx):
|
def list_users_command(ctx):
|
||||||
"""Lists user information"""
|
"""Lists user information"""
|
||||||
users = ctx.obj.user_manager.get_all_users()
|
users = ctx.obj.user_manager.get_all_users()
|
||||||
_print_list(users)
|
_print_list(users)
|
||||||
|
|
||||||
|
|
||||||
@user.command(name="add")
|
@user.command(name="add")
|
||||||
@click.argument("username", type=click.STRING, required=True)
|
@click.argument("username", type=click.STRING, required=True)
|
||||||
@click.password_option("--password", "password", help="Password for the user")
|
@click.password_option("--password", "password", help="Password for the user")
|
||||||
@click.option("-g", "--group", "groups", multiple=True,
|
@click.option("-g", "--group", "groups", multiple=True, help="Groups to set on the user")
|
||||||
help="Groups to set on the user")
|
@click.option(
|
||||||
@click.option("-p", "--permission", "permissions", multiple=True,
|
"-p",
|
||||||
help="Individual permissions to set on the user")
|
"--permission",
|
||||||
@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
|
"permissions",
|
||||||
help="Adds user to admin group")
|
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
|
@click.pass_context
|
||||||
def add_user_command(ctx, username, password, groups, permissions, is_admin):
|
def add_user_command(ctx, username, password, groups, permissions, is_admin):
|
||||||
"""Add a new user."""
|
"""Add a new user."""
|
||||||
if not groups:
|
if not groups:
|
||||||
groups = []
|
groups = []
|
||||||
|
|
||||||
if is_admin:
|
if is_admin:
|
||||||
groups.append(ctx.obj.group_manager.admin_group)
|
groups.append(ctx.obj.group_manager.admin_group)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ctx.obj.user_manager.add_user(username,
|
ctx.obj.user_manager.add_user(
|
||||||
password,
|
username, password, groups=groups, permissions=permissions, active=True
|
||||||
groups=groups,
|
)
|
||||||
permissions=permissions,
|
|
||||||
active=True)
|
|
||||||
|
|
||||||
user = ctx.obj.user_manager.find_user(username)
|
user = ctx.obj.user_manager.find_user(username)
|
||||||
if user:
|
if user:
|
||||||
click.echo("User created:")
|
click.echo("User created:")
|
||||||
click.echo("\t{}".format(_user_to_line(user.as_dict())))
|
click.echo("\t{}".format(_user_to_line(user.as_dict())))
|
||||||
except UserAlreadyExists:
|
except UserAlreadyExists:
|
||||||
click.echo("A user with the name {} does already exist!".format(username), err=True)
|
click.echo(
|
||||||
|
"A user with the name {} does already exist!".format(username), err=True
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@user.command(name="remove")
|
@user.command(name="remove")
|
||||||
@click.argument("username", type=click.STRING)
|
@click.argument("username", type=click.STRING)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def remove_user_command(ctx, username):
|
def remove_user_command(ctx, username):
|
||||||
"""Remove an existing user."""
|
"""Remove an existing user."""
|
||||||
confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
|
confirm = click.prompt(
|
||||||
type=click.STRING)
|
"This is will irreversibly destroy the user account! Enter 'yes' to confirm",
|
||||||
|
type=click.STRING,
|
||||||
|
)
|
||||||
|
|
||||||
if confirm.lower() == "yes":
|
if confirm.lower() == "yes":
|
||||||
ctx.obj.user_manager.remove_user(username)
|
ctx.obj.user_manager.remove_user(username)
|
||||||
click.echo("User {} removed.".format(username))
|
click.echo("User {} removed.".format(username))
|
||||||
else:
|
else:
|
||||||
click.echo("User {} not removed.".format(username))
|
click.echo("User {} not removed.".format(username))
|
||||||
|
|
||||||
|
|
||||||
@user.command(name="password")
|
@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.password_option("--password", "password", help="New password for user")
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def change_password_command(ctx, username, password):
|
def change_password_command(ctx, username, password):
|
||||||
"""Change an existing user's password."""
|
"""Change an existing user's password."""
|
||||||
try:
|
try:
|
||||||
ctx.obj.user_manager.change_user_password(username, password)
|
ctx.obj.user_manager.change_user_password(username, password)
|
||||||
click.echo("Password changed for user {}.".format(username))
|
click.echo("Password changed for user {}.".format(username))
|
||||||
except UnknownUser:
|
except UnknownUser:
|
||||||
click.echo("User {} does not exist!".format(username), err=True)
|
click.echo("User {} does not exist!".format(username), err=True)
|
||||||
|
|
||||||
|
|
||||||
@user.command(name="activate")
|
@user.command(name="activate")
|
||||||
@click.argument("username", type=click.STRING)
|
@click.argument("username", type=click.STRING)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def activate_command(ctx, username):
|
def activate_command(ctx, username):
|
||||||
"""Activate a user account."""
|
"""Activate a user account."""
|
||||||
try:
|
try:
|
||||||
ctx.obj.user_manager.change_user_activation(username, True)
|
ctx.obj.user_manager.change_user_activation(username, True)
|
||||||
click.echo("User {} activated.".format(username))
|
click.echo("User {} activated.".format(username))
|
||||||
|
|
||||||
user = ctx.obj.user_manager.find_user(username)
|
user = ctx.obj.user_manager.find_user(username)
|
||||||
if user:
|
if user:
|
||||||
click.echo("User created:")
|
click.echo("User created:")
|
||||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||||
except UnknownUser:
|
except UnknownUser:
|
||||||
click.echo("User {} does not exist!".format(username), err=True)
|
click.echo("User {} does not exist!".format(username), err=True)
|
||||||
|
|
||||||
|
|
||||||
@user.command(name="deactivate")
|
@user.command(name="deactivate")
|
||||||
@click.argument("username", type=click.STRING)
|
@click.argument("username", type=click.STRING)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def deactivate_command(ctx, username):
|
def deactivate_command(ctx, username):
|
||||||
"""Activate a user account."""
|
"""Activate a user account."""
|
||||||
try:
|
try:
|
||||||
ctx.obj.user_manager.change_user_activation(username, False)
|
ctx.obj.user_manager.change_user_activation(username, False)
|
||||||
click.echo("User {} activated.".format(username))
|
click.echo("User {} activated.".format(username))
|
||||||
|
|
||||||
user = ctx.obj.user_manager.find_user(username)
|
user = ctx.obj.user_manager.find_user(username)
|
||||||
if user:
|
if user:
|
||||||
click.echo("User created:")
|
click.echo("User created:")
|
||||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||||
except UnknownUser:
|
except UnknownUser:
|
||||||
click.echo("User {} does not exist!".format(username), err=True)
|
click.echo("User {} does not exist!".format(username), err=True)
|
||||||
|
|
||||||
|
|
||||||
def _print_list(users):
|
def _print_list(users):
|
||||||
click.echo("{} users registered in the system:".format(len(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"))):
|
for user in sorted(
|
||||||
click.echo("\t{}".format(_user_to_line(user)))
|
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):
|
def _user_to_line(user):
|
||||||
return "{name}" \
|
return (
|
||||||
"\n\t\tactive: {active}" \
|
"{name}"
|
||||||
"\n\t\tgroups: {groups}" \
|
"\n\t\tactive: {active}"
|
||||||
"\n\t\tpermissions: {permissions}".format(name=user.get("name"),
|
"\n\t\tgroups: {groups}"
|
||||||
active=user.get("active", "False"),
|
"\n\t\tpermissions: {permissions}".format(
|
||||||
groups=", ".join(user.get("groups", [])),
|
name=user.get("name"),
|
||||||
permissions=", ".join(user.get("permissions", [])))
|
active=user.get("active", "False"),
|
||||||
|
groups=", ".join(user.get("groups", [])),
|
||||||
|
permissions=", ".join(user.get("permissions", [])),
|
||||||
|
)
|
||||||
|
)
|
||||||
+147
-134
@@ -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
|
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:
|
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,
|
If you want to log the output to someplace different that stdout and stderr,
|
||||||
also override the echo() and error() methods.
|
also override the echo() and error() methods.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, pidfile):
|
def __init__(self, pidfile):
|
||||||
self.pidfile = pidfile
|
self.pidfile = pidfile
|
||||||
|
|
||||||
def _daemonize(self):
|
def _daemonize(self):
|
||||||
"""Daemonize class. UNIX double fork mechanism."""
|
"""Daemonize class. UNIX double fork mechanism."""
|
||||||
|
|
||||||
self._double_fork()
|
self._double_fork()
|
||||||
self._redirect_io()
|
self._redirect_io()
|
||||||
|
|
||||||
# write pidfile
|
# write pidfile
|
||||||
pid = str(os.getpid())
|
pid = str(os.getpid())
|
||||||
self.set_pid(pid)
|
self.set_pid(pid)
|
||||||
|
|
||||||
def _double_fork(self):
|
def _double_fork(self):
|
||||||
try:
|
try:
|
||||||
pid = os.fork()
|
pid = os.fork()
|
||||||
if pid > 0:
|
if pid > 0:
|
||||||
# exit first parent
|
# exit first parent
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
except OSError as err:
|
except OSError as err:
|
||||||
self.error("First fork failed: {}".format(str(err)))
|
self.error("First fork failed: {}".format(str(err)))
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# decouple from parent environment
|
# decouple from parent environment
|
||||||
os.chdir('/')
|
os.chdir("/")
|
||||||
os.setsid()
|
os.setsid()
|
||||||
os.umask(0o002)
|
os.umask(0o002)
|
||||||
|
|
||||||
# do second fork
|
# do second fork
|
||||||
try:
|
try:
|
||||||
pid = os.fork()
|
pid = os.fork()
|
||||||
if pid > 0:
|
if pid > 0:
|
||||||
# exit from second parent
|
# exit from second parent
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
except OSError as err:
|
except OSError as err:
|
||||||
self.error("Second fork failed: {}".format(str(err)))
|
self.error("Second fork failed: {}".format(str(err)))
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
def _redirect_io(self):
|
def _redirect_io(self):
|
||||||
# redirect standard file descriptors
|
# redirect standard file descriptors
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
sys.stderr.flush()
|
sys.stderr.flush()
|
||||||
si = io.open(os.devnull, 'rt', encoding='utf-8')
|
si = io.open(os.devnull, "rt", encoding="utf-8")
|
||||||
so = io.open(os.devnull, 'at+', encoding='utf-8')
|
so = io.open(os.devnull, "at+", encoding="utf-8")
|
||||||
se = 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(si.fileno(), sys.stdin.fileno())
|
||||||
os.dup2(so.fileno(), sys.stdout.fileno())
|
os.dup2(so.fileno(), sys.stdout.fileno())
|
||||||
os.dup2(se.fileno(), sys.stderr.fileno())
|
os.dup2(se.fileno(), sys.stderr.fileno())
|
||||||
|
|
||||||
def terminated(self):
|
def terminated(self):
|
||||||
self.remove_pidfile()
|
self.remove_pidfile()
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
"""Start the daemon."""
|
"""Start the daemon."""
|
||||||
|
|
||||||
# Check for a pidfile to see if the daemon already runs
|
# Check for a pidfile to see if the daemon already runs
|
||||||
pid = self.get_pid()
|
pid = self.get_pid()
|
||||||
if pid:
|
if pid:
|
||||||
self.error("pidfile {} already exist. Is the daemon already running?".format(self.pidfile))
|
self.error(
|
||||||
sys.exit(1)
|
"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
|
# Start the daemon
|
||||||
self._daemonize()
|
self._daemonize()
|
||||||
self.run()
|
self.run()
|
||||||
|
|
||||||
def stop(self, check_running=True):
|
def stop(self, check_running=True):
|
||||||
"""Stop the daemon."""
|
"""Stop the daemon."""
|
||||||
pid = self.get_pid()
|
pid = self.get_pid()
|
||||||
if not pid:
|
if not pid:
|
||||||
if not check_running:
|
if not check_running:
|
||||||
return
|
return
|
||||||
self.error("pidfile {} does not exist. Is the daemon really running?".format(self.pidfile))
|
self.error(
|
||||||
sys.exit(1)
|
"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 killing the daemon process
|
||||||
try:
|
try:
|
||||||
while 1:
|
while 1:
|
||||||
os.kill(pid, signal.SIGTERM)
|
os.kill(pid, signal.SIGTERM)
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
except OSError as err:
|
except OSError as err:
|
||||||
e = str(err.args)
|
e = str(err.args)
|
||||||
if e.find("No such process") > 0:
|
if e.find("No such process") > 0:
|
||||||
self.remove_pidfile()
|
self.remove_pidfile()
|
||||||
else:
|
else:
|
||||||
self.error(e)
|
self.error(e)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
def restart(self):
|
def restart(self):
|
||||||
"""Restart the daemon."""
|
"""Restart the daemon."""
|
||||||
self.stop(check_running=False)
|
self.stop(check_running=False)
|
||||||
self.start()
|
self.start()
|
||||||
|
|
||||||
def status(self):
|
def status(self):
|
||||||
"""Prints the daemon status."""
|
"""Prints the daemon status."""
|
||||||
if self.is_running():
|
if self.is_running():
|
||||||
self.echo("Daemon is running")
|
self.echo("Daemon is running")
|
||||||
else:
|
else:
|
||||||
self.echo("Daemon is not running")
|
self.echo("Daemon is not running")
|
||||||
|
|
||||||
def is_running(self):
|
def is_running(self):
|
||||||
"""Check if a process is running under the specified pid."""
|
"""Check if a process is running under the specified pid."""
|
||||||
pid = self.get_pid()
|
pid = self.get_pid()
|
||||||
if pid is None:
|
if pid is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
os.kill(pid, 0)
|
os.kill(pid, 0)
|
||||||
except OSError:
|
except OSError:
|
||||||
try:
|
try:
|
||||||
self.remove_pidfile()
|
self.remove_pidfile()
|
||||||
except Exception:
|
except Exception:
|
||||||
self.error("Daemon found not running, but could not remove stale pidfile")
|
self.error("Daemon found not running, but could not remove stale pidfile")
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def get_pid(self):
|
def get_pid(self):
|
||||||
"""Get the pid from the pidfile."""
|
"""Get the pid from the pidfile."""
|
||||||
try:
|
try:
|
||||||
with io.open(self.pidfile,'rt', encoding='utf-8') as pf:
|
with io.open(self.pidfile, "rt", encoding="utf-8") as pf:
|
||||||
pid = int(pf.read().strip())
|
pid = int(pf.read().strip())
|
||||||
except (IOError, ValueError):
|
except (IOError, ValueError):
|
||||||
pid = None
|
pid = None
|
||||||
return pid
|
return pid
|
||||||
|
|
||||||
def set_pid(self, pid):
|
def set_pid(self, pid):
|
||||||
"""Write the pid to the pidfile."""
|
"""Write the pid to the pidfile."""
|
||||||
with io.open(self.pidfile,'wt+', encoding='utf-8') as f:
|
with io.open(self.pidfile, "wt+", encoding="utf-8") as f:
|
||||||
f.write(str(pid) + '\n')
|
f.write(str(pid) + "\n")
|
||||||
|
|
||||||
def remove_pidfile(self):
|
def remove_pidfile(self):
|
||||||
"""Removes the pidfile."""
|
"""Removes the pidfile."""
|
||||||
if os.path.isfile(self.pidfile):
|
if os.path.isfile(self.pidfile):
|
||||||
os.remove(self.pidfile)
|
os.remove(self.pidfile)
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
"""You should override this method when you subclass Daemon.
|
"""You should override this method when you subclass Daemon.
|
||||||
|
|
||||||
It will be called after the process has been daemonized by
|
It will be called after the process has been daemonized by
|
||||||
start() or restart()."""
|
start() or restart()."""
|
||||||
|
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def echo(cls, line):
|
def echo(cls, line):
|
||||||
print(line)
|
print(line)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def error(cls, line):
|
def error(cls, line):
|
||||||
print(line, file=sys.stderr)
|
print(line, file=sys.stderr)
|
||||||
+151
-127
@@ -1,7 +1,7 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
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"
|
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
import copy
|
import copy
|
||||||
@@ -9,165 +9,189 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
import yaml
|
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
|
import yaml
|
||||||
|
|
||||||
from octoprint.plugin import EnvironmentDetectionPlugin
|
from octoprint.plugin import EnvironmentDetectionPlugin
|
||||||
from octoprint.util.platform import get_os
|
from octoprint.util.platform import get_os
|
||||||
from octoprint.util.version import get_python_version_string
|
from octoprint.util.version import get_python_version_string
|
||||||
|
|
||||||
|
|
||||||
class EnvironmentDetector(object):
|
class EnvironmentDetector(object):
|
||||||
|
def __init__(self, plugin_manager):
|
||||||
|
self._plugin_manager = plugin_manager
|
||||||
|
|
||||||
def __init__(self, plugin_manager):
|
self._cache = None
|
||||||
self._plugin_manager = plugin_manager
|
self._cache_lock = threading.RLock()
|
||||||
|
|
||||||
self._cache = None
|
self._logger = logging.getLogger(__name__)
|
||||||
self._cache_lock = threading.RLock()
|
|
||||||
|
|
||||||
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:
|
@property
|
||||||
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
|
def environment(self):
|
||||||
except Exception:
|
with self._cache_lock:
|
||||||
# just in case, see #3100...
|
if self._cache is None:
|
||||||
self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager")
|
self.run_detection()
|
||||||
self._environment_plugins = []
|
return copy.deepcopy(self._cache)
|
||||||
|
|
||||||
@property
|
def run_detection(self, notify_plugins=True):
|
||||||
def environment(self):
|
try:
|
||||||
with self._cache_lock:
|
environment = {}
|
||||||
if self._cache is None:
|
environment["os"] = self._detect_os()
|
||||||
self.run_detection()
|
environment["python"] = self._detect_python()
|
||||||
return copy.deepcopy(self._cache)
|
environment["hardware"] = self._detect_hardware()
|
||||||
|
|
||||||
def run_detection(self, notify_plugins=True):
|
plugin_result = self._detect_from_plugins()
|
||||||
try:
|
if plugin_result:
|
||||||
environment = dict()
|
environment["plugins"] = plugin_result
|
||||||
environment["os"] = self._detect_os()
|
|
||||||
environment["python"] = self._detect_python()
|
|
||||||
environment["hardware"] = self._detect_hardware()
|
|
||||||
|
|
||||||
plugin_result = self._detect_from_plugins()
|
with self._cache_lock:
|
||||||
if plugin_result:
|
self._cache = environment
|
||||||
environment["plugins"] = plugin_result
|
|
||||||
|
|
||||||
with self._cache_lock:
|
if notify_plugins:
|
||||||
self._cache = environment
|
self.notify_plugins()
|
||||||
|
|
||||||
if notify_plugins:
|
return environment
|
||||||
self.notify_plugins()
|
except Exception:
|
||||||
|
self._logger.exception("Unexpected error while detecting environment")
|
||||||
|
with self._cache_lock:
|
||||||
|
self._cache = {}
|
||||||
|
return self._cache
|
||||||
|
|
||||||
return environment
|
def _detect_os(self):
|
||||||
except Exception:
|
return {
|
||||||
self._logger.exception("Unexpected error while detecting environment")
|
"id": get_os(),
|
||||||
with self._cache_lock:
|
"platform": sys.platform,
|
||||||
self._cache = dict()
|
"bits": 64 if sys.maxsize > 2 ** 32 else 32,
|
||||||
return self._cache
|
}
|
||||||
|
|
||||||
def _detect_os(self):
|
def _detect_python(self):
|
||||||
return dict(id=get_os(),
|
result = {"version": "unknown", "pip": "unknown"}
|
||||||
platform=sys.platform)
|
|
||||||
|
|
||||||
def _detect_python(self):
|
# determine python version
|
||||||
result = dict(version="unknown",
|
try:
|
||||||
pip="unknown")
|
result["version"] = get_python_version_string()
|
||||||
|
except Exception:
|
||||||
|
self._logger.exception("Error detecting python version")
|
||||||
|
|
||||||
# determine python version
|
# determine if we are running from a virtual environment
|
||||||
try:
|
try:
|
||||||
result["version"] = get_python_version_string()
|
if hasattr(sys, "real_prefix") or (
|
||||||
except Exception:
|
hasattr(sys, "base_prefix")
|
||||||
self._logger.exception("Error detecting python version")
|
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 to find pip version
|
||||||
try:
|
try:
|
||||||
if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
|
import pkg_resources
|
||||||
result["virtualenv"] = sys.prefix
|
|
||||||
except Exception:
|
|
||||||
self._logger.exception("Error detecting whether we are running in a virtual environment")
|
|
||||||
|
|
||||||
# try to find pip version
|
result["pip"] = pkg_resources.get_distribution("pip").version
|
||||||
try:
|
except Exception:
|
||||||
import pkg_resources
|
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):
|
def _detect_hardware(self):
|
||||||
result = dict(cores="unknown",
|
result = {"cores": "unknown", "freq": "unknown", "ram": "unknown"}
|
||||||
freq="unknown",
|
|
||||||
ram="unknown")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
cores = psutil.cpu_count()
|
cores = psutil.cpu_count()
|
||||||
cpu_freq = psutil.cpu_freq()
|
cpu_freq = psutil.cpu_freq()
|
||||||
ram = psutil.virtual_memory()
|
ram = psutil.virtual_memory()
|
||||||
if cores:
|
if cores:
|
||||||
result["cores"] = cores
|
result["cores"] = cores
|
||||||
if cpu_freq and hasattr(cpu_freq, "max"):
|
if cpu_freq and hasattr(cpu_freq, "max"):
|
||||||
result["freq"] = cpu_freq.max
|
result["freq"] = cpu_freq.max
|
||||||
if ram and hasattr(ram, "total"):
|
if ram and hasattr(ram, "total"):
|
||||||
result["ram"] = ram.total
|
result["ram"] = ram.total
|
||||||
except Exception:
|
except Exception:
|
||||||
self._logger.exception("Error while detecting hardware environment")
|
self._logger.exception("Error while detecting hardware environment")
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def _detect_from_plugins(self):
|
def _detect_from_plugins(self):
|
||||||
result = dict()
|
result = {}
|
||||||
|
|
||||||
for implementation in self._environment_plugins:
|
for implementation in self._environment_plugins:
|
||||||
try:
|
try:
|
||||||
additional = implementation.get_additional_environment()
|
additional = implementation.get_additional_environment()
|
||||||
if additional is not None and isinstance(additional, dict) and len(additional):
|
if (
|
||||||
result[implementation._identifier] = additional
|
additional is not None
|
||||||
except Exception:
|
and isinstance(additional, dict)
|
||||||
self._logger.exception("Error while fetching additional "
|
and len(additional)
|
||||||
"environment data from plugin {}".format(implementation._identifier),
|
):
|
||||||
extra=dict(plugin=implementation._identifier))
|
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_detected_environment(self, only_to_handler=None):
|
||||||
def _log(message, level=logging.INFO):
|
def _log(message, level=logging.INFO):
|
||||||
if only_to_handler is not None:
|
if only_to_handler is not None:
|
||||||
import octoprint.logging
|
import octoprint.logging
|
||||||
octoprint.logging.log_to_handler(self._logger, only_to_handler, level, message, [])
|
|
||||||
else:
|
|
||||||
self._logger.log(level, message)
|
|
||||||
|
|
||||||
try:
|
octoprint.logging.log_to_handler(
|
||||||
_log(self._format())
|
self._logger, only_to_handler, level, message, []
|
||||||
except Exception:
|
)
|
||||||
self._logger.exception("Error logging detected environment")
|
else:
|
||||||
|
self._logger.log(level, message)
|
||||||
|
|
||||||
def _format(self):
|
try:
|
||||||
with self._cache_lock:
|
_log(self._format())
|
||||||
if self._cache is None:
|
except Exception:
|
||||||
self.run_detection()
|
self._logger.exception("Error logging detected environment")
|
||||||
environment = copy.deepcopy(self._cache)
|
|
||||||
|
|
||||||
dumped_environment = yaml.safe_dump(environment,
|
def _format(self):
|
||||||
default_flow_style=False,
|
with self._cache_lock:
|
||||||
indent=4,
|
if self._cache is None:
|
||||||
allow_unicode=True).strip()
|
self.run_detection()
|
||||||
environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n")))
|
environment = copy.deepcopy(self._cache)
|
||||||
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
|
|
||||||
environment["os"]["id"].title(),
|
|
||||||
environment["os"]["platform"],
|
|
||||||
environment_lines)
|
|
||||||
|
|
||||||
def notify_plugins(self):
|
dumped_environment = yaml.safe_dump(
|
||||||
with self._cache_lock:
|
environment, default_flow_style=False, indent=4, allow_unicode=True
|
||||||
if self._cache is None:
|
).strip()
|
||||||
self.run_detection(notify_plugins=False)
|
environment_lines = "\n".join(
|
||||||
environment = copy.deepcopy(self._cache)
|
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:
|
def notify_plugins(self):
|
||||||
try:
|
with self._cache_lock:
|
||||||
implementation.on_environment_detected(environment)
|
if self._cache is None:
|
||||||
except Exception:
|
self.run_detection(notify_plugins=False)
|
||||||
self._logger.exception("Error while sending environment "
|
environment = copy.deepcopy(self._cache)
|
||||||
"detection result to plugin {}".format(implementation._identifier))
|
|
||||||
|
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
@@ -2,487 +2,542 @@
|
|||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||||
|
|
||||||
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
|
__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"
|
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import queue
|
import queue
|
||||||
except ImportError:
|
except ImportError:
|
||||||
import Queue as queue
|
import Queue as queue
|
||||||
import threading
|
|
||||||
import collections
|
import collections
|
||||||
import re
|
import re
|
||||||
|
import threading
|
||||||
|
|
||||||
from octoprint.settings import settings
|
|
||||||
import octoprint.plugin
|
import octoprint.plugin
|
||||||
|
from octoprint.settings import settings
|
||||||
|
|
||||||
# singleton
|
# singleton
|
||||||
_instance = None
|
_instance = None
|
||||||
|
|
||||||
|
|
||||||
def all_events():
|
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):
|
class Events(object):
|
||||||
# server
|
# server
|
||||||
STARTUP = "Startup"
|
STARTUP = "Startup"
|
||||||
SHUTDOWN = "Shutdown"
|
SHUTDOWN = "Shutdown"
|
||||||
CONNECTIVITY_CHANGED = "ConnectivityChanged"
|
CONNECTIVITY_CHANGED = "ConnectivityChanged"
|
||||||
|
|
||||||
# connect/disconnect to printer
|
# connect/disconnect to printer
|
||||||
CONNECTING = "Connecting"
|
CONNECTING = "Connecting"
|
||||||
CONNECTED = "Connected"
|
CONNECTED = "Connected"
|
||||||
DISCONNECTING = "Disconnecting"
|
DISCONNECTING = "Disconnecting"
|
||||||
DISCONNECTED = "Disconnected"
|
DISCONNECTED = "Disconnected"
|
||||||
|
|
||||||
# State changes
|
# State changes
|
||||||
PRINTER_STATE_CHANGED = "PrinterStateChanged"
|
PRINTER_STATE_CHANGED = "PrinterStateChanged"
|
||||||
PRINTER_RESET = "PrinterReset"
|
PRINTER_RESET = "PrinterReset"
|
||||||
|
|
||||||
# connect/disconnect by client
|
# connect/disconnect by client
|
||||||
CLIENT_OPENED = "ClientOpened"
|
CLIENT_OPENED = "ClientOpened"
|
||||||
CLIENT_CLOSED = "ClientClosed"
|
CLIENT_CLOSED = "ClientClosed"
|
||||||
CLIENT_AUTHED = "ClientAuthed"
|
CLIENT_AUTHED = "ClientAuthed"
|
||||||
CLIENT_DEAUTHED = "ClientDeauthed"
|
CLIENT_DEAUTHED = "ClientDeauthed"
|
||||||
|
|
||||||
# user login/logout
|
# user login/logout
|
||||||
USER_LOGGED_IN = "UserLoggedIn"
|
USER_LOGGED_IN = "UserLoggedIn"
|
||||||
USER_LOGGED_OUT = "UserLoggedOut"
|
USER_LOGGED_OUT = "UserLoggedOut"
|
||||||
|
|
||||||
# File management
|
# File management
|
||||||
UPLOAD = "Upload"
|
UPLOAD = "Upload"
|
||||||
FILE_SELECTED = "FileSelected"
|
FILE_SELECTED = "FileSelected"
|
||||||
FILE_DESELECTED = "FileDeselected"
|
FILE_DESELECTED = "FileDeselected"
|
||||||
UPDATED_FILES = "UpdatedFiles"
|
UPDATED_FILES = "UpdatedFiles"
|
||||||
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
|
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
|
||||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||||
|
|
||||||
FILE_ADDED = "FileAdded"
|
FILE_ADDED = "FileAdded"
|
||||||
FILE_REMOVED = "FileRemoved"
|
FILE_REMOVED = "FileRemoved"
|
||||||
FOLDER_ADDED = "FolderAdded"
|
FOLDER_ADDED = "FolderAdded"
|
||||||
FOLDER_REMOVED = "FolderRemoved"
|
FOLDER_REMOVED = "FolderRemoved"
|
||||||
|
|
||||||
# SD Upload
|
# SD Upload
|
||||||
TRANSFER_STARTED = "TransferStarted"
|
TRANSFER_STARTED = "TransferStarted"
|
||||||
TRANSFER_DONE = "TransferDone"
|
TRANSFER_DONE = "TransferDone"
|
||||||
TRANSFER_FAILED = "TransferFailed"
|
TRANSFER_FAILED = "TransferFailed"
|
||||||
|
|
||||||
# print job
|
# print job
|
||||||
PRINT_STARTED = "PrintStarted"
|
PRINT_STARTED = "PrintStarted"
|
||||||
PRINT_DONE = "PrintDone"
|
PRINT_DONE = "PrintDone"
|
||||||
PRINT_FAILED = "PrintFailed"
|
PRINT_FAILED = "PrintFailed"
|
||||||
PRINT_CANCELLING = "PrintCancelling"
|
PRINT_CANCELLING = "PrintCancelling"
|
||||||
PRINT_CANCELLED = "PrintCancelled"
|
PRINT_CANCELLED = "PrintCancelled"
|
||||||
PRINT_PAUSED = "PrintPaused"
|
PRINT_PAUSED = "PrintPaused"
|
||||||
PRINT_RESUMED = "PrintResumed"
|
PRINT_RESUMED = "PrintResumed"
|
||||||
ERROR = "Error"
|
ERROR = "Error"
|
||||||
|
|
||||||
# print/gcode events
|
# print/gcode events
|
||||||
POWER_ON = "PowerOn"
|
POWER_ON = "PowerOn"
|
||||||
POWER_OFF = "PowerOff"
|
POWER_OFF = "PowerOff"
|
||||||
HOME = "Home"
|
HOME = "Home"
|
||||||
Z_CHANGE = "ZChange"
|
Z_CHANGE = "ZChange"
|
||||||
WAITING = "Waiting"
|
WAITING = "Waiting"
|
||||||
DWELL = "Dwelling"
|
DWELL = "Dwelling"
|
||||||
COOLING = "Cooling"
|
COOLING = "Cooling"
|
||||||
ALERT = "Alert"
|
ALERT = "Alert"
|
||||||
CONVEYOR = "Conveyor"
|
CONVEYOR = "Conveyor"
|
||||||
EJECT = "Eject"
|
EJECT = "Eject"
|
||||||
E_STOP = "EStop"
|
E_STOP = "EStop"
|
||||||
POSITION_UPDATE = "PositionUpdate"
|
POSITION_UPDATE = "PositionUpdate"
|
||||||
FIRMWARE_DATA = "FirmwareData"
|
FIRMWARE_DATA = "FirmwareData"
|
||||||
TOOL_CHANGE = "ToolChange"
|
TOOL_CHANGE = "ToolChange"
|
||||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||||
|
COMMAND_SUPPRESSED = "CommandSuppressed"
|
||||||
|
INVALID_TOOL_REPORTED = "InvalidToolReported"
|
||||||
|
|
||||||
# Timelapse
|
# Timelapse
|
||||||
CAPTURE_START = "CaptureStart"
|
CAPTURE_START = "CaptureStart"
|
||||||
CAPTURE_DONE = "CaptureDone"
|
CAPTURE_DONE = "CaptureDone"
|
||||||
CAPTURE_FAILED = "CaptureFailed"
|
CAPTURE_FAILED = "CaptureFailed"
|
||||||
POSTROLL_START = "PostRollStart"
|
POSTROLL_START = "PostRollStart"
|
||||||
POSTROLL_END = "PostRollEnd"
|
POSTROLL_END = "PostRollEnd"
|
||||||
MOVIE_RENDERING = "MovieRendering"
|
MOVIE_RENDERING = "MovieRendering"
|
||||||
MOVIE_DONE = "MovieDone"
|
MOVIE_DONE = "MovieDone"
|
||||||
MOVIE_FAILED = "MovieFailed"
|
MOVIE_FAILED = "MovieFailed"
|
||||||
|
|
||||||
# Slicing
|
# Slicing
|
||||||
SLICING_STARTED = "SlicingStarted"
|
SLICING_STARTED = "SlicingStarted"
|
||||||
SLICING_DONE = "SlicingDone"
|
SLICING_DONE = "SlicingDone"
|
||||||
SLICING_FAILED = "SlicingFailed"
|
SLICING_FAILED = "SlicingFailed"
|
||||||
SLICING_CANCELLED = "SlicingCancelled"
|
SLICING_CANCELLED = "SlicingCancelled"
|
||||||
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
|
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
|
||||||
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
|
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
|
||||||
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
|
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
|
||||||
|
|
||||||
# Printer Profiles
|
# Printer Profiles
|
||||||
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
|
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
|
||||||
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
|
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
|
||||||
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
|
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
|
||||||
|
|
||||||
# Settings
|
# Settings
|
||||||
SETTINGS_UPDATED = "SettingsUpdated"
|
SETTINGS_UPDATED = "SettingsUpdated"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def register_event(cls, event, prefix=None):
|
def register_event(cls, event, prefix=None):
|
||||||
name = cls._to_identifier(event)
|
name = cls._to_identifier(event)
|
||||||
if prefix:
|
if prefix:
|
||||||
event = prefix + event
|
event = prefix + event
|
||||||
name = cls._to_identifier(prefix) + name
|
name = cls._to_identifier(prefix) + name
|
||||||
setattr(cls, name, event)
|
setattr(cls, name, event)
|
||||||
return name, event
|
return name, event
|
||||||
|
|
||||||
# based on https://stackoverflow.com/a/1176023
|
# based on https://stackoverflow.com/a/1176023
|
||||||
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
|
_first_cap_re = re.compile("(.)([A-Z][a-z]+)")
|
||||||
_all_cap_re = re.compile('([a-z0-9])([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():
|
def eventManager():
|
||||||
global _instance
|
global _instance
|
||||||
if _instance is None:
|
if _instance is None:
|
||||||
_instance = EventManager()
|
_instance = EventManager()
|
||||||
return _instance
|
return _instance
|
||||||
|
|
||||||
|
|
||||||
class EventManager(object):
|
class EventManager(object):
|
||||||
"""
|
"""
|
||||||
Handles receiving events and dispatching them to subscribers
|
Handles receiving events and dispatching them to subscribers
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._registeredListeners = collections.defaultdict(list)
|
self._registeredListeners = collections.defaultdict(list)
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
|
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
|
||||||
|
|
||||||
self._startup_signaled = False
|
self._startup_signaled = False
|
||||||
self._shutdown_signaled = False
|
self._shutdown_signaled = False
|
||||||
|
|
||||||
self._queue = queue.Queue()
|
self._queue = queue.Queue()
|
||||||
self._held_back = queue.Queue()
|
self._held_back = queue.Queue()
|
||||||
|
|
||||||
self._worker = threading.Thread(target=self._work)
|
self._worker = threading.Thread(target=self._work)
|
||||||
self._worker.daemon = True
|
self._worker.daemon = True
|
||||||
self._worker.start()
|
self._worker.start()
|
||||||
|
|
||||||
def _work(self):
|
def _work(self):
|
||||||
try:
|
try:
|
||||||
while not self._shutdown_signaled:
|
while not self._shutdown_signaled:
|
||||||
event, payload = self._queue.get(True)
|
event, payload = self._queue.get(True)
|
||||||
if event == Events.SHUTDOWN:
|
if event == Events.SHUTDOWN:
|
||||||
# we've got the shutdown event here, stop event loop processing after this has been processed
|
# 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._logger.info(
|
||||||
self._shutdown_signaled = True
|
"Processing shutdown event, this will be our last event"
|
||||||
|
)
|
||||||
|
self._shutdown_signaled = True
|
||||||
|
|
||||||
eventListeners = self._registeredListeners[event]
|
eventListeners = self._registeredListeners[event]
|
||||||
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
|
self._logger_fire.debug(
|
||||||
|
"Firing event: {} (Payload: {!r})".format(event, payload)
|
||||||
|
)
|
||||||
|
|
||||||
for listener in eventListeners:
|
for listener in eventListeners:
|
||||||
self._logger.debug("Sending action to {!r}".format(listener))
|
self._logger.debug("Sending action to {!r}".format(listener))
|
||||||
try:
|
try:
|
||||||
listener(event, payload)
|
listener(event, payload)
|
||||||
except Exception:
|
except Exception:
|
||||||
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
|
self._logger.exception(
|
||||||
|
"Got an exception while sending event {} (Payload: {!r}) to {}".format(
|
||||||
|
event, payload, listener
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
octoprint.plugin.call_plugin(
|
||||||
"on_event",
|
octoprint.plugin.types.EventHandlerPlugin,
|
||||||
args=(event, payload))
|
"on_event",
|
||||||
self._logger.info("Event loop shut down")
|
args=(event, payload),
|
||||||
except Exception:
|
)
|
||||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
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):
|
def fire(self, event, payload=None):
|
||||||
"""
|
"""
|
||||||
Fire an event to anyone subscribed to it
|
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
|
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.
|
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
|
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.
|
payload being a payload object specific to the event.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
send_held_back = False
|
send_held_back = False
|
||||||
if event == Events.STARTUP:
|
if event == Events.STARTUP:
|
||||||
self._logger.info("Processing startup event, this is our first event")
|
self._logger.info("Processing startup event, this is our first event")
|
||||||
self._startup_signaled = True
|
self._startup_signaled = True
|
||||||
send_held_back = True
|
send_held_back = True
|
||||||
|
|
||||||
self._enqueue(event, payload)
|
self._enqueue(event, payload)
|
||||||
|
|
||||||
if send_held_back:
|
if send_held_back:
|
||||||
self._logger.info("Adding {} events to queue that "
|
self._logger.info(
|
||||||
"were held back before startup event".format(self._held_back.qsize()))
|
"Adding {} events to queue that "
|
||||||
while True:
|
"were held back before startup event".format(self._held_back.qsize())
|
||||||
try:
|
)
|
||||||
self._queue.put(self._held_back.get(block=False))
|
while True:
|
||||||
except queue.Empty:
|
try:
|
||||||
break
|
self._queue.put(self._held_back.get(block=False))
|
||||||
|
except queue.Empty:
|
||||||
|
break
|
||||||
|
|
||||||
def _enqueue(self, event, payload):
|
def _enqueue(self, event, payload):
|
||||||
if self._startup_signaled:
|
if self._startup_signaled:
|
||||||
q = self._queue
|
q = self._queue
|
||||||
else:
|
else:
|
||||||
q = self._held_back
|
q = self._held_back
|
||||||
|
|
||||||
q.put((event, payload))
|
q.put((event, payload))
|
||||||
|
|
||||||
def subscribe(self, event, callback):
|
def subscribe(self, event, callback):
|
||||||
"""
|
"""
|
||||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if callback in self._registeredListeners[event]:
|
if callback in self._registeredListeners[event]:
|
||||||
# callback is already subscribed to the event
|
# callback is already subscribed to the event
|
||||||
return
|
return
|
||||||
|
|
||||||
self._registeredListeners[event].append(callback)
|
self._registeredListeners[event].append(callback)
|
||||||
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
|
self._logger.debug(
|
||||||
|
"Subscribed listener {!r} for event {}".format(callback, event)
|
||||||
|
)
|
||||||
|
|
||||||
def unsubscribe (self, event, callback):
|
def unsubscribe(self, event, callback):
|
||||||
"""
|
"""
|
||||||
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
|
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
|
||||||
"""
|
"""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self._registeredListeners[event].remove(callback)
|
self._registeredListeners[event].remove(callback)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
# not registered
|
# not registered
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def join(self, timeout=None):
|
def join(self, timeout=None):
|
||||||
self._worker.join(timeout)
|
self._worker.join(timeout)
|
||||||
return self._worker.is_alive()
|
return self._worker.is_alive()
|
||||||
|
|
||||||
|
|
||||||
class GenericEventListener(object):
|
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):
|
def __init__(self):
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
def subscribe(self, events):
|
def subscribe(self, events):
|
||||||
"""
|
"""
|
||||||
Subscribes the eventCallback method for all events in the given list.
|
Subscribes the eventCallback method for all events in the given list.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
for event in events:
|
for event in events:
|
||||||
eventManager().subscribe(event, self.eventCallback)
|
eventManager().subscribe(event, self.eventCallback)
|
||||||
|
|
||||||
def unsubscribe(self, events):
|
def unsubscribe(self, events):
|
||||||
"""
|
"""
|
||||||
Unsubscribes the eventCallback method for all events in the given list
|
Unsubscribes the eventCallback method for all events in the given list
|
||||||
"""
|
"""
|
||||||
|
|
||||||
for event in events:
|
for event in events:
|
||||||
eventManager().unsubscribe(event, self.eventCallback)
|
eventManager().unsubscribe(event, self.eventCallback)
|
||||||
|
|
||||||
def eventCallback(self, event, payload):
|
def eventCallback(self, event, payload):
|
||||||
"""
|
"""
|
||||||
Actual event callback called with name of event and optional payload. Not implemented here, override in
|
Actual event callback called with name of event and optional payload. Not implemented here, override in
|
||||||
child classes.
|
child classes.
|
||||||
"""
|
"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class DebugEventListener(GenericEventListener):
|
class DebugEventListener(GenericEventListener):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
GenericEventListener.__init__(self)
|
GenericEventListener.__init__(self)
|
||||||
|
|
||||||
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
|
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
|
||||||
self.subscribe(events)
|
self.subscribe(events)
|
||||||
|
|
||||||
def eventCallback(self, event, payload):
|
def eventCallback(self, event, payload):
|
||||||
GenericEventListener.eventCallback(self, event, payload)
|
GenericEventListener.eventCallback(self, event, payload)
|
||||||
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
|
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
|
||||||
|
|
||||||
|
|
||||||
class CommandTrigger(GenericEventListener):
|
class CommandTrigger(GenericEventListener):
|
||||||
def __init__(self, printer):
|
def __init__(self, printer):
|
||||||
GenericEventListener.__init__(self)
|
GenericEventListener.__init__(self)
|
||||||
self._printer = printer
|
self._printer = printer
|
||||||
self._subscriptions = {}
|
self._subscriptions = {}
|
||||||
|
|
||||||
self._initSubscriptions()
|
self._initSubscriptions()
|
||||||
|
|
||||||
def _initSubscriptions(self):
|
def _initSubscriptions(self):
|
||||||
"""
|
"""
|
||||||
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
|
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
|
||||||
respective commands.
|
respective commands.
|
||||||
"""
|
"""
|
||||||
if not settings().get(["events"]):
|
if not settings().get(["events"]):
|
||||||
return
|
return
|
||||||
|
|
||||||
if not settings().getBoolean(["events", "enabled"]):
|
if not settings().getBoolean(["events", "enabled"]):
|
||||||
return
|
return
|
||||||
|
|
||||||
eventsToSubscribe = []
|
eventsToSubscribe = []
|
||||||
subscriptions = settings().get(["events", "subscriptions"])
|
subscriptions = settings().get(["events", "subscriptions"])
|
||||||
for subscription in subscriptions:
|
for subscription in subscriptions:
|
||||||
if not isinstance(subscription, dict):
|
if not isinstance(subscription, dict):
|
||||||
self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription))
|
self._logger.info(
|
||||||
continue
|
"Invalid subscription definition, not a dictionary: {!r}".format(
|
||||||
|
subscription
|
||||||
|
)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if not "event" in subscription or not "command" in subscription \
|
if (
|
||||||
or not "type" in subscription or not subscription["type"] in ["system", "gcode"]:
|
"event" not in subscription
|
||||||
self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription))
|
or "command" not in subscription
|
||||||
continue
|
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"]:
|
if "enabled" in subscription and not subscription["enabled"]:
|
||||||
self._logger.info("Disabled command trigger: {!r}".format(subscription))
|
self._logger.info("Disabled command trigger: {!r}".format(subscription))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
events = subscription["event"]
|
events = subscription["event"]
|
||||||
command = subscription["command"]
|
command = subscription["command"]
|
||||||
commandType = subscription["type"]
|
commandType = subscription["type"]
|
||||||
debug = subscription["debug"] if "debug" in subscription else False
|
debug = subscription["debug"] if "debug" in subscription else False
|
||||||
|
|
||||||
# "event" in the configuration can be a string, or
|
# "event" in the configuration can be a string, or
|
||||||
# a list of strings. If it's the former, convert it
|
# a list of strings. If it's the former, convert it
|
||||||
# into the latter.
|
# into the latter.
|
||||||
if not isinstance(events, (tuple, list, set)):
|
if not isinstance(events, (tuple, list, set)):
|
||||||
events = [events]
|
events = [events]
|
||||||
|
|
||||||
for event in events:
|
for event in events:
|
||||||
if event not in self._subscriptions:
|
if event not in self._subscriptions:
|
||||||
self._subscriptions[event] = []
|
self._subscriptions[event] = []
|
||||||
self._subscriptions[event].append((command, commandType, debug))
|
self._subscriptions[event].append((command, commandType, debug))
|
||||||
|
|
||||||
if event not in eventsToSubscribe:
|
if event not in eventsToSubscribe:
|
||||||
eventsToSubscribe.append(event)
|
eventsToSubscribe.append(event)
|
||||||
|
|
||||||
self.subscribe(eventsToSubscribe)
|
self.subscribe(eventsToSubscribe)
|
||||||
|
|
||||||
def eventCallback(self, event, payload):
|
def eventCallback(self, event, payload):
|
||||||
"""
|
"""
|
||||||
Event callback, iterates over all subscribed commands for the given event, processes the command
|
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.
|
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:
|
if event not in self._subscriptions:
|
||||||
return
|
return
|
||||||
|
|
||||||
for command, commandType, debug in self._subscriptions[event]:
|
for command, commandType, debug in self._subscriptions[event]:
|
||||||
try:
|
try:
|
||||||
if isinstance(command, (tuple, list, set)):
|
if isinstance(command, (tuple, list, set)):
|
||||||
processedCommand = []
|
processedCommand = []
|
||||||
for c in command:
|
for c in command:
|
||||||
processedCommand.append(self._processCommand(c, event, payload))
|
processedCommand.append(self._processCommand(c, event, payload))
|
||||||
else:
|
else:
|
||||||
processedCommand = self._processCommand(command, event, payload)
|
processedCommand = self._processCommand(command, event, payload)
|
||||||
self.executeCommand(processedCommand, commandType, debug=debug)
|
self.executeCommand(processedCommand, commandType, debug=debug)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command)
|
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):
|
def executeCommand(self, command, commandType, debug=False):
|
||||||
if commandType == "system":
|
if commandType == "system":
|
||||||
self._executeSystemCommand(command, debug=debug)
|
self._executeSystemCommand(command, debug=debug)
|
||||||
elif commandType == "gcode":
|
elif commandType == "gcode":
|
||||||
self._executeGcodeCommand(command, debug=debug)
|
self._executeGcodeCommand(command, debug=debug)
|
||||||
|
|
||||||
def _executeSystemCommand(self, command, debug=False):
|
def _executeSystemCommand(self, command, debug=False):
|
||||||
def commandExecutioner(cmd):
|
def commandExecutioner(cmd):
|
||||||
if debug:
|
if debug:
|
||||||
self._logger.info("Executing system command: {}".format(cmd))
|
self._logger.info("Executing system command: {}".format(cmd))
|
||||||
else:
|
else:
|
||||||
self._logger.info("Executing a system command")
|
self._logger.info("Executing a system command")
|
||||||
# we run this with shell=True since we have to trust whatever
|
# we run this with shell=True since we have to trust whatever
|
||||||
# our admin configured as command and since we want to allow
|
# our admin configured as command and since we want to allow
|
||||||
# shell-alike handling here...
|
# shell-alike handling here...
|
||||||
subprocess.check_call(cmd, shell=True)
|
subprocess.check_call(cmd, shell=True)
|
||||||
|
|
||||||
def process():
|
def process():
|
||||||
try:
|
try:
|
||||||
if isinstance(command, (list, tuple, set)):
|
if isinstance(command, (list, tuple, set)):
|
||||||
for c in command:
|
for c in command:
|
||||||
commandExecutioner(c)
|
commandExecutioner(c)
|
||||||
else:
|
else:
|
||||||
commandExecutioner(command)
|
commandExecutioner(command)
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
if debug:
|
if debug:
|
||||||
self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e)))
|
self._logger.warning(
|
||||||
else:
|
"Command failed with return code {}: {}".format(
|
||||||
self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
|
e.returncode, str(e)
|
||||||
except Exception:
|
)
|
||||||
self._logger.exception("Command failed")
|
)
|
||||||
|
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 = threading.Thread(target=process)
|
||||||
t.daemon = True
|
t.daemon = True
|
||||||
t.start()
|
t.start()
|
||||||
|
|
||||||
def _executeGcodeCommand(self, command, debug=False):
|
def _executeGcodeCommand(self, command, debug=False):
|
||||||
commands = [command]
|
commands = [command]
|
||||||
if isinstance(command, (list, tuple, set)):
|
if isinstance(command, (list, tuple, set)):
|
||||||
commands = list(command)
|
commands = list(command)
|
||||||
if debug:
|
if debug:
|
||||||
self._logger.info("Executing GCode commands: %r" % command)
|
self._logger.info("Executing GCode commands: %r" % command)
|
||||||
self._printer.commands(commands)
|
self._printer.commands(commands)
|
||||||
|
|
||||||
def _processCommand(self, command, event, payload):
|
def _processCommand(self, command, event, payload):
|
||||||
"""
|
"""
|
||||||
Performs string substitutions in the command string based on a few current parameters.
|
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
|
- {__currentZ} : current Z position of the print head, or -1 if not available
|
||||||
- {__eventname} : the name of the event hook being triggered
|
- {__eventname} : the name of the event hook being triggered
|
||||||
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
|
- {__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
|
- {__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
|
- {__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
|
- {__progress} : current print progress in percent, 0 if no print is in progress
|
||||||
- {__data} : the string representation of the event's payload
|
- {__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
|
- {__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
|
- {__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 = "{}"
|
json_string = "{}"
|
||||||
if payload:
|
if payload:
|
||||||
import json
|
import json
|
||||||
try:
|
|
||||||
json_string = json.dumps(payload)
|
|
||||||
except Exception:
|
|
||||||
self._logger.exception("JSON: Cannot dump %r", payload)
|
|
||||||
json_string = ""
|
|
||||||
|
|
||||||
params = {
|
try:
|
||||||
"__currentZ": "-1",
|
json_string = json.dumps(payload)
|
||||||
"__eventname": event,
|
except Exception:
|
||||||
"__filename": "NO FILE",
|
self._logger.exception("JSON: Cannot dump %r", payload)
|
||||||
"__filepath": "NO PATH",
|
json_string = ""
|
||||||
"__progress": "0",
|
|
||||||
"__data": str(payload),
|
|
||||||
"__json": json_string,
|
|
||||||
"__now": datetime.datetime.now().isoformat()
|
|
||||||
}
|
|
||||||
|
|
||||||
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:
|
currentData = self._printer.get_current_data()
|
||||||
params["__currentZ"] = str(currentData["currentZ"])
|
|
||||||
|
|
||||||
if "job" in currentData and "file" in currentData["job"] and "name" in currentData["job"]["file"] \
|
if "currentZ" in currentData and currentData["currentZ"] is not None:
|
||||||
and currentData["job"]["file"]["name"] is not None:
|
params["__currentZ"] = str(currentData["currentZ"])
|
||||||
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"]))
|
|
||||||
|
|
||||||
# now add the payload keys as well
|
if (
|
||||||
if isinstance(payload, dict):
|
"job" in currentData
|
||||||
params.update(payload)
|
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)
|
||||||
+1016
-683
File diff suppressed because it is too large.
Load diff
@@ -2,438 +2,507 @@
|
|||||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||||
|
|
||||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
__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"
|
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import queue
|
import queue
|
||||||
except ImportError:
|
except ImportError:
|
||||||
import Queue as queue
|
import Queue as queue
|
||||||
|
|
||||||
|
import collections
|
||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
import collections
|
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from octoprint.events import Events, eventManager
|
from octoprint.events import Events, eventManager
|
||||||
from octoprint.settings import settings
|
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 monotonic_time
|
||||||
from octoprint.util import get_fully_qualified_classname as fqcn, dict_merge
|
|
||||||
from octoprint.util.platform import CLOSE_FDS
|
from octoprint.util.platform import CLOSE_FDS
|
||||||
|
|
||||||
|
|
||||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
|
class QueueEntry(
|
||||||
"""
|
collections.namedtuple(
|
||||||
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
|
"QueueEntry",
|
||||||
for processing.
|
"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:
|
Arguments:
|
||||||
name (str): Name of the file to analyze.
|
name (str): Name of the file to analyze.
|
||||||
path (str): Storage location specific path to 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.
|
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.
|
At the moment, only ``gcode`` is supported here.
|
||||||
location (str): Location the file is located on.
|
location (str): Location the file is located on.
|
||||||
absolute_path (str): Absolute path on disk through which to access the file.
|
absolute_path (str): Absolute path on disk through which to access the file.
|
||||||
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
|
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
|
||||||
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
|
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return "{location}:{path}".format(location=self.location, path=self.path)
|
return "{location}:{path}".format(location=self.location, path=self.path)
|
||||||
|
|
||||||
|
|
||||||
class AnalysisAborted(Exception):
|
class AnalysisAborted(Exception):
|
||||||
def __init__(self, reenqueue=True, *args, **kwargs):
|
def __init__(self, reenqueue=True, *args, **kwargs):
|
||||||
Exception.__init__(self, *args, **kwargs)
|
Exception.__init__(self, *args, **kwargs)
|
||||||
self.reenqueue = reenqueue
|
self.reenqueue = reenqueue
|
||||||
|
|
||||||
|
|
||||||
class AnalysisQueue(object):
|
class AnalysisQueue(object):
|
||||||
"""
|
"""
|
||||||
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
|
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
|
||||||
by their machine code type.
|
by their machine code type.
|
||||||
|
|
||||||
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
|
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
|
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
|
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
|
||||||
:meth:`unregister_finish_callback`.
|
:meth:`unregister_finish_callback`.
|
||||||
|
|
||||||
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
|
: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
|
(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.
|
entry will be enqueued with the type specific analysis queue.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, queue_factories):
|
def __init__(self, queue_factories):
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
self._callbacks = []
|
self._callbacks = []
|
||||||
|
|
||||||
self._queues = dict()
|
self._queues = {}
|
||||||
for key, queue_factory in queue_factories.items():
|
for key, queue_factory in queue_factories.items():
|
||||||
self._queues[key] = queue_factory(self._analysis_finished)
|
self._queues[key] = queue_factory(self._analysis_finished)
|
||||||
|
|
||||||
def register_finish_callback(self, callback):
|
def register_finish_callback(self, callback):
|
||||||
self._callbacks.append(callback)
|
self._callbacks.append(callback)
|
||||||
|
|
||||||
def unregister_finish_callback(self, callback):
|
def unregister_finish_callback(self, callback):
|
||||||
self._callbacks.remove(callback)
|
self._callbacks.remove(callback)
|
||||||
|
|
||||||
def enqueue(self, entry, high_priority=False):
|
def enqueue(self, entry, high_priority=False):
|
||||||
if entry is None:
|
if entry is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if not entry.type in self._queues:
|
if entry.type not in self._queues:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
|
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def dequeue(self, entry):
|
def dequeue(self, entry):
|
||||||
if entry is None:
|
if entry is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if not entry.type in self._queues:
|
if entry.type not in self._queues:
|
||||||
return False
|
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):
|
def dequeue_folder(self, destination, path):
|
||||||
for q in self._queues.values():
|
for q in self._queues.values():
|
||||||
q.dequeue_folder(destination, path)
|
q.dequeue_folder(destination, path)
|
||||||
|
|
||||||
def pause(self):
|
def pause(self):
|
||||||
for q in self._queues.values():
|
for q in self._queues.values():
|
||||||
q.pause()
|
q.pause()
|
||||||
|
|
||||||
def resume(self):
|
def resume(self):
|
||||||
for q in self._queues.values():
|
for q in self._queues.values():
|
||||||
q.resume()
|
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):
|
class AbstractAnalysisQueue(object):
|
||||||
"""
|
"""
|
||||||
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
|
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
|
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
|
||||||
processing.
|
processing.
|
||||||
|
|
||||||
Arguments:
|
Arguments:
|
||||||
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
|
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
|
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.
|
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 = 100
|
||||||
LOW_PRIO_ABORTED = 75
|
LOW_PRIO_ABORTED = 75
|
||||||
HIGH_PRIO = 50
|
HIGH_PRIO = 50
|
||||||
HIGH_PRIO_ABORTED = 0
|
HIGH_PRIO_ABORTED = 0
|
||||||
|
|
||||||
def __init__(self, finished_callback):
|
def __init__(self, finished_callback):
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
self._finished_callback = finished_callback
|
self._finished_callback = finished_callback
|
||||||
|
|
||||||
self._active = threading.Event()
|
self._active = threading.Event()
|
||||||
self._active.set()
|
self._active.set()
|
||||||
|
|
||||||
self._done = threading.Event()
|
self._done = threading.Event()
|
||||||
self._done.clear()
|
self._done.clear()
|
||||||
|
|
||||||
self._currentFile = None
|
self._currentFile = None
|
||||||
self._currentProgress = None
|
self._currentProgress = None
|
||||||
|
|
||||||
self._queue = queue.PriorityQueue()
|
self._queue = queue.PriorityQueue()
|
||||||
self._current = None
|
self._current = None
|
||||||
self._current_highprio = False
|
self._current_highprio = False
|
||||||
|
|
||||||
self._worker = threading.Thread(target=self._work)
|
self._worker = threading.Thread(target=self._work)
|
||||||
self._worker.daemon = True
|
self._worker.daemon = True
|
||||||
self._worker.start()
|
self._worker.start()
|
||||||
|
|
||||||
def enqueue(self, entry, high_priority=False):
|
def enqueue(self, entry, high_priority=False):
|
||||||
"""
|
"""
|
||||||
Enqueues an ``entry`` for analysis by the queue.
|
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
|
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.
|
other entries in the queue with normal priority.
|
||||||
|
|
||||||
Arguments:
|
Arguments:
|
||||||
entry (QueueEntry): The :class:`QueueEntry` to analyze.
|
entry (QueueEntry): The :class:`QueueEntry` to analyze.
|
||||||
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
|
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
|
||||||
(False, default)
|
(False, default)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
|
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
|
||||||
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
|
self._logger.debug(
|
||||||
return
|
"Ignoring entry {entry} for analysis queue".format(entry=entry)
|
||||||
elif high_priority:
|
)
|
||||||
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
|
return
|
||||||
prio = self.__class__.HIGH_PRIO
|
elif high_priority:
|
||||||
else:
|
self._logger.debug(
|
||||||
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
|
"Adding entry {entry} to analysis queue with high priority".format(
|
||||||
prio = self.__class__.LOW_PRIO
|
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))
|
self._queue.put((prio, entry, high_priority))
|
||||||
if high_priority and self._current is not None and not self._current_highprio:
|
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._logger.debug("Aborting current analysis in favor of high priority one")
|
||||||
self._do_abort()
|
self._do_abort()
|
||||||
|
|
||||||
def dequeue(self, location, path):
|
def dequeue(self, location, path):
|
||||||
if self._current is not None and self._current.location == location \
|
if (
|
||||||
and self._current.path == path:
|
self._current is not None
|
||||||
self._do_abort(reenqueue=False)
|
and self._current.location == location
|
||||||
self._done.wait()
|
and self._current.path == path
|
||||||
self._done.clear()
|
):
|
||||||
|
self._do_abort(reenqueue=False)
|
||||||
|
self._done.wait()
|
||||||
|
self._done.clear()
|
||||||
|
|
||||||
def dequeue_folder(self, location, path):
|
def dequeue_folder(self, location, path):
|
||||||
if self._current is not None and self._current.location == location \
|
if (
|
||||||
and self._current.path.startswith(path + "/"):
|
self._current is not None
|
||||||
self._do_abort(reenqueue=False)
|
and self._current.location == location
|
||||||
self._done.wait()
|
and self._current.path.startswith(path + "/")
|
||||||
self._done.clear()
|
):
|
||||||
|
self._do_abort(reenqueue=False)
|
||||||
|
self._done.wait()
|
||||||
|
self._done.clear()
|
||||||
|
|
||||||
def pause(self):
|
def pause(self):
|
||||||
"""
|
"""
|
||||||
Pauses processing of the queue, e.g. when a print is active.
|
Pauses processing of the queue, e.g. when a print is active.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
self._logger.debug("Pausing analysis")
|
self._logger.debug("Pausing analysis")
|
||||||
self._active.clear()
|
self._active.clear()
|
||||||
if self._current is not None:
|
if self._current is not None:
|
||||||
self._logger.debug("Aborting running analysis, will restart when analyzer is resumed")
|
self._logger.debug(
|
||||||
self._do_abort()
|
"Aborting running analysis, will restart when analyzer is resumed"
|
||||||
|
)
|
||||||
|
self._do_abort()
|
||||||
|
|
||||||
def resume(self):
|
def resume(self):
|
||||||
"""
|
"""
|
||||||
Resumes processing of the queue, e.g. when a print has finished.
|
Resumes processing of the queue, e.g. when a print has finished.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
self._logger.debug("Resuming analyzer")
|
self._logger.debug("Resuming analyzer")
|
||||||
self._active.set()
|
self._active.set()
|
||||||
|
|
||||||
def _work(self):
|
def _work(self):
|
||||||
while True:
|
while True:
|
||||||
(priority, entry, high_priority) = self._queue.get()
|
(priority, entry, high_priority) = self._queue.get()
|
||||||
self._logger.debug("Processing entry {} from queue (priority {})".format(entry, priority))
|
self._logger.debug(
|
||||||
self._active.wait()
|
"Processing entry {} from queue (priority {})".format(entry, priority)
|
||||||
|
)
|
||||||
|
self._active.wait()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self._analyze(entry, high_priority=high_priority)
|
self._analyze(entry, high_priority=high_priority)
|
||||||
self._queue.task_done()
|
self._queue.task_done()
|
||||||
self._done.set()
|
self._done.set()
|
||||||
except AnalysisAborted as ex:
|
except AnalysisAborted as ex:
|
||||||
if ex.reenqueue:
|
if ex.reenqueue:
|
||||||
self._queue.put((self.__class__.HIGH_PRIO_ABORTED if high_priority else self.__class__.LOW_PRIO_ABORTED,
|
self._queue.put(
|
||||||
entry,
|
(
|
||||||
high_priority))
|
self.__class__.HIGH_PRIO_ABORTED
|
||||||
self._logger.debug("Running analysis of entry {} aborted".format(entry))
|
if high_priority
|
||||||
self._queue.task_done()
|
else self.__class__.LOW_PRIO_ABORTED,
|
||||||
self._done.set()
|
entry,
|
||||||
else:
|
high_priority,
|
||||||
time.sleep(1.0)
|
)
|
||||||
|
)
|
||||||
|
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):
|
def _analyze(self, entry, high_priority=False):
|
||||||
path = entry.absolute_path
|
path = entry.absolute_path
|
||||||
if path is None or not os.path.exists(path):
|
if path is None or not os.path.exists(path):
|
||||||
return
|
return
|
||||||
|
|
||||||
self._current = entry
|
self._current = entry
|
||||||
self._current_highprio = high_priority
|
self._current_highprio = high_priority
|
||||||
self._current_progress = 0
|
self._current_progress = 0
|
||||||
|
|
||||||
try:
|
try:
|
||||||
start_time = monotonic_time()
|
start_time = monotonic_time()
|
||||||
self._logger.info("Starting analysis of {}".format(entry))
|
self._logger.info("Starting analysis of {}".format(entry))
|
||||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
|
eventManager().fire(
|
||||||
"path": entry.path,
|
Events.METADATA_ANALYSIS_STARTED,
|
||||||
"origin": entry.location,
|
{
|
||||||
"type": entry.type})
|
"name": entry.name,
|
||||||
try:
|
"path": entry.path,
|
||||||
result = self._do_analysis(high_priority=high_priority)
|
"origin": entry.location,
|
||||||
except TypeError:
|
"type": entry.type,
|
||||||
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)
|
try:
|
||||||
finally:
|
result = self._do_analysis(high_priority=high_priority)
|
||||||
self._current = None
|
except TypeError:
|
||||||
self._current_progress = None
|
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):
|
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
|
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
|
||||||
overridden by sub classes.
|
overridden by sub classes.
|
||||||
|
|
||||||
Arguments:
|
Arguments:
|
||||||
high_priority (bool): Whether the current entry has high priority or not.
|
high_priority (bool): Whether the current entry has high priority or not.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
|
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
|
||||||
construction.
|
construction.
|
||||||
"""
|
"""
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _do_abort(self, reenqueue=True):
|
def _do_abort(self, reenqueue=True):
|
||||||
"""
|
"""
|
||||||
Aborts analysis of the current entry. Needs to be overridden by sub classes.
|
Aborts analysis of the current entry. Needs to be overridden by sub classes.
|
||||||
"""
|
"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
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::
|
.. list-table::
|
||||||
:widths: 25 70
|
:widths: 25 70
|
||||||
|
|
||||||
- * **Key**
|
- * **Key**
|
||||||
* **Description**
|
* **Description**
|
||||||
- * ``estimatedPrintTime``
|
- * ``estimatedPrintTime``
|
||||||
* Estimated time the file take to print, in seconds
|
* Estimated time the file take to print, in seconds
|
||||||
- * ``filament``
|
- * ``filament``
|
||||||
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
|
* 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.
|
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
|
||||||
- * ``filament.toolX.length``
|
- * ``filament.toolX.length``
|
||||||
* The extruded length in mm
|
* The extruded length in mm
|
||||||
- * ``filament.toolX.volume``
|
- * ``filament.toolX.volume``
|
||||||
* The extruded volume in cm³
|
* The extruded volume in cm³
|
||||||
- * ``printingArea``
|
- * ``printingArea``
|
||||||
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
|
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
|
||||||
- * ``printingArea.minX``
|
- * ``printingArea.minX``
|
||||||
* Minimum X coordinate of the printed object
|
* Minimum X coordinate of the printed object
|
||||||
- * ``printingArea.maxX``
|
- * ``printingArea.maxX``
|
||||||
* Maximum X coordinate of the printed object
|
* Maximum X coordinate of the printed object
|
||||||
- * ``printingArea.minY``
|
- * ``printingArea.minY``
|
||||||
* Minimum Y coordinate of the printed object
|
* Minimum Y coordinate of the printed object
|
||||||
- * ``printingArea.maxY``
|
- * ``printingArea.maxY``
|
||||||
* Maximum Y coordinate of the printed object
|
* Maximum Y coordinate of the printed object
|
||||||
- * ``printingArea.minZ``
|
- * ``printingArea.minZ``
|
||||||
* Minimum Z coordinate of the printed object
|
* Minimum Z coordinate of the printed object
|
||||||
- * ``printingArea.maxZ``
|
- * ``printingArea.maxZ``
|
||||||
* Maximum Z coordinate of the printed object
|
* Maximum Z coordinate of the printed object
|
||||||
- * ``dimensions``
|
- * ``dimensions``
|
||||||
* Dimensions of the printed object in X, Y, Z
|
* Dimensions of the printed object in X, Y, Z
|
||||||
- * ``dimensions.width``
|
- * ``dimensions.width``
|
||||||
* Width of the printed model along the X axis, in mm
|
* Width of the printed model along the X axis, in mm
|
||||||
- * ``dimensions.depth``
|
- * ``dimensions.depth``
|
||||||
* Depth of the printed model along the Y axis, in mm
|
* Depth of the printed model along the Y axis, in mm
|
||||||
- * ``dimensions.height``
|
- * ``dimensions.height``
|
||||||
* Height of the printed model along the Z axis, in mm
|
* Height of the printed model along the Z axis, in mm
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, finished_callback):
|
def __init__(self, finished_callback):
|
||||||
AbstractAnalysisQueue.__init__(self, finished_callback)
|
AbstractAnalysisQueue.__init__(self, finished_callback)
|
||||||
|
|
||||||
self._aborted = False
|
self._aborted = False
|
||||||
self._reenqueue = False
|
self._reenqueue = False
|
||||||
|
|
||||||
def _do_analysis(self, high_priority=False):
|
def _do_analysis(self, high_priority=False):
|
||||||
import sarge
|
import sys
|
||||||
import sys
|
|
||||||
import yaml
|
|
||||||
|
|
||||||
if self._current.analysis and all(map(lambda x: x in self._current.analysis, ("printingArea",
|
import sarge
|
||||||
"dimensions",
|
import yaml
|
||||||
"estimatedPrintTime",
|
|
||||||
"filament"))):
|
|
||||||
return self._current.analysis
|
|
||||||
|
|
||||||
try:
|
if self._current.analysis and all(
|
||||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
|
map(
|
||||||
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
lambda x: x in self._current.analysis,
|
||||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
("printingArea", "dimensions", "estimatedPrintTime", "filament"),
|
||||||
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
|
)
|
||||||
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
|
):
|
||||||
speedx = self._current.printer_profile["axes"]["x"]["speed"]
|
return self._current.analysis
|
||||||
speedy = self._current.printer_profile["axes"]["y"]["speed"]
|
|
||||||
offsets = self._current.printer_profile["extruder"]["offsets"]
|
|
||||||
|
|
||||||
command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
|
try:
|
||||||
"--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
|
throttle = (
|
||||||
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
|
settings().getFloat(["gcodeAnalysis", "throttle_highprio"])
|
||||||
"--throttle-lines={}".format(throttle_lines)]
|
if high_priority
|
||||||
for offset in offsets[1:]:
|
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||||
command += ["--offset", str(offset[0]), str(offset[1])]
|
)
|
||||||
if g90_extruder:
|
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||||
command += ["--g90-extruder"]
|
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
|
||||||
command.append(self._current.absolute_path)
|
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
|
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
|
||||||
p = sarge.run(command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture())
|
|
||||||
|
|
||||||
while len(p.commands) == 0:
|
self._aborted = False
|
||||||
# somewhat ugly... we can't use wait_events because
|
p = sarge.run(
|
||||||
# the events might not be all set if an exception
|
command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture()
|
||||||
# by sarge is triggered within the async process
|
)
|
||||||
# thread
|
|
||||||
time.sleep(0.01)
|
|
||||||
|
|
||||||
# by now we should have a command, let's wait for its
|
while len(p.commands) == 0:
|
||||||
# process to have been prepared
|
# somewhat ugly... we can't use wait_events because
|
||||||
p.commands[0].process_ready.wait()
|
# 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:
|
# by now we should have a command, let's wait for its
|
||||||
# the process might have been set to None in case of any exception
|
# process to have been prepared
|
||||||
raise RuntimeError("Error while trying to run command {}".format(" ".join(command)))
|
p.commands[0].process_ready.wait()
|
||||||
|
|
||||||
try:
|
if not p.commands[0].process:
|
||||||
# let's wait for stuff to finish
|
# the process might have been set to None in case of any exception
|
||||||
while p.returncode is None:
|
raise RuntimeError(
|
||||||
if self._aborted:
|
"Error while trying to run command {}".format(" ".join(command))
|
||||||
# oh, we shall abort, let's do so!
|
)
|
||||||
p.commands[0].terminate()
|
|
||||||
raise AnalysisAborted(reenqueue=self._reenqueue)
|
|
||||||
|
|
||||||
# else continue
|
try:
|
||||||
p.commands[0].poll()
|
# let's wait for stuff to finish
|
||||||
finally:
|
while p.returncode is None:
|
||||||
p.close()
|
if self._aborted:
|
||||||
|
# oh, we shall abort, let's do so!
|
||||||
|
p.commands[0].terminate()
|
||||||
|
raise AnalysisAborted(reenqueue=self._reenqueue)
|
||||||
|
|
||||||
output = p.stdout.text
|
# else continue
|
||||||
self._logger.debug("Got output: {!r}".format(output))
|
p.commands[0].poll()
|
||||||
|
finally:
|
||||||
|
p.close()
|
||||||
|
|
||||||
if not "RESULTS:" in output:
|
output = p.stdout.text
|
||||||
raise RuntimeError("No analysis result found")
|
self._logger.debug("Got output: {!r}".format(output))
|
||||||
|
|
||||||
_, output = output.split("RESULTS:")
|
if "RESULTS:" not in output:
|
||||||
analysis = yaml.safe_load(output)
|
raise RuntimeError("No analysis result found")
|
||||||
|
|
||||||
result = dict()
|
_, output = output.split("RESULTS:")
|
||||||
result["printingArea"] = analysis["printing_area"]
|
analysis = yaml.safe_load(output)
|
||||||
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]
|
|
||||||
}
|
|
||||||
|
|
||||||
if self._current.analysis and isinstance(self._current.analysis, dict):
|
result = {}
|
||||||
return dict_merge(result, self._current.analysis)
|
result["printingArea"] = analysis["printing_area"]
|
||||||
else:
|
result["dimensions"] = analysis["dimensions"]
|
||||||
return result
|
if analysis["total_time"]:
|
||||||
finally:
|
result["estimatedPrintTime"] = analysis["total_time"] * 60
|
||||||
self._gcode = None
|
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):
|
if self._current.analysis and isinstance(self._current.analysis, dict):
|
||||||
self._aborted = True
|
return dict_merge(result, self._current.analysis)
|
||||||
self._reenqueue = reenqueue
|
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
Reference in new issue
Block a user