Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
112a8b9c8b | ||
|
|
98b692d845 | ||
|
|
a657ebd528 | ||
|
|
e628aedbc1 | ||
|
|
38fce1665b | ||
|
|
f51a98768c | ||
|
|
4d04c323f6 | ||
|
|
94116bfd53 | ||
|
|
a05761e63f | ||
|
|
89469d38ae | ||
|
|
bd2616e888 | ||
|
|
02e996436d | ||
|
|
a3f2e0b56c | ||
|
|
d60cab1962 | ||
|
|
b01e327f9d | ||
|
|
09af2813d0 | ||
|
|
13260fa219 | ||
|
|
8292408c79 | ||
|
|
9165f83084 | ||
|
|
c2ef371089 | ||
|
|
ac129a2576 | ||
|
|
db8d420860 | ||
|
|
7d7cbb1760 | ||
|
|
89979f1bee | ||
|
|
bd241e8e6c | ||
|
|
7939b0ae4d | ||
|
|
6b57ba2d7d | ||
|
|
2c5465f9a6 | ||
|
|
1565129cfb | ||
|
|
b8d4a58207 | ||
|
|
900f03dc8a | ||
|
|
0c4c4a9d18 | ||
|
|
ff4ed38329 | ||
|
|
5f78ab7b73 | ||
|
|
6556d555bd | ||
|
|
d318ff82b8 | ||
|
|
ff53a826f9 | ||
|
|
d79e777911 | ||
|
|
335e635ec7 | ||
|
|
a5754a8552 | ||
|
|
a8c91ff6ba | ||
|
|
6285fd8010 | ||
|
|
799aedcaed | ||
|
|
de42ce73f7 | ||
|
|
962e09906e | ||
|
|
f607f55683 | ||
|
|
1b45047826 | ||
|
|
edd4d90b12 | ||
|
|
0a3ad8a880 | ||
|
|
82615791a2 | ||
|
|
2b5af2c36a | ||
|
|
b2e50e13d4 | ||
|
|
cb4404a833 | ||
|
|
38bb81cfe7 | ||
|
|
1667f9bd52 | ||
|
|
1ec61a9fe6 | ||
|
|
98c84b6bb9 | ||
|
|
76f48b3b13 | ||
|
|
8596ae5c4a | ||
|
|
c1482eaacd | ||
|
|
e23fe4a925 | ||
|
|
2f08b90200 | ||
|
|
68ca2c5e51 | ||
|
|
343195477b | ||
|
|
4caf4ef09b | ||
|
|
0325628693 | ||
|
|
e14c00f135 | ||
|
|
b0a4a49f99 | ||
|
|
5b4839369e | ||
|
|
1ff02b9f1c | ||
|
|
e2c1fa3d43 | ||
|
|
39a466e316 | ||
|
|
9e940eacc3 | ||
|
|
2e38f237de | ||
|
|
7f36ffdafd | ||
|
|
39b2da3230 | ||
|
|
c489829efb | ||
|
|
e30e129e2a | ||
|
|
32d5b25013 | ||
|
|
6227a0dfb9 | ||
|
|
e234c6146e | ||
|
|
c146731e5a | ||
|
|
5ee242be4a | ||
|
|
556878a774 | ||
|
|
00aa4876e9 | ||
|
|
e5e8581f9a | ||
|
|
95a9f84b39 | ||
|
|
371f1a818f | ||
|
|
4ed5f7ed28 | ||
|
|
4eb81aae9d | ||
|
|
dafa4c97ad | ||
|
|
0268cafa90 | ||
|
|
a5caac8d38 | ||
|
|
7ca9d56327 | ||
|
|
d9323b7172 | ||
|
|
8f6d67195d | ||
|
|
342d526a51 | ||
|
|
d7c5f57c98 | ||
|
|
d89ca38ee8 | ||
|
|
cb969be403 | ||
|
|
7cb649c303 | ||
|
|
6d7d365b27 | ||
|
|
8ad720e554 | ||
|
|
37190da2d6 | ||
|
|
2746139fa6 | ||
|
|
c9f10ae723 | ||
|
|
202006149c | ||
|
|
671973062e | ||
|
|
1d15c2a176 | ||
|
|
5e490ec7fd | ||
|
|
1889a40241 | ||
|
|
6d2be1743a | ||
|
|
e9e4adf09b | ||
|
|
535ad6eae6 | ||
|
|
c4167a82c5 | ||
|
|
087a9ece2c | ||
|
|
b77380a8ac | ||
|
|
169275b052 | ||
|
|
757dfcf5c7 | ||
|
|
8e39eac207 | ||
|
|
9e48b8ab65 | ||
|
|
36b07b2337 | ||
|
|
e57c46fb67 | ||
|
|
df8226b8c5 | ||
|
|
2f89082df2 | ||
|
|
e0943527d6 | ||
|
|
108db045ce | ||
|
|
025986794f | ||
|
|
ac2354907a | ||
|
|
7b5d2e3e0c | ||
|
|
efa556a812 | ||
|
|
7f9764c386 | ||
|
|
e95e546c08 | ||
|
|
b0e7df47a6 | ||
|
|
257fc0d1cd | ||
|
|
3fe2b611bc | ||
|
|
d6c63a5cb9 | ||
|
|
ad8205c386 | ||
|
|
6efd4dfd08 | ||
|
|
469bf844ee | ||
|
|
4f58c64881 | ||
|
|
b428faacc8 | ||
|
|
4e3adcc3f3 | ||
|
|
f88147003c | ||
|
|
bbbe85f737 | ||
|
|
fc97d0b424 | ||
|
|
b054ec47ad | ||
|
|
87e7a19fdd | ||
|
|
fed257b5d8 | ||
|
|
e53ae8cd56 | ||
|
|
a9f76dd1a3 | ||
|
|
6bc5b8a7a9 | ||
|
|
cb9bedb6a0 | ||
|
|
5ff790048d | ||
|
|
f32ea65b2c | ||
|
|
1f957e1ee2 | ||
|
|
32be5ca87c | ||
|
|
8876ab0ce5 | ||
|
|
ad8910354c | ||
|
|
e8d6a9b221 | ||
|
|
f3cfe2ba48 | ||
|
|
d2ecb0a28f | ||
|
|
134ee77e4a | ||
|
|
10f3f72b9c | ||
|
|
78b6d3a5e2 | ||
|
|
a920c4fe21 | ||
|
|
52468e7e1c | ||
|
|
9112a800c8 | ||
|
|
177d235b29 | ||
|
|
2de2dc7c31 | ||
|
|
8074a06d33 | ||
|
|
75c801d63f | ||
|
|
ed07764f09 | ||
|
|
a929100889 | ||
|
|
286376321c | ||
|
|
4a36a3eed2 | ||
|
|
8bf9b8650d | ||
|
|
d6da819cd6 | ||
|
|
2fbc81604a | ||
|
|
2ca63febee | ||
|
|
224674f27e | ||
|
|
2f1d71a98c | ||
|
|
7366110f07 | ||
|
|
e5eb72cbfb | ||
|
|
b0028cd3fb | ||
|
|
2343caea30 | ||
|
|
61d037f188 | ||
|
|
2a79d9183a | ||
|
|
5dbc88b6f2 | ||
|
|
83876806db | ||
|
|
5a5785be4a | ||
|
|
25cd4f8201 | ||
|
|
2d72a52338 | ||
|
|
b5a161594d | ||
|
|
a24363c4b0 | ||
|
|
524562527e | ||
|
|
26856d052f | ||
|
|
17f8817b78 | ||
|
|
4eb1d2bf80 | ||
|
|
62120affae | ||
|
|
66b501cfaa | ||
|
|
140bf9aa5a | ||
|
|
711ca457f2 | ||
|
|
07ae4ffe14 | ||
|
|
3800b21e69 | ||
|
|
196b152ec4 | ||
|
|
970810dc92 | ||
|
|
4fec14197b | ||
|
|
b354334a2e | ||
|
|
a934750504 | ||
|
|
9dc29689f4 | ||
|
|
8518b40b5f | ||
|
|
aabd624f88 | ||
|
|
6ae88ab8c6 | ||
|
|
6251031d6e | ||
|
|
249b3f442b | ||
|
|
ff6012bb00 | ||
|
|
a137946e3a | ||
|
|
909dd551d6 | ||
|
|
687b449207 | ||
|
|
efe552264c | ||
|
|
b7e788ec1b | ||
|
|
e964d2410c | ||
|
|
09284cd9b9 | ||
|
|
97d37c5078 | ||
|
|
432090a56a | ||
|
|
1847b41f7e | ||
|
|
4963a4b849 | ||
|
|
46e425de88 | ||
|
|
376d38e0cf | ||
|
|
92c43ee6f9 | ||
|
|
cce37f0501 | ||
|
|
2e8f543aa3 | ||
|
|
d2dfd22a2c | ||
|
|
b51cb31b46 | ||
|
|
eea1050a18 | ||
|
|
71b2cc87a3 | ||
|
|
a37165d7d9 | ||
|
|
b06f804e9e | ||
|
|
d64ca79f05 | ||
|
|
490ade5e17 | ||
|
|
573503e84d | ||
|
|
9e0e4bf7b6 | ||
|
|
452645d950 | ||
|
|
d2bb731bd7 | ||
|
|
2062acd372 | ||
|
|
40b5c272c4 | ||
|
|
31e4df44f9 | ||
|
|
cd3c8ebbe6 | ||
|
|
fe13348fd3 | ||
|
|
903dd36d68 | ||
|
|
59a435a787 | ||
|
|
71cc312ccc | ||
|
|
8d1ae438e5 | ||
|
|
7ebcb47955 | ||
|
|
71e60183c5 | ||
|
|
9c055137eb | ||
|
|
eaa8933782 | ||
|
|
0d330e3c5a | ||
|
|
18ed113122 | ||
|
|
48e454856c | ||
|
|
917b86655f | ||
|
|
7a2225b332 | ||
|
|
20237a73ac | ||
|
|
4a3f894064 | ||
|
|
0c9098f7bf | ||
|
|
53a2e04501 | ||
|
|
c6f5f1a0f7 | ||
|
|
1cff2581db | ||
|
|
5cf02ac9ee | ||
|
|
460481c9c2 | ||
|
|
2806676707 | ||
|
|
9559f09ec7 | ||
|
|
542edbc3e6 | ||
|
|
f82d50b0f6 | ||
|
|
e224b0ac71 | ||
|
|
68f4ecefb0 | ||
|
|
d73d930e5f | ||
|
|
8c1262dd3f | ||
|
|
792fe328ef | ||
|
|
111a37e97e | ||
|
|
c2bb234c20 | ||
|
|
0a634a76a0 | ||
|
|
41c0dac19d | ||
|
|
f728423f29 | ||
|
|
61e5184377 | ||
|
|
a2527998c2 | ||
|
|
2dda3a0e32 | ||
|
|
e2394446b0 | ||
|
|
1befd0ecc1 | ||
|
|
386ae7609d | ||
|
|
7587f34c94 | ||
|
|
6b54a15ed9 | ||
|
|
d391f0c12b | ||
|
|
8460a4173d | ||
|
|
fe7149c715 | ||
|
|
443647e78e | ||
|
|
50bb0bcfd4 | ||
|
|
e15946ff79 | ||
|
|
fd94fc94a0 | ||
|
|
798bc2b225 | ||
|
|
6728302bb3 | ||
|
|
f7a3e6a6ee | ||
|
|
0834288cfc | ||
|
|
faff20943f | ||
|
|
14661339ef | ||
|
|
8ca188e509 | ||
|
|
3da4877d50 | ||
|
|
382f10557e | ||
|
|
d9c6cca370 | ||
|
|
abf4f90f0e | ||
|
|
13ab34a5c8 | ||
|
|
2a67772f46 | ||
|
|
f69718b060 | ||
|
|
a97b8c2fd9 | ||
|
|
08c384ac68 | ||
|
|
00354f4a1e | ||
|
|
1a9b6c01a6 | ||
|
|
c4dc7d0f55 | ||
|
|
5a60af9d13 | ||
|
|
887304fe18 | ||
|
|
2bd8aa00f3 | ||
|
|
cb8ce62ec4 | ||
|
|
e49a4d8cfa | ||
|
|
fdf0f75ffa | ||
|
|
5fb8674937 | ||
|
|
d3871e3487 | ||
|
|
9dd9badb33 | ||
|
|
3de9635180 | ||
|
|
e2f626d421 | ||
|
|
b7a8c29fb4 | ||
|
|
15f10d4a84 | ||
|
|
0faf2792e9 | ||
|
|
caa1a3d76f | ||
|
|
fae01d2c75 | ||
|
|
248235c5e0 | ||
|
|
2febfcd8b3 | ||
|
|
704331525f | ||
|
|
6c279f155a | ||
|
|
e5afde2c2c | ||
|
|
f5b99a6e34 | ||
|
|
8ef13ba529 | ||
|
|
654055da61 | ||
|
|
68f67219ed | ||
|
|
436ffb6db8 | ||
|
|
b569cc456b | ||
|
|
023b9eda90 | ||
|
|
fe2dbf699d | ||
|
|
17c6c83503 | ||
|
|
688e4d36d1 | ||
|
|
86b886ede7 | ||
|
|
392149b504 | ||
|
|
85ef3f1df2 | ||
|
|
6e44149284 | ||
|
|
534f3aa2d4 | ||
|
|
13e5cf45ec | ||
|
|
4cb103e042 | ||
|
|
db81bf1e72 | ||
|
|
9c89c4c999 | ||
|
|
d133bd47e5 | ||
|
|
90391d2897 | ||
|
|
d124efdb71 | ||
|
|
4f1b781219 | ||
|
|
6673536e10 | ||
|
|
118afd4720 | ||
|
|
a0cbc10ba7 | ||
|
|
38b7640769 | ||
|
|
b266f1ca55 | ||
|
|
0ef0eff917 | ||
|
|
fd29efe88e | ||
|
|
cd3acfb384 | ||
|
|
f9548a7ece | ||
|
|
ce5275c91e | ||
|
|
8a1db8e4c5 | ||
|
|
0d120b2977 | ||
|
|
bf71a20ac1 | ||
|
|
846d3a63bc | ||
|
|
15d6bf3a70 | ||
|
|
cec1bc6c0f | ||
|
|
5456f5a70a | ||
|
|
e980444f86 | ||
|
|
9d1f4fb126 | ||
|
|
3de5bca48b | ||
|
|
81471df419 | ||
|
|
99ef84788a | ||
|
|
bfbf9fb66e | ||
|
|
6074a3d964 | ||
|
|
74e82afa24 | ||
|
|
2b5c14b3c3 | ||
|
|
e5b167bcb4 | ||
|
|
a70928aac6 | ||
|
|
7548e7a623 | ||
|
|
8d9034b5a4 | ||
|
|
b5194ffc00 | ||
|
|
fa6cda3356 | ||
|
|
4d9ec9a7e3 | ||
|
|
e44a2fdd97 | ||
|
|
95ac669d5c | ||
|
|
5e899204f0 | ||
|
|
c3eebdb158 | ||
|
|
13b85fbbd0 | ||
|
|
ddd2711f95 | ||
|
|
9addbbb9a1 | ||
|
|
735e2c6c94 | ||
|
|
9d2ee2b55b | ||
|
|
7988e7487f | ||
|
|
4bbe49ac6d | ||
|
|
9e32439f44 | ||
|
|
3ebb36f877 | ||
|
|
b2996f10ff | ||
|
|
42fb4f4700 | ||
|
|
52934602cd | ||
|
|
2a0eda5c34 | ||
|
|
a3b3fbe269 | ||
|
|
2fe177ffb8 | ||
|
|
d8bc75222f | ||
|
|
c3bb651d9e | ||
|
|
135cf6a9cc | ||
|
|
be4b98b9da | ||
|
|
673b367902 | ||
|
|
81626ceec5 | ||
|
|
b653ee59c8 | ||
|
|
79abe31a06 | ||
|
|
30a523b8c1 | ||
|
|
c104f45b16 | ||
|
|
a9bc814016 | ||
|
|
edd00cfa80 | ||
|
|
60baf54d7b | ||
|
|
536f5458bb | ||
|
|
a4cc3a9309 | ||
|
|
f72b92caff | ||
|
|
d3e7842c3a | ||
|
|
555bdefd46 | ||
|
|
206c22f6aa | ||
|
|
14959c2d66 | ||
|
|
eb3760715f | ||
|
|
e02679a587 | ||
|
|
4064b3fc72 | ||
|
|
e3f2a16e92 | ||
|
|
a9441400b3 | ||
|
|
09781613ce | ||
|
|
63b63f6aad | ||
|
|
1637187c76 | ||
|
|
303ef405bb | ||
|
|
bf3da2a662 | ||
|
|
b8194ecc84 | ||
|
|
472ab367b0 | ||
|
|
8f50180543 | ||
|
|
11eae082fc | ||
|
|
885446328d | ||
|
|
8cb4d84905 | ||
|
|
0da52cb366 | ||
|
|
57ea18a9a4 | ||
|
|
06478415b5 | ||
|
|
6a8a1c31e3 | ||
|
|
cce7961ee3 | ||
|
|
725227338a | ||
|
|
c55c568bbd | ||
|
|
45d8c28883 | ||
|
|
8076e59861 | ||
|
|
b41df46491 | ||
|
|
5205d2e352 | ||
|
|
9c923be5f0 | ||
|
|
88328bbe0e | ||
|
|
132614045c | ||
|
|
a33b037364 | ||
|
|
33b27e450f | ||
|
|
a5d541dafc | ||
|
|
258f3725bf | ||
|
|
c4d8e344d1 | ||
|
|
f3128a15d9 | ||
|
|
6f224bd825 | ||
|
|
58bbbc2ad9 | ||
|
|
75de062b55 | ||
|
|
85dfcbd156 | ||
|
|
a6cec7d2ef | ||
|
|
7e0b187cb8 | ||
|
|
025f545ef7 | ||
|
|
6af1afb546 | ||
|
|
1dd1eb3768 | ||
|
|
77d126fc09 | ||
|
|
4a3902c060 | ||
|
|
83cdd4d79d | ||
|
|
1d1191eae0 | ||
|
|
1efa0fa1e6 | ||
|
|
085424f192 | ||
|
|
db23bed00b | ||
|
|
9c31fa88a5 | ||
|
|
c5439da9d2 | ||
|
|
561bf83d88 | ||
|
|
baf8941f31 | ||
|
|
f7dec5542b | ||
|
|
6ec8b97ddb | ||
|
|
35343705ca | ||
|
|
22e894c245 | ||
|
|
4ef01610d0 | ||
|
|
bb065828f2 | ||
|
|
d0637f61d4 | ||
|
|
84319366d1 | ||
|
|
2152c401bf | ||
|
|
0070349d66 | ||
|
|
0cbad44055 | ||
|
|
2571d32134 | ||
|
|
64ee8bac60 | ||
|
|
da392b9c9f | ||
|
|
3179a1846f | ||
|
|
b3912b2281 | ||
|
|
db14723ea2 | ||
|
|
28831a68dd | ||
|
|
6f18495395 | ||
|
|
fc2ef8a09c | ||
|
|
0809540bd7 | ||
|
|
3a71d39785 | ||
|
|
c41aecc2b8 | ||
|
|
06f62bd874 | ||
|
|
23bcbba013 | ||
|
|
cb18d3fe32 | ||
|
|
95694453f4 | ||
|
|
0825e0660f | ||
|
|
819d4d0fdf | ||
|
|
1c43e193ba | ||
|
|
4f1cd6b3a2 |
No files matched your search
@@ -11,6 +11,7 @@ trim_trailing_whitespace = true
|
||||
|
||||
[**.py]
|
||||
indent_style = tab
|
||||
indent_size = 4
|
||||
|
||||
[src/octoprint/static/js/app/**.js]
|
||||
indent_style = space
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help improve OctoPrint
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
READ THE FOLLOWING FIRST:
|
||||
|
||||
If not already done, please read the the Contribution Guidelines that
|
||||
are linked to the right under "Helpful resources" > "Contributing".
|
||||
|
||||
Also read the FAQ: https://faq.octoprint.org
|
||||
|
||||
This is a bug and feature tracker, please only use it to report bugs
|
||||
or request features within OctoPrint (not OctoPi, not any OctoPrint
|
||||
plugins and not unofficial OctoPrint versions).
|
||||
|
||||
Do not seek support here ("I need help with ...", "I have a
|
||||
question ..."), that belongs on the community forum at
|
||||
discourse.octoprint.org, NOT here.
|
||||
|
||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||
reports fully fill out the bug reporting template (if you don't know
|
||||
where to find some information - it's all described in the Contribution
|
||||
Guidelines linked up there in the big yellow box).
|
||||
|
||||
When reporting a bug do NOT delete ANY lines from the template.
|
||||
|
||||
Make sure any bug you want to report is still present with the CURRENT
|
||||
OctoPrint version and that it does not vanish when you start OctoPrint
|
||||
in safe mode - how to do that is also explained in the Contribution
|
||||
Guidelines linked up there in the big yellow box.
|
||||
|
||||
Thank you!
|
||||
-->
|
||||
|
||||
#### What were you doing?
|
||||
|
||||
<!--
|
||||
Please be as specific as possible here. The maintainers will need to
|
||||
reproduce your issue in order to fix it and that is not possible if they
|
||||
don't know what you did to get it to happen in the first place.
|
||||
|
||||
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||
-->
|
||||
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
<!--
|
||||
If you encountered a problem with specific files of any sorts, make sure
|
||||
to also include a link to a file with which to reproduce the problem.
|
||||
-->
|
||||
|
||||
#### What did you expect to happen?
|
||||
|
||||
#### What happened instead?
|
||||
|
||||
#### Did the same happen when running OctoPrint in safe mode?
|
||||
|
||||
<!--
|
||||
Test if you can reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.
|
||||
|
||||
If you can't reproduce in safe mode, this is a bug with one of your
|
||||
installed third party plugins. Don't open a ticket here!
|
||||
|
||||
If you can't test this in safe mode, state why.
|
||||
-->
|
||||
|
||||
#### Version of OctoPrint
|
||||
|
||||
<!--
|
||||
Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.
|
||||
-->
|
||||
|
||||
#### Operating System running OctoPrint
|
||||
|
||||
<!--
|
||||
OctoPi, Linux, Windows, MacOS, something else? With version please.
|
||||
OctoPi's version can be found in /etc/octopi_version or in the lower left
|
||||
corner of the web interface.
|
||||
-->
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
<!--
|
||||
If applicable, always include if unsure.
|
||||
-->
|
||||
|
||||
#### Browser and version of browser, operating system running browser
|
||||
|
||||
<!--
|
||||
If applicable, always include if unsure.
|
||||
-->
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
<!--
|
||||
On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
|
||||
|
||||
The Contribution Guidelines tell you where to find that.
|
||||
-->
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
<!--
|
||||
On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
reporting communication issues. Never truncate.
|
||||
|
||||
serial.log is usually not written due to performance reasons and must be
|
||||
enabled explicitly. Provide at the very least the FULL contents of your
|
||||
terminal tab at the time of the bug occurrence, even if you do not have
|
||||
a serial.log (which the Contribution Guidelines tell you where to find).
|
||||
-->
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
<!--
|
||||
On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.
|
||||
|
||||
The Contribution Guidelines tell you where to find that.
|
||||
-->
|
||||
|
||||
#### Screenshot(s)/video(s) showing the problem:
|
||||
|
||||
<!--
|
||||
If applicable. Always include if unsure or reporting UI issues.
|
||||
-->
|
||||
|
||||
I have read the FAQ.
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
Please make sure to add [Request] to your issue's title. Thank you!
|
||||
-->
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -11,22 +11,23 @@
|
||||
master
|
||||
meta/.*
|
||||
rc/.*
|
||||
hotfix/.*
|
||||
prerelease
|
||||
|
||||
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.7
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.9
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
fix/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
improve/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.7rc4
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.10rc5
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
|
||||
regressionfix/.* 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
|
||||
staging/maintenance 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
|
||||
regressionfix/.* 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -87,6 +87,13 @@ date of first contribution):
|
||||
* [Josh Major](https://github.com/astateofblank)
|
||||
* ["alex-gh"](https://github.com/alex-gh)
|
||||
* [Bernd Zeimetz](https://github.com/bzed)
|
||||
* [Daniele Forsi](https://github.com/dforsi)
|
||||
* [Ganey](https://github.com/ganey)
|
||||
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
||||
* [Andy Castille](https://github.com/klikini)
|
||||
* [Gaston Dombiak](https://github.com/gdombiak)
|
||||
* [Brad Fisher](https://github.com/bradcfisher)
|
||||
* [Aldo Hoeben](https://github.com/fieldofview)
|
||||
|
||||
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
|
||||
|
||||
@@ -27,7 +27,7 @@ to **address problems in a timely manner** but also keep it possible for them
|
||||
to **fix bugs, add new and improve on existing functionality** instead of doing
|
||||
nothing but ticket management.
|
||||
|
||||

|
||||

|
||||
|
||||
- **[Read the FAQ](https://faq.octoprint.org)**
|
||||
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
|
||||
@@ -39,11 +39,11 @@ nothing but ticket management.
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
|
||||
such support issues.
|
||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
||||
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
|
||||
`[Brainstorming] New plugin hook for doing some cool stuff`).
|
||||
changes to the plugin system, please get in touch on the
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
|
||||
- If you need **support**, have a **question** or some **other reason** that
|
||||
doesn't fit any of the above categories, the issue tracker is not the right place.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
|
||||
|
||||
No matter what kind of ticket you create, never mix two or more "ticket reasons"
|
||||
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
@@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
> A bot is in place that monitors new tickets, automatically
|
||||
> categorizes them and checks new bug reports for usage of the provided template.
|
||||
> That bot will only bother you if you open a ticket that appears to be a bug (no
|
||||
> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
|
||||
> `[Request]` in the title) without the complete template, and it
|
||||
> will do that only to ensure that all information needed to solve the issue is
|
||||
> available for the maintainers to directly start tackling that problem.
|
||||
|
||||
@@ -301,7 +301,8 @@ the documentation.
|
||||
the discussion going on how best to solve *this* in OctoPrint's plugin
|
||||
system - maybe that's the actual PR you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large or otherwise disruptive changes to the
|
||||
code or appearance, please open a "Brainstorming" ticket first** so
|
||||
code or appearance, please get in touch on the
|
||||
[forums](https://discourse.octoprint.org/c/development)** first so
|
||||
that we can determine if it's a good time for your specific pull
|
||||
request. It might be that we're currently in the process of making
|
||||
heavy changes to the code locations you'd target as well, or your
|
||||
@@ -311,7 +312,8 @@ the documentation.
|
||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
||||
`dev/myNewFeature`)[1].
|
||||
4. Create your pull request **only against the `maintenance` or `devel` branch**:
|
||||
* if it's a bug fix for a bug in the current stable version: `maintenance` branch
|
||||
* if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
|
||||
*small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
|
||||
* otherwise: `devel` branch
|
||||
5. Create **one pull request per feature/bug fix**.
|
||||
6. Make sure there are **only relevant changes** included in your PR. No
|
||||
@@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 2017-11-22: Added note on how to run the unit tests
|
||||
* 2018-03-15: Link to new community forum and some clarifications re bug
|
||||
reporting
|
||||
* 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
|
||||
new features, suggest getting in touch on the forum for larger changes
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
# OctoPrint
|
||||
|
||||
[](https://badge.fury.io/gh/foosel%2FOctoPrint)
|
||||
|
||||

|
||||
[](https://travis-ci.org/foosel/OctoPrint)
|
||||
[](https://discourse.octoprint.org)
|
||||
[](https://chat.octoprint.org)
|
||||
[](https://twitter.com/OctoPrint3d)
|
||||
|
||||
|
||||
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).
|
||||
@@ -9,6 +15,8 @@ Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=gi
|
||||
|
||||
The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint).
|
||||
|
||||
The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||
|
||||
@@ -1,58 +1,57 @@
|
||||
# Supporters
|
||||
|
||||
Development of this version of OctoPrint wouldn't have been possible without
|
||||
[financial support by the community](http://octoprint.org/support-octoprint/) -
|
||||
[the financial support by the community](https://octoprint.org/support-octoprint/) -
|
||||
thanks to everyone who contributed!
|
||||
|
||||
## Patreon Patrons
|
||||
|
||||
* Andre Bubel
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brian E. Tyler
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* COLLE+McVOY
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* E3D BigBox
|
||||
* Eric Betts
|
||||
* Eric Slape
|
||||
* Ernesto Martinez
|
||||
* F. Kunsmann
|
||||
* Frank Sander
|
||||
* Gary Deen
|
||||
* günter weber
|
||||
* James Seigel
|
||||
* Jeff Moe
|
||||
* George Robles
|
||||
* Jared Go
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
* Joseph Payne
|
||||
* Josh Daniels
|
||||
* Joshua Wills
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kodama Inc.
|
||||
* LA 3D Printer Repair
|
||||
* Lewis Newby
|
||||
* LulzBot®
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Martin Beattie
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* mitchell hirsch
|
||||
* Mohammed khorakiwala
|
||||
* Noe Ruiz
|
||||
* Mosaic Manufacturing
|
||||
* Patrick McGinnis
|
||||
* Peter Schmehl
|
||||
* Prof Yuh Wen Chen
|
||||
* Randy C. Will
|
||||
* Robert Gusek
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Samer Najia
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Stephane Schittly
|
||||
* Sven Mueller
|
||||
* Symbiotic Devices
|
||||
* Thomas Hatley
|
||||
* Timothy D Hoogland
|
||||
* Trent Shumay
|
||||
|
||||
and 1233 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1446 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -71,7 +71,6 @@
|
||||
* [ddt](https://github.com/txels/ddt): MIT
|
||||
* [mock](https://github.com/testing-cabal/mock): BSD
|
||||
* [nose](http://pythonhosted.org/nose/): LGPL
|
||||
* [pypandoc](https://github.com/bebraw/pypandoc): MIT
|
||||
* [Sphinx](http://sphinx-doc.org/): BSD
|
||||
* [sphinxcontrib-httpdomain](https://bitbucket.org/birkenfeld/sphinx-contrib/src/default/httpdomain/): BSD
|
||||
* [sphinxcontrib-mermad](https://github.com/mgaitan/sphinxcontrib-mermaid): BSD
|
||||
|
||||
@@ -263,8 +263,11 @@ File information
|
||||
- Path to type of file in extension tree. E.g. ``["model", "stl"]`` for ``.stl`` files, or ``["machinecode", "gcode"]``
|
||||
for ``.gcode`` files. ``["folder"]`` for folders.
|
||||
|
||||
Additional properties depend on ``type``. For a ``type`` value of ``folder``, see "Folders". For any other value
|
||||
see "Files".
|
||||
Additional properties depend on ``type``.
|
||||
For a ``type`` value of ``folder``, see :ref:`Folders <sec-api-datamodel-files-folders>`.
|
||||
For any other value see :ref:`Files <sec-api-datamodel-files-files>`.
|
||||
|
||||
.. _sec-api-datamodel-files-folders:
|
||||
|
||||
Folders
|
||||
'''''''
|
||||
@@ -280,13 +283,14 @@ Folders
|
||||
* - ``children``
|
||||
- 0..*
|
||||
- Array of :ref:`File information items <sec-api-datamodel-files-file>`
|
||||
- Contained children for entries of type ``folder``. Will only include children in subfolders in recursive
|
||||
listings. Not present in non recursive listings, this might be revisited in the future.
|
||||
- Contained children for entries of type ``folder``. On non recursive listings only present on first level
|
||||
sub folders!
|
||||
* - ``size``
|
||||
- 0..1
|
||||
- Number
|
||||
- The size of all files contained in the folder and its subfolders. Not present in non recursive listings, this might
|
||||
be revisited in the future.
|
||||
- The size of all files contained in the folder and its subfolders. Not present in non recursive listings!
|
||||
|
||||
.. _sec-api-datamodel-files-files:
|
||||
|
||||
Files
|
||||
'''''
|
||||
@@ -385,14 +389,58 @@ GCODE analysis information
|
||||
- 0..1
|
||||
- Object
|
||||
- The estimated usage of filament
|
||||
* - ``filament.length``
|
||||
* - ``filament.tool{n}.length``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The length of filament used, in mm
|
||||
* - ``filament.volume``
|
||||
* - ``filament.tool{n}.volume``
|
||||
- 0..1
|
||||
- Float
|
||||
- The volume of filament used, in cm³
|
||||
* - ``dimensions``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the size of the printed model
|
||||
* - ``dimensions.depth``
|
||||
- 0..1
|
||||
- Float
|
||||
- The depth of the printed model, in mm
|
||||
* - ``dimensions.height``
|
||||
- 0..1
|
||||
- Float
|
||||
- The height of the printed model, in mm
|
||||
* - ``dimensions.width``
|
||||
- 0..1
|
||||
- Float
|
||||
- The width of the printed model, in mm
|
||||
* - ``printingArea``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the size of the printing area
|
||||
* - ``printingArea.maxX``
|
||||
- 0..1
|
||||
- Float
|
||||
- The maximum X coordinate of the printed model, in mm
|
||||
* - ``printingArea.maxY``
|
||||
- 0..1
|
||||
- Float
|
||||
- The maximum Y coordinate of the printed model, in mm
|
||||
* - ``printingArea.maxZ``
|
||||
- 0..1
|
||||
- Float
|
||||
- The maximum Z coordinate of the printed model, in mm
|
||||
* - ``printingArea.minX``
|
||||
- 0..1
|
||||
- Float
|
||||
- The minimum X coordinate of the printed model, in mm
|
||||
* - ``printingArea.minY``
|
||||
- 0..1
|
||||
- Float
|
||||
- The minimum Y coordinate of the printed model, in mm
|
||||
* - ``printingArea.minZ``
|
||||
- 0..1
|
||||
- Float
|
||||
- The minimum Z coordinate of the printed model, in mm
|
||||
|
||||
|
||||
.. _sec-api-datamodel-files-ref:
|
||||
@@ -421,4 +469,3 @@ References
|
||||
- URL
|
||||
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
|
||||
folders.
|
||||
|
||||
@@ -82,8 +82,37 @@ Retrieve all files
|
||||
"path": "folderA",
|
||||
"type": "folder",
|
||||
"typePath": ["folder"],
|
||||
"children": [],
|
||||
"size": 1334
|
||||
"children": [
|
||||
{
|
||||
"name": "whistle_v2_copy.gcode",
|
||||
"path": "whistle_v2_copy.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "...",
|
||||
"size": 1468987,
|
||||
"date": 1378847754,
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/folderA/whistle_v2_copy.gcode",
|
||||
"download": "http://example.com/downloads/files/local/folderA/whistle_v2_copy.gcode"
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"estimatedPrintTime": 1188,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"print": {
|
||||
"failure": 4,
|
||||
"success": 23,
|
||||
"last": {
|
||||
"date": 1387144346,
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"free": "3.2GB"
|
||||
@@ -443,7 +472,7 @@ Upload file or create folder
|
||||
:form select: Whether to select the file directly after upload (``true``) or not (``false``). Optional, defaults
|
||||
to ``false``. Ignored when creating a folder.
|
||||
:form print: Whether to start printing the file directly after upload (``true``) or not (``false``). If set, ``select``
|
||||
is implicitely ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder.
|
||||
is implicitly ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder.
|
||||
:form userdata: [Optional] An optional string that if specified will be interpreted as JSON and then saved along
|
||||
with the file as metadata (metadata key ``userdata``). Ignored when creating a folder.
|
||||
:form foldername: The name of the folder to create. Ignored when uploading a file.
|
||||
|
||||
@@ -12,8 +12,11 @@ Authorization
|
||||
=============
|
||||
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one, a user specific one if "Access Control" is enabled or an :ref:`App Session Key <sec-api-apps-sessionkey>`.
|
||||
Users are able to generate and revoke their custom API key via the "Change password" dialog.
|
||||
configured one, a user specific one if "Access Control" is enabled or an app and user specific one as generated
|
||||
by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
|
||||
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
|
||||
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
|
||||
|
||||
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
|
||||
@@ -23,7 +26,7 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`.
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`.
|
||||
|
||||
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||
|
||||
@@ -120,3 +123,94 @@ If CORS is not enabled you will get errors like the following::
|
||||
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
|
||||
header is present on the requested resource.
|
||||
|
||||
.. _sec-api-general-login:
|
||||
|
||||
Login
|
||||
=====
|
||||
|
||||
.. http:post:: /api/login
|
||||
|
||||
Creates a login session or retrieves information about the currently existing session ("passive login").
|
||||
|
||||
Can be used in one of two ways: to login a user via username and password and create a persistent session (usually
|
||||
from a UI in the browser), or to retrieve information about the active user (from an existing session or an API key)
|
||||
via the ``passive`` flag.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
|
||||
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
|
||||
|
||||
:json passive: If present, performs a passive login only, returning information about the current user that's
|
||||
active either through an existing session or the used API key
|
||||
:json user: (active login only) Username
|
||||
:json pass: (active login only) Password
|
||||
:json remember: (active login only) Whether to set a "remember me" cookie on the session
|
||||
:status 200: Successful login
|
||||
:status 401: Username/password mismatch or unknown user
|
||||
:status 403: Deactivated account
|
||||
|
||||
.. _sec-api-general-logout:
|
||||
|
||||
Logout
|
||||
======
|
||||
|
||||
.. http:post:: /api/logout
|
||||
|
||||
Ends the current login session of the current user.
|
||||
|
||||
Only makes sense in the context of browser based workflows.
|
||||
|
||||
Will return a :http:statuscode:`204`.
|
||||
|
||||
:status 204: No error
|
||||
|
||||
.. _sec-api-general-datamodel:
|
||||
|
||||
Data model
|
||||
==========
|
||||
|
||||
.. _sec-api-general-datamodel-login:
|
||||
|
||||
Login response
|
||||
--------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- the user's name/id
|
||||
* - ``active``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user's account is active or not
|
||||
* - ``admin``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has admin rights or not
|
||||
* - ``user``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has user rights or not (always ``true``)
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- string or None
|
||||
- The user's API key, if set
|
||||
* - ``settings``
|
||||
- 1
|
||||
- dict
|
||||
- The user's settings, if any
|
||||
* - ``session``
|
||||
- 1
|
||||
- string
|
||||
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
|
||||
* - ``_is_external_client``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the client that made the request got detected as external from the local network or not.
|
||||
@@ -37,7 +37,7 @@ Besides that, OctoPrint also provides a :ref:`full state report of the printer <
|
||||
OctoPrint's internal webserver is single threaded and can only handle one request at a time. This is
|
||||
not a problem generally since asynchronous programming allows to just have one request which is waiting for
|
||||
data from a long running backend operation to sleep while handling other requests. The internal framework
|
||||
used for providing the REST API though, Flask, is based on WSGI, which is synchrounous in nature. This means
|
||||
used for providing the REST API though, Flask, is based on WSGI, which is synchronous in nature. This means
|
||||
that it is impossible to wait in a non blocking wait while handling a request on the REST API. So in order to
|
||||
return the response of a command sent to the printer, the single thread of the webserver would have to be blocked
|
||||
by the API while the response wasn't available yet. Which in turn would mean that the whole web server would
|
||||
@@ -219,7 +219,7 @@ Issue a print head command
|
||||
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
|
||||
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
|
||||
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
|
||||
interpreted as an integer signifying the speed in mm/s, to append to the command.
|
||||
interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
home
|
||||
Homes the print head in all of the given axes. Additional parameters are:
|
||||
@@ -229,7 +229,7 @@ Issue a print head command
|
||||
feedrate
|
||||
Changes the feedrate factor to apply to the movements of the axes.
|
||||
|
||||
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 50 and 200%.
|
||||
* ``factor``: The new factor, percentage between 50 and 200% as integer (``50`` to ``200``) or float (``0.5`` to ``2.0``).
|
||||
|
||||
All of these commands except ``feedrate`` may only be sent if the printer is currently operational and not printing.
|
||||
Otherwise a :http:statuscode:`409` is returned.
|
||||
@@ -280,9 +280,9 @@ Issue a print head command
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example feed rate request**
|
||||
**Example feed rate request (1/2)**
|
||||
|
||||
Set the feed rate factor to 105%.
|
||||
Set the feed rate factor to 105% using an integer argument.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
@@ -300,6 +300,26 @@ Issue a print head command
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example feed rate request (2/2)**
|
||||
|
||||
Set the feed rate factor to 105% using a float argument.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/printhead HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "feedrate",
|
||||
"factor": 1.05
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``jog`` or ``home``.
|
||||
:json number x: ``jog`` command: The amount to travel on the X axis in mm.
|
||||
:json number y: ``jog`` command: The amount to travel on the Y axis in mm.
|
||||
@@ -342,11 +362,13 @@ Issue a tool command
|
||||
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
|
||||
|
||||
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
|
||||
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
|
||||
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
flowrate
|
||||
Changes the flow rate factor to apply to extrusion of the tool.
|
||||
|
||||
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 75 and 125%.
|
||||
* ``factor``: The new factor, percentage between 75 and 125% as integer (``75`` to ``125``) or float (``0.75`` to ``1.25``).
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational and -- in case of ``select`` and
|
||||
``extrude`` -- not printing. Otherwise a :http:statuscode:`409` is returned.
|
||||
@@ -461,9 +483,9 @@ Issue a tool command
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example flow rate request**
|
||||
**Example flow rate request (1/2)**
|
||||
|
||||
Set the flow rate factor to 95%.
|
||||
Set the flow rate factor to 95% using an integer attribute.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
@@ -481,6 +503,26 @@ Issue a tool command
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example flow rate request (2/2)**
|
||||
|
||||
Set the flow rate factor to 95% using a float attribute.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/tool HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "flowrate",
|
||||
"factor": 0.95
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``target``, ``offset``, ``select`` or ``extrude``.
|
||||
:json object targets: ``target`` command: The target temperatures to set. Valid properties have to match the format ``tool{n}``.
|
||||
:json object offsets: ``offset`` command: The offset temperature to set. Valid properties have to match the format ``tool{n}``.
|
||||
|
||||
@@ -581,7 +581,7 @@ Profile
|
||||
* - ``axes``
|
||||
- 0..1
|
||||
- Object
|
||||
- Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maxium speed
|
||||
- Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maximum speed
|
||||
and whether this axis is inverted or not.
|
||||
* - ``axes.{axis}.speed``
|
||||
- 0..1
|
||||
|
||||
@@ -47,23 +47,41 @@ Clients must ignore any unknown messages.
|
||||
|
||||
The data model of the attached payloads is described further below.
|
||||
|
||||
OctoPrint's SockJS socket also accepts one command from the client to the server,
|
||||
the ``throttle`` command. Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
OctoPrint's SockJS socket also accepts two commands from the client to the server.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
|
||||
existing user session with the socket. That is of special importance to receive
|
||||
any kind of messages if the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` is enabled
|
||||
(as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated
|
||||
clients.
|
||||
|
||||
.. sourcecode:: javascript
|
||||
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
|
||||
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
Example for a ``auth`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"auth": "someuser:LGZ0trf8By"
|
||||
}
|
||||
|
||||
* ``throttle``: Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
|
||||
.. _sec-api-push-datamodel:
|
||||
|
||||
|
||||
@@ -86,6 +86,266 @@ Regenerate the system wide API key
|
||||
:status 200: No error
|
||||
:status 403: No admin rights
|
||||
|
||||
.. _sec-api-settings-fetchtemplaatedata:
|
||||
|
||||
Fetch template data
|
||||
===================
|
||||
|
||||
.. http:get:: /api/settings/templates
|
||||
|
||||
Fetch data (currently only the sorting order) of all registered template components in the system.
|
||||
|
||||
Use this to get a full list of the identifiers of all UI components provided either by core OctoPrint or any
|
||||
currently active plugins.
|
||||
|
||||
Example:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/settings/templates HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"order": {
|
||||
"about": [
|
||||
{
|
||||
"id": "about",
|
||||
"name": "About OctoPrint"
|
||||
},
|
||||
{
|
||||
"id": "supporters",
|
||||
"name": "Supporters"
|
||||
},
|
||||
{
|
||||
"id": "authors",
|
||||
"name": "Authors"
|
||||
},
|
||||
{
|
||||
"id": "changelog",
|
||||
"name": "Changelog"
|
||||
},
|
||||
{
|
||||
"id": "license",
|
||||
"name": "OctoPrint License"
|
||||
},
|
||||
{
|
||||
"id": "thirdparty",
|
||||
"name": "Third Party Licenses"
|
||||
},
|
||||
{
|
||||
"id": "plugin_pluginmanager",
|
||||
"name": "Plugin Licenses",
|
||||
"plugin_id": "pluginmanager",
|
||||
"plugin_name": "Plugin Manager"
|
||||
}
|
||||
],
|
||||
"generic": [
|
||||
{
|
||||
"id": "plugin_announcements",
|
||||
"name": "plugin_announcements",
|
||||
"plugin_id": "announcements",
|
||||
"plugin_name": "Announcement Plugin"
|
||||
}
|
||||
],
|
||||
"navbar": [
|
||||
{
|
||||
"id": "settings",
|
||||
"name": "settings"
|
||||
},
|
||||
{
|
||||
"id": "systemmenu",
|
||||
"name": "systemmenu"
|
||||
},
|
||||
{
|
||||
"id": "plugin_announcements",
|
||||
"name": "plugin_announcements",
|
||||
"plugin_id": "announcements",
|
||||
"plugin_name": "Announcement Plugin"
|
||||
},
|
||||
{
|
||||
"id": "login",
|
||||
"name": "login"
|
||||
}
|
||||
],
|
||||
"plugin_pluginmanager_about_thirdparty": [],
|
||||
"settings": [
|
||||
{
|
||||
"id": "section_printer",
|
||||
"name": "Printer"
|
||||
},
|
||||
{
|
||||
"id": "serial",
|
||||
"name": "Serial Connection"
|
||||
},
|
||||
{
|
||||
"id": "printerprofiles",
|
||||
"name": "Printer Profiles"
|
||||
},
|
||||
{
|
||||
"id": "temperatures",
|
||||
"name": "Temperatures"
|
||||
},
|
||||
{
|
||||
"id": "terminalfilters",
|
||||
"name": "Terminal Filters"
|
||||
},
|
||||
{
|
||||
"id": "gcodescripts",
|
||||
"name": "GCODE Scripts"
|
||||
},
|
||||
{
|
||||
"id": "section_features",
|
||||
"name": "Features"
|
||||
},
|
||||
{
|
||||
"id": "features",
|
||||
"name": "Features"
|
||||
},
|
||||
{
|
||||
"id": "webcam",
|
||||
"name": "Webcam & Timelapse"
|
||||
},
|
||||
{
|
||||
"id": "accesscontrol",
|
||||
"name": "Access Control"
|
||||
},
|
||||
{
|
||||
"id": "gcodevisualizer",
|
||||
"name": "GCODE Visualizer"
|
||||
},
|
||||
{
|
||||
"id": "api",
|
||||
"name": "API"
|
||||
},
|
||||
{
|
||||
"id": "section_octoprint",
|
||||
"name": "OctoPrint"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"name": "Server"
|
||||
},
|
||||
{
|
||||
"id": "folders",
|
||||
"name": "Folders"
|
||||
},
|
||||
{
|
||||
"id": "appearance",
|
||||
"name": "Appearance"
|
||||
},
|
||||
{
|
||||
"id": "plugin_logging",
|
||||
"name": "Logging",
|
||||
"plugin_id": "logging",
|
||||
"plugin_name": "Logging"
|
||||
},
|
||||
{
|
||||
"id": "plugin_pluginmanager",
|
||||
"name": "Plugin Manager",
|
||||
"plugin_id": "pluginmanager",
|
||||
"plugin_name": "Plugin Manager"
|
||||
},
|
||||
{
|
||||
"id": "plugin_softwareupdate",
|
||||
"name": "Software Update",
|
||||
"plugin_id": "softwareupdate",
|
||||
"plugin_name": "Software Update"
|
||||
},
|
||||
{
|
||||
"id": "plugin_announcements",
|
||||
"name": "Announcements",
|
||||
"plugin_id": "announcements",
|
||||
"plugin_name": "Announcement Plugin"
|
||||
},
|
||||
{
|
||||
"id": "section_plugins",
|
||||
"name": "Plugins"
|
||||
},
|
||||
{
|
||||
"id": "plugin_action_command_prompt",
|
||||
"name": "Action Command Prompt",
|
||||
"plugin_id": "action_command_prompt",
|
||||
"plugin_name": "Action Command Prompt Support"
|
||||
},
|
||||
{
|
||||
"id": "plugin_cura",
|
||||
"name": "CuraEngine (<= 15.04)",
|
||||
"plugin_id": "cura",
|
||||
"plugin_name": "CuraEngine (<= 15.04)"
|
||||
}
|
||||
],
|
||||
"sidebar": [
|
||||
{
|
||||
"id": "plugin_printer_safety_check",
|
||||
"name": "Printer Safety Warning",
|
||||
"plugin_id": "printer_safety_check",
|
||||
"plugin_name": "Printer Safety Check"
|
||||
},
|
||||
{
|
||||
"id": "connection",
|
||||
"name": "Connection"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"name": "State"
|
||||
},
|
||||
{
|
||||
"id": "files",
|
||||
"name": "Files"
|
||||
}
|
||||
],
|
||||
"tab": [
|
||||
{
|
||||
"id": "temperature",
|
||||
"name": "Temperature"
|
||||
},
|
||||
{
|
||||
"id": "control",
|
||||
"name": "Control"
|
||||
},
|
||||
{
|
||||
"id": "gcodeviewer",
|
||||
"name": "GCode Viewer"
|
||||
},
|
||||
{
|
||||
"id": "terminal",
|
||||
"name": "Terminal"
|
||||
},
|
||||
{
|
||||
"id": "timelapse",
|
||||
"name": "Timelapse"
|
||||
}
|
||||
],
|
||||
"usersettings": [
|
||||
{
|
||||
"id": "access",
|
||||
"name": "Access"
|
||||
},
|
||||
{
|
||||
"id": "interface",
|
||||
"name": "Interface"
|
||||
}
|
||||
],
|
||||
"wizard": []
|
||||
}
|
||||
}
|
||||
|
||||
Requires admin rights.
|
||||
|
||||
.. warning::
|
||||
|
||||
This API endpoint is in beta. Things might change. If you happen to want to develop against it, you should drop
|
||||
me an email to make sure I can give you a heads-up when something changes in an backwards incompatible way.
|
||||
|
||||
:status 200: No error
|
||||
:status 403: No admin rights
|
||||
|
||||
.. _sec-api-settings-datamodel:
|
||||
|
||||
Data model
|
||||
@@ -106,7 +366,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
* - ``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:`regenerting it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
|
||||
only :ref:`regenerating it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
|
||||
possible through `config.yaml`.
|
||||
* - ``api.allowCrossOrigin``
|
||||
-
|
||||
@@ -136,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
-
|
||||
* - ``feature.sdSupport``
|
||||
-
|
||||
* - ``feature.sdReleativePath``
|
||||
* - ``feature.sdRelativePath``
|
||||
-
|
||||
* - ``feature.sdAlwaysAvailable``
|
||||
-
|
||||
|
||||
@@ -30,6 +30,14 @@ Test paths or URLs
|
||||
existence but also whether it is of the specified type. Optional.
|
||||
* ``check_access``: A list of any of ``r``, ``w`` and ``x``. If present it will also
|
||||
be checked if OctoPrint has read, write, execute permissions on the specified path.
|
||||
* ``allow_create_dir``: If ``check_type`` is provided and set to ``dir``, this will allow
|
||||
OctoPrint to create the target ``path`` as a directory if it doesn't yet exist to allow
|
||||
for further tests.
|
||||
* ``check_writable_dir``: If ``check_type`` is provided and set to ``dir``, this will
|
||||
check that the provided ``path`` is a writable directory. OctoPrint not only check if the
|
||||
permissions on the directory allow for writing but also attempt to write (and delete) a
|
||||
small test file ``.testballoon.txt`` to the directory to test if writing is actually
|
||||
possible.
|
||||
|
||||
The ``path`` command returns a :http:statuscode:`200` with a :ref:`path test result <sec-api-util-datamodel-pathtestresult>`
|
||||
when the test could be performed. The status code of the response does NOT reflect the
|
||||
@@ -65,6 +73,12 @@ Test paths or URLs
|
||||
from the URL check will be returned as part of the check result as well. ``json`` will attempt
|
||||
to parse the response as json and return the parsed result. ``true`` or ``bytes`` will base64 encode the body
|
||||
and return that.
|
||||
* ``content_type_whitelist``: Optional array of supported content types. If set and the URL returns a content
|
||||
type not included in this list, the test will fail. E.g. ``["image/*", "text/plain"]``.
|
||||
* ``content_type_blacklist``: Optional array of unsupported content types. If set and the URL returns a content
|
||||
type included in this list, the test wil fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist``
|
||||
to further limit broader content type definition, e.g. by putting ``image/*`` into the whitelist, but disallowing
|
||||
PNG by including ``image/png`` on the blacklist.
|
||||
|
||||
The ``url`` command returns :http:statuscode:`200` with a :ref:`URL test result <sec-api-util-datamodel-urltestresult>`
|
||||
when the test could be performed. The status code of the response does NOT reflect the
|
||||
@@ -272,19 +286,23 @@ Test paths or URLs
|
||||
"result": true
|
||||
}
|
||||
|
||||
:json command: The command to execute, currently either ``path`` or ``url``
|
||||
:json path: ``path`` command only: the path to test
|
||||
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
|
||||
:json check_access: ``path`` command only: a list of access permissions to check for
|
||||
:json url: ``url`` command only: the URL to test
|
||||
:json status: ``url`` command only: one or more expected status codes
|
||||
:json method: ``url`` command only: the HTTP method to use for the check
|
||||
:json timeout: ``url`` and ``server`` commands only: the timeout for the test request
|
||||
:json response: ``url`` command only: whether to include response data and if so in what form
|
||||
:json host: ``server`` command only: the server to test
|
||||
:json port: ``server`` command only: the port to test
|
||||
:json protocol: ``server`` command only: the protocol to test
|
||||
:statuscode 200: No error occurred
|
||||
:json command: The command to execute, currently either ``path`` or ``url``
|
||||
:json path: ``path`` command only: the path to test
|
||||
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
|
||||
:json check_access: ``path`` command only: a list of access permissions to check for
|
||||
:json allow_create_dir: ``path`` command and ``checktype`` of ``dir`` only: whether to allow creation of the
|
||||
directory if it doesn't yet exist (``true``) or not (``false``, default)
|
||||
:json check_writable_dir: ``path`` command and ``checktype`` of ``dir`` only: whether to test if the directory
|
||||
is writable by also trying to create a test file in it (``true``) or not (``false``, default)
|
||||
:json url: ``url`` command only: the URL to test
|
||||
:json status: ``url`` command only: one or more expected status codes
|
||||
:json method: ``url`` command only: the HTTP method to use for the check
|
||||
:json timeout: ``url`` and ``server`` commands only: the timeout for the test request
|
||||
:json response: ``url`` command only: whether to include response data and if so in what form
|
||||
:json host: ``server`` command only: the server to test
|
||||
:json port: ``server`` command only: the port to test
|
||||
:json protocol: ``server`` command only: the protocol to test
|
||||
:statuscode 200: No error occurred
|
||||
|
||||
.. _sec-api-util-datamodel:
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
.. _sec-bundledplugins-action_command_prompt:
|
||||
|
||||
Action Command Prompt support
|
||||
=============================
|
||||
|
||||
The OctoPrint Action Command Prompt Support Plugin comes bundled with OctoPrint (starting with 1.3.9).
|
||||
|
||||
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
|
||||
in case its no longer needed, e.g. due to the user proceeding on the printer's own controller.
|
||||
|
||||
The choice of the user can be communicated back to the firmware via a configurable GCODE command with a
|
||||
placeholder for the selected option's index.
|
||||
|
||||
.. _fig-bundledplugins-action_command_prompt-example:
|
||||
.. figure:: ../images/bundledplugins-action_command_prompt-example.png
|
||||
:align: center
|
||||
:alt: Simple prompt example
|
||||
|
||||
A simple dialog example triggered by the firmware
|
||||
|
||||
.. _sec-bundledplugins-action_command_prompt-firststeps:
|
||||
|
||||
First Steps
|
||||
-----------
|
||||
|
||||
In order for this plugin to work, you'll need to configure it with the command your firmware uses to accept
|
||||
dialog selections. You can do that in the settings dialog.
|
||||
|
||||
Currently there is no agreed upon command for this since no firmware has yet made use of this feature, so OctoPrint
|
||||
ships with an empty value here.
|
||||
|
||||
.. _sec-bundledplugins-action_command_prompt-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin supports the following configuration keys:
|
||||
|
||||
* ``selection_command``: The command to send to the firmware on choice, including the ``{choice}`` placeholder, e.g. ``M876 S{choice}``.
|
||||
|
||||
You can modify them either through the plugin's configuration dialog under Settings, or by directly editing ``config.yaml``.
|
||||
|
||||
.. _sec-bundledplugins-action_command_prompt-action_commands:
|
||||
|
||||
Supported action commands
|
||||
-------------------------
|
||||
|
||||
prompt_begin <message>
|
||||
Starts the definition of a prompt dialog. ``<message>`` is the message to display to the user. Will be ignored
|
||||
if a dialog is already defined.
|
||||
|
||||
prompt_choice <text>
|
||||
Defines a choice with the associated ``<text>``. Will be ignored if no dialog has been defined yet.
|
||||
|
||||
prompt_button <text>
|
||||
Same as ``prompt_choice``.
|
||||
|
||||
prompt_show
|
||||
Tells OctoPrint that the dialog is now fully defined and to prompt the user. Will be ignored if no dialog is
|
||||
defined yet.
|
||||
|
||||
prompt_end
|
||||
Tells OctoPrint that the dialog should now be closed (e.g. the user made the choice on the printer directly instead
|
||||
of through OctoPrint). Will be ignored if no dialog is defined yet.
|
||||
|
||||
.. _sec-bundledplugins-action_command_prompt-example:
|
||||
|
||||
Example communication with the firmware
|
||||
---------------------------------------
|
||||
|
||||
.. _sec-bundledplugins-action_command_prompt-sourcecode:
|
||||
|
||||
To display the :ref:`above dialog <fig-bundledplugins-action_command_prompt-example>` the firmware sent these action commands:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
//action:prompt_begin Filament unloaded, swap then proceed
|
||||
//action:prompt_choice Filament swapped
|
||||
//action:prompt_show
|
||||
|
||||
If the user clicks the button, assuming a ``selection_command`` of ``M876 S{choice}`` is configured, OctoPrint
|
||||
will send back ``M876 S0`` (0-based index).
|
||||
|
||||
A more complicated example with three options would be the following:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
//action:prompt_begin Filament runout detected. Please choose how to proceed:
|
||||
//action:prompt_choice Swap filament
|
||||
//action:prompt_choice Home X/Y and pause print
|
||||
//action:prompt_choice Abort print
|
||||
//action:prompt_show
|
||||
|
||||
This would produce the following output:
|
||||
|
||||
.. _fig-bundledplugins-action_command_prompt-example2:
|
||||
.. figure:: ../images/bundledplugins-action_command_prompt-example2.png
|
||||
:align: center
|
||||
:alt: Another prompt example
|
||||
|
||||
Another dialog example triggered by the firmware
|
||||
|
||||
If the user selects "Abort print", OctoPrint will send ``2`` as selected choice.
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Action Command Prompt Support plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/action_command_prompt``.
|
||||
@@ -0,0 +1,67 @@
|
||||
.. _sec-bundledplugins-announcements:
|
||||
|
||||
Announcement Plugin
|
||||
===================
|
||||
|
||||
The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11).
|
||||
|
||||
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
|
||||
via RSS or Atom feed URLs.
|
||||
|
||||
.. _fig-bundledplugins-announcements-example1:
|
||||
.. figure:: ../images/bundledplugins-announcements-example1.png
|
||||
:align: center
|
||||
:alt: Example notification
|
||||
|
||||
An example notification from the Announcement Plugin.
|
||||
|
||||
.. _fig-bundledplugins-announcements-example2:
|
||||
.. figure:: ../images/bundledplugins-announcements-example2.png
|
||||
:align: center
|
||||
:alt: Announcement reader
|
||||
|
||||
The Announcement Plugin's reader dialog.
|
||||
|
||||
.. _fig-bundledplugins-announcements-settings:
|
||||
.. figure:: ../images/bundledplugins-announcements-settings.png
|
||||
:align: center
|
||||
:alt: Announcement settings
|
||||
|
||||
The Announcement Plugin's settings dialog.
|
||||
|
||||
.. _sec-bundledplugins-announcements-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog.
|
||||
|
||||
On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the
|
||||
configuration of the existing channels through ``config.yaml``.
|
||||
|
||||
The available configuration keys are:
|
||||
|
||||
* ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure
|
||||
that follows this format:
|
||||
|
||||
* ``name``: Name of the channel, used e.g. in the title of the displayed notifications.
|
||||
* ``description``: Description of the channel.
|
||||
* ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification).
|
||||
* ``type``: Currently unused.
|
||||
* ``url``: URL for the feed acting as notification source, must be RSS or Atom format.
|
||||
|
||||
* ``enabled_channels``: List of identifiers of enabled channels.
|
||||
* ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly).
|
||||
* ``channel_order``: List of channel identifiers in the order they should appear in the UI.
|
||||
* ``ttl``: Time to live of the channel cache in minutes (default: 6 hours).
|
||||
* ``display_limit``: Limit of items to display per channel (default: 3).
|
||||
* ``summary_limit``: Limit of characters to display from each channel entry (default: 300).
|
||||
|
||||
.. _sec-bundledplugins-announcements-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Announcement plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/announcements``.
|
||||
@@ -0,0 +1,543 @@
|
||||
.. _sec-bundledplugins-appkeys:
|
||||
|
||||
Application Keys Plugin
|
||||
=======================
|
||||
|
||||
The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10).
|
||||
|
||||
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 per-user base as well as globally by administrators.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-confirmation:
|
||||
.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png
|
||||
:align: center
|
||||
:alt: Confirmation
|
||||
|
||||
The plugin's confirmation generated for a new application key request.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-user_settings:
|
||||
.. figure:: ../images/bundledplugins-appkeys-user_settings.png
|
||||
:align: center
|
||||
:alt: Key management via user settings
|
||||
|
||||
Users can manage the application specific API keys registered to their account via their user settings.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-settings:
|
||||
.. figure:: ../images/bundledplugins-appkeys-settings.png
|
||||
:align: center
|
||||
:alt: Global key management via settings
|
||||
|
||||
Administrators can manage all application specific API keys registered to any user.
|
||||
|
||||
.. _sec-bundledplugins-appkeys-workflow:
|
||||
|
||||
Workflow
|
||||
--------
|
||||
|
||||
The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist
|
||||
of the following steps:
|
||||
|
||||
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
|
||||
enters their username which is also their user ID into the App.
|
||||
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
|
||||
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
|
||||
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
|
||||
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
|
||||
authorization process.
|
||||
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
|
||||
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
|
||||
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
|
||||
signals that no decision has been made yet.
|
||||
6. The User either accepts or denies the access request which makes the Webinterface send a
|
||||
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
|
||||
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
|
||||
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
|
||||
an HTTP :http:statuscode:`404`.
|
||||
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant App
|
||||
participant Webinterface
|
||||
participant Server
|
||||
|
||||
note over User, Server: Step 1, 2 & 3
|
||||
|
||||
User->>App: enters URL of instance to connect to and optional user_id
|
||||
|
||||
App->>Server: GET /plugin/appkeys/probe
|
||||
|
||||
alt Workflow unsupported
|
||||
|
||||
Server->>App: 404
|
||||
App->>User: alternative workflow, copy-paste key manually
|
||||
|
||||
else Workflow supported
|
||||
|
||||
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
|
||||
|
||||
note over User, Server: Step 4
|
||||
|
||||
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
|
||||
Webinterface-->>User: Display confirmation dialog
|
||||
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
|
||||
|
||||
note over User, Server: Step 5
|
||||
|
||||
loop Poll for decision
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 202
|
||||
end
|
||||
|
||||
note over User, Server: Step 6 & 7
|
||||
|
||||
alt User accepts
|
||||
|
||||
User-->>Webinterface: Allow access
|
||||
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (True)
|
||||
Server->>Webinterface: 204
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 200, api_key
|
||||
|
||||
else User denies
|
||||
|
||||
User-->>Webinterface: Deny access
|
||||
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (False)
|
||||
Server->>Webinterface: 204
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 404
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api:
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-probe:
|
||||
|
||||
Probe for workflow support
|
||||
..........................
|
||||
|
||||
.. http:get:: /plugin/appkeys/probe
|
||||
|
||||
Probes for support of the workflow.
|
||||
|
||||
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
|
||||
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
|
||||
|
||||
:status 204: the workflow is supported
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-startauthprocess:
|
||||
|
||||
Start authorization process
|
||||
...........................
|
||||
|
||||
.. http:post:: /plugin/appkeys/request
|
||||
|
||||
Starts the authorization process.
|
||||
|
||||
Expects a :ref:`Key request <sec-bundledplugins-appkey-datamodel-keyrequest>` as request body.
|
||||
|
||||
The ``app`` parameter should be a human readable identifier to use
|
||||
for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively,
|
||||
so ``My App`` and ``my APP`` are considered the same application identifiers.
|
||||
|
||||
The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter
|
||||
is left unset, any user will be able to complete the authorization process and grant access to the app with their
|
||||
account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use
|
||||
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
|
||||
is logged in on.
|
||||
|
||||
:json app: application identifier to use for the request, case insensitive
|
||||
:json user: optional user id to restrict the decision to the specified user
|
||||
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-polldecision:
|
||||
|
||||
Poll for decision on existing request
|
||||
.....................................
|
||||
|
||||
.. http:get:: /plugin/appkeys/request/<str:app_token>
|
||||
|
||||
Endpoint generated per authorization request to poll for the result.
|
||||
|
||||
Returns an HTTP :http:statuscode:`202` while no decision has been made yet, an HTTP :http:statuscode:`200` and
|
||||
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
|
||||
HTTP :http:statuscode:`404` if the request has been denied or timed out.
|
||||
|
||||
.. note::
|
||||
|
||||
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
|
||||
for more than 5s.
|
||||
|
||||
:status 200: access granted, API key in response body
|
||||
:status 202: no decision has been made yet, continue polling
|
||||
:status 404: access denied or request timed out
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-decide:
|
||||
|
||||
Decide on existing request
|
||||
..........................
|
||||
|
||||
.. http:post:: /plugin/appkeys/decision/<str:user_token>
|
||||
|
||||
Endpoint to decide on the authorization request.
|
||||
|
||||
Expects a :ref:`Decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` as request body.
|
||||
|
||||
Returns an HTTP :http:statuscode:`204` on success.
|
||||
|
||||
:json decision: boolean value to indicate whether to confirm (``True``) or deny (``False``) access
|
||||
:status 204: success
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-fetchlist:
|
||||
|
||||
Fetch list of existing application keys
|
||||
.......................................
|
||||
|
||||
.. http:get:: /api/plugin/appkeys
|
||||
|
||||
Fetches a list of existing application keys and pending requests registered in the system for the current user.
|
||||
|
||||
If the additional optional parameter ``all`` is provided and the user has administrator rights, fetches a list
|
||||
of *all** application keys and pending requests registered in the system for any user.
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`List response <sec-bundledplugins-appkey-datamodel-listreponse>` in the
|
||||
body upon success.
|
||||
|
||||
:query all: Fetch all application keys and pending requests from all users. Requires administrator rights.
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-issuecommand:
|
||||
|
||||
Issue an application key command
|
||||
................................
|
||||
|
||||
.. http:post:: /api/plugin/appkeys
|
||||
|
||||
Application key commands allow revoking existing application keys and manually generating new ones. The available
|
||||
commands are:
|
||||
|
||||
revoke
|
||||
Revokes an existing application key. Must belong to the user issuing the command, unless the user has admin rights
|
||||
in which case they make revoke any application key in the system. Expects the key in question as parameter ``key``.
|
||||
|
||||
generate
|
||||
Generates a new application key for the user, using the application identifier provided as parameter ``app``.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires user rights.
|
||||
|
||||
**Example revoke request**
|
||||
|
||||
Revokes the (fictional) key ``aabbccddeeff112233445566``.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/plugin/appkeys HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "revoke",
|
||||
"key": "aabbccddeeff112233445566"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example generate request**
|
||||
|
||||
Generates a new key for application identifier "My awesome application 1.0".
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/plugin/appkeys HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "generate",
|
||||
"key": "My awesome application 1.0"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``revoke`` or ``generate``
|
||||
:json string key: ``revoke`` command: The key to revoke
|
||||
:json string app: ``generate`` command: Application identifier for which to generate a key
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: Invalid or missing parameter
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel:
|
||||
|
||||
Data model
|
||||
----------
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keyrequest:
|
||||
|
||||
Key request
|
||||
...........
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``app``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier to use for the request
|
||||
* - ``user``
|
||||
- 0..1
|
||||
- str
|
||||
- User identifier/name to restrict the request to
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keyresponse:
|
||||
|
||||
Key response
|
||||
............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- str
|
||||
- the API key generated for the application
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-decisionrequest:
|
||||
|
||||
Decision request
|
||||
................
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``decision``
|
||||
- 1
|
||||
- boolean
|
||||
- ``True`` if the access request it to be granted, ``False`` otherwise
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-listreponse:
|
||||
|
||||
List response
|
||||
.............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``keys``
|
||||
- 1
|
||||
- list of :ref:`key list entries <sec-bundledplugins-appkey-datamodel-keylistentry>`
|
||||
- Keys registered in the system
|
||||
* - ``pending``
|
||||
- 1
|
||||
- list of :ref:`pending list entries <sec-bundledplugins-appkey-datamodel-pendinglistentry>`
|
||||
- Currently pending authorization requests
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keylistentry:
|
||||
|
||||
Key list entry
|
||||
..............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``api_key``
|
||||
- 1
|
||||
- str
|
||||
- API key
|
||||
* - ``app_id``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier
|
||||
* - ``user_id``
|
||||
- 1
|
||||
- str
|
||||
- User ID of the key's owner
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-pendinglistentry:
|
||||
|
||||
Pending list entry
|
||||
..................
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``app_id``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier
|
||||
* - ``user_id``
|
||||
- 0..1
|
||||
- str
|
||||
- optional: User ID of user who can grant or deny request
|
||||
* - ``user_token``
|
||||
- 1
|
||||
- str
|
||||
- Token to grant or deny request
|
||||
|
||||
.. _sec-bundledplugins-appkeys-jsclientlib:
|
||||
|
||||
JavaScript Client Library
|
||||
-------------------------
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.getKeys(opts)
|
||||
|
||||
Retrieves registered keys and pending requests for the current user.
|
||||
|
||||
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.getAllKeys(opts)
|
||||
|
||||
Retrieves registered keys and pending requests for all users.
|
||||
|
||||
Needs administrator rights.
|
||||
|
||||
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.generateKey(app, opts)
|
||||
|
||||
Generates a key for the given ``app`` and the current user.
|
||||
|
||||
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
|
||||
|
||||
:param string app: Application identifier
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.revokeKey(key, opts)
|
||||
|
||||
Revokes the given ``key``. The key must belong to the current user, or the current user must have administrator
|
||||
rights.
|
||||
|
||||
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
|
||||
|
||||
:param string key: Key to revoke
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.decide(token, decision, opts)
|
||||
|
||||
Decides on an existing authorization request.
|
||||
|
||||
See :ref:`Decide on existing request <sec-bundledplugins-appkeys-api-decide>` for more details.
|
||||
|
||||
:param string token: User token for which to make the decision, as pushed to the client via the socket.
|
||||
:param boolean decision: Whether to grant access (``true``) or not (``false``).
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
|
||||
|
||||
Probes for workflow support.
|
||||
|
||||
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` identifier.
|
||||
|
||||
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.requestForUser(app, user, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` and ``user`` identifiers.
|
||||
|
||||
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.checkDecision(token, opts)
|
||||
|
||||
Polls for a decision on an existing authorization request identified by ``token``.
|
||||
|
||||
See :ref:`Poll for decision on existing request <sec-bundledplugins-appkeys-api-polldecision>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
|
||||
|
||||
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
|
||||
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
|
||||
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
|
||||
for the workflow, the promise is rejected.
|
||||
|
||||
**Example usage**
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
OctoPrint.plugins.appkeys.authenticate("My App", "some_user")
|
||||
.done(function(api_key) {
|
||||
console.log("Got our API key:", api_key);
|
||||
})
|
||||
.fail(function() {
|
||||
console.log("No API key for us");
|
||||
})
|
||||
|
||||
:param string app: Application identifier
|
||||
:param string user: Optional user identifier
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. _sec-bundledplugins-appkeys-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Application Keys plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/appkeys``.
|
||||
@@ -0,0 +1,70 @@
|
||||
.. _sec-bundledplugins-backup:
|
||||
|
||||
Backup Plugin
|
||||
=============
|
||||
|
||||
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 [#]_.
|
||||
|
||||
This allows easy migration
|
||||
to newly setup instances as well as making regular backups to prevent data loss.
|
||||
|
||||
.. _fig-bundledplugins-backup-settings:
|
||||
.. figure:: ../images/bundledplugins-backup-settings.png
|
||||
:align: center
|
||||
:alt: OctoPrint Backup Plugin
|
||||
|
||||
The plugin's settings panel with existing backups, the backup creation and restore sections.
|
||||
|
||||
As long as plugins adhere to the standard of storing their data and settings in OctoPrint's plugin data folders, their
|
||||
data will be part of the backup. Note that the backups made by the Backup Plugin will *not* be part of any backups -
|
||||
you'll need to persist the resulting zip files yourself!
|
||||
|
||||
.. _sec-bundledplugins-backup-cli:
|
||||
|
||||
Command line usage
|
||||
------------------
|
||||
|
||||
The Backup Plugin implements a command line interface that allows creation and restoration of backups.
|
||||
It adds two new commands, ``backup:backup`` and ``backup_restore``.
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
$ octoprint plugins backup:backup --help
|
||||
Initializing settings & plugin subsystem...
|
||||
Usage: octoprint plugins backup:backup [OPTIONS]
|
||||
|
||||
Creates a new backup.
|
||||
|
||||
Options:
|
||||
--exclude TEXT Identifiers of data folders to exclude, e.g. 'uploads' to
|
||||
exclude uploads or 'timelapse' to exclude timelapses.
|
||||
--help Show this message and exit.
|
||||
|
||||
$ octoprint plugins backup:restore --help
|
||||
Initializing settings & plugin subsystem...
|
||||
Usage: octoprint plugins backup:restore [OPTIONS] PATH
|
||||
|
||||
Restores an existing backup from the backup zip provided as argument.
|
||||
|
||||
OctoPrint does not need to run for this to proceed.
|
||||
|
||||
Options:
|
||||
--help Show this message and exit.
|
||||
|
||||
.. note::
|
||||
|
||||
The ``backup:backup`` command can be useful in combination with a cronjob to create backups in regular intervals.
|
||||
|
||||
.. _sec-bundledplugins-backup-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Backup plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/backup``.
|
||||
|
||||
.. [#] Note that only those plugins that are available on `OctoPrint's official plugin repository <https://plugins.octoprint.org>`_
|
||||
can be automatically restored. If you have plugins installed that are not available on there you'll get their
|
||||
names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them.
|
||||
@@ -57,18 +57,10 @@ path to that in the plugin settings.
|
||||
Compiling for Raspbian
|
||||
++++++++++++++++++++++
|
||||
|
||||
.. note::
|
||||
Raspbian Jessie and later
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
A binary of CuraEngine 15.04.06 precompiled on Raspbian Jessie Lite 2016-03-18 is available
|
||||
`here <http://bit.ly/octopi_cura_engine_150406>`__. Don't forget to make it
|
||||
executable after copying it to your preferred destination on your Pi
|
||||
(suggestion: ``/usr/local/bin``) with ``chmod +x cura_engine``. Use at your
|
||||
own risk.
|
||||
|
||||
Raspbian Jessie
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Building on Raspbian Jessie is as easy as::
|
||||
Building on Raspbian Jessie and later is as easy as::
|
||||
|
||||
sudo apt-get -y install gcc-4.7 g++-4.7
|
||||
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
.. _sec-bundledplugins-forcelogin:
|
||||
|
||||
ForceLogin Plugin
|
||||
=================
|
||||
|
||||
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
|
||||
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
|
||||
instead forces users to log in if they want to get any kind of information from OctoPrint.
|
||||
|
||||
.. _fig-bundledplugins-forcelogin:
|
||||
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
|
||||
:align: center
|
||||
:alt: Forced login dialog
|
||||
|
||||
OctoPrint's new forced login dialog.
|
||||
|
||||
.. warning::
|
||||
|
||||
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
|
||||
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
|
||||
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
|
||||
is not OctoPrint itself.
|
||||
|
||||
.. note::
|
||||
|
||||
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
|
||||
the ForceLogin Plugin in OctoPrint's plugin manager.
|
||||
|
||||
.. _sec-bundledplugins-forcelogin-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/forcelogin``.
|
||||
@@ -7,8 +7,13 @@ Bundled Plugins
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
action_command_prompt.rst
|
||||
announcements.rst
|
||||
appkeys.rst
|
||||
backup.rst
|
||||
cura.rst
|
||||
discovery.rst
|
||||
forcelogin.rst
|
||||
logging.rst
|
||||
pluginmanager.rst
|
||||
printer_safety_check.rst
|
||||
|
||||
@@ -16,17 +16,12 @@ such identification.
|
||||
|
||||
An example of a warning generated by the Printer Safety Check
|
||||
|
||||
Currently the following firmwares produce this warning:
|
||||
|
||||
* Anet A8 stock firmware
|
||||
Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
for a list of currently identified printers.
|
||||
|
||||
If you know of further printers/printer firmwares that need to be added here, please
|
||||
`get in touch on the forum and provide their response to an M115 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
|
||||
.. note::
|
||||
|
||||
Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
|
||||
|
||||
@@ -151,7 +151,7 @@ appearance or to modify the order and presence of the various UI components:
|
||||
|
||||
# order of settings, if settings plugins are registered gets extended internally by
|
||||
# section_plugins and all settings plugins
|
||||
settings
|
||||
settings:
|
||||
- section_printer
|
||||
- serial
|
||||
- printerprofiles
|
||||
@@ -209,7 +209,7 @@ appearance or to modify the order and presence of the various UI components:
|
||||
tab:
|
||||
- plugin_helloworld
|
||||
|
||||
OctoPrint will then turn this into the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``,
|
||||
OctoPrint will then display the tabs in the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``,
|
||||
``terminal``, ``timelapse`` plus any other plugins.
|
||||
|
||||
|
||||
@@ -454,7 +454,7 @@ the estimation of the left print time during an active job utilizes this section
|
||||
.. code-block:: yaml
|
||||
|
||||
estimation:
|
||||
# Parameters for the print time estmation during an ongoing print job
|
||||
# Parameters for the print time estimation during an ongoing print job
|
||||
printTime:
|
||||
# Until which percentage to do a weighted mixture of statistical duration (analysis or
|
||||
# past prints) with the result from the calculated estimate if that's already available.
|
||||
@@ -560,6 +560,10 @@ Use the following settings to enable or disable OctoPrint features:
|
||||
# Defaults to only M117.
|
||||
autoUppercaseBlacklist:
|
||||
- M117
|
||||
- M118
|
||||
|
||||
# whether G90/G91 also influence absolute/relative mode of extruders
|
||||
g90InfluencesExtruder: false
|
||||
|
||||
.. _sec-configuration-config_yaml-folder:
|
||||
|
||||
@@ -616,15 +620,16 @@ Settings pertaining to the server side GCODE analysis implementation.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# Maximum number of extruders to support/to sanity check for
|
||||
maxExtruders: 10
|
||||
gcodeAnalysis:
|
||||
# Maximum number of extruders to support/to sanity check for
|
||||
maxExtruders: 10
|
||||
|
||||
# Pause between each processed GCODE line in normal priority mode, seconds
|
||||
throttle_normalprio: 0.01
|
||||
# Pause between each processed GCODE line in normal priority mode, seconds
|
||||
throttle_normalprio: 0.01
|
||||
|
||||
# Pause between each processed GCODE line in high priority mode (e.g. on fresh
|
||||
# uploads), seconds
|
||||
throttle_highprio: 0.0
|
||||
# Pause between each processed GCODE line in high priority mode (e.g. on fresh
|
||||
# uploads), seconds
|
||||
throttle_highprio: 0.0
|
||||
|
||||
.. _sec-configuration-config_yaml-gcodeviewer:
|
||||
|
||||
@@ -635,16 +640,17 @@ Settings pertaining to the built in GCODE Viewer.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# Whether to enable the GCODE viewer in the UI
|
||||
enabled: true
|
||||
gcodeViewer:
|
||||
# Whether to enable the GCODE viewer in the UI
|
||||
enabled: true
|
||||
|
||||
# Maximum size a GCODE file may have on mobile devices to automatically be loaded
|
||||
# into the viewer, defaults to 2MB
|
||||
mobileSizeThreshold: 2097152
|
||||
# Maximum size a GCODE file may have on mobile devices to automatically be loaded
|
||||
# into the viewer, defaults to 2MB
|
||||
mobileSizeThreshold: 2097152
|
||||
|
||||
# Maximum size a GCODE file may have to automatically be loaded into the viewer,
|
||||
# defaults to 20MB
|
||||
sizeThreshold: 20971520
|
||||
# Maximum size a GCODE file may have to automatically be loaded into the viewer,
|
||||
# defaults to 20MB
|
||||
sizeThreshold: 20971520
|
||||
|
||||
.. _sec-configuration-config_yaml-plugins:
|
||||
|
||||
@@ -893,7 +899,7 @@ Use the following settings to configure the serial connection to the printer:
|
||||
supportResendsWithoutOk: false
|
||||
|
||||
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
|
||||
# the responds skips on the ok)
|
||||
# the response skips on the ok)
|
||||
triggerOkForM29: true
|
||||
|
||||
capabilities:
|
||||
@@ -934,7 +940,7 @@ Use the following settings to configure the server:
|
||||
|
||||
# Settings if OctoPrint is running behind a reverse proxy (haproxy, nginx, apache, ...).
|
||||
# These are necessary in order to make OctoPrint generate correct external URLs so
|
||||
# that AJAX requests and download URLs work.
|
||||
# that AJAX requests and download URLs work, and so that client IPs are read correctly.
|
||||
reverseProxy:
|
||||
|
||||
# The request header from which to determine the URL prefix under which OctoPrint
|
||||
@@ -968,6 +974,14 @@ Use the following settings to configure the server:
|
||||
# (X-Forwarded-Host by default, see above) with forwarded requests.
|
||||
hostFallback:
|
||||
|
||||
# List of trusted downstream servers for which to ignore the IP address when trying to determine
|
||||
# the connecting client's IP address. If you have OctoPrint behind more than one reverse proxy
|
||||
# you should add their IPs here so that they won't be interpreted as the client's IP. One reverse
|
||||
# proxy will be handled correctly by default.
|
||||
trustedDownstream:
|
||||
- 192.168.1.254
|
||||
- 192.168.23.42
|
||||
|
||||
# Settings for file uploads to OctoPrint, such as maximum allowed file size and
|
||||
# header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in
|
||||
# order to allow streaming of large file uploads to the application rather than just storing
|
||||
@@ -1047,6 +1061,15 @@ Use the following settings to configure the server:
|
||||
# How many days to leave unused entries in the preemptive cache config
|
||||
until: 7
|
||||
|
||||
# Configuration of the client IP check to warn about connections from external networks
|
||||
ipCheck:
|
||||
|
||||
# whether to enable the check, defaults to true
|
||||
enabled: true
|
||||
|
||||
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
|
||||
trustedSubnets: []
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -1092,7 +1115,12 @@ System
|
||||
|
||||
Use the following settings to add custom system commands to the "System" dropdown within OctoPrint's top bar.
|
||||
|
||||
Commands consist of a name, an action identifier, the commandline to execute and an optional confirmation message to
|
||||
Commands consist of a ``name`` shown to the user, an ``action`` identifier used by the code and the actual
|
||||
``command`` including any argument needed for its execution.
|
||||
By default OctoPrint blocks until the command has returned so that the exit code can be used to show a success
|
||||
or failure message; use the flag ``async: true`` for commands that don't return.
|
||||
|
||||
Optionally you can add a confirmation message to
|
||||
display before actually executing the command (should be set to False if a confirmation dialog is not desired).
|
||||
|
||||
The following example defines a command for shutting down the system under Linux. It assumes that the user under which
|
||||
@@ -1149,7 +1177,7 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
|
||||
# A list of filters to display in the terminal tab. Defaults to the filters shown below
|
||||
terminalFilters:
|
||||
- name: Suppress temperature messages
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv: ok T:)'
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)'
|
||||
- name: Suppress SD status messages
|
||||
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
|
||||
- name: Suppress wait responses
|
||||
|
||||
@@ -57,60 +57,71 @@ You can simulate certain conditions and communications through the terminal tab
|
||||
|
||||
All commands start with ``!!DEBUG:`` and are followed by the command you want to execute. For instance, sending
|
||||
``!!DEBUG:action_disconnect`` will disconnect the printer. Sending ``!!DEBUG`` without command will show a help
|
||||
message with all the available commands.
|
||||
message with all the available commands:
|
||||
|
||||
Action Triggers
|
||||
...............
|
||||
.. code-block:: none
|
||||
|
||||
``action_pause``
|
||||
Sends a "// action:pause" action trigger to the host.
|
||||
OctoPrint Virtual Printer debug commands
|
||||
|
||||
``action_resume``
|
||||
Sends a "// action:resume" action trigger to the host.
|
||||
help
|
||||
?
|
||||
| This help.
|
||||
|
||||
``action_disconnect``
|
||||
Sends a "// action:disconnect" action trigger to the host.
|
||||
# Action Triggers
|
||||
|
||||
``action_custom <action>[ <parameters>]``
|
||||
Sends a custom "// action:<action> <parameters>" action trigger to the host.
|
||||
action_pause
|
||||
| Sends a "// action:pause" action trigger to the host.
|
||||
action_resume
|
||||
| Sends a "// action:resume" action trigger to the host.
|
||||
action_disconnect
|
||||
| Sends a "// action:disconnect" action trigger to the
|
||||
| host.
|
||||
action_custom <action>[ <parameters>]
|
||||
| Sends a custom "// action:<action> <parameters>"
|
||||
| action trigger to the host.
|
||||
|
||||
Communication Errors
|
||||
....................
|
||||
# Communication Errors
|
||||
|
||||
``dont_answer``
|
||||
Will not acknowledge the next command.
|
||||
dont_answer
|
||||
| Will not acknowledge the next command.
|
||||
go_awol
|
||||
| Will completely stop replying
|
||||
trigger_resend_lineno
|
||||
| Triggers a resend error with a line number mismatch
|
||||
trigger_resend_checksum
|
||||
| Triggers a resend error with a checksum mismatch
|
||||
trigger_missing_checksum
|
||||
| Triggers a resend error with a missing checksum
|
||||
trigger_missing_lineno
|
||||
| Triggers a "no line number with checksum" error w/o resend request
|
||||
drop_connection
|
||||
| Drops the serial connection
|
||||
prepare_ok <broken ok>
|
||||
| Will cause <broken ok> to be enqueued for use,
|
||||
| will be used instead of actual "ok"
|
||||
|
||||
``go_awol``
|
||||
Will completely stop replying.
|
||||
# Reply Timing / Sleeping
|
||||
|
||||
``trigger_resend_lineno``
|
||||
Triggers a resend error with a line number mismatch
|
||||
sleep <int:seconds>
|
||||
| Sleep <seconds> s
|
||||
sleep_after <str:command> <int:seconds>
|
||||
| Sleeps <seconds> s after each execution of <command>
|
||||
sleep_after_next <str:command> <int:seconds>
|
||||
| Sleeps <seconds> s after execution of next <command>
|
||||
|
||||
``trigger_resend_checksum``
|
||||
Triggers a resend error with a checksum mismatch
|
||||
# SD printing
|
||||
|
||||
``drop_connection``
|
||||
Drops the serial connection
|
||||
start_sd <str:file>
|
||||
| Select and start printing file <file> from SD
|
||||
select_sd <str:file>
|
||||
| Select file <file> from SD, don't start printing it yet. Use
|
||||
| start_sd to start the print
|
||||
cancel_sd
|
||||
| Cancels an ongoing SD print
|
||||
|
||||
``prepare_ok <broken ok>``
|
||||
Will cause <broken ok> to be enqueued for use, will be used instead of actual "ok"
|
||||
# Misc
|
||||
|
||||
Reply Timing / Sleeping
|
||||
.......................
|
||||
``sleep <int:seconds>``
|
||||
Sleep <seconds> s
|
||||
|
||||
``sleep_after <str:command> <int:seconds>``
|
||||
Sleeps <seconds> s after each execution of <command>
|
||||
|
||||
``sleep_after_next <str:command> <int:seconds>``
|
||||
Sleeps <seconds> s after execution of next <command>
|
||||
|
||||
Misc
|
||||
....
|
||||
|
||||
``help``
|
||||
Show the available commands.
|
||||
|
||||
``send <str:message>``
|
||||
Sends back <message>
|
||||
send <str:message>
|
||||
| Sends back <message>
|
||||
reset
|
||||
| Simulates a reset. Internal state will be lost.
|
||||
@@ -207,8 +207,8 @@ FolderAdded
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the folders's path within its storage location
|
||||
* ``name``: the folders's name
|
||||
* ``path``: the folder's path within its storage location
|
||||
* ``name``: the folder's name
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -220,8 +220,8 @@ FolderRemoved
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the folders's path within its storage location
|
||||
* ``name``: the folders's name
|
||||
* ``path``: the folder's path within its storage location
|
||||
* ``name``: the folder's name
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -338,6 +338,8 @@ PrintFailed
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``time``: the elapsed time of the print when it failed, in seconds (float)
|
||||
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
|
||||
@@ -31,7 +31,13 @@ Internet!).
|
||||
.. hint::
|
||||
|
||||
If you plan to have your OctoPrint instance accessible over the internet,
|
||||
**always enable Access Control**.
|
||||
**always enable Access Control** and ideally **don't make it accessible to
|
||||
everyone over the internet but instead use a VPN** or at the very least
|
||||
HTTP basic authentication on a layer above OctoPrint.
|
||||
|
||||
A physical device that includes heaters and stepper motors really should not be
|
||||
publicly reachable by everyone with an internet connection, even with access
|
||||
control enabled.
|
||||
|
||||
.. _sec-features-access_control-rerunning_wizard:
|
||||
|
||||
|
||||
@@ -29,12 +29,27 @@ pause
|
||||
When this command is received from the printer, OctoPrint will pause a current print job just like if the
|
||||
"Pause" button had been clicked.
|
||||
|
||||
paused
|
||||
When this command is received from the printer, OctoPrint will pause a current print job but *without* triggering
|
||||
any GCODE scripts or sending SD print control commands to the printer. This might be interesting for firmware
|
||||
that wants to signal to OctoPrint that a print should be paused but without any control interference from
|
||||
OctoPrint, e.g. in case of a filament change fully managed by the firmware.
|
||||
|
||||
resume
|
||||
When this command is received from the printer, OctoPrint will resume a current print job just like if
|
||||
the "Resume" button had been clicked.
|
||||
|
||||
resumed
|
||||
When this command is received from the printer, OctoPrint will resume a current print job but *without* triggering
|
||||
any GCODE scripts or sending SD print control commands to the printer. This might be interesting for firmware
|
||||
that wants to signal to OctoPrint that a print should be resumed but without any control interference from
|
||||
OctoPrint, e.g. in case of a filament change fully managed by the firmware.
|
||||
|
||||
disconnect
|
||||
When this command is received from the printer, OctoPrint will immediately disconnect from it.
|
||||
|
||||
If the bundled :ref:`Action Command Prompt Support Plugin <sec-bundledplugins-action_command_prompt>` is enabled (which
|
||||
should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands <sec-bundledplugins-action_command_prompt-action_commands>`.
|
||||
|
||||
Support for additional commands may be added by plugins by implementing a handler for the
|
||||
:ref:`octoprint.comm.protocol.action <sec-plugins-hook-comm-protocol-action>` hook.
|
||||
@@ -75,7 +75,7 @@ All GCODE scripts have access to the following template variables through the te
|
||||
* ``last_temperature``: Last actual and target temperature reported for all available tools and if available the
|
||||
heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``,
|
||||
...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped
|
||||
to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be
|
||||
to the corresponding temperature in degrees Celsius. Note that not all tools your printer has must necessarily be
|
||||
present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also
|
||||
note that ``actual`` and ``target`` might be ``None``.
|
||||
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
|
||||
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
|
||||
.. code-block:: jinja
|
||||
:caption: Default ``disable_hotends`` snippet
|
||||
|
||||
{% if printer_profile.extruder.sharedNozzle %}
|
||||
M104 T0 S0
|
||||
{% else %}
|
||||
{% for tool in range(printer_profile.extruder.count) %}
|
||||
M104 T{{ tool }} S0
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
The ``disable_bed`` snippet is defined as follows:
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
@@ -417,7 +417,7 @@
|
||||
|
||||
Creates a custom exception class. ``name`` may be either a function in which case it will be used
|
||||
as constructor for the new exception class, or a string, in which case a constructor with proper
|
||||
``name``, ``message`` and ``stack`` attributes will be created. The class hierarchy will be propery
|
||||
``name``, ``message`` and ``stack`` attributes will be created. The class hierarchy will be properly
|
||||
setup to subclass ``Error``.
|
||||
|
||||
**Example:**
|
||||
|
||||
@@ -189,7 +189,7 @@
|
||||
A boolean value, specifies whether to immediately start printing the file after the upload
|
||||
completes (true) or not (false, default)
|
||||
userdata
|
||||
An optional object or a serialized JSON string of additional user supplised data to associate with
|
||||
An optional object or a serialized JSON string of additional user supplied data to associate with
|
||||
the uploaded file.
|
||||
|
||||
See :ref:`Upload file or create folder <sec-api-fileops-uploadfile>` for more details on the file upload API and
|
||||
|
||||
@@ -80,9 +80,13 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s
|
||||
|
||||
.. seealso::
|
||||
|
||||
`OctoPrint-ForceLogin <https://github.com/OctoPrint/OctoPrint-ForceLogin>`_
|
||||
A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the
|
||||
client library's :ref:`browser component <sec-jsclientlib-browser>` to login the user.
|
||||
:ref:`Application Key Plugin <sec-bundledplugins-appkeys>`
|
||||
A bundled plugin that implements an authorization workflow for third party clients. It adds various additional
|
||||
methods to the JS Client Library.
|
||||
:ref:`ForceLogin Plugin <sec-bundledplugins-forcelogin>`
|
||||
A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and
|
||||
various hooks. Utilizes the client library's :ref:`browser component <sec-jsclientlib-browser>` to login the
|
||||
user.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
.. js:function:: OctoPrintClient.socket.onRateTooHigh(measured, maximum)
|
||||
|
||||
Called by the socket client when the last measured round trip time was higher than the
|
||||
current upper procesisng limit, indicating that the messages are now processed slower than
|
||||
current upper processing limit, indicating that the messages are now processed slower than
|
||||
the current rate requires and a slower rate might be necessary.
|
||||
|
||||
Can be overwritten with custom handler methods. The default implementation will call
|
||||
|
||||
@@ -6,4 +6,10 @@ octoprint.util
|
||||
.. automodule:: octoprint.util
|
||||
:members:
|
||||
|
||||
.. _sec-modules-util-commandline:
|
||||
|
||||
octoprint.util.commandline
|
||||
--------------------------
|
||||
|
||||
.. automodule:: octoprint.util.commandline
|
||||
:members:
|
||||
@@ -410,8 +410,8 @@ Now look at that!
|
||||
Settings Galore: How to make parts of your plugin user adjustable
|
||||
-----------------------------------------------------------------
|
||||
|
||||
Remember that Wikipedia link we added to our little link in the navigation bar? It links to the english Wikipedia. But
|
||||
what if we want to allow our users to adjust that according to their wishes, e.g. to link to the german language node
|
||||
Remember that Wikipedia link we added to our little link in the navigation bar? It links to the English Wikipedia. But
|
||||
what if we want to allow our users to adjust that according to their wishes, e.g. to link to the German language node
|
||||
about "Hello World" programs instead?
|
||||
|
||||
To allow your users to customized the behaviour of your plugin you'll need to implement the :class:`~octoprint.plugin.SettingsPlugin`
|
||||
@@ -509,7 +509,7 @@ section doesn't yet exist in the file, create it):
|
||||
# [...]
|
||||
|
||||
Restart OctoPrint. Not only should the URL displayed in the log file have changed, but also the link should now (after
|
||||
a proper shift-reload) point to the german Wikipedia node about "Hello World" programs::
|
||||
a proper shift-reload) point to the German Wikipedia node about "Hello World" programs::
|
||||
|
||||
2015-01-30 11:47:18,634 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://de.wikipedia.org/wiki/Hallo-Welt-Programm)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Helpers
|
||||
=======
|
||||
|
||||
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
|
||||
Helpers are methods that plugins can expose to other plugins in order to make common functionality available on the
|
||||
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
|
||||
|
||||
An example for providing some helper functions to the system can be found in the
|
||||
|
||||
@@ -66,7 +66,7 @@ the general type of script for which to look for additions ("gcode") and the scr
|
||||
return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take
|
||||
care to add prefix and suffix as necessary after a small round of preprocessing.
|
||||
|
||||
Plugins can easily add their own hooks too. For example, the `Software Update Plugin <https://github.com/OctoPrint/OctoPrint-SoftwareUpdate>`_
|
||||
Plugins can easily add their own hooks too. For example, the `Software Update Plugin <https://github.com/foosel/OctoPrint/tree/master/src/octoprint/plugins/softwareupdate>`_
|
||||
declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order
|
||||
to register themselves with the Software Update Plugin by returning their own update check configuration.
|
||||
|
||||
@@ -380,6 +380,66 @@ octoprint.cli.commands
|
||||
OctoPrint's CLI.
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-comm-firmware-info:
|
||||
|
||||
octoprint.comm.firmware.info
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs)
|
||||
|
||||
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
|
||||
report line and provides the parsed ``firmware_name`` and additional ``firmware_data`` contained therein. A
|
||||
response line ``FIRMWARE_NAME:Some Firmware Name FIRMWARE_VERSION:1.2.3 PROTOCOL_VERSION:1.0`` for example will
|
||||
be turned into a ``dict`` looking like this:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
dict(FIRMWARE_NAME="Some Firmware Name",
|
||||
FIRMWARE_VERSION="1.2.3",
|
||||
PROTOCOL_VERSION="1.0")
|
||||
|
||||
``firmware_name`` will be ``Some Firmware Name`` in this case.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str firmware_name: The name of the parsed capability
|
||||
:param dict firmware_data: All data contained in the ``M115`` report
|
||||
|
||||
.. _sec-plugins-hook-comm-firmware-capabilities:
|
||||
|
||||
octoprint.comm.firmware.capabilities
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs)
|
||||
|
||||
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
|
||||
line and provides the parsed ``capability`` and whether it's ``enabled`` to the handler. Additionally all already
|
||||
parsed capabilities will also be provided.
|
||||
|
||||
Note that hook handlers will be called once per received capability line.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str capability: The name of the parsed capability
|
||||
:param bool enabled: Whether the capability is reported as enabled or disabled
|
||||
:param dict already_defined: Already defined capabilities (capability name mapped to enabled flag)
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-action:
|
||||
|
||||
octoprint.comm.protocol.action
|
||||
@@ -389,11 +449,18 @@ octoprint.comm.protocol.action
|
||||
|
||||
React to a :ref:`action command <sec-features-action_commands>` received from the printer.
|
||||
|
||||
Hook handlers may use this to react to react to custom firmware messages. OctoPrint parses the received action
|
||||
Hook handlers may use this to react to custom firmware messages. OctoPrint parses the received action
|
||||
command ``line`` and provides the parsed ``action`` (so anything after ``// action:``) to the hook handler.
|
||||
|
||||
No returned value is expected.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware.
|
||||
@@ -431,6 +498,13 @@ This describes actually two hooks:
|
||||
trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to
|
||||
:ref:`the action command hook <sec-plugins-hook-comm-protocol-action>`.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
|
||||
you will effectively block the send/receive loops, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a
|
||||
@@ -577,6 +651,13 @@ This describes actually four hooks:
|
||||
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
|
||||
to one already in the queue will give an error.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the send loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
The following hook handler replaces all ``M107`` ("Fan Off", deprecated) with an ``M106 S0`` ("Fan On" with speed
|
||||
@@ -612,6 +693,13 @@ octoprint.comm.protocol.gcode.received
|
||||
empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
|
||||
``return`` statement is used or just nothing is returned explicitly from the handler.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Looks for the response of an ``M115``, which contains information about the ``MACHINE_TYPE``, among other things.
|
||||
@@ -641,6 +729,13 @@ octoprint.comm.protocol.gcode.error
|
||||
Plugins might utilize this hook to handle errors generated by the printer that are recoverable in one way or
|
||||
the other and should not trigger the normal handling that assumes the worst.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the
|
||||
@@ -716,6 +811,13 @@ octoprint.comm.protocol.temperatures.received
|
||||
additional sanity checking to be applied and invalid values to be filtered out. If a handler returns an empty
|
||||
dictionary or ``None``, no further processing will take place.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C.
|
||||
@@ -801,6 +903,44 @@ octoprint.comm.transport.serial.factory
|
||||
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
|
||||
optionally ``baudrate`` and ``timeout`` attributes as described above.
|
||||
|
||||
.. _sec-plugins-hook-filemanager-analysis-factory:
|
||||
|
||||
octoprint.filemanager.analysis.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: analysis_queue_factory_hook(*args, **kwargs)
|
||||
|
||||
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
|
||||
to analysis queue factory. Analysis queue factories are expected to be :class:`~octoprint.filemanager.analysis.AbstractAnalysisQueue`
|
||||
subclasses or factory methods taking one argument (the finish callback to be used by the queue implementation
|
||||
to signal that an analysis has been finished to the system). See the source of :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue`
|
||||
for an example.
|
||||
|
||||
By default, only one analysis queue factory is registered in the system, for file type ``gcode``: :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue`.
|
||||
This can be replaced by plugins using this hook, allowing other approaches to file analysis.
|
||||
|
||||
This is useful for plugins wishing to provide (alternative) methods of metadata analysis for printable files.
|
||||
|
||||
**Example:**
|
||||
|
||||
The following handler would replace the existing analysis queue for ``gcode`` files with a custom implementation:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from octoprint.filemanager.analysis import AbstractAnalysisQueue
|
||||
|
||||
class MyCustomGcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
# ... custom implementation here ...
|
||||
|
||||
def custom_gcode_analysis_queue(*args, **kwargs):
|
||||
return dict(gcode=MyCustomGcodeAnalysisQueue)
|
||||
|
||||
:return: A dictionary of analysis queue factories, mapped by their targeted file type.
|
||||
:rtype: dict
|
||||
|
||||
.. _sec-plugins-hook-filemanager-extensiontree:
|
||||
|
||||
octoprint.filemanager.extension_tree
|
||||
@@ -903,6 +1043,100 @@ octoprint.printer.factory
|
||||
:return: The ``printer`` instance to use globally.
|
||||
:rtype: PrinterInterface subclass or None
|
||||
|
||||
.. _sec-plugins-hook-printer-estimation-factory:
|
||||
|
||||
octoprint.printer.estimation.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: print_time_estimator_factory(*args, **kwargs)
|
||||
|
||||
Return a :class:`~octoprint.printer.estimation.PrintTimeEstimator` subclass (or factory) to use for print time
|
||||
estimation. This will be called on each start of a print or streaming job with a single parameter ``job_type``
|
||||
denoting the type of job that was just started: ``local`` meaning a print of a local file through the serial connection,
|
||||
``sdcard`` a print of a file stored on the printer's SD card, ``stream`` the streaming of a local file to the
|
||||
printer's SD card.
|
||||
|
||||
This is useful for plugins wishing to provide alternative methods of live print time estimation.
|
||||
|
||||
If none of the registered factories return a ``PrintTimeEstimator`` subclass, the default :class:`~octoprint.printer.estimation.PrintTimeEstimator`
|
||||
will be used.
|
||||
|
||||
**Example:**
|
||||
|
||||
The following example would replace the stock print time estimator with (a nonsensical) one that always estimates
|
||||
two hours of print time left:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from octoprint.printer.estimation import PrintTimeEstimator
|
||||
|
||||
class CustomPrintTimeEstimator(PrintTimeEstimator):
|
||||
def __init__(self, job_type):
|
||||
pass
|
||||
|
||||
def estimate(self, progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType):
|
||||
# always reports 2h as printTimeLeft
|
||||
return 2 * 60 * 60, "estimate"
|
||||
|
||||
def create_estimator_factory(*args, **kwargs):
|
||||
return CustomPrintTimeEstimator
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.printer.estimation.factory": create_estimator_factory
|
||||
}
|
||||
|
||||
|
||||
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
|
||||
:rtype: class or function
|
||||
|
||||
.. _sec-plugins-hook-server-http-after_request:
|
||||
|
||||
octoprint.server.api.after_request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: after_request_handlers_hook(*args, **kwargs)
|
||||
|
||||
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. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-before_request:
|
||||
|
||||
octoprint.server.api.before_request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: after_request_handlers_hook(*args, **kwargs)
|
||||
|
||||
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. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-access_validator:
|
||||
|
||||
octoprint.server.http.access_validator
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: access_validator_hook(request, *args, **kwargs)
|
||||
|
||||
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. See the bundled
|
||||
"Force Login" plugin for a usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-bodysize:
|
||||
|
||||
octoprint.server.http.bodysize
|
||||
@@ -1004,6 +1238,85 @@ octoprint.server.http.routes
|
||||
:return: a list of 3-tuples with additional routes as defined above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-authed:
|
||||
|
||||
octoprint.server.sockjs.authed
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
|
||||
|
||||
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-register:
|
||||
|
||||
octoprint.server.sockjs.register
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
|
||||
|
||||
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``
|
||||
signals to not register the client.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:return: whether to proceed with registration (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-emit:
|
||||
|
||||
octoprint.server.sockjs.emit
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
|
||||
|
||||
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.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object on which a message is about to be emitted
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:param string message: the message type about to be emitted
|
||||
:param dict payload: the payload of the message about to be emitted (may be None)
|
||||
:return: whether to proceed with sending the message (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-timelapse-extensions:
|
||||
|
||||
octoprint.timelapse.extensions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: timelapse_extension_hook(*args, **kwargs)
|
||||
|
||||
Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of
|
||||
additional file extensions.
|
||||
|
||||
**Example**
|
||||
|
||||
Allow the management of timelapse GIFs with extension ``gif``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_timelapse_extensions(*args, **kwargs):
|
||||
return ["gif"]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.timelapse.extensions": get_timelapse_extensions
|
||||
}
|
||||
|
||||
:return: a list of additional file extensions
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-ui-web-templatetypes:
|
||||
|
||||
octoprint.ui.web.templatetypes
|
||||
|
||||
@@ -56,9 +56,9 @@ Example:
|
||||
// more of your view model's implementation
|
||||
}
|
||||
|
||||
// we don't explicitely declare a name property here
|
||||
// we don't explicitly declare a name property here
|
||||
// our view model will be registered under "myCustomViewModel" (implicit
|
||||
// name derived from contructor name) and "yourCustomViewModel" (explicitely
|
||||
// name derived from constructor name) and "yourCustomViewModel" (explicitly
|
||||
// provided as additional name)
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: MyCustomViewModel,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[metadata]
|
||||
description-file = README.md
|
||||
license_file = LICENSE.txt
|
||||
|
||||
[versioneer]
|
||||
VCS = git
|
||||
|
||||
@@ -12,44 +12,46 @@ import octoprint_setuptools
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Supported python versions
|
||||
PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
"flask>=0.9,<0.11",
|
||||
"Jinja2>=2.8,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"flask>=0.10.1,<0.11",
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
"werkzeug>=0.8.3,<0.9",
|
||||
"tornado==4.0.2", # pinned for now, we need to migrate to a newer tornado, but due
|
||||
# to some voodoo needed to get large streamed uploads and downloads
|
||||
# to work that is probably not completely straightforward and therefore
|
||||
# something for post-1.3.0-stable release
|
||||
"sockjs-tornado>=1.0.3,<1.1",
|
||||
"tornado==4.5.3",
|
||||
#"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a
|
||||
# vendored one
|
||||
"PyYAML>=3.10,<3.11",
|
||||
"Flask-Login>=0.2.2,<0.3",
|
||||
"Flask-Login>=0.2.11,<0.3",
|
||||
"Flask-Principal>=0.3.5,<0.4",
|
||||
"Flask-Babel>=0.9,<0.10",
|
||||
"Flask-Assets>=0.10,<0.11",
|
||||
"markdown>=2.6.4,<2.7",
|
||||
"pyserial>=2.7,<3.5",
|
||||
"netaddr>=0.7.17,<0.8",
|
||||
"markdown>=2.6.9,<2.7",
|
||||
"pyserial>=3.4,<3.5",
|
||||
"netaddr>=0.7.19,<0.8",
|
||||
"watchdog>=0.8.3,<0.9",
|
||||
"sarge>=0.1.4,<0.2",
|
||||
"netifaces>=0.10,<0.11",
|
||||
"sarge==0.1.5post0",
|
||||
"netifaces>=0.10.6,<0.11",
|
||||
"pylru>=1.0.9,<1.1",
|
||||
"rsa>=3.2,<3.3",
|
||||
"pkginfo>=1.2.1,<1.3",
|
||||
"rsa>=3.2.3,<3.3",
|
||||
"pkginfo>=1.4.2,<1.5",
|
||||
"requests>=2.18.4,<3",
|
||||
"semantic_version>=2.4.2,<2.5",
|
||||
"psutil>=5.4.1,<6",
|
||||
"psutil>=5.4.6,<5.5",
|
||||
"Click>=6.2,<6.3",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
"chainmap>=1.0.2,<1.1",
|
||||
"future>=0.15,<0.16",
|
||||
"future>=0.15.2,<0.16",
|
||||
"scandir>=1.3,<1.4",
|
||||
"websocket-client>=0.40,<0.41",
|
||||
"python-dateutil>=2.6,<2.7",
|
||||
"wrapt>=1.10.10,<1.11",
|
||||
"websocket-client>=0.40.0,<0.41",
|
||||
"python-dateutil>=2.6.1,<2.7",
|
||||
"wrapt>=1.10.11,<1.11",
|
||||
"futures>=3.1.1,<3.2",
|
||||
"emoji>=0.4.5,<0.5",
|
||||
"monotonic>=1.3,<1.4",
|
||||
@@ -73,9 +75,6 @@ EXTRA_REQUIRES = dict(
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid>=0.3",
|
||||
"sphinx_rtd_theme",
|
||||
|
||||
# PyPi upload related
|
||||
"pypandoc"
|
||||
],
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
@@ -84,15 +83,19 @@ EXTRA_REQUIRES = dict(
|
||||
]
|
||||
)
|
||||
|
||||
# Additional requirements for setup
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
# Anything below here is just command setup and general setup configuration
|
||||
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
def read_file_contents(path):
|
||||
import codecs
|
||||
with codecs.open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def data_copy_build_py_factory(files, baseclass):
|
||||
class data_copy_build_py(baseclass):
|
||||
files = dict()
|
||||
@@ -148,45 +151,49 @@ def params():
|
||||
version = versioneer.get_version()
|
||||
cmdclass = get_cmdclass()
|
||||
|
||||
description = "A snappy web interface for 3D printers"
|
||||
long_description = open("README.md").read()
|
||||
description = "The snappy web interface for your 3D printer"
|
||||
long_description = read_file_contents(os.path.join(here, "README.md"))
|
||||
long_description_content_type = "text/markdown"
|
||||
|
||||
python_requires = PYTHON_REQUIRES
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
setup_requires = SETUP_REQUIRES
|
||||
|
||||
try:
|
||||
import pypandoc
|
||||
setup_requires += ["setuptools-markdown"]
|
||||
long_description_markdown_filename = "README.md"
|
||||
del pypandoc
|
||||
except:
|
||||
pass
|
||||
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Environment :: Web Environment",
|
||||
"Framework :: Flask",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: Education",
|
||||
"Intended Audience :: End Users/Desktop",
|
||||
"Intended Audience :: Manufacturing",
|
||||
"Intended Audience :: Other Audience",
|
||||
"Intended Audience :: Science/Research",
|
||||
"License :: OSI Approved :: GNU Affero General Public License v3",
|
||||
"Natural Language :: English",
|
||||
"Natural Language :: German",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 2",
|
||||
"Programming Language :: Python :: 2.7",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
"Programming Language :: JavaScript",
|
||||
"Topic :: Internet :: WWW/HTTP",
|
||||
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
|
||||
"Topic :: Internet :: WWW/HTTP :: WSGI",
|
||||
"Topic :: Printing",
|
||||
"Topic :: System :: Networking :: Monitoring"
|
||||
"Topic :: System :: Monitoring"
|
||||
]
|
||||
author = "Gina Häußge"
|
||||
author_email = "osd@foosel.net"
|
||||
url = "http://octoprint.org"
|
||||
license = "AGPLv3"
|
||||
author_email = "gina@octoprint.org"
|
||||
url = "https://octoprint.org"
|
||||
license = "GNU Affero General Public License v3"
|
||||
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
|
||||
|
||||
project_urls={
|
||||
"Community Forum": "https://discourse.octoprint.org",
|
||||
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
|
||||
"Source": "https://github.com/foosel/OctoPrint",
|
||||
"Funding": "https://donate.octoprint.org"
|
||||
}
|
||||
|
||||
packages = find_packages(where="src")
|
||||
package_dir = {
|
||||
|
||||
@@ -50,15 +50,24 @@ del version_info
|
||||
|
||||
#~~ custom exceptions
|
||||
|
||||
class FatalStartupError(BaseException):
|
||||
pass
|
||||
class FatalStartupError(Exception):
|
||||
def __init__(self, message, cause=None):
|
||||
self.cause = cause
|
||||
Exception.__init__(self, message)
|
||||
|
||||
def __str__(self):
|
||||
result = Exception.__str__(self)
|
||||
if self.cause:
|
||||
return "{}: {}".format(result, str(self.cause))
|
||||
else:
|
||||
return result
|
||||
|
||||
#~~ init methods to bring up platform
|
||||
|
||||
def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
logging_config=None, debug=False, verbosity=0, uncaught_logger=None,
|
||||
uncaught_handler=None, safe_mode=False, ignore_blacklist=False, after_preinit_logging=None,
|
||||
after_settings=None, after_logging=None, after_safe_mode=None,
|
||||
after_settings_init=None, after_logging=None, after_safe_mode=None, after_settings_valid=None,
|
||||
after_event_manager=None, after_connectivity_checker=None,
|
||||
after_plugin_manager=None, after_environment_detector=None):
|
||||
kwargs = dict()
|
||||
@@ -70,55 +79,80 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
if callable(after_preinit_logging):
|
||||
after_preinit_logging(**kwargs)
|
||||
|
||||
settings = init_settings(basedir, configfile)
|
||||
try:
|
||||
settings = init_settings(basedir, configfile)
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Could not initialize settings manager", cause=ex)
|
||||
kwargs["settings"] = settings
|
||||
if callable(after_settings):
|
||||
after_settings(**kwargs)
|
||||
if callable(after_settings_init):
|
||||
after_settings_init(**kwargs)
|
||||
|
||||
try:
|
||||
logger = init_logging(settings,
|
||||
use_logging_file=use_logging_file,
|
||||
logging_file=logging_file,
|
||||
default_config=logging_config,
|
||||
debug=debug,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=uncaught_logger,
|
||||
uncaught_handler=uncaught_handler)
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Could not initialize logging", cause=ex)
|
||||
|
||||
logger = init_logging(settings,
|
||||
use_logging_file=use_logging_file,
|
||||
logging_file=logging_file,
|
||||
default_config=logging_config,
|
||||
debug=debug,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=uncaught_logger,
|
||||
uncaught_handler=uncaught_handler)
|
||||
kwargs["logger"] = logger
|
||||
|
||||
if callable(after_logging):
|
||||
after_logging(**kwargs)
|
||||
|
||||
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
|
||||
safe_mode = safe_mode or settings_safe_mode
|
||||
kwargs["safe_mode"] = safe_mode
|
||||
|
||||
if callable(after_safe_mode):
|
||||
after_safe_mode(**kwargs)
|
||||
|
||||
event_manager = init_event_manager(settings)
|
||||
# now before we continue, let's make sure *all* our folders are sane
|
||||
try:
|
||||
settings.sanity_check_folders()
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Configured folders didn't pass sanity check", cause=ex)
|
||||
if callable(after_settings_valid):
|
||||
after_settings_valid(**kwargs)
|
||||
|
||||
try:
|
||||
event_manager = init_event_manager(settings)
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Could not initialize event manager", cause=ex)
|
||||
|
||||
kwargs["event_manager"] = event_manager
|
||||
if callable(after_event_manager):
|
||||
after_event_manager(**kwargs)
|
||||
|
||||
connectivity_checker = init_connectivity_checker(settings, event_manager)
|
||||
try:
|
||||
connectivity_checker = init_connectivity_checker(settings, event_manager)
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Could not initialize connectivity checker", cause=ex)
|
||||
|
||||
kwargs["connectivity_checker"] = connectivity_checker
|
||||
if callable(after_connectivity_checker):
|
||||
after_connectivity_checker(**kwargs)
|
||||
|
||||
plugin_manager = init_pluginsystem(settings,
|
||||
safe_mode=safe_mode,
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
connectivity_checker=connectivity_checker)
|
||||
kwargs["plugin_manager"] = plugin_manager
|
||||
try:
|
||||
plugin_manager = init_pluginsystem(settings,
|
||||
safe_mode=safe_mode,
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
connectivity_checker=connectivity_checker)
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Could not initialize settings manager", cause=ex)
|
||||
|
||||
kwargs["plugin_manager"] = plugin_manager
|
||||
if callable(after_plugin_manager):
|
||||
after_plugin_manager(**kwargs)
|
||||
|
||||
environment_detector = init_environment_detector(plugin_manager)
|
||||
kwargs["environment_detector"] = environment_detector
|
||||
try:
|
||||
environment_detector = init_environment_detector(plugin_manager)
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Could not initialize environment detector", cause=ex)
|
||||
|
||||
kwargs["environment_detector"] = environment_detector
|
||||
if callable(after_environment_detector):
|
||||
after_environment_detector(**kwargs)
|
||||
|
||||
@@ -198,7 +232,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"class": "octoprint.logging.handlers.OctoPrintStreamHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "simple",
|
||||
"stream": "ext://sys.stdout"
|
||||
@@ -561,6 +595,9 @@ def main():
|
||||
# cut off stuff from the beginning
|
||||
args = args[-1 * sys_args_length:] if sys_args_length else []
|
||||
|
||||
from octoprint.util.fixes import patch_sarge_async_on_py2
|
||||
patch_sarge_async_on_py2()
|
||||
|
||||
from octoprint.cli import octo
|
||||
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
|
||||
|
||||
|
||||
@@ -71,3 +71,6 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
click.echo("DONE:{}s".format(time.time() - start_time))
|
||||
click.echo("RESULTS:")
|
||||
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
|
||||
|
||||
if __name__ == "__main__":
|
||||
gcode_command()
|
||||
@@ -82,12 +82,16 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
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:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error starting up OctoPrint.", err=True)
|
||||
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,
|
||||
|
||||
@@ -256,7 +256,7 @@ class FileManager(object):
|
||||
file_name = storage_manager.split_path(path)
|
||||
|
||||
# we'll use the default printer profile for the backlog since we don't know better
|
||||
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
|
||||
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None)
|
||||
if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority):
|
||||
counter += 1
|
||||
|
||||
@@ -476,12 +476,9 @@ class FileManager(object):
|
||||
|
||||
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
|
||||
|
||||
if analysis is None:
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
else:
|
||||
self._add_analysis_result(destination, path, analysis)
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
@@ -700,7 +697,7 @@ class FileManager(object):
|
||||
def _on_analysis_finished(self, entry, result):
|
||||
self._add_analysis_result(entry.location, entry.path, result)
|
||||
|
||||
def _analysis_queue_entry(self, destination, path, printer_profile=None):
|
||||
def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
@@ -709,6 +706,6 @@ class FileManager(object):
|
||||
file_type = get_file_type(absolute_path)
|
||||
|
||||
if file_type:
|
||||
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile)
|
||||
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis)
|
||||
else:
|
||||
return None
|
||||
@@ -20,7 +20,7 @@ from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
|
||||
"""
|
||||
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
|
||||
for processing.
|
||||
@@ -33,6 +33,7 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio
|
||||
location (str): Location the file is located on.
|
||||
absolute_path (str): Absolute path on disk through which to access the file.
|
||||
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
|
||||
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
|
||||
"""
|
||||
|
||||
def __str__(self):
|
||||
@@ -50,8 +51,6 @@ class AnalysisQueue(object):
|
||||
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
|
||||
by their machine code type.
|
||||
|
||||
At the moment, only the analysis of GCODE files for 3D printing is supported, through :class:`GcodeAnalysisQueue`.
|
||||
|
||||
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
|
||||
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
|
||||
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
|
||||
@@ -62,12 +61,13 @@ class AnalysisQueue(object):
|
||||
entry will be enqueued with the type specific analysis queue.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, queue_factories):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._callbacks = []
|
||||
self._queues = dict(
|
||||
gcode=GcodeAnalysisQueue(self._analysis_finished)
|
||||
)
|
||||
|
||||
self._queues = dict()
|
||||
for key, queue_factory in queue_factories.items():
|
||||
self._queues[key] = queue_factory(self._analysis_finished)
|
||||
|
||||
def register_finish_callback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
@@ -299,7 +299,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
- * **Key**
|
||||
* **Description**
|
||||
- * ``estimatedPrintTime``
|
||||
* Estimated time the file take to print, in minutes
|
||||
* Estimated time the file take to print, in seconds
|
||||
- * ``filament``
|
||||
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
|
||||
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
|
||||
@@ -307,6 +307,28 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
* The extruded length in mm
|
||||
- * ``filament.toolX.volume``
|
||||
* The extruded volume in cm³
|
||||
- * ``printingArea``
|
||||
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
|
||||
- * ``printingArea.minX``
|
||||
* Minimum X coordinate of the printed object
|
||||
- * ``printingArea.maxX``
|
||||
* Maximum X coordinate of the printed object
|
||||
- * ``printingArea.minY``
|
||||
* Minimum Y coordinate of the printed object
|
||||
- * ``printingArea.maxY``
|
||||
* Maximum Y coordinate of the printed object
|
||||
- * ``printingArea.minZ``
|
||||
* Minimum Z coordinate of the printed object
|
||||
- * ``printingArea.maxZ``
|
||||
* Maximum Z coordinate of the printed object
|
||||
- * ``dimensions``
|
||||
* Dimensions of the printed object in X, Y, Z
|
||||
- * ``dimensions.width``
|
||||
* Width of the printed model along the X axis, in mm
|
||||
- * ``dimensions.depth``
|
||||
* Depth of the printed model along the Y axis, in mm
|
||||
- * ``dimensions.height``
|
||||
* Height of the printed model along the Z axis, in mm
|
||||
"""
|
||||
|
||||
def __init__(self, finished_callback):
|
||||
@@ -320,6 +342,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
import sys
|
||||
import yaml
|
||||
|
||||
if self._current.analysis:
|
||||
return self._current.analysis
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
|
||||
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
@@ -343,7 +367,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
|
||||
|
||||
self._aborted = False
|
||||
p = sarge.run(command, async=True, stdout=sarge.Capture())
|
||||
p = sarge.run(command, async_=True, stdout=sarge.Capture())
|
||||
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
|
||||
@@ -153,7 +153,8 @@ class StorageInterface(object):
|
||||
from root of base folder
|
||||
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
|
||||
filtering will take place
|
||||
:param bool recursive: will also step into sub folders for building the complete list if set to True
|
||||
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
|
||||
do one step down into sub folders to be able to populate the ``children``.
|
||||
:return: a dictionary mapping entry names to entry data that represents the whole file list
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
@@ -176,14 +177,14 @@ class StorageInterface(object):
|
||||
Removes the folder at ``path``
|
||||
|
||||
:param string path: the path of the folder to remove
|
||||
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will
|
||||
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
|
||||
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
|
||||
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_folder(self, source, destination):
|
||||
"""
|
||||
Copys the folder ``source`` to ``destination``
|
||||
Copies the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
@@ -232,7 +233,7 @@ class StorageInterface(object):
|
||||
|
||||
def copy_file(self, source, destination):
|
||||
"""
|
||||
Copys the file ``source`` to ``destination``
|
||||
Copies the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
@@ -443,7 +444,7 @@ class LocalFileStorage(StorageInterface):
|
||||
"""
|
||||
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
|
||||
|
||||
Metadata is managed inside ``.metadata.yaml`` files in the respective folders, indexed by the sanitized filenames
|
||||
Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames
|
||||
stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead.
|
||||
|
||||
This storage type implements :func:`path_on_disk`.
|
||||
@@ -564,7 +565,7 @@ class LocalFileStorage(StorageInterface):
|
||||
path = os.path.join(self.basefolder, path)
|
||||
|
||||
def last_modified_for_path(p):
|
||||
metadata = os.path.join(p, ".metadata.yaml")
|
||||
metadata = os.path.join(p, ".metadata.json")
|
||||
if os.path.exists(metadata):
|
||||
return max(os.stat(p).st_mtime, os.stat(metadata).st_mtime)
|
||||
else:
|
||||
@@ -633,7 +634,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
empty = True
|
||||
for entry in scandir(folder_path):
|
||||
if entry.name == ".metadata.yaml":
|
||||
if entry.name == ".metadata.json" or entry.name == ".metadata.yaml":
|
||||
continue
|
||||
empty = False
|
||||
break
|
||||
@@ -1114,7 +1115,7 @@ class LocalFileStorage(StorageInterface):
|
||||
try:
|
||||
print_time = float(print_time)
|
||||
except:
|
||||
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.yaml: {!r}".format(name, path, print_time))
|
||||
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
|
||||
continue
|
||||
|
||||
if not printer_profile in former_print_times:
|
||||
@@ -1277,7 +1278,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if metadata_dirty:
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _list_folder(self, path, base="", entry_filter=None, recursive=True, **kwargs):
|
||||
def _list_folder(self, path, base="", entry_filter=None, recursive=True, include_children=True, **kwargs):
|
||||
if entry_filter is None:
|
||||
entry_filter = kwargs.get("filter", None)
|
||||
|
||||
@@ -1385,8 +1386,14 @@ class LocalFileStorage(StorageInterface):
|
||||
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
|
||||
recursive=recursive)
|
||||
entry_data["children"] = sub_result
|
||||
elif include_children:
|
||||
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
|
||||
recursive=False, include_children=False)
|
||||
entry_data["children"] = sub_result
|
||||
|
||||
if not entry_filter or entry_filter(entry_name, entry_data):
|
||||
# only add folders passing the optional filter
|
||||
|
||||
def get_size():
|
||||
total_size = 0
|
||||
for element in entry_data["children"].values():
|
||||
@@ -1395,7 +1402,6 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
return total_size
|
||||
|
||||
# only add folders passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_data)
|
||||
if recursive:
|
||||
@@ -1512,14 +1518,16 @@ class LocalFileStorage(StorageInterface):
|
||||
if path in self._metadata_cache:
|
||||
return deepcopy(self._metadata_cache[path])
|
||||
|
||||
metadata_path = os.path.join(path, ".metadata.yaml")
|
||||
self._migrate_metadata(path)
|
||||
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
if os.path.exists(metadata_path):
|
||||
with open(metadata_path) as f:
|
||||
try:
|
||||
import yaml
|
||||
metadata = yaml.safe_load(f)
|
||||
import json
|
||||
metadata = json.load(f)
|
||||
except:
|
||||
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
|
||||
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
|
||||
else:
|
||||
if isinstance(metadata, dict):
|
||||
self._metadata_cache[path] = deepcopy(metadata)
|
||||
@@ -1528,27 +1536,63 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def _save_metadata(self, path, metadata):
|
||||
with self._get_metadata_lock(path):
|
||||
metadata_path = os.path.join(path, ".metadata.yaml")
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
try:
|
||||
import yaml
|
||||
import json
|
||||
with atomic_write(metadata_path) as f:
|
||||
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
json.dump(metadata, f, indent=4, separators=(",", ": "))
|
||||
except:
|
||||
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
|
||||
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
|
||||
else:
|
||||
self._metadata_cache[path] = deepcopy(metadata)
|
||||
|
||||
def _delete_metadata(self, path):
|
||||
with self._get_metadata_lock(path):
|
||||
metadata_path = os.path.join(path, ".metadata.yaml")
|
||||
if os.path.exists(metadata_path):
|
||||
try:
|
||||
os.remove(metadata_path)
|
||||
except:
|
||||
self._logger.exception("Error while deleting .metadata.yaml from {path}".format(**locals()))
|
||||
metadata_files = (".metadata.json", ".metadata.yaml")
|
||||
for metadata_file in metadata_files:
|
||||
metadata_path = os.path.join(path, metadata_file)
|
||||
if os.path.exists(metadata_path):
|
||||
try:
|
||||
os.remove(metadata_path)
|
||||
except:
|
||||
self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
|
||||
if path in self._metadata_cache:
|
||||
del self._metadata_cache[path]
|
||||
|
||||
def _migrate_metadata(self, path):
|
||||
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
|
||||
import yaml
|
||||
import json
|
||||
|
||||
with self._get_metadata_lock(path):
|
||||
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
|
||||
metadata_path_json = os.path.join(path, ".metadata.json")
|
||||
|
||||
if not os.path.exists(metadata_path_yaml):
|
||||
# nothing to migrate
|
||||
return
|
||||
|
||||
if os.path.exists(metadata_path_json):
|
||||
# already migrated
|
||||
# TODO 1.3.10 Remove ".metadata.yaml" files
|
||||
return
|
||||
|
||||
with open(metadata_path_yaml) as f:
|
||||
try:
|
||||
metadata = yaml.safe_load(f)
|
||||
except:
|
||||
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
|
||||
return
|
||||
|
||||
if not isinstance(metadata, dict):
|
||||
# looks invalid, ignore it
|
||||
return
|
||||
|
||||
with atomic_write(metadata_path_json) as f:
|
||||
json.dump(metadata, f, indent=4, separators=(",", ": "))
|
||||
|
||||
# TODO 1.3.10 Remove ".metadata.yaml" files
|
||||
|
||||
@contextmanager
|
||||
def _get_metadata_lock(self, path):
|
||||
with self._metadata_lock_mutex:
|
||||
@@ -1560,8 +1604,9 @@ class LocalFileStorage(StorageInterface):
|
||||
counter += 1
|
||||
self._metadata_locks[path] = (counter, lock)
|
||||
|
||||
yield lock
|
||||
yield lock
|
||||
|
||||
with self._metadata_lock_mutex:
|
||||
counter = self._metadata_locks[path][0]
|
||||
counter -= 1
|
||||
if counter <= 0:
|
||||
|
||||
@@ -6,10 +6,30 @@ import os
|
||||
import re
|
||||
import time
|
||||
|
||||
# noinspection PyCompatibility
|
||||
import concurrent.futures
|
||||
|
||||
|
||||
class AsyncLogHandlerMixin(logging.Handler):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
|
||||
|
||||
def emit(self, record):
|
||||
try:
|
||||
self._executor.submit(self._emit, record)
|
||||
except:
|
||||
self.handleError(record)
|
||||
|
||||
def _emit(self, record):
|
||||
# noinspection PyUnresolvedReferences
|
||||
super(AsyncLogHandlerMixin, self).emit(record)
|
||||
|
||||
|
||||
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
logging.handlers.TimedRotatingFileHandler.__init__(self, *args, **kwargs)
|
||||
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
|
||||
|
||||
# clean up old files on handler start
|
||||
if self.backupCount > 0:
|
||||
@@ -17,7 +37,7 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler
|
||||
os.remove(s)
|
||||
|
||||
|
||||
class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
|
||||
class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler):
|
||||
rollover_callbacks = []
|
||||
|
||||
@classmethod
|
||||
@@ -25,32 +45,33 @@ class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
|
||||
cls.rollover_callbacks.append((callback, args, kwargs))
|
||||
|
||||
def doRollover(self):
|
||||
CleaningTimedRotatingFileHandler.doRollover(self)
|
||||
super(OctoPrintLogHandler, self).doRollover()
|
||||
|
||||
for rcb in self.rollover_callbacks:
|
||||
callback, args, kwargs = rcb
|
||||
callback(*args, **kwargs)
|
||||
|
||||
|
||||
class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
|
||||
pass
|
||||
|
||||
_do_rollover = False
|
||||
_suffix_template = "%Y-%m-%d_%H-%M-%S"
|
||||
_file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
|
||||
|
||||
class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
|
||||
|
||||
do_rollover = False
|
||||
suffix_template = "%Y-%m-%d_%H-%M-%S"
|
||||
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
|
||||
|
||||
@classmethod
|
||||
def on_open_connection(cls):
|
||||
cls._do_rollover = True
|
||||
cls.do_rollover = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
logging.handlers.RotatingFileHandler.__init__(self, *args, **kwargs)
|
||||
super(SerialLogHandler, self).__init__(*args, **kwargs)
|
||||
self.cleanupFiles()
|
||||
|
||||
def emit(self, record):
|
||||
logging.handlers.RotatingFileHandler.emit(self, record)
|
||||
|
||||
def shouldRollover(self, record):
|
||||
return self.__class__._do_rollover
|
||||
return self.do_rollover
|
||||
|
||||
def getFilesToDelete(self):
|
||||
"""
|
||||
@@ -64,7 +85,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
for fileName in fileNames:
|
||||
if fileName[:plen] == prefix:
|
||||
suffix = fileName[plen:]
|
||||
if self.__class__._file_pattern.match(suffix):
|
||||
if type(self).file_pattern.match(suffix):
|
||||
result.append(os.path.join(dirName, fileName))
|
||||
result.sort()
|
||||
if len(result) < self.backupCount:
|
||||
@@ -79,7 +100,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
os.remove(path)
|
||||
|
||||
def doRollover(self):
|
||||
self.__class__._do_rollover = False
|
||||
self.do_rollover = False
|
||||
|
||||
if self.stream:
|
||||
self.stream.close()
|
||||
@@ -88,7 +109,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
if os.path.exists(self.baseFilename):
|
||||
# figure out creation date/time to use for file suffix
|
||||
t = time.localtime(os.stat(self.baseFilename).st_mtime)
|
||||
dfn = self.baseFilename + "." + time.strftime(self.__class__._suffix_template, t)
|
||||
dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t)
|
||||
if os.path.exists(dfn):
|
||||
os.remove(dfn)
|
||||
os.rename(self.baseFilename, dfn)
|
||||
@@ -98,8 +119,8 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
self.stream = self._open()
|
||||
|
||||
class RecordingLogHandler(logging.Handler):
|
||||
def __init__(self, target=None, level=logging.NOTSET):
|
||||
logging.Handler.__init__(self, level=level)
|
||||
def __init__(self, target=None, *args, **kwargs):
|
||||
super(RecordingLogHandler, self).__init__(*args, **kwargs)
|
||||
self._buffer = []
|
||||
self._target = target
|
||||
|
||||
@@ -133,6 +154,7 @@ class RecordingLogHandler(logging.Handler):
|
||||
return len(self._buffer)
|
||||
|
||||
|
||||
# noinspection PyAbstractClass
|
||||
class CombinedLogHandler(logging.Handler):
|
||||
def __init__(self, *handlers):
|
||||
logging.Handler.__init__(self)
|
||||
|
||||
@@ -21,6 +21,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import os
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
@@ -94,7 +95,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
"octoprint.printer.factory"]
|
||||
"octoprint.printer.factory",
|
||||
"octoprint.timelapse.extensions"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
|
||||
@@ -167,7 +169,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
||||
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None,
|
||||
initialized=True):
|
||||
"""
|
||||
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
|
||||
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||
@@ -205,7 +208,6 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
|
||||
is determined be presence of injected ``_identifier`` property.
|
||||
|
||||
"""
|
||||
|
||||
if not isinstance(types, (list, tuple)):
|
||||
@@ -215,18 +217,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||
for plugin in plugins:
|
||||
if initialized and not hasattr(plugin, "_identifier"):
|
||||
continue
|
||||
|
||||
if hasattr(plugin, method):
|
||||
logger.debug("Calling {} on {}".format(method, plugin._identifier))
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(plugin._identifier, plugin, result)
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
|
||||
logger.exception("Error while calling plugin %s" % plugin._identifier)
|
||||
if error_callback:
|
||||
error_callback(plugin._identifier, plugin, exc)
|
||||
|
||||
|
||||
@@ -630,30 +630,46 @@ class PluginManager(object):
|
||||
def plugin_hooks(self):
|
||||
return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()}
|
||||
|
||||
def find_plugins(self, existing=None, ignore_uninstalled=True):
|
||||
def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False):
|
||||
added, found = self._find_plugins(existing=existing, ignore_uninstalled=ignore_uninstalled)
|
||||
if incl_all_found:
|
||||
return added, found
|
||||
else:
|
||||
return added
|
||||
|
||||
def _find_plugins(self, existing=None, ignore_uninstalled=True):
|
||||
if existing is None:
|
||||
existing = dict(self.plugins)
|
||||
|
||||
result = OrderedDict()
|
||||
result_added = OrderedDict()
|
||||
result_found = []
|
||||
|
||||
if self.plugin_folders:
|
||||
try:
|
||||
result.update(self._find_plugins_from_folders(self.plugin_folders,
|
||||
existing,
|
||||
ignored_uninstalled=ignore_uninstalled))
|
||||
added, found = self._find_plugins_from_folders(self.plugin_folders,
|
||||
existing,
|
||||
ignored_uninstalled=ignore_uninstalled)
|
||||
result_added.update(added)
|
||||
result_found += found
|
||||
except:
|
||||
self.logger.exception("Error fetching plugins from folders")
|
||||
|
||||
if self.plugin_entry_points:
|
||||
existing.update(result)
|
||||
existing.update(result_added)
|
||||
try:
|
||||
result.update(self._find_plugins_from_entry_points(self.plugin_entry_points,
|
||||
existing,
|
||||
ignore_uninstalled=ignore_uninstalled))
|
||||
added, found = self._find_plugins_from_entry_points(self.plugin_entry_points,
|
||||
existing,
|
||||
ignore_uninstalled=ignore_uninstalled)
|
||||
result_added.update(added)
|
||||
result_found += found
|
||||
except:
|
||||
self.logger.exception("Error fetching plugins from entry points")
|
||||
return result
|
||||
|
||||
return result_added, result_found
|
||||
|
||||
def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True):
|
||||
result = OrderedDict()
|
||||
added = OrderedDict()
|
||||
found = []
|
||||
|
||||
for folder in folders:
|
||||
try:
|
||||
@@ -691,7 +707,8 @@ class PluginManager(object):
|
||||
# whatever this is, we ignore it
|
||||
continue
|
||||
|
||||
if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
found.append(key)
|
||||
if key in existing or key in added or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
@@ -702,16 +719,17 @@ class PluginManager(object):
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.enabled = False
|
||||
result[key] = plugin
|
||||
added[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
|
||||
except:
|
||||
self.logger.exception("Error processing folder {}".format(folder))
|
||||
|
||||
return result
|
||||
return added, found
|
||||
|
||||
def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True):
|
||||
result = OrderedDict()
|
||||
added = OrderedDict()
|
||||
found = []
|
||||
|
||||
# let's make sure we have a current working set ...
|
||||
working_set = pkg_resources.WorkingSet()
|
||||
@@ -745,25 +763,25 @@ class PluginManager(object):
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
found.append(key)
|
||||
if key in existing or key in added or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined or marked as uninstalled, ignore it
|
||||
continue
|
||||
|
||||
kwargs = dict(module_name=module_name, version=version)
|
||||
package_name = None
|
||||
package_name = entry_point.dist.project_name
|
||||
try:
|
||||
module_pkginfo = InstalledEntryPoint(entry_point)
|
||||
entry_point_metadata = EntryPointMetadata(entry_point)
|
||||
except:
|
||||
self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
|
||||
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
|
||||
else:
|
||||
kwargs.update(dict(
|
||||
name=module_pkginfo.name,
|
||||
summary=module_pkginfo.summary,
|
||||
author=module_pkginfo.author,
|
||||
url=module_pkginfo.home_page,
|
||||
license=module_pkginfo.license
|
||||
name=entry_point_metadata.name,
|
||||
summary=entry_point_metadata.summary,
|
||||
author=entry_point_metadata.author,
|
||||
url=entry_point_metadata.home_page,
|
||||
license=entry_point_metadata.license
|
||||
))
|
||||
package_name = module_pkginfo.name
|
||||
|
||||
plugin = self._import_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
@@ -783,11 +801,11 @@ class PluginManager(object):
|
||||
module_name,
|
||||
plugin.location))
|
||||
|
||||
result[key] = plugin
|
||||
added[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
|
||||
|
||||
return result
|
||||
return added, found
|
||||
|
||||
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None,
|
||||
author=None, url=None, license=None, bundled=False):
|
||||
@@ -843,7 +861,7 @@ class PluginManager(object):
|
||||
if plugin.check():
|
||||
return plugin
|
||||
else:
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
|
||||
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
def _is_plugin_disabled(self, key):
|
||||
@@ -870,11 +888,26 @@ class PluginManager(object):
|
||||
if force_reload is None:
|
||||
force_reload = []
|
||||
|
||||
plugins = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload))
|
||||
self.disabled_plugins.update(plugins)
|
||||
added, found = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload),
|
||||
incl_all_found=True)
|
||||
|
||||
# let's clean everything we DIDN'T find first
|
||||
removed = [key for key in self.enabled_plugins.keys() + self.disabled_plugins.keys() if key not in found]
|
||||
for key in removed:
|
||||
try:
|
||||
del self.enabled_plugins[key]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
try:
|
||||
del self.disabled_plugins[key]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
self.disabled_plugins.update(added)
|
||||
|
||||
# 1st pass: loading the plugins
|
||||
for name, plugin in plugins.items():
|
||||
for name, plugin in added.items():
|
||||
try:
|
||||
if not plugin.blacklisted and not plugin.forced_disabled:
|
||||
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
|
||||
@@ -888,7 +921,7 @@ class PluginManager(object):
|
||||
force_reload=force_reload)
|
||||
|
||||
# 2nd pass: enabling those plugins that need enabling
|
||||
for name, plugin in plugins.items():
|
||||
for name, plugin in added.items():
|
||||
try:
|
||||
if plugin.loaded and not plugin.forced_disabled:
|
||||
if plugin.blacklisted:
|
||||
@@ -1591,56 +1624,25 @@ def is_editable_install(install_dir, package, module, location):
|
||||
return False
|
||||
|
||||
|
||||
class InstalledEntryPoint(pkginfo.Installed):
|
||||
|
||||
def __init__(self, entry_point, metadata_version=None):
|
||||
class EntryPointMetadata(pkginfo.Distribution):
|
||||
def __init__(self, entry_point):
|
||||
self.entry_point = entry_point
|
||||
package = entry_point.module_name
|
||||
pkginfo.Installed.__init__(self, package, metadata_version=metadata_version)
|
||||
self.extractMetadata()
|
||||
|
||||
def read(self):
|
||||
import sys
|
||||
import glob
|
||||
import warnings
|
||||
|
||||
opj = os.path.join
|
||||
if self.package is not None:
|
||||
package = self.package.__package__
|
||||
if package is None:
|
||||
package = self.package.__name__
|
||||
metadata_files = ("METADATA", # wheel
|
||||
"PKG-INFO") # egg
|
||||
|
||||
project = pkg_resources.to_filename(pkg_resources.safe_name(self.entry_point.dist.project_name))
|
||||
if self.entry_point and self.entry_point.dist:
|
||||
for metadata_file in metadata_files:
|
||||
try:
|
||||
return self.entry_point.dist.get_metadata(metadata_file)
|
||||
except:
|
||||
pass
|
||||
|
||||
package_pattern = '%s*.egg-info' % package
|
||||
project_pattern = '%s*.egg-info' % project
|
||||
|
||||
file = getattr(self.package, '__file__', None)
|
||||
if file is not None:
|
||||
candidates = []
|
||||
|
||||
def _add_candidate(where):
|
||||
candidates.extend(glob.glob(where))
|
||||
|
||||
for entry in sys.path:
|
||||
if file.startswith(entry):
|
||||
_add_candidate(opj(entry, 'EGG-INFO')) # egg?
|
||||
for pattern in (package_pattern, project_pattern): # dist-installed?
|
||||
_add_candidate(opj(entry, pattern))
|
||||
|
||||
dir, name = os.path.split(self.package.__file__)
|
||||
for pattern in (package_pattern, project_pattern):
|
||||
_add_candidate(opj(dir, pattern))
|
||||
_add_candidate(opj(dir, '..', pattern))
|
||||
|
||||
for candidate in candidates:
|
||||
if os.path.isdir(candidate):
|
||||
path = opj(candidate, 'PKG-INFO')
|
||||
else:
|
||||
path = candidate
|
||||
if os.path.exists(path):
|
||||
with open(path) as f:
|
||||
return f.read()
|
||||
warnings.warn('No PKG-INFO found for package: %s' % self.package_name)
|
||||
warnings.warn('No package metadata found for package: {}'.format(self.entry_point.module_name))
|
||||
|
||||
|
||||
class Plugin(object):
|
||||
|
||||
@@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
class OctoPrintPlugin(Plugin):
|
||||
"""
|
||||
The parent class of all OctoPrint plugin mixins.
|
||||
@@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
|
||||
externally reachable, use :func:`on_after_startup` instead or additionally.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``StartupPlugin.on_startup``.
|
||||
|
||||
:param string host: the host the server will listen on, may be ``0.0.0.0``
|
||||
@@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
Called just after launch of the server, so when the listen loop is actually running already.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``StartupPlugin.on_after_startup``.
|
||||
"""
|
||||
|
||||
@@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
Called upon the imminent shutdown of OctoPrint.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``ShutdownPlugin.on_shutdown``.
|
||||
"""
|
||||
pass
|
||||
@@ -225,6 +234,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
js
|
||||
JavaScript files, such as additional view models
|
||||
jsclient
|
||||
JavaScript files containing additional parts for the JS Client Library (since 1.3.10)
|
||||
css
|
||||
CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode.
|
||||
less
|
||||
@@ -239,6 +250,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=['js/my_file.js', 'js/my_other_file.js'],
|
||||
clientjs=['clientjs/my_file.js'],
|
||||
css=['css/my_styles.css'],
|
||||
less=['less/my_styles.less']
|
||||
)
|
||||
@@ -1443,7 +1455,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users)
|
||||
should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will
|
||||
return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted,
|
||||
return its settings on the REST API even to anonymous clients, but will filter out fields it knows are restricted,
|
||||
therefore you **must** make sure that you specify sensitive information accordingly to limit access as required!
|
||||
"""
|
||||
|
||||
@@ -1799,6 +1811,10 @@ class EventHandlerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
Called by OctoPrint upon processing of a fired event on the platform.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
Arguments:
|
||||
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
|
||||
for possible values
|
||||
@@ -1984,7 +2000,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information
|
||||
about the slicing job under the following keys:
|
||||
|
||||
_analysis
|
||||
analysis
|
||||
Analysis result of the generated machine code as returned by the slicer itself. This should match the
|
||||
data structure described for the analysis queue of the matching machine code format, e.g.
|
||||
:class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files.
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server import user_permission
|
||||
|
||||
import flask
|
||||
from flask_babel import gettext
|
||||
|
||||
class Prompt(object):
|
||||
|
||||
def __init__(self, text):
|
||||
self.text = text
|
||||
self.choices = []
|
||||
|
||||
self._active = False
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
return self._active
|
||||
|
||||
def add_choice(self, text):
|
||||
self.choices.append(text)
|
||||
|
||||
def activate(self):
|
||||
self._active = True
|
||||
|
||||
def validate_choice(self, choice):
|
||||
return 0 <= choice < len(self.choices)
|
||||
|
||||
|
||||
class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._prompt = None
|
||||
self._selection_command = None
|
||||
|
||||
def initialize(self):
|
||||
self._selection_command = self._settings.get([b"selection_command"])
|
||||
|
||||
#~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/action_command_prompt.js"],
|
||||
clientjs=["clientjs/action_command_prompt.js"])
|
||||
|
||||
#~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(selection_command=None)
|
||||
|
||||
def on_settings_save(self, data):
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
self._selection_command = self._settings.get([b"selection_command"])
|
||||
|
||||
#~ SimpleApiPlugin
|
||||
|
||||
def get_api_commands(self):
|
||||
return dict(select=["choice"])
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if command == "select":
|
||||
if not user_permission.can():
|
||||
return flask.abort(403, "Insufficient permissions")
|
||||
|
||||
if self._prompt is None:
|
||||
return flask.abort(409, "No active prompt")
|
||||
|
||||
choice = data["choice"]
|
||||
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
|
||||
return flask.abort(400, "{!r} is not a valid value for choice".format(choice))
|
||||
|
||||
self._answer_prompt(choice)
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not user_permission.can():
|
||||
return flask.abort(403, "Insufficient permissions")
|
||||
if self._prompt is None:
|
||||
return flask.jsonify()
|
||||
else:
|
||||
return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices)
|
||||
|
||||
#~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="settings", name=gettext("Action Command Prompt"), custom_bindings=False)]
|
||||
|
||||
#~ action command handler
|
||||
|
||||
def action_command_handler(self, comm, line, action, *args, **kwargs):
|
||||
if not action.startswith(b"prompt_"):
|
||||
return
|
||||
|
||||
if self._selection_command is None:
|
||||
self._logger.info("Got a prompt command from the printer but no selection command is defined")
|
||||
return
|
||||
|
||||
parts = action.split(None, 1)
|
||||
if len(parts) == 1:
|
||||
action = parts[0]
|
||||
parameter = b""
|
||||
else:
|
||||
action, parameter = parts
|
||||
|
||||
if action == b"prompt_begin":
|
||||
if self._prompt is not None and self._prompt.active:
|
||||
self._logger.warn("Prompt is already defined")
|
||||
return
|
||||
self._prompt = Prompt(parameter.strip())
|
||||
|
||||
elif action == b"prompt_choice" or action == b"prompt_button":
|
||||
if self._prompt is None:
|
||||
return
|
||||
if self._prompt.active:
|
||||
self._logger.warn("Prompt is already active")
|
||||
return
|
||||
self._prompt.add_choice(parameter.strip())
|
||||
|
||||
elif action == b"prompt_show":
|
||||
if self._prompt is None:
|
||||
return
|
||||
if self._prompt.active:
|
||||
self._logger.warn("Prompt is already active")
|
||||
return
|
||||
self._show_prompt()
|
||||
|
||||
elif action == b"prompt_end":
|
||||
if self._prompt is None:
|
||||
return
|
||||
self._close_prompt()
|
||||
self._prompt = None
|
||||
|
||||
#~ prompt handling
|
||||
|
||||
def _show_prompt(self):
|
||||
self._prompt.activate()
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(action="show",
|
||||
text=self._prompt.text,
|
||||
choices=self._prompt.choices))
|
||||
|
||||
def _close_prompt(self):
|
||||
self._prompt = None
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(action="close"))
|
||||
|
||||
def _answer_prompt(self, choice):
|
||||
self._close_prompt()
|
||||
self._printer.commands([self._selection_command.format(choice=choice)])
|
||||
|
||||
|
||||
__plugin_name__ = "Action Command Prompt Support"
|
||||
__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
|
||||
"confirmation or selection prompts in OctoPrint")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = ActionCommandPromptPlugin()
|
||||
__plugin_hooks__ = {
|
||||
b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
|
||||
var data = {
|
||||
choice: choice
|
||||
};
|
||||
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
|
||||
return OctoPrintActionCommandPromptClient;
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
$(function() {
|
||||
function ActionCommandPromptViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self._modal = undefined;
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.isUser()) return;
|
||||
|
||||
OctoPrint.plugins.action_command_prompt.get()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
|
||||
self._showPrompt(data.text, data.choices);
|
||||
}
|
||||
};
|
||||
|
||||
self._showPrompt = function(text, buttons) {
|
||||
var opts = {
|
||||
title: gettext("Message from your printer"),
|
||||
message: text,
|
||||
selections: buttons,
|
||||
onselect: function(index) {
|
||||
if (index > -1) {
|
||||
self._select(index);
|
||||
}
|
||||
},
|
||||
onclose: function() {
|
||||
self._modal = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
self._modal = showSelectionDialog(opts)
|
||||
};
|
||||
|
||||
self._select = function(index) {
|
||||
OctoPrint.plugins.action_command_prompt.select(index);
|
||||
};
|
||||
|
||||
self._closePrompt = function() {
|
||||
if (self._modal) {
|
||||
self._modal.modal("hide");
|
||||
}
|
||||
};
|
||||
|
||||
self.onStartupComplete = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (!self.loginState.isUser()) return;
|
||||
if (plugin !== "action_command_prompt") {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (data.action) {
|
||||
case "show": {
|
||||
self._showPrompt(data.text, data.choices);
|
||||
break;
|
||||
}
|
||||
case "close": {
|
||||
self._closePrompt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ActionCommandPromptViewModel,
|
||||
dependencies: ["loginStateViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
<h3>{{ _('Action Command Prompt Settings') }}</h3>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Selection Command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.selection_command">
|
||||
<div class="help-block">{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace <code>{choice}</code> with the index of the selected choice. E.g. <code>M876 S{choice}</code> will become <code>M123 S1</code>') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -372,15 +372,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
result = []
|
||||
if "entries" in feed:
|
||||
for entry in feed["entries"]:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
try:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
except:
|
||||
self._logger.exception("Error while converting entry from feed, skipping it")
|
||||
return result
|
||||
|
||||
def _to_internal_entry(self, entry, read_until=None):
|
||||
"""Convert feed entries to internal data structure."""
|
||||
|
||||
published = calendar.timegm(entry["published_parsed"])
|
||||
timestamp = entry.get("published_parsed",
|
||||
entry.get("updated_parsed",
|
||||
None))
|
||||
if timestamp is None:
|
||||
return None
|
||||
|
||||
published = calendar.timegm(timestamp)
|
||||
|
||||
read = True
|
||||
if read_until is not None:
|
||||
|
||||
@@ -66,9 +66,11 @@ $(function() {
|
||||
return link;
|
||||
};
|
||||
|
||||
self.markRead = function(channel, until) {
|
||||
self.markRead = function(channel, until, reload) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
reload = !!reload;
|
||||
|
||||
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
|
||||
|
||||
var payload = {
|
||||
@@ -83,7 +85,9 @@ $(function() {
|
||||
data: JSON.stringify(payload),
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
success: function() {
|
||||
self.retrieveData()
|
||||
if (reload) {
|
||||
self.retrieveData()
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<div class="content" data-bind="html: $data.summary"></div>
|
||||
<div class="actions">
|
||||
<span class="articlelink"><small><a data-bind="text: $root.cleanedLink($data), attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
|
||||
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="fa fa-eye"></i> {{ _('Mark as last read') }}</a></small></span>
|
||||
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published, true) }"><i class="fa fa-eye"></i> {{ _('Mark as last read') }}</a></small></span>
|
||||
</div>
|
||||
</article>
|
||||
<!-- /ko -->
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import flask
|
||||
import threading
|
||||
import os
|
||||
import yaml
|
||||
import codecs
|
||||
import time
|
||||
from binascii import hexlify
|
||||
from collections import defaultdict
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
||||
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
|
||||
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
|
||||
class AppAlreadyExists(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PendingDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
self.user_token = user_token
|
||||
self.created = monotonic_time()
|
||||
|
||||
if callable(timeout_callback):
|
||||
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
|
||||
self.poll_timeout.start()
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
user_id=self.user_id,
|
||||
user_token=self.user_token)
|
||||
|
||||
|
||||
class ReadyDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
|
||||
@classmethod
|
||||
def for_pending(cls, pending, user_id):
|
||||
return cls(pending.app_id, pending.app_token, user_id)
|
||||
|
||||
|
||||
class ActiveKey(object):
|
||||
def __init__(self, app_id, api_key, user_id):
|
||||
self.app_id = app_id
|
||||
self.api_key = api_key
|
||||
self.user_id = user_id
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key,
|
||||
user_id=self.user_id)
|
||||
|
||||
def internal(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key)
|
||||
|
||||
@classmethod
|
||||
def for_internal(cls, internal, user_id):
|
||||
return cls(internal["app_id"], internal["api_key"], user_id)
|
||||
|
||||
|
||||
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._pending_decisions = []
|
||||
self._pending_lock = threading.RLock()
|
||||
|
||||
self._ready_decisions = []
|
||||
self._ready_lock = threading.RLock()
|
||||
|
||||
self._keys = defaultdict(list)
|
||||
self._keys_lock = threading.RLock()
|
||||
|
||||
self._key_path = None
|
||||
|
||||
def initialize(self):
|
||||
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
|
||||
self._load_keys()
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="usersettings", name=gettext("Application Keys")),
|
||||
dict(type="settings", name=gettext("Application Keys"))]
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/appkeys.js"],
|
||||
clientjs=["clientjs/appkeys.js"],
|
||||
less=["less/appkeys.less"],
|
||||
css=["css/appkeys.css"])
|
||||
|
||||
##~~ BlueprintPlugin mixin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def handle_probe(self):
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
def handle_request(self):
|
||||
data = flask.request.json
|
||||
if not "app" in data:
|
||||
return flask.make_response("No app name provided", 400)
|
||||
|
||||
app_name = data["app"]
|
||||
user_id = None
|
||||
if "user" in data:
|
||||
user_id = data["user"]
|
||||
|
||||
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
|
||||
app_name=app_name,
|
||||
user_token=user_token,
|
||||
user_id=user_id))
|
||||
response = flask.jsonify(app_token=app_token)
|
||||
response.status_code = 201
|
||||
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
||||
@no_firstrun_access
|
||||
def handle_decision_poll(self, app_token):
|
||||
result = self._get_pending_by_app_token(app_token)
|
||||
if result:
|
||||
for pending_decision in result:
|
||||
pending_decision.poll_timeout.reset()
|
||||
|
||||
response = flask.jsonify(message="Awaiting decision")
|
||||
response.status_code = 202
|
||||
return response
|
||||
|
||||
result = self._get_decision(app_token)
|
||||
if result:
|
||||
return flask.jsonify(api_key=result)
|
||||
|
||||
return flask.abort(404)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
|
||||
@restricted_access
|
||||
def handle_decision(self, user_token):
|
||||
data = flask.request.json
|
||||
if not "decision" in data:
|
||||
return flask.make_response("No decision provided", 400)
|
||||
decision = data["decision"] in valid_boolean_trues
|
||||
user_id = current_user.get_name()
|
||||
|
||||
result = self._set_decision(user_token, decision, user_id)
|
||||
if not result:
|
||||
return flask.abort(404)
|
||||
|
||||
# Close access_request dialog for this request on all open OctoPrint connections
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
return False # No API key required to request API access
|
||||
|
||||
##~~ SimpleApiPlugin mixin
|
||||
|
||||
def get_api_commands(self):
|
||||
return dict(generate=["app"],
|
||||
revoke=["key"])
|
||||
|
||||
def on_api_get(self, request):
|
||||
user_id = current_user.get_name()
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
|
||||
keys = self._all_api_keys()
|
||||
else:
|
||||
keys = self._api_keys_for_user(user_id)
|
||||
|
||||
return flask.jsonify(keys=map(lambda x: x.external(), keys),
|
||||
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
user_id = current_user.get_name()
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if command == "revoke":
|
||||
api_key = data.get("key")
|
||||
if not api_key:
|
||||
return flask.abort(400)
|
||||
|
||||
if not admin_permission.can():
|
||||
user_for_key = self._user_for_api_key(api_key)
|
||||
if user_for_key is None or user_for_key.user_id != user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
self._delete_api_key(api_key)
|
||||
|
||||
elif command == "generate":
|
||||
# manual generateKey
|
||||
app_name = data.get("app")
|
||||
if not app_name:
|
||||
return flask.abort(400)
|
||||
|
||||
self._add_api_key(user_id, app_name.strip())
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
##~~ key validator hook
|
||||
|
||||
def validate_api_key(self, api_key, *args, **kwargs):
|
||||
return self._user_for_api_key(api_key)
|
||||
|
||||
##~~ Helpers
|
||||
|
||||
def _add_pending_decision(self, app_name, user_id=None):
|
||||
app_token = self._generate_key()
|
||||
user_token = self._generate_key()
|
||||
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
|
||||
timeout_callback=self._expire_pending))
|
||||
|
||||
return app_token, user_token
|
||||
|
||||
def _get_pending_by_app_token(self, app_token):
|
||||
result = []
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.app_token == app_token:
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _get_pending_by_user_id(self, user_id):
|
||||
result = []
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.user_id == user_id or data.user_id is None:
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _expire_pending(self, user_token):
|
||||
with self._pending_lock:
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
len_after = len(self._pending_decisions)
|
||||
|
||||
if len_after < len_before:
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
|
||||
def _remove_stale_pending(self):
|
||||
with self._pending_lock:
|
||||
cutoff = monotonic_time() - CUTOFF_TIME
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.created >= cutoff,
|
||||
self._pending_decisions)
|
||||
len_after = len(self._pending_decisions)
|
||||
if len_after < len_before:
|
||||
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
|
||||
|
||||
def _set_decision(self, user_token, decision, user_id):
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
|
||||
pending = data
|
||||
break
|
||||
else:
|
||||
return False # not found
|
||||
|
||||
if decision:
|
||||
with self._ready_lock:
|
||||
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
|
||||
|
||||
with self._pending_lock:
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
|
||||
return True
|
||||
|
||||
def _get_decision(self, app_token):
|
||||
self._remove_stale_pending()
|
||||
|
||||
with self._ready_lock:
|
||||
for data in self._ready_decisions:
|
||||
if data.app_token == app_token:
|
||||
decision = data
|
||||
break
|
||||
else:
|
||||
return False # not found
|
||||
|
||||
api_key = self._add_api_key(decision.user_id, decision.app_id)
|
||||
|
||||
with self._ready_lock:
|
||||
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
|
||||
|
||||
return api_key
|
||||
|
||||
def _add_api_key(self, user_id, app_name):
|
||||
with self._keys_lock:
|
||||
for key in self._keys[user_id]:
|
||||
if key.app_id.lower() == app_name.lower():
|
||||
return key.api_key
|
||||
|
||||
key = ActiveKey(app_name, self._generate_key(), user_id)
|
||||
self._keys[user_id].append(key)
|
||||
self._save_keys()
|
||||
return key.api_key
|
||||
|
||||
def _delete_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
self._keys[user_id] = filter(lambda x: x.api_key != api_key, data)
|
||||
self._save_keys()
|
||||
|
||||
def _user_for_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
if filter(lambda x: x.api_key == api_key, data):
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
return None
|
||||
|
||||
def _api_keys_for_user(self, user_id):
|
||||
with self._keys_lock:
|
||||
return self._keys[user_id]
|
||||
|
||||
def _all_api_keys(self):
|
||||
with self._keys_lock:
|
||||
result = []
|
||||
for user_id, keys in self._keys.items():
|
||||
result += keys
|
||||
return result
|
||||
|
||||
def _generate_key(self):
|
||||
return hexlify(os.urandom(16))
|
||||
|
||||
def _load_keys(self):
|
||||
with self._keys_lock:
|
||||
if not os.path.exists(self._key_path):
|
||||
return
|
||||
|
||||
try:
|
||||
with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
|
||||
persisted = yaml.safe_load(f)
|
||||
except:
|
||||
self._logger.exception("Could not load application keys from {}".format(self._key_path))
|
||||
return
|
||||
|
||||
if not isinstance(persisted, dict):
|
||||
return
|
||||
|
||||
keys = defaultdict(list)
|
||||
for user_id, persisted_keys in persisted.items():
|
||||
keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
|
||||
self._keys = keys
|
||||
|
||||
def _save_keys(self):
|
||||
with self._keys_lock:
|
||||
to_persist = dict()
|
||||
for user_id, keys in self._keys.items():
|
||||
to_persist[user_id] = [x.internal() for x in keys]
|
||||
|
||||
try:
|
||||
with atomic_write(self._key_path) as f:
|
||||
yaml.safe_dump(to_persist, f)
|
||||
except:
|
||||
self._logger.exception("Could not write application keys to {}".format(self._key_path))
|
||||
|
||||
__plugin_name__ = u"Application Keys Plugin"
|
||||
__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys"
|
||||
__plugin_author__ = u"Gina Häußge, Aldo Hoeben"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to "
|
||||
u"obtain an API key without you manually copy-pasting it.")
|
||||
__plugin_implementation__ = AppKeysPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintAppKeysClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
|
||||
return this.base.simpleApiGet("appkeys", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
|
||||
return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.probe = function(opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
|
||||
return this.requestForUser(app, undefined, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
|
||||
var deferred = $.Deferred();
|
||||
var client = this;
|
||||
|
||||
client.probe()
|
||||
.done(function() {
|
||||
client.requestForUser(app, user)
|
||||
.done(function(response) {
|
||||
var token = response.app_token;
|
||||
if (!token) {
|
||||
// no token received, something went wrong
|
||||
deferred.reject();
|
||||
return;
|
||||
}
|
||||
|
||||
var interval = 1000;
|
||||
var poll = function() {
|
||||
client.checkDecision(token)
|
||||
.done(function(response) {
|
||||
if (response.api_key) {
|
||||
// got a decision, resolve the promise
|
||||
deferred.resolve(response.api_key);
|
||||
} else {
|
||||
// no decision yet, poll a bit more
|
||||
deferred.notify();
|
||||
window.setTimeout(poll, interval);
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
};
|
||||
window.setTimeout(poll, interval);
|
||||
})
|
||||
.fail(function() {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
})
|
||||
.fail(function() {
|
||||
// workflow unsupported
|
||||
deferred.reject();
|
||||
});
|
||||
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient);
|
||||
return OctoPrintAppKeysClient;
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}
|
||||
@@ -0,0 +1,308 @@
|
||||
$(function() {
|
||||
function UserAppKeysViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.userkeys",
|
||||
{
|
||||
"app": function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
|
||||
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"app",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
);
|
||||
self.pending = {};
|
||||
self.openRequests = {};
|
||||
|
||||
self.editorApp = ko.observable();
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getKeys()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
self.pending = response.pending;
|
||||
_.each(self.pending, function(data, token) {
|
||||
self.openRequests[token] = self.promptForAccess(data.app_id, token);
|
||||
})
|
||||
};
|
||||
|
||||
self.generateKey = function() {
|
||||
return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
|
||||
.done(self.requestData)
|
||||
.done(function() {
|
||||
self.editorApp("");
|
||||
});
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.allowApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, true)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.denyApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, false)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.promptForAccess = function(app, token) {
|
||||
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
|
||||
message = _.sprintf(message, {app: app});
|
||||
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
|
||||
return new PNotify({
|
||||
title: gettext("Access Request"),
|
||||
text: message,
|
||||
hide: false,
|
||||
icon: "fa fa-key",
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Allow"),
|
||||
click: function(notice) {
|
||||
self.allowApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}, {
|
||||
text: gettext("Deny"),
|
||||
click: function(notice) {
|
||||
self.denyApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
},
|
||||
buttons: {
|
||||
sticker: false,
|
||||
closer: false
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onUserSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "appkeys") {
|
||||
return;
|
||||
}
|
||||
|
||||
var app, token, user;
|
||||
|
||||
if (data.type === "request_access" && self.loginState.isUser()) {
|
||||
app = data.app_name;
|
||||
token = data.user_token;
|
||||
user = data.user_id;
|
||||
|
||||
if (user && user !== self.loginState.username()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.pending[token] !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.openRequests[token] = self.promptForAccess(app, token);
|
||||
|
||||
} else if (data.type === "end_request") {
|
||||
token = data.user_token;
|
||||
|
||||
if (self.openRequests[token] !== undefined) {
|
||||
// another instance responded to the access request before the current user did
|
||||
if (self.openRequests[token].state !== "closed") {
|
||||
self.openRequests[token].remove();
|
||||
}
|
||||
delete self.openRequests[token]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function AllAppKeysViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.allkeys",
|
||||
{
|
||||
"user_app": function (a, b) {
|
||||
// sorts ascending, first by user, then by app
|
||||
if (a["user_id"] > b["user_id"]) return 1;
|
||||
if (a["user_id"] < b["user_id"]) return -1;
|
||||
|
||||
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
|
||||
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"user_app",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
self.users = ko.observableArray([]);
|
||||
self.apps = ko.observableArray([]);
|
||||
|
||||
self.markedForDeletion = ko.observableArray([]);
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getAllKeys()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
|
||||
var users = [];
|
||||
var apps = [];
|
||||
_.each(response.keys, function(key) {
|
||||
users.push(key.user_id);
|
||||
apps.push(key.app_id.toLowerCase());
|
||||
});
|
||||
|
||||
users = _.uniq(users);
|
||||
users.sort();
|
||||
self.users(users);
|
||||
|
||||
apps = _.uniq(apps);
|
||||
apps.sort();
|
||||
self.apps(apps);
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.revokeMarked = function() {
|
||||
var perform = function() {
|
||||
self._bulkRevoke(self.markedForDeletion())
|
||||
.done(function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markAllOnPageForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
|
||||
};
|
||||
|
||||
self.markAllForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
|
||||
};
|
||||
|
||||
self.markAllByUserForDeletion = function(user) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
|
||||
};
|
||||
|
||||
self.markAllByAppForDeletion = function(app) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); })
|
||||
};
|
||||
|
||||
self.markAllByFilterForDeletion = function(filter) {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))));
|
||||
};
|
||||
|
||||
self.clearMarked = function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
};
|
||||
|
||||
self._bulkRevoke = function(keys) {
|
||||
var title, message, handler;
|
||||
|
||||
title = gettext("Revoking application keys");
|
||||
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length});
|
||||
handler = function(key) {
|
||||
return OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: keys.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(keys, function(key) {
|
||||
var request = handler(key);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UserAppKeysViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#usersettings_plugin_appkeys"]
|
||||
]);
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AllAppKeysViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#settings_plugin_appkeys"]
|
||||
])
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
#settings_plugin_appkeys_userkeys_table,
|
||||
#settings_plugin_appkeys_allkeys_table {
|
||||
.settings_plugin_appkeys_app {
|
||||
}
|
||||
.settings_plugin_appkeys_actions {
|
||||
width: 75px;
|
||||
text-align: center;
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
}
|
||||
.settings_plugin_appkeys_user {
|
||||
width: 100px;
|
||||
}
|
||||
.settings_plugin_appkeys_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<div data-bind="visible: keys.allSize() <= 0">
|
||||
<p>{{ _('There are no application keys registered yet.') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: keys.allSize() > 0">
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllOnPageForDeletion">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllForDeletion">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li class="dropdown-submenu">
|
||||
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by user...') }}</a>
|
||||
<ul class="dropdown-menu" data-bind="foreach: users">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByUserForDeletion($data) }, text: $data"></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="dropdown-submenu">
|
||||
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by app...') }}</a>
|
||||
<ul class="dropdown-menu" data-bind="foreach: apps">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByAppForDeletion($data) }, text: $data"></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarked">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: revokeMarked, enable: markedForDeletion().length > 0">{{ _('Revoke selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_allkeys_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_appkeys_checkbox"></th>
|
||||
<th class="settings_plugin_appkeys_user">{{ _('User') }}</th>
|
||||
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
|
||||
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_checkbox"><input type="checkbox" data-bind="value: api_key, checked: $root.markedForDeletion"></td>
|
||||
<td class="settings_plugin_appkeys_user"><span data-bind="text: user_id"></span></td>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: keys.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,49 @@
|
||||
<legend>{{ _('Registered application keys') }}</legend>
|
||||
|
||||
<div data-bind="visible: keys.allSize() <= 0">
|
||||
<p>{{ _('There are no application keys registered yet.') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: keys.allSize() > 0">
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_userkeys_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
|
||||
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: keys.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('Manually generate an application key') }}</legend>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Application identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" data-bind="value: editorApp">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="click: generateKey">{{ _('Generate') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,925 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.plugin.core import FolderOrigin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import is_os_compatible
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
try:
|
||||
import zlib # check if zlib is available
|
||||
except ImportError:
|
||||
zlib = None
|
||||
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import codecs
|
||||
import flask
|
||||
import logging
|
||||
import os
|
||||
import requests
|
||||
import sarge
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
import json
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
|
||||
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
|
||||
|
||||
|
||||
class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin):
|
||||
|
||||
_pip_caller = None
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._in_progress = []
|
||||
self._in_progress_lock = threading.RLock()
|
||||
|
||||
##~~ StarupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
self._clean_dir_backup(self._settings._basedir,
|
||||
on_log_progress=self._logger.info)
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/backup.js"],
|
||||
clientjs=["clientjs/backup.js"],
|
||||
css=["css/backup.css"],
|
||||
less=["less/backup.less"])
|
||||
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_state(self):
|
||||
backups = self._get_backups()
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(backups=backups,
|
||||
backup_in_progress=len(self._in_progress) > 0,
|
||||
unknown_plugins=unknown_plugins,
|
||||
restore_supported=is_os_compatible(["!windows"]))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_unknown_plugins(self):
|
||||
# TODO add caching
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(unknown_plugins=unknown_plugins)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def delete_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
pass
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_backups(self):
|
||||
backups = self._get_backups()
|
||||
return flask.jsonify(backups=backups)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def create_backup(self):
|
||||
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
|
||||
|
||||
data = flask.request.json
|
||||
exclude = data.get("exclude", [])
|
||||
|
||||
def on_backup_start(name, temporary_path, exclude):
|
||||
self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path,
|
||||
u",".join(exclude) if len(exclude) else "-"))
|
||||
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.append(name)
|
||||
self._send_client_message("backup_started", payload=dict(name=name))
|
||||
|
||||
def on_backup_done(name, final_path, exclude):
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.remove(name)
|
||||
self._send_client_message("backup_done", payload=dict(name=name))
|
||||
|
||||
self._logger.info(u"... done creating backup zip.")
|
||||
|
||||
def on_backup_error(name, exc_info):
|
||||
with self._in_progress_lock:
|
||||
try:
|
||||
self._in_progress.remove(name)
|
||||
except ValueError:
|
||||
# we'll ignore that
|
||||
pass
|
||||
|
||||
self._send_client_message("backup_error", payload=dict(name=name,
|
||||
error=u"{}".format(exc_info[1])))
|
||||
self._logger.error(u"Error while creating backup zip", exc_info=exc_info)
|
||||
|
||||
thread = threading.Thread(target=self._create_backup,
|
||||
args=(backup_file,),
|
||||
kwargs=dict(exclude=exclude,
|
||||
settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_backup_start=on_backup_start,
|
||||
on_backup_done=on_backup_done,
|
||||
on_backup_error=on_backup_error))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
response = flask.jsonify(started=True,
|
||||
name=backup_file)
|
||||
response.status_code = 201
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def delete_backup(self, filename):
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
full_path = os.path.realpath(os.path.join(backup_folder, filename))
|
||||
if full_path.startswith(backup_folder) \
|
||||
and os.path.exists(full_path) \
|
||||
and not is_hidden_path(full_path):
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except:
|
||||
self._logger.exception(u"Could not delete {}".format(filename))
|
||||
raise
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def perform_restore(self):
|
||||
if not is_os_compatible(["!windows"]):
|
||||
return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400)
|
||||
|
||||
input_name = "file"
|
||||
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
||||
|
||||
if input_upload_path in flask.request.values:
|
||||
# file to restore was uploaded
|
||||
path = flask.request.values[input_upload_path]
|
||||
|
||||
elif flask.request.json and "path" in flask.request.json:
|
||||
# existing backup is supposed to be restored
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"]))
|
||||
if not path.startswith(backup_folder) \
|
||||
or not os.path.exists(path) \
|
||||
or is_hidden_path(path):
|
||||
return flask.abort(404)
|
||||
|
||||
else:
|
||||
return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400)
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def on_log(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", dict(line=line, type="stdout"))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
|
||||
octoprint_compatible=octoprint_compatible,
|
||||
os_compatible=os_compatible))
|
||||
continue
|
||||
|
||||
self._logger.info(u"Installing plugin {}".format(plugin["id"]))
|
||||
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=on_log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
self._send_client_message("unknown_plugins", payload=dict(plugins=plugins))
|
||||
|
||||
def on_log_progress(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stdout"))
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
self._logger.error(line, exc_info=exc_info)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stderr"))
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr"))
|
||||
|
||||
def on_restore_start(path):
|
||||
self._send_client_message("restore_started")
|
||||
|
||||
def on_restore_done(path):
|
||||
self._send_client_message("restore_done")
|
||||
|
||||
def on_restore_failed(path):
|
||||
self._send_client_message("restore_failed")
|
||||
|
||||
def on_invalid_backup(line):
|
||||
on_log_error(line)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
archive.close()
|
||||
shutil.copy(path, archive.name)
|
||||
path = archive.name
|
||||
|
||||
# noinspection PyTypeChecker
|
||||
thread = threading.Thread(target=self._restore_backup,
|
||||
args=(path,),
|
||||
kwargs=dict(settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_invalid_backup=on_invalid_backup,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_restore_start=on_restore_start,
|
||||
on_restore_done=on_restore_done,
|
||||
on_restore_failed=on_restore_failed))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return flask.jsonify(started=True)
|
||||
|
||||
##~~ tornado hook
|
||||
|
||||
def route_hook(self, *args, **kwargs):
|
||||
from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.server import app
|
||||
from octoprint.server.util.tornado import access_validation_factory
|
||||
from octoprint.server.util.flask import admin_validator
|
||||
|
||||
return [
|
||||
(r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(),
|
||||
as_attachment=True,
|
||||
path_validation=path_validation_factory(lambda path: not is_hidden_path(path),
|
||||
status_code=404),
|
||||
access_validation=access_validation_factory(app, admin_validator)))
|
||||
]
|
||||
|
||||
def bodysize_hook(self, current_max_body_sizes, *args, **kwargs):
|
||||
# max upload size of 1GB for the restore endpoint
|
||||
return [("POST", r"/restore", 1024 * 1024 * 1024)]
|
||||
|
||||
##~~ CLI hook
|
||||
|
||||
def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
import click
|
||||
|
||||
@click.command("backup")
|
||||
@click.option("--exclude", multiple=True,
|
||||
help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or "
|
||||
"'timelapse' to exclude timelapses.")
|
||||
def backup_command(exclude):
|
||||
"""
|
||||
Creates a new backup.
|
||||
"""
|
||||
|
||||
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
|
||||
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
|
||||
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
click.echo("Creating backup at {}, please wait...".format(backup_file))
|
||||
self._create_backup(backup_file,
|
||||
exclude=exclude,
|
||||
settings=settings,
|
||||
plugin_manager=cli_group.plugin_manager,
|
||||
datafolder=datafolder)
|
||||
click.echo("Done.")
|
||||
|
||||
@click.command("restore")
|
||||
@click.argument("path")
|
||||
def restore_command(path):
|
||||
"""
|
||||
Restores an existing backup from the backup zip provided as argument.
|
||||
|
||||
OctoPrint does not need to run for this to proceed.
|
||||
"""
|
||||
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
|
||||
plugin_manager = cli_group.plugin_manager
|
||||
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
# register plugin manager plugin setting overlays
|
||||
plugin_info = plugin_manager.get_plugin_info("pluginmanager")
|
||||
if plugin_info and plugin_info.implementation:
|
||||
default_settings_overlay = dict(plugins=dict())
|
||||
default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults()
|
||||
settings.add_overlay(default_settings_overlay, at_end=True)
|
||||
|
||||
if not os.path.isabs(path):
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
path = os.path.join(datafolder, path)
|
||||
|
||||
if not os.path.exists(path):
|
||||
click.echo(u"Backup {} does not exist".format(path), err=True)
|
||||
sys.exit(-1)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
archive.close()
|
||||
shutil.copy(path, archive.name)
|
||||
path = archive.name
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def log(line):
|
||||
click.echo(u"\t{}".format(line))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
continue
|
||||
|
||||
click.echo(u"Installing plugin {}".format(plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.")
|
||||
for plugin in plugins:
|
||||
click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
|
||||
|
||||
def on_log_progress(line):
|
||||
click.echo(line)
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
click.echo(line, err=True)
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
click.echo(line.rstrip(), err=True)
|
||||
|
||||
if self._restore_backup(path,
|
||||
settings=settings,
|
||||
plugin_manager=plugin_manager,
|
||||
datafolder=datafolder,
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_invalid_backup=on_log_error):
|
||||
click.echo(u"Restored from {}".format(path))
|
||||
else:
|
||||
click.echo(u"Restoring from {} failed".format(path), err=True)
|
||||
|
||||
return [backup_command, restore_command]
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def _get_backups(self):
|
||||
backups = []
|
||||
for entry in scandir(self.get_plugin_data_folder()):
|
||||
if is_hidden_path(entry.path):
|
||||
continue
|
||||
if not entry.is_file():
|
||||
continue
|
||||
if not entry.name.endswith(".zip"):
|
||||
continue
|
||||
|
||||
backups.append(dict(name=entry.name,
|
||||
date=entry.stat().st_mtime,
|
||||
size=entry.stat().st_size,
|
||||
url=flask.url_for("index") + "plugin/backup/download/" + entry.name))
|
||||
return backups
|
||||
|
||||
def _get_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
if os.path.exists(data_file):
|
||||
try:
|
||||
with codecs.open(data_file, mode="r", encoding="utf-8") as f:
|
||||
unknown_plugins = json.load(f)
|
||||
|
||||
assert isinstance(unknown_plugins, list)
|
||||
assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins))
|
||||
|
||||
installed_plugins = self._plugin_manager.plugins
|
||||
unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
|
||||
if not unknown_plugins:
|
||||
# no plugins left uninstalled, delete data file
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return unknown_plugins
|
||||
except:
|
||||
self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file))
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def _clean_dir_backup(cls, basedir,
|
||||
on_log_progress=None):
|
||||
basedir_backup = basedir + ".bck"
|
||||
|
||||
if os.path.exists(basedir_backup):
|
||||
def remove_bck():
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Found config folder backup from prior restore, deleting it...")
|
||||
shutil.rmtree(basedir_backup)
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"... deleted.")
|
||||
|
||||
thread = threading.Thread(target=remove_bck)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
@classmethod
|
||||
def _get_disk_size(cls, path):
|
||||
total = 0
|
||||
for entry in scandir(path):
|
||||
if entry.is_dir():
|
||||
total += cls._get_disk_size(entry.path)
|
||||
elif entry.is_file():
|
||||
total += entry.stat().st_size
|
||||
return total
|
||||
|
||||
@classmethod
|
||||
def _free_space(cls, path, size):
|
||||
from psutil import disk_usage
|
||||
return disk_usage(path).free > size
|
||||
|
||||
@classmethod
|
||||
def _get_plugin_repository_data(cls, url, logger=None):
|
||||
if logger is None:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
except:
|
||||
logger.exception(u"Error while fetching the plugin repository data from {}".format(url))
|
||||
return dict()
|
||||
|
||||
from octoprint.plugins.pluginmanager import map_repository_entry
|
||||
return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()))
|
||||
|
||||
@classmethod
|
||||
def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None):
|
||||
if pip_args is None:
|
||||
pip_args = []
|
||||
|
||||
if on_log is None:
|
||||
on_log = logging.getLogger(__name__).info
|
||||
|
||||
# prepare pip caller
|
||||
def log(prefix, *lines):
|
||||
for line in lines:
|
||||
on_log(u"{} {}".format(prefix, line.rstrip()))
|
||||
|
||||
def log_call(*lines):
|
||||
log(u">", *lines)
|
||||
|
||||
def log_stdout(*lines):
|
||||
log(u"<", *lines)
|
||||
|
||||
def log_stderr(*lines):
|
||||
log(u"!", *lines)
|
||||
|
||||
if cls._pip_caller is None:
|
||||
cls._pip_caller = LocalPipCaller(force_user=force_user)
|
||||
|
||||
cls._pip_caller.on_log_call = log_call
|
||||
cls._pip_caller.on_log_stdout = log_stdout
|
||||
cls._pip_caller.on_log_stderr = log_stderr
|
||||
|
||||
# install plugin
|
||||
pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir']
|
||||
|
||||
if plugin.get("follow_dependency_links"):
|
||||
pip.append("--process-dependency-links")
|
||||
|
||||
if force_user:
|
||||
pip.append("--user")
|
||||
|
||||
if pip_args:
|
||||
pip += pip_args
|
||||
|
||||
cls._pip_caller.execute(*pip)
|
||||
|
||||
@classmethod
|
||||
def _create_backup(cls, name,
|
||||
exclude=None,
|
||||
settings=None,
|
||||
plugin_manager=None,
|
||||
datafolder=None,
|
||||
on_backup_start=None,
|
||||
on_backup_done=None,
|
||||
on_backup_error=None):
|
||||
try:
|
||||
if exclude is None:
|
||||
exclude = []
|
||||
|
||||
configfile = settings._configfile
|
||||
basedir = settings._basedir
|
||||
|
||||
temporary_path = os.path.join(datafolder, ".{}".format(name))
|
||||
final_path = os.path.join(datafolder, name)
|
||||
|
||||
size = cls._get_disk_size(basedir)
|
||||
if not cls._free_space(os.path.dirname(temporary_path), size):
|
||||
raise InsufficientSpace()
|
||||
|
||||
own_folder = datafolder
|
||||
defaults = [os.path.join(basedir, "config.yaml"),] + \
|
||||
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
|
||||
|
||||
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
|
||||
|
||||
if callable(on_backup_start):
|
||||
on_backup_start(name, temporary_path, exclude)
|
||||
|
||||
with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip:
|
||||
def add_to_zip(source, target, ignored=None):
|
||||
if ignored is None:
|
||||
ignored = []
|
||||
|
||||
if source in ignored:
|
||||
return
|
||||
|
||||
if os.path.isdir(source):
|
||||
for entry in scandir(source):
|
||||
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
|
||||
elif os.path.isfile(source):
|
||||
zip.write(source, arcname=target)
|
||||
|
||||
# add metadata
|
||||
metadata = dict(version=get_octoprint_version_string(),
|
||||
excludes=exclude)
|
||||
zip.writestr("metadata.json", json.dumps(metadata))
|
||||
|
||||
# backup current config file
|
||||
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
|
||||
|
||||
# backup configured folder paths
|
||||
for folder in default_settings["folder"].keys():
|
||||
if folder in exclude:
|
||||
continue
|
||||
|
||||
if folder in ("generated", "logs", "watched",):
|
||||
continue
|
||||
|
||||
add_to_zip(settings.global_get_basefolder(folder),
|
||||
"basedir/" + folder.replace("_", "/"),
|
||||
ignored=[own_folder,])
|
||||
|
||||
# backup anything else that might be lying around in our basedir
|
||||
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
|
||||
|
||||
# add list of installed plugins
|
||||
plugins = []
|
||||
plugin_folder = settings.global_get_basefolder("plugins")
|
||||
for key, plugin in plugin_manager.plugins.items():
|
||||
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
|
||||
# ignore anything bundled or from the plugins folder we already include in the backup
|
||||
continue
|
||||
|
||||
plugins.append(dict(key=plugin.key,
|
||||
name=plugin.name,
|
||||
url=plugin.url))
|
||||
|
||||
if len(plugins):
|
||||
zip.writestr("plugin_list.json", json.dumps(plugins))
|
||||
|
||||
os.rename(temporary_path, final_path)
|
||||
|
||||
if callable(on_backup_done):
|
||||
on_backup_done(name, final_path, exclude)
|
||||
except:
|
||||
if callable(on_backup_error):
|
||||
exc_info = sys.exc_info()
|
||||
try:
|
||||
on_backup_error(name, exc_info)
|
||||
finally:
|
||||
del exc_info
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def _restore_backup(cls, path,
|
||||
settings=None,
|
||||
plugin_manager=None,
|
||||
datafolder=None,
|
||||
on_install_plugins=None,
|
||||
on_report_unknown_plugins=None,
|
||||
on_invalid_backup=None,
|
||||
on_log_progress=None,
|
||||
on_log_error=None,
|
||||
on_restore_start=None,
|
||||
on_restore_done=None,
|
||||
on_restore_failed=None):
|
||||
if not is_os_compatible(["!windows"]):
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Restore is not supported on this operating system")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
basedir = settings._basedir
|
||||
cls._clean_dir_backup(basedir,
|
||||
on_log_progress=on_log_progress)
|
||||
|
||||
plugin_repo = dict()
|
||||
repo_url = settings.global_get(["plugins", "pluginmanager", "repository"])
|
||||
if repo_url:
|
||||
plugin_repo = cls._get_plugin_repository_data(repo_url)
|
||||
|
||||
if callable(on_restore_start):
|
||||
on_restore_start(path)
|
||||
|
||||
try:
|
||||
|
||||
with zipfile.ZipFile(path, "r") as zip:
|
||||
# read metadata
|
||||
try:
|
||||
metadata_zipinfo = zip.getinfo("metadata.json")
|
||||
except KeyError:
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
metadata_bytes = zip.read(metadata_zipinfo)
|
||||
metadata = json.loads(metadata_bytes)
|
||||
|
||||
backup_version = get_comparable_version(metadata["version"], base=True)
|
||||
if backup_version > get_octoprint_version(base=True):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
# unzip to temporary folder
|
||||
temp = tempfile.mkdtemp()
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacking backup to {}...".format(temp))
|
||||
abstemp = os.path.abspath(temp)
|
||||
for member in zip.infolist():
|
||||
abspath = os.path.abspath(os.path.join(temp, member.filename))
|
||||
if abspath.startswith(abstemp):
|
||||
zip.extract(member, temp)
|
||||
|
||||
# sanity check
|
||||
configfile = os.path.join(temp, "basedir", "config.yaml")
|
||||
if not os.path.exists(configfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks config.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
import yaml
|
||||
|
||||
with codecs.open(configfile) as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
|
||||
if configdata.get("accessControl", dict()).get("enabled", True):
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks users.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacked")
|
||||
|
||||
# install available plugins
|
||||
with codecs.open(os.path.join(temp, "plugin_list.json"), "r") as f:
|
||||
plugins = json.load(f)
|
||||
|
||||
known_plugins = []
|
||||
unknown_plugins = []
|
||||
if plugins:
|
||||
if plugin_repo:
|
||||
for plugin in plugins:
|
||||
if plugin["key"] in plugin_manager.plugins:
|
||||
# already installed
|
||||
continue
|
||||
|
||||
if plugin["key"] in plugin_repo:
|
||||
# not installed, can be installed from repository url
|
||||
known_plugins.append(plugin_repo[plugin["key"]])
|
||||
else:
|
||||
# not installed, not installable
|
||||
unknown_plugins.append(plugin)
|
||||
|
||||
else:
|
||||
# no repo, all plugins are not installable
|
||||
unknown_plugins = plugins
|
||||
|
||||
if callable(on_log_progress):
|
||||
if known_plugins:
|
||||
on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins))))
|
||||
if unknown_plugins:
|
||||
on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins))))
|
||||
|
||||
if callable(on_install_plugins):
|
||||
on_install_plugins(known_plugins)
|
||||
|
||||
if callable(on_report_unknown_plugins):
|
||||
on_report_unknown_plugins(unknown_plugins)
|
||||
|
||||
# move config data
|
||||
basedir_backup = basedir + ".bck"
|
||||
basedir_extracted = os.path.join(temp, "basedir")
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
|
||||
os.rename(basedir, basedir_backup)
|
||||
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
|
||||
os.rename(basedir_extracted, basedir)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
|
||||
on_log_error(u"Rolling back old config data")
|
||||
|
||||
os.rename(basedir_backup, basedir)
|
||||
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if unknown_plugins:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Writing info file about unknown plugins")
|
||||
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f:
|
||||
json.dump(unknown_plugins, f)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
|
||||
exc_info = sys.exc_info())
|
||||
|
||||
finally:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary unpacked folder")
|
||||
shutil.rmtree(temp)
|
||||
|
||||
except:
|
||||
exc_info = sys.exc_info()
|
||||
try:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while running restore", exc_info=exc_info)
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
finally:
|
||||
del exc_info
|
||||
return False
|
||||
|
||||
finally:
|
||||
# remove zip
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary zip")
|
||||
os.remove(path)
|
||||
|
||||
# restart server
|
||||
if restart_command:
|
||||
import sarge
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Restarting...")
|
||||
if callable(on_restore_done):
|
||||
on_restore_done(path)
|
||||
|
||||
try:
|
||||
sarge.run(restart_command, async_=True)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restarting via command {}".format(restart_command),
|
||||
exc_info=sys.exc_info())
|
||||
on_log_error(u"Please restart OctoPrint manually")
|
||||
return False
|
||||
|
||||
else:
|
||||
if callable(on_restore_done):
|
||||
on_restore_done(path)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _send_client_message(self, message, payload=None):
|
||||
if payload is None:
|
||||
payload = dict()
|
||||
payload["type"] = message
|
||||
self._plugin_manager.send_plugin_message(self._identifier, payload)
|
||||
|
||||
|
||||
|
||||
class InsufficientSpace(Exception):
|
||||
pass
|
||||
|
||||
__plugin_name__ = gettext(u"Backup & Restore")
|
||||
__plugin_author__ = u"Gina Häußge"
|
||||
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
|
||||
u"& restore your OctoPrint settings and data.")
|
||||
__plugin_license__ = u"AGPLv3"
|
||||
__plugin_implementation__ = BackupPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
|
||||
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
|
||||
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintBackupClient = function(base) {
|
||||
this.base = base;
|
||||
this.url = this.base.getBlueprintUrl("backup");
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.url, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
|
||||
exclude = exclude || [];
|
||||
|
||||
var data = {
|
||||
exclude: exclude
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url + "backup", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
|
||||
return this.base.delete(this.url + "backup/" + backup, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
|
||||
var data = {
|
||||
path: backup
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url + "restore", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) {
|
||||
data = data || {};
|
||||
|
||||
var filename = data.filename || undefined;
|
||||
return this.base.upload(this.url + "restore", file, filename, data);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) {
|
||||
return this.base.delete(this.url + "unknown_plugins", opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient);
|
||||
return OctoPrintBackupClient;
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
|
||||
@@ -0,0 +1,289 @@
|
||||
$(function() {
|
||||
function BackupViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
self.backups = new ItemListHelper(
|
||||
"plugin.backup.backups",
|
||||
{
|
||||
"date": function (a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"date",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
|
||||
self.markedForBackupDeletion = ko.observableArray([]);
|
||||
|
||||
self.excludeFromBackup = ko.observableArray([]);
|
||||
self.backupInProgress = ko.observable(false);
|
||||
self.restoreSupported = ko.observable(true);
|
||||
|
||||
self.backupUploadButton = $("#settings-backup-upload");
|
||||
self.backupUploadData = undefined;
|
||||
self.backupUploadButton.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
if (data.files.length === 0) {
|
||||
// no files? ignore
|
||||
return false;
|
||||
}
|
||||
|
||||
self.backupUploadName(data.files[0].name);
|
||||
self.backupUploadData = data;
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.backupUploadName(undefined);
|
||||
self.backupUploadData = undefined;
|
||||
}
|
||||
});
|
||||
self.backupUploadName = ko.observable();
|
||||
self.restoreInProgress = ko.observable(false);
|
||||
self.restoreTitle = ko.observable();
|
||||
self.restoreDialog = undefined;
|
||||
self.restoreOutput = undefined;
|
||||
self.unknownPlugins = ko.observableArray([]);
|
||||
|
||||
self.loglines = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.backup.get()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.backups.updateItems(response.backups);
|
||||
self.unknownPlugins(response.unknown_plugins);
|
||||
self.restoreSupported(response.restore_supported);
|
||||
};
|
||||
|
||||
self.createBackup = function() {
|
||||
var excluded = self.excludeFromBackup();
|
||||
OctoPrint.plugins.backup.createBackup(excluded)
|
||||
.done(function() {
|
||||
self.excludeFromBackup([]);
|
||||
})
|
||||
};
|
||||
|
||||
self.removeBackup = function(backup) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteBackup(backup)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.restoreBackup = function(backup) {
|
||||
if (!self.restoreSupported()) return;
|
||||
|
||||
var perform = function() {
|
||||
self.restoreInProgress(true);
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: "Preparing to restore...", stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.performRestoreFromUpload = function() {
|
||||
if (self.backupUploadData === undefined) return;
|
||||
|
||||
var perform = function() {
|
||||
self.restoreInProgress(true);
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
|
||||
self.backupUploadData.submit();
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.deleteUnknownPluginRecord = function() {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteUnknownPlugins()
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markFilesOnPage = function() {
|
||||
self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
|
||||
};
|
||||
|
||||
self.markAllFiles = function() {
|
||||
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedFiles = function() {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.removeMarkedFiles = function() {
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForBackupDeletion())
|
||||
.done(function() {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
|
||||
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "backup") return;
|
||||
|
||||
if (data.type === "backup_done") {
|
||||
self.requestData();
|
||||
self.backupInProgress(false);
|
||||
new PNotify({
|
||||
title: gettext("Backup created successfully"),
|
||||
type: "success"
|
||||
});
|
||||
} else if (data.type === "backup_started") {
|
||||
self.backupInProgress(true);
|
||||
} else if (data.type === "backup_error") {
|
||||
self.requestData();
|
||||
self.backupInProgress(false);
|
||||
new PNotify({
|
||||
title: gettext("Creating the backup failed"),
|
||||
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
} else if (data.type === "restore_started") {
|
||||
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
} else if (data.type === "restore_failed") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "restore_done") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "install_plugin") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}),
|
||||
stream: "message"
|
||||
});
|
||||
} else if (data.type === "plugin_incompatible") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}),
|
||||
stream: "stderr"
|
||||
});
|
||||
} else if (data.type === "unknown_plugins") {
|
||||
if (data.plugins.length > 0) {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"});
|
||||
_.each(data.plugins, function(plugin) {
|
||||
self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"});
|
||||
});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.unknownPlugins(data.plugins);
|
||||
}
|
||||
} else if (data.type === "logline") {
|
||||
self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream}));
|
||||
self._scrollRestoreOutputToEnd();
|
||||
}
|
||||
};
|
||||
|
||||
self._scrollRestoreOutputToEnd = function() {
|
||||
self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height());
|
||||
};
|
||||
|
||||
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
};
|
||||
|
||||
self._bulkRemove = function(files) {
|
||||
var title, message, handler;
|
||||
|
||||
title = gettext("Deleting backups");
|
||||
message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
|
||||
handler = function(filename) {
|
||||
return OctoPrint.plugins.backup.deleteBackup(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: files.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function(filename) {
|
||||
var request = handler(filename);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: BackupViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#settings_plugin_backup"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
#settings_plugin_backup_backup_table {
|
||||
.settings_plugin_backup_name {
|
||||
}
|
||||
.settings_plugin_backup_actions {
|
||||
width: 75px;
|
||||
text-align: center;
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
}
|
||||
.settings_plugin_backup_date {
|
||||
width: 200px;
|
||||
text-align: right;
|
||||
}
|
||||
.settings_plugin_backup_size {
|
||||
width: 100px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.settings_plugin_backup_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_backup_restoredialog_output {
|
||||
.message {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.error {
|
||||
font-weight: bold;
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.stdout {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.stderr {
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.call {
|
||||
color: #000099;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
<div class="alert" data-bind="visible: unknownPlugins().length > 0">
|
||||
{% trans %}
|
||||
Some plugins during the last restore could not be identified and hence not automatically installed.
|
||||
Please install them manually, they are listed below including their stated homepages:
|
||||
{% endtrans %}
|
||||
<ul data-bind="foreach: unknownPlugins">
|
||||
<li><span data-bind="text: name"></span>: <a data-bind="text: url, attr: {href: url}" target="_blank" rel="noreferrer noopener"></a></li>
|
||||
</ul>
|
||||
<small><a href="javascript:void(0)" data-bind="click: deleteUnknownPluginRecord">{{ _('Delete record of unknown plugins') }}</a></small>
|
||||
</div>
|
||||
|
||||
|
||||
<h3>{{ _('Existing backups') }}</h3>
|
||||
|
||||
<div data-bind="visible: backups.allSize() <= 0">
|
||||
<p>{{ _('There are no backups. Maybe create one below?') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: backups.allSize() > 0">
|
||||
<p>{{ _('These are the backups of your settings and files that already exist on this OctoPrint instance. You may delete, download or restore them.') }}</p>
|
||||
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForBackupDeletion().length > 0">{{ _('Delete selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_backup_backup_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_backup_checkbox"></th>
|
||||
<th class="settings_plugin_backup_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_backup_date">{{ _('Date') }}</th>
|
||||
<th class="settings_plugin_backup_size">{{ _('Size') }}</th>
|
||||
<th class="settings_plugin_backup_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: backups.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_backup_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForBackupDeletion"></td>
|
||||
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
|
||||
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
|
||||
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a> | <a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()"> | <a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: backups.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: backups.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: backups.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.backups.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.backups.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: backups.currentPage() === backups.lastPage()}"><a href="javascript:void(0)" data-bind="click: backups.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Create backup') }}</h3>
|
||||
|
||||
<p>{{ _('Create a new backup of the current state.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: 'timelapse', checked: excludeFromBackup"> {{ _('Exclude timelapses from backup') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: createBackup"><i class="fa fa-spinner fa-spin" data-bind="visible: backupInProgress"></i> {{ _('Create backup now') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div data-bind="visible: restoreSupported()">
|
||||
<h3>{{ _('Restore from uploaded backup') }}</h3>
|
||||
|
||||
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Backup file') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="btn fileinput-button">
|
||||
<span>{{ _('Browse...') }}</span>
|
||||
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
|
||||
</span>
|
||||
<span class="add-on" data-bind="text: backupUploadName"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div data-bind="visible: !restoreSupported()">
|
||||
{{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to <a href="%(url)s" target="_blank" rel="noopener noreferrer">restore your backups manually for now</a>.', url='https://faq.octoprint.org/manual-restore') }}
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_backup_restoredialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<h3>{{ _('Restoring from backup...') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_backup_restoredialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.restoreInProgress()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,14 +1,22 @@
|
||||
<h3>{{ _('Access Control') }}</h3>
|
||||
|
||||
{% trans %}<p>
|
||||
{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}<p>
|
||||
<strong>Please read the following, it is very important for your printer's health!</strong>
|
||||
</p>
|
||||
<p>
|
||||
OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
|
||||
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
|
||||
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
|
||||
malicious intent - to gain access to your printer</strong> via an untrustworthy network
|
||||
and using it in such a way that it is damaged or worse (i.e. causes a fire).
|
||||
</p>
|
||||
<p>
|
||||
If you plan on accessing OctoPrint remotely over the internet, <strong>you should not only rely on the built-in
|
||||
Access Control mechanisms</strong> however -
|
||||
<a href="{{ safe_remote_url }}" target="_blank" rel="noopener noreferrer">take additional precautions</a>.
|
||||
Your OctoPrint enabled printer is a critical home appliance you really should not give anyone who happens to be
|
||||
connected to the internet access to - even read-only! <strong>An instance available publicly on the internet
|
||||
will be found, and people will try to break it open.</strong>
|
||||
</p>
|
||||
<p>
|
||||
It looks like you haven't configured access control yet. Please <strong>set up a username and password</strong> for the
|
||||
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
|
||||
@@ -36,12 +44,12 @@
|
||||
</div>
|
||||
</form>
|
||||
{% trans %}<p>
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy local network and you don't
|
||||
need Access Control for other reasons, you may alternatively disable Access Control. You should only
|
||||
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
|
||||
<strong>Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!</strong>
|
||||
</p>{% endtrans %}
|
||||
|
||||
<div class="row-fluid">
|
||||
|
||||
@@ -312,7 +312,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
working_dir))
|
||||
|
||||
import sarge
|
||||
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p = sarge.run(args, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p.wait_events()
|
||||
self._slicing_commands[machinecode_path] = p.commands[0]
|
||||
|
||||
|
||||
@@ -359,6 +359,8 @@ class Profile(object):
|
||||
regex_print_temperature = re.compile("print_temperature(\d?)")
|
||||
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
|
||||
|
||||
regex_broken_replacements = re.compile("\?([a-zA-Z0-9_]*)\?")
|
||||
|
||||
@classmethod
|
||||
def from_cura_ini(cls, path):
|
||||
import logging
|
||||
@@ -685,9 +687,9 @@ class Profile(object):
|
||||
gcode = defaults[key]
|
||||
|
||||
if key in ("start_gcode", "end_gcode"):
|
||||
return gcode[extruder_count-1]
|
||||
return self.regex_broken_replacements.sub("{\\1}", gcode[extruder_count-1])
|
||||
else:
|
||||
return gcode
|
||||
return self.regex_broken_replacements.sub("{\\1}", gcode)
|
||||
|
||||
def get_profile_string(self):
|
||||
import base64
|
||||
@@ -749,17 +751,16 @@ class Profile(object):
|
||||
|
||||
if key == "start_gcode":
|
||||
contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count)
|
||||
prefix += self.get_start_gcode_prefix(contents)
|
||||
prefix += self.get_start_gcode_prefix(contents, extruder_count=extruder_count)
|
||||
|
||||
else:
|
||||
contents = self.get_gcode_template(key, extruder_count=extruder_count)
|
||||
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
|
||||
|
||||
def get_start_gcode_prefix(self, contents):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
def get_start_gcode_prefix(self, contents, extruder_count=1):
|
||||
prefix = ""
|
||||
without_comments = Profile.regex_strip_comments.sub("", contents)
|
||||
|
||||
gcode_parameter_key = "S"
|
||||
if self.get("gcode_flavor") == GcodeFlavors.MACH3:
|
||||
@@ -773,12 +774,12 @@ class Profile(object):
|
||||
bed_temp = 0
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
bed_temp = self.get_float("print_bed_temperature")
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in without_comments
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M140 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp)
|
||||
|
||||
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
|
||||
if temp > 0 and not "{print_temperature}" in without_comments:
|
||||
if extruder_count > 0:
|
||||
def temp_line(temp, extruder, param, template):
|
||||
t = temp
|
||||
|
||||
@@ -181,6 +181,15 @@ $(function() {
|
||||
self.uploadDialog.modal("hide");
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
self.uploadBusy(false);
|
||||
new PNotify({
|
||||
title: gettext("Profile import failed"),
|
||||
text: gettext("Could not import the provided profile, it might be invalid. Check <code>octoprint.log</code> for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine, valueUpdate: 'afterkeydown'">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine, valueUpdate: 'afterkeydown'" id="settings-cura-path">
|
||||
<button class="btn" type="button" data-bind="click: testEnginePath, enable: settings.plugins.cura.cura_engine(), css: {disabled: !settings.plugins.cura.cura_engine()}">{{ _('Test') }}</button>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: pathBroken() || pathOk(), text: pathText"></span>
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
</form>
|
||||
<small>{% trans %}
|
||||
You can import your existing profile <code>.ini</code> files from <strong>Cura 15.04.x or older</strong>
|
||||
here. Anything but those are <strong>not supported</strong>. That especiallymeans that <code>.json</code>
|
||||
here. Anything but those are <strong>not supported</strong>. That especially means that <code>.json</code>
|
||||
profiles from Cura 15.06.x and <code>.curaprofile</code> profiles from Cura 2.x will not work, and neither
|
||||
will custom Cura profile formats that third party tools like e.g. Repetier create.
|
||||
{% endtrans %}</small>
|
||||
|
||||
@@ -194,8 +194,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
params["txtRecord"] = pybonjour.TXTRecord(txt_record)
|
||||
|
||||
key = (reg_type, port)
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
|
||||
|
||||
counter = 1
|
||||
while True:
|
||||
try:
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self._logger.info(u"Registered '{name}' for {regtype}".format(**params))
|
||||
return True
|
||||
except pybonjour.BonjourError as be:
|
||||
if be.errorCode == pybonjour.kDNSServiceErr_NameConflict:
|
||||
# Name already registered by different service, let's try a counter postfix. See #2852
|
||||
counter += 1
|
||||
params["name"] = u"{} ({})".format(name, counter)
|
||||
else:
|
||||
raise
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
@@ -601,8 +613,14 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
alive message
|
||||
"""
|
||||
|
||||
from BaseHTTPServer import BaseHTTPRequestHandler
|
||||
from StringIO import StringIO
|
||||
try:
|
||||
# noinspection PyCompatibility
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
except ImportError:
|
||||
# noinspection PyCompatibility
|
||||
from BaseHTTPServer import BaseHTTPRequestHandler
|
||||
|
||||
from io import BytesIO
|
||||
import socket
|
||||
|
||||
socket.setdefaulttimeout(timeout)
|
||||
@@ -617,8 +635,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
class Request(BaseHTTPRequestHandler):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self, request_text):
|
||||
self.rfile = StringIO(request_text)
|
||||
self.rfile = BytesIO(request_text)
|
||||
self.raw_requestline = self.rfile.readline()
|
||||
self.error_code = self.error_message = None
|
||||
self.parse_request()
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import flask
|
||||
import flask_login
|
||||
from flask_babel import gettext
|
||||
|
||||
from collections import defaultdict
|
||||
import threading
|
||||
|
||||
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
MAX_BACKLOG_LEN = 100
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._message_backlog = defaultdict(list)
|
||||
self._message_backlog_mutex = threading.RLock()
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/viewmodel.js"]
|
||||
)
|
||||
|
||||
def will_handle_ui(self, request):
|
||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return False
|
||||
|
||||
from octoprint.server.util.flask import passive_login
|
||||
|
||||
result = passive_login()
|
||||
if hasattr(result, "status_code") and result.status_code == 200:
|
||||
# passive login successful, no need to handle that
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def on_ui_render(self, now, request, render_kwargs):
|
||||
from flask import render_template, make_response
|
||||
|
||||
"""
|
||||
Support theming of the login dialog, just in case the core UI is themed as well.
|
||||
|
||||
Example usage by a plugin:
|
||||
|
||||
def forcelogin_theming():
|
||||
from flask import url_for
|
||||
return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.forcelogin.theming": forcelogin_theming
|
||||
}
|
||||
|
||||
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
|
||||
url_for like in the example above to be prepared for any configured prefix URLs.
|
||||
"""
|
||||
additional_assets = []
|
||||
for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
|
||||
try:
|
||||
assets = hook()
|
||||
if isinstance(assets, (tuple, list)):
|
||||
additional_assets += assets
|
||||
except:
|
||||
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name))
|
||||
|
||||
render_kwargs.update(dict(forcelogin_theming=additional_assets))
|
||||
return make_response(render_template("forcelogin_index.jinja2", **render_kwargs))
|
||||
|
||||
def get_ui_custom_tracked_files(self):
|
||||
from os.path import join as opj
|
||||
|
||||
paths = [opj("static", "css", "forcelogin.css"),
|
||||
opj("static", "js", "main.js"),
|
||||
opj("static", "js", "viewmodel.js"),
|
||||
opj("static", "less", "forcelogin.less"),
|
||||
opj("templates", "parts", "forcelogin_css.jinja2"),
|
||||
opj("templates", "parts", "forcelogin_javascripts.jinja2"),
|
||||
opj("templates", "forcelogin_index.jinja2")]
|
||||
|
||||
return [opj(self._basefolder, path) for path in paths]
|
||||
|
||||
def get_ui_preemptive_caching_enabled(self):
|
||||
return False
|
||||
|
||||
def get_before_request_handlers(self):
|
||||
def check_login_required():
|
||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return
|
||||
|
||||
if flask.request.endpoint in ("api.login",):
|
||||
return
|
||||
|
||||
user = flask_login.current_user
|
||||
if user is None or user.is_anonymous() or not user.is_active():
|
||||
return flask.make_response("Forbidden", 403)
|
||||
|
||||
return [check_login_required]
|
||||
|
||||
def access_validator(self, request):
|
||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return
|
||||
|
||||
import tornado.web
|
||||
from octoprint.server.util.flask import get_flask_user_from_request
|
||||
|
||||
user = get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated():
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
def socket_register_validator(self, socket, user):
|
||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return True
|
||||
|
||||
return user is not None and not user.is_anonymous() and user.is_active()
|
||||
|
||||
def socket_authed(self, socket, user):
|
||||
with self._message_backlog_mutex:
|
||||
backlog = self._message_backlog.pop(socket, [])
|
||||
|
||||
if len(backlog):
|
||||
for message, payload in backlog:
|
||||
socket._do_emit(message, payload)
|
||||
self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog)))
|
||||
|
||||
def socket_emit_validator(self, socket, user, message, payload):
|
||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return True
|
||||
|
||||
if message in ("connected", "reauthRequired"):
|
||||
return True
|
||||
|
||||
if user is not None and not user.is_anonymous() and user.is_active():
|
||||
return True
|
||||
|
||||
with self._message_backlog_mutex:
|
||||
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
|
||||
self._message_backlog[socket].append((message, payload))
|
||||
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
|
||||
else:
|
||||
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
|
||||
|
||||
return False
|
||||
|
||||
|
||||
__plugin_name__ = "Force Login"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Forces users to login, disables read-only mode."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your "
|
||||
"OctoPrint instance. Only disable this if you are comfortable with this, your "
|
||||
"OctoPrint instance is not publicly reachable on the internet and you fully "
|
||||
"trust everyone who has access to your local network!")
|
||||
|
||||
__plugin_implementation__ = ForceLoginPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
|
||||
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
|
||||
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
|
||||
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
|
||||
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Will get included into the login dialog, NOT into the regular OctoPrint
|
||||
* web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
var overlayElement = $("#login-overlay");
|
||||
var errorElement = $("#login-error");
|
||||
var offlineElement = $("#login-offline");
|
||||
var buttonElement = $("#login-button");
|
||||
var reconnectElement = $("#login-reconnect");
|
||||
|
||||
buttonElement.click(function() {
|
||||
var usernameElement = $("#login-user");
|
||||
var passwordElement = $("#login-password");
|
||||
var rememberElement = $("#login-remember");
|
||||
|
||||
var username = usernameElement.val();
|
||||
var password = passwordElement.val();
|
||||
var remember = rememberElement.checked;
|
||||
|
||||
overlayElement.addClass("in");
|
||||
errorElement.removeClass("in");
|
||||
|
||||
OctoPrint.browser.login(username, password, remember)
|
||||
.done(function() {
|
||||
location.reload();
|
||||
})
|
||||
.fail(function() {
|
||||
usernameElement.val("");
|
||||
passwordElement.val("");
|
||||
|
||||
overlayElement.removeClass("in");
|
||||
errorElement.addClass("in");
|
||||
});
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
var OctoPrint = window.OctoPrint;
|
||||
|
||||
OctoPrint.options.baseurl = BASE_URL;
|
||||
|
||||
OctoPrint.socket.onMessage("connected", function(data) {
|
||||
var payload = data.data;
|
||||
OctoPrint.options.apikey = payload.apikey;
|
||||
|
||||
// update the API key directly in jquery's ajax options too,
|
||||
// to ensure the fileupload plugin and any plugins still using
|
||||
// $.ajax directly still work fine too
|
||||
UI_API_KEY = payload["apikey"];
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
});
|
||||
|
||||
OctoPrint.socket.onConnected = function() {
|
||||
buttonElement.prop("disabled", false);
|
||||
offlineElement.removeClass("in");
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function() {
|
||||
buttonElement.prop("disabled", true);
|
||||
offlineElement.addClass("in");
|
||||
};
|
||||
|
||||
reconnectElement.click(function() {
|
||||
OctoPrint.socket.reconnect();
|
||||
});
|
||||
|
||||
OctoPrint.socket.connect();
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* View model that takes care to redirect to / on logout in the regular
|
||||
* OctoPrint web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
function ForceLoginViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([ForceLoginViewModel, [], []]);
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
body {
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.form-signin {
|
||||
max-width: 300px;
|
||||
padding: 19px 29px 29px;
|
||||
margin: 0 auto 20px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #e5e5e5;
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
|
||||
.form-signin-heading, .checkbox {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
input[type="text"], input[type="password"] {
|
||||
font-size: 16px;
|
||||
height: auto;
|
||||
margin-bottom: 15px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
}
|
||||
|
||||
#login-error,
|
||||
#login-offline {
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
#login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.background {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #000000;
|
||||
filter:alpha(opacity=50);
|
||||
-moz-opacity:0.5;
|
||||
-khtml-opacity: 0.5;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
|
||||
.outer {
|
||||
display: table;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.inner {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
|
||||
.content {
|
||||
text-align: center;
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>OctoPrint Login</title>
|
||||
|
||||
{% include "parts/forcelogin_css.jinja2" %}
|
||||
|
||||
{% include "parts/forcelogin_javascripts.jinja2" %}
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin">
|
||||
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
|
||||
|
||||
<div id="login-error" class="alert alert-error">{{ _('Incorrect username or password.') }}</div>
|
||||
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
|
||||
|
||||
<input type="text" id="login-user" class="input-block-level" placeholder="{{ _('Username') }}">
|
||||
<input type="password" id="login-password" class="input-block-level" placeholder="{{ _('Password') }}">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="login-remember"> {{ _('Remember me') }}
|
||||
</label>
|
||||
<button class="btn btn-block btn-large btn-primary" id="login-button" type="submit">{{ _('Log in') }}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="login-overlay">
|
||||
<div class="background"></div>
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<i class="fa fa-spinner fa-spin fa-4x"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,10 @@
|
||||
<!-- le CSS -->
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("plugin.forcelogin.static", filename="css/forcelogin.css") }}">
|
||||
|
||||
{% for url in forcelogin_theming %}
|
||||
<link rel="stylesheet" href="{{ url }}">
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,15 @@
|
||||
<!-- le javascript -->
|
||||
|
||||
<script>
|
||||
var BASE_URL = "{{ url_for('index') }}";
|
||||
</script>
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
{% assets "js_client" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
<script src="{{ url_for("plugin.forcelogin.static", filename="js/main.js") }}"></script>
|
||||
@@ -100,12 +100,12 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def _get_usage(self):
|
||||
import psutil
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
|
||||
return usage.free, usage.total
|
||||
|
||||
def _getLogFiles(self):
|
||||
files = []
|
||||
basedir = settings().getBaseFolder("logs")
|
||||
basedir = settings().getBaseFolder("logs", check_writable=False)
|
||||
for entry in scandir(basedir):
|
||||
files.append({
|
||||
"name": entry.name,
|
||||
@@ -195,6 +195,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/logging.js"],
|
||||
clientjs=["clientjs/logging.js"],
|
||||
less=["less/logging.less"],
|
||||
css=["css/logging.css"])
|
||||
|
||||
|
||||