Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
777c02135e | ||
|
|
793bb714eb | ||
|
|
8229842334 | ||
|
|
38a711ac56 | ||
|
|
a8747f7e36 | ||
|
|
17e6f5d508 | ||
|
|
133a4658ee | ||
|
|
0a2e2ed297 | ||
|
|
6b41dbc12b | ||
|
|
3f4a70cf92 | ||
|
|
41eb9481b3 | ||
|
|
743d590d52 | ||
|
|
900e8a2aaf | ||
|
|
06816fb8dc | ||
|
|
cc0a17f2ac | ||
|
|
9b1b4420a3 | ||
|
|
263925625b | ||
|
|
f72dfb48e1 | ||
|
|
e064400900 | ||
|
|
107954021b | ||
|
|
99e1c3ac00 | ||
|
|
2ea8981a48 | ||
|
|
d1f54b5a22 | ||
|
|
1c55a12207 | ||
|
|
58dba3a79a | ||
|
|
e9d17f0f0f | ||
|
|
4ea76f84c5 | ||
|
|
ac345daba2 | ||
|
|
3cf694a333 | ||
|
|
26c8c5f03f | ||
|
|
f2bd5d605e | ||
|
|
0560e9da02 | ||
|
|
cec8d15b46 | ||
|
|
38c9840e30 | ||
|
|
f77e49be7f | ||
|
|
00cb71898a | ||
|
|
328c08b775 | ||
|
|
ca7aa322c3 | ||
|
|
5c20e264e2 | ||
|
|
aa65671ac7 | ||
|
|
14bd0632c0 | ||
|
|
d174d7ab80 | ||
|
|
a2d38016ec | ||
|
|
cf25291dee | ||
|
|
6d4f8266cd | ||
|
|
991dab58d5 | ||
|
|
0de0e4ea9b | ||
|
|
9b3c1947d9 | ||
|
|
364d692db2 | ||
|
|
b002e41a00 | ||
|
|
f3080daa47 | ||
|
|
06ab173b21 | ||
|
|
26789a2bb7 | ||
|
|
4a5308b4ab | ||
|
|
f4eb60dc6a | ||
|
|
a0a8d641c3 | ||
|
|
e32f469de4 | ||
|
|
8bc99f928c | ||
|
|
6221175649 | ||
|
|
b252da477c | ||
|
|
8a977e8777 | ||
|
|
65753a0539 | ||
|
|
f1518e6fe6 | ||
|
|
c7e248b142 | ||
|
|
59ca2188d9 | ||
|
|
c479c5455c | ||
|
|
ebfc6f2f26 | ||
|
|
0b1db60d8b | ||
|
|
f9c738541f | ||
|
|
6c21911eb0 | ||
|
|
fd7fdec565 | ||
|
|
b892b43ee1 | ||
|
|
14c1dfe9a3 | ||
|
|
1180e4e27b | ||
|
|
b2d70de144 | ||
|
|
0bb343e1d3 | ||
|
|
92b048c789 | ||
|
|
a6eac3911b | ||
|
|
80bc82df55 | ||
|
|
651a8f315b | ||
|
|
69f9c523f9 | ||
|
|
2364474ea6 | ||
|
|
00067768da | ||
|
|
3ef97bf4d7 | ||
|
|
5aad696c5c | ||
|
|
9837f67140 | ||
|
|
dc53942015 | ||
|
|
79581c390a | ||
|
|
c30e54d75c | ||
|
|
55adb7ca33 | ||
|
|
980b72607e | ||
|
|
ce16f861b3 | ||
|
|
51406b7c42 | ||
|
|
2fcbf49348 | ||
|
|
5f34d5df27 | ||
|
|
a0df4e78b5 | ||
|
|
772ee76e76 | ||
|
|
532ac0264d | ||
|
|
caaaa2e4e9 | ||
|
|
02aad445aa | ||
|
|
bf7d4173cd | ||
|
|
0ff0da4a7b | ||
|
|
b2552795dc | ||
|
|
4b5eff5ec6 | ||
|
|
bedcbb80be | ||
|
|
09509ca61d | ||
|
|
8bf3f4ff50 | ||
|
|
2d925a2665 | ||
|
|
490ef61e19 | ||
|
|
a1548e1c1d | ||
|
|
77e48335da | ||
|
|
14b8fd7fa5 | ||
|
|
0afa854763 | ||
|
|
3d1f3be4fc | ||
|
|
38c410f80f | ||
|
|
46bd2ce7e9 | ||
|
|
10fc631700 | ||
|
|
8f78784be3 | ||
|
|
4479dd0222 | ||
|
|
9466e5d001 | ||
|
|
4b3d883639 | ||
|
|
4439f5aad0 | ||
|
|
cb50646134 | ||
|
|
c8e5820c7d | ||
|
|
8e03dbfa14 | ||
|
|
8372b1f433 | ||
|
|
b6cf895c56 | ||
|
|
25e05418d8 | ||
|
|
2e134ba8b0 | ||
|
|
76f4ffc0a1 | ||
|
|
21cc58ad14 | ||
|
|
b65a3bb903 | ||
|
|
e49adcac85 | ||
|
|
813c2be35a | ||
|
|
3ad4b7b0a5 | ||
|
|
e7b455f880 | ||
|
|
a9819cc2f9 | ||
|
|
0b95894da1 | ||
|
|
9c3d7bbbc3 | ||
|
|
01b3b8a0e0 | ||
|
|
50983c8524 | ||
|
|
e99f762974 | ||
|
|
468155c9c8 | ||
|
|
7df78defb1 | ||
|
|
d0aa81c977 | ||
|
|
13de4b4b1d | ||
|
|
4fba88d197 | ||
|
|
77753ca026 | ||
|
|
fd53f47f86 | ||
|
|
af4f97f2df | ||
|
|
44f5916cd4 | ||
|
|
4e80d69e51 | ||
|
|
020180a4a7 | ||
|
|
a21934abba | ||
|
|
42ac133436 | ||
|
|
42018ae29a | ||
|
|
054bbd8a9b | ||
|
|
4093995ba0 | ||
|
|
d1fdbd5080 | ||
|
|
abfcc6e5aa | ||
|
|
b89b6970c6 | ||
|
|
40eb3c1072 | ||
|
|
178131945e | ||
|
|
452ee8e156 | ||
|
|
807b44a35e | ||
|
|
f4e7ab424b | ||
|
|
e88e6ba292 | ||
|
|
25c56a5402 | ||
|
|
c5e7212fa2 | ||
|
|
0f8f4579d6 | ||
|
|
12126621c5 | ||
|
|
a093dbc36f | ||
|
|
0f325b95c1 | ||
|
|
7fc0f48659 | ||
|
|
dfe345007e | ||
|
|
4fe6e0545a | ||
|
|
c84e199e87 | ||
|
|
791f0457fb | ||
|
|
56ad1841d4 | ||
|
|
b161a1f093 | ||
|
|
79f7a5a1e7 | ||
|
|
679674df22 | ||
|
|
5989d243d3 | ||
|
|
97cb0088f6 | ||
|
|
2ed36ed383 | ||
|
|
12b8a54081 | ||
|
|
a35e145649 | ||
|
|
f77be701a2 | ||
|
|
e9401b7090 | ||
|
|
b138c2bccf | ||
|
|
76c2113ad4 | ||
|
|
bfe5bc179c | ||
|
|
d7298cee06 | ||
|
|
fbcbb3f5f7 | ||
|
|
0c2169dd9c | ||
|
|
7828258fdb | ||
|
|
edb4d0fe04 | ||
|
|
69dec6e83f | ||
|
|
4d27de032d | ||
|
|
7073c12444 | ||
|
|
60be6349f5 | ||
|
|
ec55890c55 | ||
|
|
e508898564 | ||
|
|
c33e9e4c85 | ||
|
|
1f9fe8c868 | ||
|
|
8f2e4ad978 | ||
|
|
b82d955ec7 | ||
|
|
832d2f4155 | ||
|
|
c336452f6c | ||
|
|
a9b6edde2b | ||
|
|
d59ef5c711 | ||
|
|
375480c707 | ||
|
|
60cacb9447 | ||
|
|
a21f5c4497 | ||
|
|
c159ab7fe2 | ||
|
|
251ed7a2a2 | ||
|
|
e949e0198f | ||
|
|
1a6dbb3f4a | ||
|
|
10e834f623 | ||
|
|
5ce34f774e | ||
|
|
0456896d71 | ||
|
|
e06c09e206 | ||
|
|
a6d3299b91 | ||
|
|
0a7f2a209b | ||
|
|
67f7580506 | ||
|
|
aab3a7bd63 | ||
|
|
d0f5592421 | ||
|
|
bb6ea4d81b | ||
|
|
7e32e5be8f | ||
|
|
266cae3509 | ||
|
|
0dcbffb9d2 | ||
|
|
fb8c56be57 | ||
|
|
2bc0c4a77f | ||
|
|
187c09e7da | ||
|
|
5c62b33967 | ||
|
|
5db9acb359 | ||
|
|
962d6ab27f | ||
|
|
21699699b6 | ||
|
|
8fec0859d9 | ||
|
|
1b9ff1b0e2 | ||
|
|
ee2d644239 | ||
|
|
a50db4b08e | ||
|
|
6f5707a0fc | ||
|
|
cf053ddbed | ||
|
|
b1101f5150 | ||
|
|
3a9d581423 | ||
|
|
142a1b0dcb | ||
|
|
a33f44ea25 | ||
|
|
23e58d2fc1 | ||
|
|
2e897f19ac | ||
|
|
16e96743c5 | ||
|
|
4c6c764c5c | ||
|
|
e86ba9a395 | ||
|
|
c1c09d417d | ||
|
|
f8d225a768 | ||
|
|
4c3f4c2a8b | ||
|
|
cc3d34635e | ||
|
|
c81c93896b | ||
|
|
3cdc59d7f1 | ||
|
|
5156cdbe68 | ||
|
|
0915c45f72 | ||
|
|
b2c1bb4b53 | ||
|
|
3bb06a1a33 | ||
|
|
8ad165c625 | ||
|
|
841b86a017 | ||
|
|
c0c249ece9 | ||
|
|
5fc194accd | ||
|
|
ed6c01c12a | ||
|
|
e309646504 | ||
|
|
96ee80afd2 | ||
|
|
8aec836d22 | ||
|
|
697df4f3ce | ||
|
|
ac3f4d598c | ||
|
|
836fbef6d8 | ||
|
|
ce4cf38547 | ||
|
|
38a5da1c35 | ||
|
|
b205e84d4b | ||
|
|
7ab4d12548 | ||
|
|
f6c3e5991d | ||
|
|
188b59a319 | ||
|
|
b3594e367e | ||
|
|
12d40122d1 | ||
|
|
2e11a7b860 | ||
|
|
f20185db3a | ||
|
|
0db323d0c5 | ||
|
|
639d8d4c5f | ||
|
|
5e0b53b651 | ||
|
|
1ebfa4b1dd | ||
|
|
35c45df86c | ||
|
|
a50e8bbbb5 | ||
|
|
4665070601 | ||
|
|
b34fc8e05e | ||
|
|
a3ece229f2 | ||
|
|
fc53febb87 | ||
|
|
dad956b5c9 | ||
|
|
981110d4b2 | ||
|
|
cbd94a9020 | ||
|
|
77db00a2ea | ||
|
|
665078e1a4 | ||
|
|
cfae406a4c | ||
|
|
00c14e6936 | ||
|
|
6a1b162e7b | ||
|
|
a2fd39b3c4 | ||
|
|
bda2fd94e3 | ||
|
|
9e207ca8a1 | ||
|
|
5d321926bb | ||
|
|
3d3e0212c6 | ||
|
|
e3d44d7d06 | ||
|
|
d39c124f35 | ||
|
|
8603ea4b6f | ||
|
|
a681048df6 | ||
|
|
d689496802 | ||
|
|
5a23b46c11 | ||
|
|
2b96e57923 | ||
|
|
885e88a5e0 | ||
|
|
fe481e12b3 | ||
|
|
cbdf85c27a | ||
|
|
674637f6b2 | ||
|
|
9056f5d610 | ||
|
|
b55c4ef5ca | ||
|
|
b9747d0f0e | ||
|
|
0feae3ba18 | ||
|
|
1cc3ddb03c | ||
|
|
33cafbbd8a | ||
|
|
d274a9c73d | ||
|
|
c3619a3795 | ||
|
|
dffb33727d | ||
|
|
78724163b1 | ||
|
|
b6a09abb83 | ||
|
|
77b6d83e0b | ||
|
|
7c6b85a0ad | ||
|
|
df038e6a4d | ||
|
|
ce1541e956 | ||
|
|
bd1d0e6073 | ||
|
|
ff89cdf6d0 | ||
|
|
76f58e05ec | ||
|
|
2a600d7d00 | ||
|
|
4a84fa95e4 | ||
|
|
557c761e80 | ||
|
|
10cb60acca | ||
|
|
5e55d637af | ||
|
|
8942d7d50d | ||
|
|
0ad09e422d | ||
|
|
0657160389 | ||
|
|
cfde6342a8 | ||
|
|
832c27ed18 | ||
|
|
59d78ba893 | ||
|
|
7770ee3d08 | ||
|
|
2d9ad41e49 | ||
|
|
821156c9d6 | ||
|
|
9e5982be29 | ||
|
|
39c87d19b7 | ||
|
|
d029abc8f3 | ||
|
|
7b5848b9c3 | ||
|
|
53bfbf5acf | ||
|
|
917c9e54ba | ||
|
|
d8d9c7fe64 | ||
|
|
6c0f2de780 | ||
|
|
700975d670 | ||
|
|
9fac314d71 | ||
|
|
9dfee34f01 | ||
|
|
dc8473bc4d | ||
|
|
c1c75f032d | ||
|
|
9ad180c02a | ||
|
|
7795320fc8 | ||
|
|
a54c8fbeb7 | ||
|
|
337957198b | ||
|
|
2bae87b85a | ||
|
|
51959319eb | ||
|
|
6d73e6557b | ||
|
|
4c65313c7f | ||
|
|
41cf85d9db | ||
|
|
3fbd477d15 | ||
|
|
2c73dd36c5 | ||
|
|
c91fe0c4fc | ||
|
|
3bfc4725d2 | ||
|
|
b6fbe6fafd | ||
|
|
263c297bed | ||
|
|
dba95ee94f | ||
|
|
f0b63a8e7f | ||
|
|
e166765f7f | ||
|
|
15e8bbe147 | ||
|
|
853bb2fc16 | ||
|
|
ccc3c4ef32 | ||
|
|
72898360f3 | ||
|
|
2caa10f15e | ||
|
|
399ec5a909 | ||
|
|
c844217f82 | ||
|
|
f32d7c434d | ||
|
|
844494a9d5 | ||
|
|
f1254622c5 | ||
|
|
060aa1274a | ||
|
|
fe0aa0301f | ||
|
|
cda48f3b71 | ||
|
|
c69ef1598a | ||
|
|
0161d915d6 | ||
|
|
f5fad5186e | ||
|
|
2817979c3d | ||
|
|
cc44c1a981 | ||
|
|
dda3a303d2 | ||
|
|
b79606da70 | ||
|
|
fb9131f67a | ||
|
|
358a252736 | ||
|
|
fd7c81c7fb | ||
|
|
a09b54d374 | ||
|
|
2a7cebfe55 | ||
|
|
0f6edabea3 | ||
|
|
45231ea7f8 | ||
|
|
c00b46ef5c | ||
|
|
251a1ea4b5 | ||
|
|
bba9d6cc18 | ||
|
|
9bcce4e56a | ||
|
|
6465175e09 | ||
|
|
fe585e7115 | ||
|
|
b84432c8a5 | ||
|
|
c6623c8883 | ||
|
|
ef01560199 | ||
|
|
1666a1f607 | ||
|
|
4109b2f6c2 | ||
|
|
9f32e91e05 | ||
|
|
7c8f148fa8 | ||
|
|
d1c6381792 | ||
|
|
a477268beb | ||
|
|
346f818707 | ||
|
|
956d9581c5 | ||
|
|
7828ab0bf9 | ||
|
|
41e9d96815 | ||
|
|
09d1025dfc | ||
|
|
163fd83bf5 | ||
|
|
e109bf0ca6 | ||
|
|
4d324c5239 | ||
|
|
8cbf5a74b3 | ||
|
|
b24851ca05 | ||
|
|
1219939189 | ||
|
|
d72c7c144e | ||
|
|
5c0a564592 | ||
|
|
d27dd26a61 | ||
|
|
52633d0433 | ||
|
|
ea3b7ab1da | ||
|
|
a01b9fe8d4 | ||
|
|
f1cf482919 | ||
|
|
18e14aa412 | ||
|
|
c3ad1d3691 | ||
|
|
35d9775e51 | ||
|
|
fda67f48ff | ||
|
|
e97c9f954d | ||
|
|
01ad9b8b14 | ||
|
|
2d105517c9 | ||
|
|
41d8b3476c | ||
|
|
97b2a02926 | ||
|
|
517fd6f3ab | ||
|
|
fb2f9ba593 | ||
|
|
3ec2d7bd14 | ||
|
|
675a54aa05 | ||
|
|
880b99faaf | ||
|
|
5535a9aeb0 | ||
|
|
3bc77ffe3d | ||
|
|
896aad3ab0 | ||
|
|
01e970553f | ||
|
|
6613d580f2 | ||
|
|
ac6900ffb6 | ||
|
|
6465b58384 | ||
|
|
fa73fd3c14 | ||
|
|
13714dc8d9 | ||
|
|
5a6edefec1 | ||
|
|
87be930a68 | ||
|
|
627d11fa51 | ||
|
|
315a80a7a7 | ||
|
|
1b91790f5f | ||
|
|
3e5923b21e | ||
|
|
c1fdbaa1e7 | ||
|
|
6d1e28ae9c | ||
|
|
1e482369b8 | ||
|
|
a6c4f8ba3b |
No files matched your search
+45
-27
@@ -1,31 +1,34 @@
|
||||
READ THE FOLLOWING FIRST:
|
||||
|
||||
If not already done, please read the "guidelines for contributing"
|
||||
that are linked ^-- just up there in the big yellow box. Also read
|
||||
the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
|
||||
aka the Contribution Guidelines that are linked ^-- just up there
|
||||
in the big yellow box.
|
||||
|
||||
Also read the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
|
||||
|
||||
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 ..."), that belongs on
|
||||
the mailing list or the G+ community (both linked in the "guidelines
|
||||
for contributing" linked above, read it!), NOT here.
|
||||
Do not seek support here ("I need help with ...", "I have a
|
||||
question ..."), that belongs on the mailing list or the G+ community
|
||||
(both linked in the "guidelines for contributing" linked above, read
|
||||
them!), NOT here.
|
||||
|
||||
Mark requests with a "[Request]" prefix in the title please. Fully fill
|
||||
out the bug reporting template for bug reports (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).
|
||||
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 but
|
||||
When reporting a bug do NOT delete ANY lines from the template but
|
||||
those enclosed in [ and ] - and those please DO delete, they are
|
||||
only provided for your information and removing them makes your
|
||||
ticket more readable :)
|
||||
|
||||
Make sure any bug you want to repor tis still present with the CURRENT
|
||||
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.
|
||||
in safe mode - how to do that is also explained in the Contribution
|
||||
Guidelines linked up there in the big yellow box.
|
||||
|
||||
Thank you!
|
||||
|
||||
@@ -37,23 +40,36 @@ by heart ;))
|
||||
|
||||
#### What were you doing?
|
||||
|
||||
[Please describe the steps to reproduce your issue. 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.
|
||||
[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. ...
|
||||
2. ...
|
||||
3. ...
|
||||
|
||||
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 and what happened instead?
|
||||
#### What did you expect to happen?
|
||||
|
||||
#### Branch & Commit or Version of OctoPrint
|
||||
#### What happened instead?
|
||||
|
||||
#### Did the same happen when running OctoPrint in safe mode?
|
||||
|
||||
[Try to reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.]
|
||||
|
||||
#### 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, Linux, Windows, MacOS, something else? With version please.
|
||||
OctoPi's version can be found in /etc/octopi_version]
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
@@ -61,29 +77,31 @@ to also include a link to a file with which to reproduce the problem.]
|
||||
|
||||
#### Browser and Version of Browser, Operating System running Browser
|
||||
|
||||
[If applicable, always include if unsure or reporting UI issues.]
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
|
||||
[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 any kind of communication issues between OctoPrint and your printer.
|
||||
Never truncate.
|
||||
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.]
|
||||
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.]
|
||||
always include if unsure or reporting UI issues.
|
||||
|
||||
#### Screenshot(s) or video(s) showing the problem:
|
||||
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.]
|
||||
|
||||
|
||||
+9
-4
@@ -16,11 +16,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.2
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.6
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
fix/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
improve/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.6rc4
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.6rc4 a8747f7e36a03ff2449b62cdf68b8a26a6fa61b3 pep440-dev
|
||||
regressionfix/.* 1.3.6rc4 a8747f7e36a03ff2449b62cdf68b8a26a6fa61b3 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
|
||||
+10
-3
@@ -1,6 +1,6 @@
|
||||
# Authors
|
||||
|
||||
The following people have contributed to OctoPrint's code base (ordered by
|
||||
The following people have contributed to OctoPrint's code base (ordered roughly by
|
||||
date of first contribution):
|
||||
|
||||
* [Gina Häußge](https://github.com/foosel)
|
||||
@@ -61,10 +61,11 @@ date of first contribution):
|
||||
* [Siim Raud](https://github.com/2ndalpha)
|
||||
* ["geoporalis"](https://github.com/geoporalis)
|
||||
* [Andrew Malota](https://github.com/2bitoperations)
|
||||
* [Alexander Leisentritt](https://github.com/Alex9779)
|
||||
* [therealbstern](https://github.com/therealbstern)
|
||||
* [Ishwar Agarwal](https://github.com/agarwali)
|
||||
* [Kye Hoover](https://github.com/eykrevooh)
|
||||
* [Joseph Carrick](https://github.com/carricktel)
|
||||
* [Alexander Leisentritt](https://github.com/Alex9779)
|
||||
* [therealbstern](https://github.com/therealbstern)
|
||||
* [Philipp Baum](https://github.com/philphilphil)
|
||||
* [Kyle Evans](https://github.com/kevans91)
|
||||
* [Javier Martínez Arrieta](https://github.com/Javierma)
|
||||
@@ -79,6 +80,12 @@ date of first contribution):
|
||||
* [Greg Hulands](https://github.com/ghulands)
|
||||
* [Andreas Werner](https://github.com/gallore)
|
||||
* [Shawn Bruce](https://github.com/kantlivelong)
|
||||
* [Claudiu Ceia](https://github.com/ClaudiuCeia)
|
||||
* [Goswin von Brederlow](https://github.com/mrvn)
|
||||
* [Luke McKechnie](https://github.com/galamdring)
|
||||
* [Peter Backx](https://github.com/pbackx)
|
||||
* [Josh Major](https://github.com/astateofblank)
|
||||
* ["alex-gh"](https://github.com/alex-gh)
|
||||
|
||||
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
|
||||
|
||||
+335
@@ -1,5 +1,340 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.6 (2017-12-12)
|
||||
|
||||
### Note for upgraders and plugin authors: Change in the bundling of JS assets can lead to issues in plugins
|
||||
|
||||
A change to solve issues with plugins bundling JS assets that cause interference with other plugins (e.g. through the declaration of `"use strict"`) and in general to add better isolation and error handling might cause errors for some plugins that go beyond your run-off-the-mill view model and also implicitly declare new globals.
|
||||
|
||||
If you happen to run into any such issues, you can switch back to the old way of bundling JS assets via the newly introduced "Settings > Feature > Enable legacy plugin asset bundling" toggle (check it, save the settings, restart the server). This is provided to allow for a minimally invasive adjustment period until affected plugins have been updated.
|
||||
|
||||
You can find out more about the change, how to know if a plugin is even affected and what do about it [on the OctoBlog](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/).
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#203](https://github.com/foosel/OctoPrint/issues/203) - Allow selecting the current tab via URL hashs. Also update URL hash when switching tabs, thus adding this to the browser history and allowing quicker back and forth navigation through the browser's back and forward buttons.
|
||||
* [#1026](https://github.com/foosel/OctoPrint/issues/1026) - Automatically upper case parameters in GCODE commands sent from the Terminal tab. A black list is in place that prevent upper casing of parameters for GCODE commands where it doesn't make sense (default: `M117`). See also [#2177](https://github.com/foosel/OctoPrint/pull/2177).
|
||||
* [#2050](https://github.com/foosel/OctoPrint/issues/2050) - New hook [`octoprint.comm.protocol.temperatures.received`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-temperatures-received) that allows plugins to further preprocess/sanitize temperature data received from the printer.
|
||||
* [#2055](https://github.com/foosel/OctoPrint/issues/2055) - Increased the size of the API key field in the settings.
|
||||
* [#2056](https://github.com/foosel/OctoPrint/issues/2056) - Added a Copy button to the API key field in the settings and user settings.
|
||||
* [#2094](https://github.com/foosel/OctoPrint/issues/2094) - Allow UTF-8 display names for uploaded files. The files will still get an ASCII only name on disk, but the UTF-8 name used during upload will also be persisted and shown in the file list. This also allows using emojis in your file and folder names now.
|
||||
* [#2104](https://github.com/foosel/OctoPrint/issues/2104) - Allow more URL schemes for installing plugins from. Supported schemes should now mirror what `pip` itself supports: `http`, `https`, `git`, `git+http`, `git+https`, `git+ssh`, `git+git`, `hg+http`, `hg+https`, `hg+static-http`, `hg+ssh`, `svn`, `svn+svn`, `svn+http`, `svn+https`, `svn+ssh`, `bzr+http`, `bzr+https`, `bzr+ssh`, `bzr+sftp`, `bzr+ftp`, `bzr+lp`.
|
||||
* [#2109](https://github.com/foosel/OctoPrint/pull/2109) - New decorator `@firstrun_only_access` for API endpoints that should only be available before first setup has been completed.
|
||||
* [#2111](https://github.com/foosel/OctoPrint/issues/2111) - Made the file list's scroll bar wider.
|
||||
* [#2131](https://github.com/foosel/OctoPrint/issues/2131) - Added warning to restart, shutdown, reboot and update confirmations that that may disrupt ongoing prints, even those run from the printer's internal storage/SD. See also [#2146](https://github.com/foosel/OctoPrint/pull/2146) and [#2152](https://github.com/foosel/OctoPrint/pull/2152).
|
||||
* [#2138](https://github.com/foosel/OctoPrint/issues/2138) - Slightly longer timeout when attempting to read from serial during auto detection via programming mode. Might help with detection of some slower printer controllers under certain circumstances.
|
||||
* [#2200](https://github.com/foosel/OctoPrint/issues/2200) - Wrap all JS assets of plugins into one anonymous function per plugin. That way plugins using `"use strict";` won't cause hard to debug and weird issues with other plugins bundled after them. The down side is that plugins currently relying on implicit declaration of global helper functions or variables (`function convert(value) { ... }`) to be available outside of their own plugin's JS assets will now run into errors. To compensate for that while affected plugins are adjusted to declare globals explicitly (`window.convert = function(value) { ... }`), a temporary feature flag was added as "Settings > Features > Enable legacy plugin asset bundling" that switches back to the old form of bundling until plugins you rely on are updated. This flag will be removed again in a later version (currently planned for 1.3.8). See also the note above and [#2246](https://github.com/foosel/OctoPrint/issues/2246).
|
||||
* [#2229](https://github.com/foosel/OctoPrint/issues/2229) - Added note to printer profile dialog that the nozzle offsets for multi extruder setups are only to be configured if they are not already set in the printer's firmware.
|
||||
* [#2232](https://github.com/foosel/OctoPrint/issues/2232) - Disable movement distance buttons when not connected to the printer or when printing, since they don't have any use then.
|
||||
* [#2239](https://github.com/foosel/OctoPrint/pull/2239) - Improved the check summing speed, thus improving the general achievable throughput on the comm layer.
|
||||
* Allow cancelling of file transfers
|
||||
* Made check of how old an unrendered timelapse is more lenient buy looking at both the creation and last modification date and using the younger one.
|
||||
* Made notifications in general auto-close faster.
|
||||
* Make the first profile saved for a slicer the default profile for that slicer.
|
||||
* New command `server` for testing server connections on the [JS test API](http://docs.octoprint.org/en/maintenance/api/util.html#post--api-util-test).
|
||||
* New hook [`octoprint.accesscontrol.keyvalidator`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-accesscontrol-keyvalidator) that allows plugins to validate their own customized API keys to be used to access OctoPrint.
|
||||
* Updated `cookiecutter`, `requests` and `psutil` dependencies.
|
||||
* Added safety warning to first run wizard.
|
||||
* More error resilience against broken view models.
|
||||
* New sub command `octoprint safemode`. Will set the `server.startOnceInSafeMode` setting in the config so that the next (re)start of the server after issuing this command will happen in safe mode.
|
||||
* New sub command `octoprint config effective`. Will report the effective config.
|
||||
* New centralized plugin blacklist (opt-in). Allows to prevent plugins/certain versions of plugins known to cause crippling issues with the normal operation of OctoPrint to be disabled from loading, if the user has opted to do so in the settings/wizard.
|
||||
* Log how to enable `serial.log` to `serial.log` if it's disabled. That will hopefully put at least a small dent in the amount of "It's empty!" responses in tickets ;)
|
||||
* Force new Pypi index URL in `requirements.txt` as an additional work around against old tooling.
|
||||
* Prefer plain `pip` over `git` for updating OctoPrint.
|
||||
* Added environment detection and logging on startup. That should give us more information about the environment to produce a reported bug in.
|
||||
* Added OctoPi support plugin that provides information about the detected OctoPi version. Will only load if OctoPi is detected.
|
||||
* More dynamic plugin mixin detection. Now using a base class instead of having to list all types manually. Should greatly reduce overhead of adding new mixin types.
|
||||
* Support leaf merging for file extension tree, allowing to add new file extensions to types registered by default.
|
||||
* Allow non GCODE SD file transfers if registered as `machinecode` through e.g. a plugin's file extension hook. Caution: This doesn't make streaming arbitrary files to the printer via serial work magically. It merely allows that, it's up to the firmware to actually be able to handle that. Also, the regular GCODE streaming protocol is used, so if the streamed file contains control characters from that (e.g. `M29` to signal the end of the streaming process), stuff will break!
|
||||
* Added a test button for the online connectivity check.
|
||||
* Announcements plugin: Added UTM Tags.
|
||||
* Cura plugin: Less `not configured yet` logging.
|
||||
* GCODE viewer: Added advanced options that allow configuring display of bounding boxes, sorting by layers and hiding of empty layers.
|
||||
* GCODE viewer: Persist all options to local storage so they will be automatically set again the next time the GCODE viewer is used in the same browser.
|
||||
* Software update: Auto-hide "Everything is up-to-date" notification.
|
||||
* Easier copying of terminal contents thanks to dedicated copy button.
|
||||
* Timelapse: [#2067](https://github.com/foosel/OctoPrint/issues/2067) - Added rate limiting to z-based timelapse capturing to prevent issues when accidentally leaving this mode on with vase mode prints.
|
||||
* Timelapse: Refactored configuration form & added reset button to switch back to currently active settings.
|
||||
* Timelapse: Sort timelapses by modification instead of creation time (creation time can be newer if a backup restore was done).
|
||||
* Virtual printer: Support configurable ambient temperature for testing.
|
||||
* Virtual printer: Support configurable reset lines.
|
||||
* Virtual printer: Added new debug trigger `trigger_missing_lineno`.
|
||||
* Virtual printer: Allow empty/`None` prepared oks, allowing to simulate lost acknowledgements right on start.
|
||||
* Docs: [#2142](https://github.com/foosel/OctoPrint/pull/2142) - Added documentation for the bundled virtual printer plugin.
|
||||
* Docs: [#2234](https://github.com/foosel/OctoPrint/pull/2234) - Added info on how to install under Suse Linux.
|
||||
* Docs: Added example PyCharm run configuration that includes automatic dependency updates on start.
|
||||
* Docs: Added information on how to run the test suite.
|
||||
* Various refactorings
|
||||
* Various documentation updates
|
||||
* Fetch plugin blacklist (and also announcements, plugin notices and plugin repository) via https instead of http.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#2044](https://github.com/foosel/OctoPrint/pull/2044) - Fix various typos in strings and comments
|
||||
* [#2048](https://github.com/foosel/OctoPrint/pull/2048) & [#2176](https://github.com/foosel/OctoPrint/pull/2176) - Fixed various warnings during documentation generation.
|
||||
* [#2077](https://github.com/foosel/OctoPrint/issues/2077) - Fix an issue with shared nozzles and the temperature graph, causing temperature to not be reported properly when another tool but the first one is selected. See also [#2077](https://github.com/foosel/OctoPrint/pull/2123)
|
||||
* [#2108](https://github.com/foosel/OctoPrint/issues/2108) - Added no-op default action to login form so that username + password aren't sent as GET parameters if for some reason the user tries to log in before the view models are properly bound and thus the AJAX POST submission method is attached.
|
||||
* [#2111](https://github.com/foosel/OctoPrint/issues/2111) - Prevent file list's scroll bar from fading out.
|
||||
* [#2146](https://github.com/foosel/OctoPrint/issues/2147) - Fix initialization of temperature graph if it's not on the first tab due to tab reordering.
|
||||
* [#2166](https://github.com/foosel/OctoPrint/issues/2166) - Workaround for a Firefox bug that causes the Drag-n-Drop overlay to never go away if the file is dragged outside of the browser window.
|
||||
* [#2167](https://github.com/foosel/OctoPrint/issues/2167) - Fixed grammar of print time estimation tooltip
|
||||
* [#2175](https://github.com/foosel/OctoPrint/issues/2175) - Cancel printing when an external reset of the printer is detected on the serial connection.
|
||||
* [#2181](https://github.com/foosel/OctoPrint/issues/2181) - More resilience against non-standard `M115` responses.
|
||||
* [#2182](https://github.com/foosel/OctoPrint/pull/2182) - Don't start tracking non existing or nonfunctional tools if encountering a temperature command referencing said tool. See also [kantlivelong/OctoPrint-PSUControl#68](https://github.com/kantlivelong/OctoPrint-PSUControl/issues/68).
|
||||
* [#2196](https://github.com/foosel/OctoPrint/issues/2196) - Marked API key fields as `readonly` instead of `disabled` to allow their contents to be copied in Firefox (which wasn't possible before).
|
||||
* [#2203](https://github.com/foosel/OctoPrint/issues/2203) - Reset temperature offsets to 0 when disconnected from the printer.
|
||||
* [#2206](https://github.com/foosel/OctoPrint/issues/2206) - Disable pre-configured timelapse if snapshot URL of ffmpeg path are unset.
|
||||
* [#2214](https://github.com/foosel/OctoPrint/issues/2214) - Fixed temperature fields not selecting in MS Edge on focus.
|
||||
* [#2217](https://github.com/foosel/OctoPrint/pull/2217) - Fix an issue in `octoprint.util` causing a crash when running under PyPy instead of CPython.
|
||||
* [#2226](https://github.com/foosel/OctoPrint/issues/2226) - Handle `No Line Number with checksum, Last Line: ...` errors from the firmware.
|
||||
* [#2233](https://github.com/foosel/OctoPrint/pull/2233) - Respond with `411 Length Required` when content length is missing on file uploads.
|
||||
* [#2242](https://github.com/foosel/OctoPrint/issues/2242) - Fixed an issue where print time left could show "1 days" instead of "1 day".
|
||||
* [#2262](https://github.com/foosel/OctoPrint/issues/2262) (regression) - Fixed a bug causing `Error:checksum mismatch, Last Line: ...` errors from the firmware to be handled incorrectly.
|
||||
* [#2267](https://github.com/foosel/OctoPrint/issues/2267) (regression) - Fixed a bug causing the GCODE viewer to not get properly initialized due to a JS error on load if "Also show next layer" was selected.
|
||||
* [#2268](https://github.com/foosel/OctoPrint/issues/2268) (regression) - Fixed a bug causing a display error with the temperature offsets. If one offset was changed, all others seemed to revert back to 0.
|
||||
* Fixed cleanup of unrendered timelapses with certain names.
|
||||
* Fixed a caching issue with the file list API and the slicing API.
|
||||
* Fixed initial sizing of the temperature graph.
|
||||
* More resilience against corrupt `.metadata.yaml` files.
|
||||
* More resilience against corrupt/invalid entries for system actions.
|
||||
* More resilience against invalid JSON command requests.
|
||||
* More resilience against broken packages in the python environment.
|
||||
* Don't evaluate `onWebcamLoaded` more than once when switching to the webcam tab.
|
||||
* Fixed `octoprint config` sub command.
|
||||
* Fixed deactivated user accounts being able to login (albeit without a persistent session). Show fitting error instead.
|
||||
* Fixed temperature auto report after an external reset.
|
||||
* Don't log full request headers in Tornado on an error.
|
||||
* Fix displayed notification message for synchronous system commands. Was accidentally swapped with the one for asynchronous system commands.
|
||||
* GCODE viewer: Fix error on empty layers.
|
||||
* Virtual printer: Fix resend simuation.
|
||||
* Docs: Fixed CSS of line numbered listings.
|
||||
* Docs: Updated mermaid to fix a deprecation warning.
|
||||
* Fixed ordering of plugin assets, should be alphabetical based on the plugin identifier. (regression)
|
||||
* Fixed an issue causing redundant software update configuration settings to be written to `config.yaml`, in turn causing issues when downgrading to <1.3.5. (regression)
|
||||
* Fixed an issue detecting whether the installed version is a release version or a development version. (regression)
|
||||
|
||||
### More Information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.5...1.3.6)
|
||||
* Release Candidates:
|
||||
* [1.3.6rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc1)
|
||||
* [1.3.6rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc2)
|
||||
* [1.3.6rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc3)
|
||||
* A special **Thank you!** to everyone who reported back on these release candidates this time: [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [bjarchi](https://github.com/bjarchi), [chippypilot](https://github.com/chippypilot), [ChrisHeerschap](https://github.com/ChrisHeerschap), [cosmith71](https://github.com/cosmith71), [Crowlord](https://github.com/Crowlord), [ctgreybeard](https://github.com/ctgreybeard), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [jbjones27](https://github.com/jbjones27), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [Lordxv](https://github.com/Lordxv), [malnvenshorn](https://github.com/malnvenshorn), [mcp5500](https://github.com/mcp5500), [ntoff](https://github.com/ntoff), [ripp2003](https://github.com/ripp2003) and [schorsch3000](https://github.com/schorsch3000)
|
||||
|
||||
## 1.3.5 (2017-10-16)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#1162](https://github.com/foosel/OctoPrint/pull/1162) - Allow `octoprint.comm.protocol.gcode.queuing` hook to return a list of commands.
|
||||
* [#1572](https://github.com/foosel/OctoPrint/issues/1572) & [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Refactored web interface startup process to minimise risk of race conditions and speed improvements. Also added sequence diagram to the documentation showing the new processing order.
|
||||
* [#1640](https://github.com/foosel/OctoPrint/issues/1640) - Mouse over temperature graph to get exact data for that time.
|
||||
* [#1679](https://github.com/foosel/OctoPrint/issues/1679) - Support temperature autoreporting by the firmware instead of polling if the firmware reports to support it. For this to work with Marlin 1.1.0 to 1.1.3 you'll need to explicitly enable `EXTENDED_CAPABILITIES_REPORT` *and* `AUTO_REPORT_TEMPERATURES` in your firmware configuration, otherwise your firmware won't report that it actually supports this feature.
|
||||
* [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder).
|
||||
* [#1842](https://github.com/foosel/OctoPrint/issues/1842) - Update bundled FontAwesome to 4.7 (see also [#1915](https://github.com/foosel/OctoPrint/pull/1915)).
|
||||
* [#1910](https://github.com/foosel/OctoPrint/issues/1910) - Make last/pause/cancel temperature available for GCODE scripts.
|
||||
* [#1925](https://github.com/foosel/OctoPrint/issues/1925) - Include configured webcam stream URL in "Webcam stream not loaded" message for logged in users/admins. Slightly different wording for guests vs users vs admins.
|
||||
* [#1941](https://github.com/foosel/OctoPrint/issues/1941) - Enable "block while dwelling" flag when Malyan firmware is detected since that firmware seems to handle `G4` identically to Repetier Firmware instead of Marlin (like it claims to). See also [#1762](https://github.com/foosel/OctoPrint/issues/1762).
|
||||
* [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Add option to disable position logging on cancel/pause. See "Log position on cancel" and "Log position on pause" under Settings > Serial > Advanced options.
|
||||
* [#1971](https://github.com/foosel/OctoPrint/issues/1971) - Refactored temperature inputs. They now sport some fancy +/- buttons to increment/decrement the current temperature (which also auto submit after a couple of seconds) and easier editing by keyboard. The temperature offset was also slightly redesigned to make room for that.
|
||||
* [#1975](https://github.com/foosel/OctoPrint/issues/1975) - Better error reporting when deleting timelapses.
|
||||
* [#2010](https://github.com/foosel/OctoPrint/pull/2010) - Slight refactoring in the terminal tab: Full width input field, auto focus of input field when just clicking on terminal output.
|
||||
* [#2011](https://github.com/foosel/OctoPrint/issues/2011) - Centralized online connectivity check (with opt-in of course). None of the bundled plugins will attempt to fetch data from the net when the connectivity check indicates that would fail anyhow. This should improve server startup times and various requests when running isolated.
|
||||
* [#2025](https://github.com/foosel/OctoPrint/issues/2025) - More verbose logging of asynchronous system commands (e.g. restart/shutdown).
|
||||
* Allow timelapse configuration through UI even when not connected to the printer (suggested in [#1918](https://github.com/foosel/OctoPrint/issues/1918))
|
||||
* Disable "Upload to SD" UI elements while printing (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
|
||||
* Update bundled SockJS to 1.1.2 incl. source maps
|
||||
* Set `X-Robots` HTTP header and remove `Server` header from all responses, also set `robots` meta tag in page.
|
||||
* Don't require to enter programmer mode for printer port autodetection when there's only one possible port candidate anyhow.
|
||||
* More sensible sorting of baudrates (additionally configured, then 115200, then 250000, then everything else).
|
||||
* Don't show "Unhandled communication error" on autodetection failure.
|
||||
* Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937))
|
||||
* Add `ToolChange` event and tool change GCODE scripts
|
||||
* Support parsing GCODE subcodes.
|
||||
* Add `octoprint.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses.
|
||||
* Corewizard: Disable view model and client code if it's not actually required.
|
||||
* Corewizard: Disable injection of JS files into UI when it's not actually required.
|
||||
* GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems.
|
||||
* GCODE viewer: Ignore coordinates outside bed when zooming/centering on model. Those usually are nozzle priming routines.
|
||||
* JS Client Lib: Add centralized browser detection as `OctoPrint.coreui.browser`. Available properties: `chrome`, `firefox`, `safari`, `ie`, `edge`, `opera` as well as `mobile` and `desktop`, all of which are boolean values.
|
||||
* Plugin Manager plugin: Detect if a plugin requires a reconnect to the printer to become fully active/inactive.
|
||||
* Software Update plugin: Force exact version when updating OctoPrint and tracking releases.
|
||||
* Software Update plugin: "Devel RCs" release channel now also tracks maintenance RCs. That way people don't have to toggle between the two any more to get *all* RCs.
|
||||
* Software Update plugin: `bitbucket_commit` check type now supports API credentials (see also [#1993](https://github.com/foosel/OctoPrint/pull/1993)).
|
||||
* Wizard: Allow suppressing the "the settings got updated" dialog through subwizards, in case they need to update settings asynchronously as part of their workflow.
|
||||
* More resilience against expected folders being files.
|
||||
* More resilience against a wrong user manager class being configured.
|
||||
* Some code refactoring & cleanup.
|
||||
* Some HTML & CSS improvements.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#1916](https://github.com/foosel/OctoPrint/issues/1916) - Fix webcam not loading if first/initial tab is "Control"
|
||||
* [#1924](https://github.com/foosel/OctoPrint/issues/1924) - Filter out source map links from bundled JS webassets.
|
||||
* [#1943](https://github.com/foosel/OctoPrint/issues/1943) - Fix issue causing unnecessary creation of default printer profile on startup
|
||||
* [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Decouple writing of print log from everything else. Fixes delay in cancel processing.
|
||||
* [#1963](https://github.com/foosel/OctoPrint/issues/1963) & [#1974](https://github.com/foosel/OctoPrint/issues/1974) - Allow empty & custom size in print job events. Also fixes an issue with timelapses when printing from SD on printers that require the GPX plugin to work.
|
||||
* [#1996](https://github.com/foosel/OctoPrint/issues/1996) - Support all line ending variantes in the GCODE viewer. Solves an issue with GCODE generated for Prusa's multi material extruder since that uses only `\r` for some reason.
|
||||
* [#2007](https://github.com/foosel/OctoPrint/issues/2007) - Fix issue parsing temperature lines from the printer that contain negative values.
|
||||
* [#2012](https://github.com/foosel/OctoPrint/issues/2012) - Fix command line interface of Software Update plugin.
|
||||
* [#2017](https://github.com/foosel/OctoPrint/issues/2017) - Fix issue in GCODE viewer with files that contain a visit to the first layer twice (e.g. brim, then nose dive from higher z for actual model), causing all but the last layer segment to not be rendered.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for legend in graph not updating with current values on mouse over.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for new temperature inputs not fitting on one line in Firefox.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab & GCODE viewer: Fix for available tools (and offsets) not properly updating on change of printer profile.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Wizard: Fix sorting of required wizards not properly handling non-ASCII unicode.
|
||||
* [#2035](https://github.com/foosel/OctoPrint/issues/2035) (regression) - Fix an issue of the server not starting up if there's a file in the analysis backlog. The reason for this is that spawning a new process while the intermediary server is active causes the server port to be blocked (this is due to how subprocessing works by default), in turn leading to an error on startup since the port cannot be bound by the actual server. Since the GCODE analysis takes now place in its own subprocess and hence triggers this problem, it had to be moved until after the actual server has already started up to avoid this problem.
|
||||
* [#2059](https://github.com/foosel/OctoPrint/issues/2059) (regression) - Fix an issue causing the new temperature controls to wrap on touch enabled devices when the temperature dropdown is opened.
|
||||
* [#2090](https://github.com/foosel/OctoPrint/issues/2090) (regression) - Fix an issue causing an aborted server startup under Windows if the timing is just right.
|
||||
* [#2135](https://github.com/foosel/OctoPrint/issues/2135) (regression) - Fix an issue causing import errors inside the GCODE analysis tool in certain environments due to `sys.path` entries causing relative imports.
|
||||
* [#2136](https://github.com/foosel/OctoPrint/issues/2136) (regression) - Fix wrong minimum version for `sockjs-tornado` dependency.
|
||||
* [#2137](https://github.com/foosel/OctoPrint/issues/2137) (regression) - Fix issue with session cookies getting lost when running an OctoPrint instance on a subpath of another (e.g. `octopi.local/` and `octopi.local/octoprint2`).
|
||||
* [#2140](https://github.com/foosel/OctoPrint/issues/2140) (regression) - Fix issue with locale dependent sorting of sub wizards during first time setup causing issues leading to the wizard not being able to complete.
|
||||
* Fix various popup buttons allowing multiple clicks (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
|
||||
* Software Update Plugin: Perform server restart asynchronously. Should reduce restart times on updates significantly.
|
||||
* Don't hex-escape `\t`, `\r` or `\n` in terminal output
|
||||
* Use client side default printer profile if the default profile could not be found on the server
|
||||
* Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances.
|
||||
* Fix potential race condition in resend request handling.
|
||||
* Fix potential race condition in web socket handling.
|
||||
* Fix handling of tool offsets in GCODE analysis - diverted too far from firmware implementations, causing wrong calculations.
|
||||
* Fix `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved` events not being fired with the correct event name.
|
||||
* Fix potential division by zero in progress reporting if the timing was just right.
|
||||
* Fix sorting order for multiple tools in the "State" panel.
|
||||
* Fix file position vs. line ending handling in GCODE viewer. Could lead to slightly off file position calculation and hence possibly to the wrong move being plotted when synchronizing with print progress.
|
||||
* Wizard: Fix `onWizardPreventSettingsRefreshDialog` callback invocation. (regression)
|
||||
* Corewizard plugin: Fix `firstrunonly` wizards (e.g. for printer profile configuration) being displayed again if _any_ of the sub wizards (e.g. for the online check opt-in and configuration) is active. (regression)
|
||||
* Fix an issue causing rollover of `serial.log` to fail under Windows. (regression)
|
||||
|
||||
### More Information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5)
|
||||
* Release Candidates:
|
||||
* [1.3.5rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc1)
|
||||
* [1.3.5rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc2)
|
||||
* [1.3.5rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc3)
|
||||
* [1.3.5rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc4)
|
||||
* A special **Thank you!** to everyone who reported back on these release candidates this time: [alexxy](https://github.com/alexxy), [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [BillyBlaze](https://github.com/BillyBlaze), [CapnBry](https://github.com/CapnBry), [chippypilot](https://github.com/chippypilot), [ctgreybeard](https://github.com/ctgreybeard), [cxt666](https://github.com/cxt666), [DaSTIG](https://github.com/DaSTIG), [fhbmax](https://github.com/fhbmax), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [mgrl](https://github.com/mgrl), [MoonshineSG](https://github.com/MoonshineSG), [nate-ubiquisoft](https://github.com/nate-ubiquisoft), [Neoolog](https://github.com/Neoolog), [ntoff](https://github.com/ntoff), [oferfrid](https://github.com/oferfrid), [roygilby](https://github.com/roygilby), [SAinc](https://github.com/SAinc), [sbts](https://github.com/sbts), [thess](https://github.com/thess), [tkurbad](https://github.com/tkurbad), [tsillini](https://github.com/tsillini) and [TylonHH](https://github.com/TylonHH).
|
||||
|
||||
## 1.3.4 (2017-06-01)
|
||||
|
||||
### Note for owners of Malyan M200/Monoprice Select Mini
|
||||
|
||||
OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically:
|
||||
|
||||
* Always assume SD card is present (`feature.sdAlwaysAvailable`)
|
||||
* Send a checksum with the command: Always (`feature.alwaysSendChecksum`)
|
||||
|
||||
Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)!
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#1942](https://github.com/foosel/OctoPrint/issues/1942) - Fixed crash on startup in case of an invalid default printer profile combined with "auto-connect on startup" being selected and the printer available to connect to.
|
||||
|
||||
### More information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2)
|
||||
* Release Candidates:
|
||||
* None since this constitutes a hotfix release to fix an apparently very rare bug introduced with 1.3.3 that seems to be affecting a small number of users.
|
||||
|
||||
## 1.3.3 (2017-05-31)
|
||||
|
||||
### Note for owners of Malyan M200/Monoprice Select Mini
|
||||
|
||||
OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically:
|
||||
|
||||
* Always assume SD card is present (`feature.sdAlwaysAvailable`)
|
||||
* Send a checksum with the command: Always (`feature.alwaysSendChecksum`)
|
||||
|
||||
Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)!
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#478](https://github.com/foosel/OctoPrint/issues/478) - Made webcam stream container fixed height (with selectable aspect ratio) to prevent jumps of the controls beneath it on load.
|
||||
* [#748](https://github.com/foosel/OctoPrint/issues/748) - Added delete confirmation and bulk delete for timelapses. See also the discussion in brainstorming ticket [#1807](https://github.com/foosel/OctoPrint/issues/1807).
|
||||
* [#1092](https://github.com/foosel/OctoPrint/issues/1092) - Added new events to the file manager: `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved`. Contrary to the `Upload` event, `FileAdded` will always fire when a file was added to storage through the file manager, not only when added through the web interface. Extended documentation accordingly.
|
||||
* [#1521](https://github.com/foosel/OctoPrint/issues/1521) - Software update plugin: Display timestamp of last version cache refresh in "Advanced options" area.
|
||||
* [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Treat default/initial printer profile like all other printer profiles, persisting it to disk instead of `config.yaml` and allowing deletion. OctoPrint will migrate the existing default profile to the new location on first start.
|
||||
* [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Better communication of what actions are available for printer profiles.
|
||||
* [#1739](https://github.com/foosel/OctoPrint/issues/1739) - Software update plugin: Added option to hide update notification from users without admin rights, added "ignore" button and note to get in touch with an admit to update notifications for non admin users.
|
||||
* [#1762](https://github.com/foosel/OctoPrint/issues/1762) - Added Malyan M200/Monoprice Select Mini to firmware autodetection.
|
||||
* [#1811](https://github.com/foosel/OctoPrint/issues/1811) - Slight rewording and rearrangement in timelapse configuration, better feedback if settings have been saved.
|
||||
* [#1818](https://github.com/foosel/OctoPrint/issues/1818) - Support both Marlin/Repetier and Smoothieware interpretations of `G90` after an `M83` in GCODE viewer and analysis. Select "G90/G91 overrides relative extruder mode" in Settings > Features for the Smoothieware interpretation.
|
||||
* [#1858](https://github.com/foosel/OctoPrint/issues/1858) - Announcement plugin: Images from registered feeds now are lazy loading.
|
||||
* [#1862](https://github.com/foosel/OctoPrint/issues/1862) - Automatically re-enable fancy terminal functionality when performance recovers.
|
||||
* [#1875](https://github.com/foosel/OctoPrint/issues/1875) - Marked the command input field in the Terminal tab as not supporting autocomplete to work around an issue in Safari. Note that this is probably only a temporary workaround due to browser vendors [working on deprecating `autocomplete="off"` support](https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164) and a different solution will need to be found in the future.
|
||||
* Added link to [`SerialException` FAQ entry](https://github.com/foosel/OctoPrint/wiki/FAQ#octoprint-randomly-loses-connection-to-the-printer-with-a-serialexception) to terminal output when such an error is encountered, as suggested in [#1876](https://github.com/foosel/OctoPrint/issues/1876).
|
||||
* Force refresh of settings on login/logout.
|
||||
* Made system wide API key management mirror user API key management.
|
||||
* Make sure to always migrate and merge saved printer profiles with default profile to ensure all parameters are set. Should avoid issues with plugins trying to save outdated/incomplete profiles.
|
||||
* Added note on lack of language pack repository & to use the wiki for now.
|
||||
* Earlier validation of file to select for printing.
|
||||
* Limit verbosity of failed system event handlers.
|
||||
* Made bundled python client `octoprint_client` support multiple client instances.
|
||||
* Disable "Reload" button in the "Please reload" overlay once clicked, added spinner.
|
||||
* Updated pnotify to 2.1.0.
|
||||
* Get rid of ridiculous float precision in temperature commands.
|
||||
* Detect invalid settings data to persist (not a dict), send 400 status in such a case.
|
||||
* More logging for preemptive caching, to help narrow down any performance issues that might be related to this.
|
||||
* Further decoupling of some startup tasks from initial server startup thread for better parallelization and improved startup times.
|
||||
* Announcement plugin: Added combined OctoBlog feed, replacing news and spotlight feed, added corresponding config migration.
|
||||
* Announcement plugin: Subscribe to all registered feeds by default to ensure better communication flow (all subscriptions but the "Important" channel can however be unsubscribed easily, added corresponding note to the notifications and also a configuration button to the announcement reader).
|
||||
* Announcement plugin: Auto-hide announcements on logout.
|
||||
* Announcement plugin: Order channels server-side based on new order config setting.
|
||||
* Plugin manager: Show warning when disabling a bundled plugin that is not recommended to be disabled, including a reason why disabling it is not recommended. Applies to the bundled announcement, core wizard, discovery and software update plugins.
|
||||
* Plugin manager: Support for plugin notices for specific plugins from the plugin repository, e.g. to inform users of specific plugins about known issues with the plugin or instruct to update when the software update mechanism of the current plugin version turns out to be misconfigured. Supports matching installed plugin versions and OctoPrint versions to target only affected users.
|
||||
* Plugin manager: Better visualization of plugins disabled on the repository, no longer shown as "incompatible" but "disabled", with link to the plugin repository page that contains more information.
|
||||
* Plugin manager: Detect necessity to reinstall a plugin provided through archive URL or upload and immediately do that instead of reporting an "unknown error" without further information.
|
||||
* Plugin manager: Added `freebsd` for compatibility check.
|
||||
* Plugin manager: More general flexibility for OS compatibility check:
|
||||
* Support for arbitrary values to match against
|
||||
* Allow 1:1 check again `sys.platform` values (with `startswith`).
|
||||
* Support black listing (`!windows`) additionally to white listing. A detected OS must match all provided white list elements (if the white list is empty that is considered to be always the case) and none of the black list elements (if the black list is empty that is also considered to be always the case).
|
||||
* Software update plugin: New check type `bitbucket_commit` (see also [#1898](https://github.com/foosel/OctoPrint/pull/1898))
|
||||
* Docs: Now referring to dedicated Jinja 2.8 documentation as hosted at [jinja.octoprint.org](http://jinja.octoprint.org) for all template needs, to avoid confusion when consulting current Jinja documentation as available on its project page (2.9+, which OctoPrint can't upgrade to due to backwards incompatible changes).
|
||||
* Docs: Better documentation of what kind of input the `FileManager` accepts for `select_file`.
|
||||
* Docs: Specified OctoPrint version required for plugin tutorial.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#202](https://github.com/foosel/OctoPrint/issues/202) - Fixed an issue with the drag-n-drop area flickering if the mouse was moved too slow while dragging (see also [#1867](https://github.com/foosel/OctoPrint/pull/1867)).
|
||||
* [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed obsolete entry of no longer available filter for empty folders from file list options.
|
||||
* [#1821](https://github.com/foosel/OctoPrint/issues/1821) - Properly reset "Capture post roll images" setting in timelapse configuration when switching from "off" to "timed" timelapse mode.
|
||||
* [#1822](https://github.com/foosel/OctoPrint/issues/1822) - Properly reset file metadata when a file is overwritten with a new version.
|
||||
* [#1836](https://github.com/foosel/OctoPrint/issues/1836) - Fixed order of `PrintCancelled` and `PrintFailed` events on print cancel.
|
||||
* [#1837](https://github.com/foosel/OctoPrint/issues/1837) - Fixed a race condition causing OctoPrint trying to read data from the current job on job cancel that was no longer there.
|
||||
* [#1838](https://github.com/foosel/OctoPrint/issues/1838) - Fixed a rare race condition causing an error right at the very start of a print.
|
||||
* [#1863](https://github.com/foosel/OctoPrint/issues/1863) - Fixed an issue in the analysis of GCODE files containing coordinate offsets for X, Y or Z via `G92`, leading to a wrong calculation of the model size thanks to accumulating offsets.
|
||||
* [#1882](https://github.com/foosel/OctoPrint/issues/1882) - Fixed a rare race condition occurring at the start of streaming a file to the printer's SD card, leading to endless line number mismatches.
|
||||
* [#1884](https://github.com/foosel/OctoPrint/issues/1884) - CuraEngine plugin: Fixed a potential encoding issue when logging non-ASCII parameters supplied to CuraEngine
|
||||
* [#1891](https://github.com/foosel/OctoPrint/issues/1891) - Fixed error when handling unicode passwords.
|
||||
* [#1893](https://github.com/foosel/OctoPrint/issues/1893) - CuraEngine plugin: Fixed handling of multiple consecutive uploads of slicing profiles (see also [#1894](https://github.com/foosel/OctoPrint/issues/1894))
|
||||
* [#1897](https://github.com/foosel/OctoPrint/issues/1897) - Removed possibility to concurrently try to perform multiple tests of the configured snapshot URL.
|
||||
* [#1906](https://github.com/foosel/OctoPrint/issues/1906) - Fixed interpretation of `G92` in GCODE analysis.
|
||||
* [#1907](https://github.com/foosel/OctoPrint/issues/1907) - Don't send temperature commands with tool parameter when a shared nozzle is defined.
|
||||
* [#1917](https://github.com/foosel/OctoPrint/issues/1917) (regression) - Fix job data resetting on print job completion.
|
||||
* [#1918](https://github.com/foosel/OctoPrint/issues/1918) (regression) - Fix "save as default" checkbox not being disabled when other controls are disabled.
|
||||
* [#1919](https://github.com/foosel/OctoPrint/issues/1919) (regression) - Fix call to no longer existing function in Plugin Manager UI.
|
||||
* [#1934](https://github.com/foosel/OctoPrint/issues/1934) (regression) - Fix consecutive timed timelapse captures without configured post roll.
|
||||
* Fixed API key QR Code being shown (for "n/a" value) when no API key was set.
|
||||
* Fixed timelapse configuration API not returning 400 status code on some bad parameters.
|
||||
* Fixed a typo (see also [#1826](https://github.com/foosel/OctoPrint/pull/1826)).
|
||||
* Fixed `filter` and `force` parameters on `/api/files/<origin>`.
|
||||
* Fixed message catchall `*` not working in the socket client library.
|
||||
* Fixed analysis backlog calculation for sub folders.
|
||||
* Fixed `PrinterInterface.is_ready` to behave as documented.
|
||||
* Use black listing instead of white listing again to detect if the `daemon` sub command is supported or not. Should resolve issues users of FreeBSD and the like where having with `octoprint daemon`.
|
||||
* Use `pip` instead of `python setup.py develop` in `octoprint dev plugin:install` command to avoid issues on Windows.
|
||||
* Docs: Fixed a wrong command in the plugin tutorial (see also [#1860](https://github.com/foosel/OctoPrint/pull/1860)).
|
||||
|
||||
### More information
|
||||
|
||||
- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.2...1.3.3)
|
||||
- Release Candidates:
|
||||
- [1.3.3rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc1)
|
||||
- [1.3.3rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc2)
|
||||
- [1.3.3rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc3)
|
||||
|
||||
## 1.3.2 (2017-03-16)
|
||||
|
||||
### Note for plugin authors
|
||||
|
||||
+48
-8
@@ -142,6 +142,12 @@ only provided here as some additional information for you), **even if only addin
|
||||
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. ...
|
||||
2. ...
|
||||
3. ...
|
||||
|
||||
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.]
|
||||
|
||||
@@ -149,10 +155,20 @@ only provided here as some additional information for you), **even if only addin
|
||||
|
||||
#### What happened instead?
|
||||
|
||||
#### Branch & Commit or Version of OctoPrint
|
||||
#### Did the same happen when running OctoPrint in safe mode?
|
||||
|
||||
[Try to reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.]
|
||||
|
||||
#### 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]
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
@@ -163,7 +179,8 @@ only provided here as some additional information for you), **even if only addin
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
|
||||
[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
|
||||
|
||||
@@ -178,16 +195,19 @@ only provided here as some additional information for you), **even if only addin
|
||||
#### 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.]
|
||||
always include if unsure or reporting UI issues.
|
||||
|
||||
#### Screenshot(s) showing the problem:
|
||||
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.
|
||||
|
||||
Copy-paste this template **completely**. Do not skip any lines or the bot
|
||||
*will* complain!
|
||||
Copy-paste this template **completely** (or use the version that gets pre-filled
|
||||
into the "new issue" form). Do not skip any lines or the bot *will* complain! Provide
|
||||
all requested information or your ticket will be closed.
|
||||
|
||||
### Where can I find which version and branch I'm on?
|
||||
|
||||
@@ -243,6 +263,8 @@ See [How to open the Javascript Console in different browsers](https://webmaster
|
||||
## Setting up a development environment
|
||||
|
||||
See [the corresponding chapter in the documentation](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment).
|
||||
This also includes information on how to run the test suite and how to build
|
||||
the documentation.
|
||||
|
||||
## Pull requests
|
||||
|
||||
@@ -283,7 +305,17 @@ See [the corresponding chapter in the documentation](http://docs.octoprint.org/e
|
||||
* Make sure you do not add dead code (e.g. commented out left-overs
|
||||
from experiments).
|
||||
8. Ensure your changes **pass the existing unit tests**. PRs that break
|
||||
those cannot be accepted.
|
||||
those cannot be accepted. You can run the unit tests locally (after
|
||||
[initial development environment setup with "develop" dependencies](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment))
|
||||
by running
|
||||
|
||||
```
|
||||
nosetests --with-doctest
|
||||
```
|
||||
|
||||
in the OctoPrint checkout folder. A [travis build](https://travis-ci.org/foosel/OctoPrint)
|
||||
is also setup so that if the tests should fail, your PR will be marked
|
||||
accordingly.
|
||||
9. **Test your changes thoroughly**. That also means testing with usage
|
||||
scenarios you don't normally use, e.g. if you only use access control, test
|
||||
without and vice versa. If you only test with your printer, test with the
|
||||
@@ -345,10 +377,16 @@ There are three main branches in OctoPrint:
|
||||
the `maintenance` branch and are now being pushed on the "Maintenance"
|
||||
pre release channel for further testing. Version number follows the scheme
|
||||
`<x>.<y>.<z>rc<n>` (e.g. `1.2.9rc1`).
|
||||
* `staging/maintenance`: Any preparation for potential follow-up RCs takes place here.
|
||||
Version number follows the scheme `<x>.<y>.<z>rc<n+1>.dev<commits since increase of n>` (e.g.
|
||||
`1.2.9rc1.dev3`) for a current Maintenance RC of `<x>.<y>.<z>rc<n>`.
|
||||
* `rc/devel`: This branch is reserved for future releases that have graduated from
|
||||
the `devel` branch and are now being pushed on the "Devel" pre release channel
|
||||
for further testing. Version number follows the scheme `<x>.<y+1>.0rc<n>` (e.g. `1.3.0rc1`)
|
||||
for a current stable OctoPrint version of `<x>.<y>.<z>`.
|
||||
* `staging/devel`: Any preparation for potential follow-up Devel RCs takes place
|
||||
here. Version number follows the scheme `<x>.<y>.0rc<n+1>.dev<commits since increase of n>` (e.g.
|
||||
`1.3.0rc1.dev12`) for a current Devel RC of `<x>.<y>.0rc<n>`.
|
||||
|
||||
Additionally, from time to time you might see other branches pop up in the repository.
|
||||
Those usually have one of the following prefixes:
|
||||
@@ -360,7 +398,7 @@ Those usually have one of the following prefixes:
|
||||
* `dev/...` or `feature/...`: New functionality under development that is to be merged
|
||||
into the `devel` branch.
|
||||
|
||||
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of
|
||||
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a few
|
||||
older development branches that are slowly being migrated or deleted.
|
||||
|
||||
## How OctoPrint is versioned
|
||||
@@ -405,6 +443,8 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 2017-03-09: Allow PRs against `maintenance` branch for bugs in stable.
|
||||
* 2017-03-10: Reproduce bugs in safe mode to make sure they are really caused
|
||||
by OctoPrint itself and not a misbehaving plugin.
|
||||
* 2017-03-27: Added safe mode section to ticket template.
|
||||
* 2017-11-22: Added note on how to run the unit tests
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
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).
|
||||
|
||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||
|
||||
The official plugin repository can be reached at [plugins.octoprint.org](http://plugins.octoprint.org).
|
||||
The official plugin repository can be reached at [plugins.octoprint.org](https://plugins.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
OctoPrint's development wouldn't be possible without the [financial support by its community](http://octoprint.org/support-octoprint/).
|
||||
If you enjoy OctoPrint, please consider becoming a regular supporter!
|
||||
**OctoPrint's development wouldn't be possible without the [financial support by its community](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
|
||||
If you enjoy OctoPrint, please consider becoming a regular supporter!**
|
||||
|
||||

|
||||
|
||||
@@ -29,7 +29,7 @@ Contributions of all kinds are welcome, not only in the form of code but also wi
|
||||
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), support
|
||||
of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues),
|
||||
[the Mailinglist](https://groups.google.com/group/octoprint) or
|
||||
[the G+ Community](https://plus.google.com/communities/102771308349328485741) and also [financially](http://octoprint.org/support-octoprint/).
|
||||
[the G+ Community](https://plus.google.com/communities/102771308349328485741) and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
|
||||
|
||||
If you think something is bad about OctoPrint or its documentation the way it is, please help
|
||||
in any way to make it better instead of just complaining about it -- this is an Open Source Project
|
||||
@@ -67,7 +67,7 @@ and at its settings.
|
||||
|
||||
## Dependencies
|
||||
|
||||
OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint via `setup.py`:
|
||||
|
||||
python setup.py install
|
||||
|
||||
+10
-16
@@ -1,4 +1,4 @@
|
||||
# Supporters
|
||||
# Supporters
|
||||
|
||||
Development of this version of OctoPrint wouldn't have been possible without
|
||||
[financial support by the community](http://octoprint.org/support-octoprint/) -
|
||||
@@ -10,58 +10,52 @@ thanks to everyone who contributed!
|
||||
* Aleph Objects, Inc.
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* BEEVERYCREATIVE
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brent Fiegle
|
||||
* Brian E. Tyler
|
||||
* Christopher Day
|
||||
* Christian Petropolis
|
||||
* COLLE+McVOY
|
||||
* CreativeTools
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Doug Johnson
|
||||
* E3D BigBox
|
||||
* Ernesto Martinez
|
||||
* Exovite
|
||||
* F. Kunsmann
|
||||
* Frank Sander
|
||||
* Gary Deen
|
||||
* Gary N McKinney
|
||||
* George Robles
|
||||
* günter weber
|
||||
* James Seigel
|
||||
* Jamie R McGuigan
|
||||
* Jamie van Dyke
|
||||
* Jason Lawrence
|
||||
* Jeff Moe
|
||||
* Josh Daniels
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Lamin Kivelä
|
||||
* Makespace Madrid
|
||||
* Marcus Ackermann
|
||||
* Mark Qvist
|
||||
* Mark Walker
|
||||
* Masayoshi Mitsui
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* mitchell hirsch
|
||||
* Mohammed khorakiwala
|
||||
* Noe Ruiz
|
||||
* Patrick McGinnis
|
||||
* Peter Grace
|
||||
* Peter Schmehl
|
||||
* PRINT3Dforum.com
|
||||
* Robert Gusek
|
||||
* Randy C. Will
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Samer Najia
|
||||
* SD3D
|
||||
* SeeMeCNC
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Stephane Schittly
|
||||
* Sven Mueller
|
||||
* Terrance Shaw
|
||||
* Symbiotic Devices
|
||||
* Thomas Hatley
|
||||
* Timeshell.ca
|
||||
* Trent Shumay
|
||||
|
||||
and 1041 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1062 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -6,7 +6,7 @@
|
||||
* [Babel JavaScript Support](https://github.com/mitsuhiko/babel/blob/master/contrib/babel.js): BSD
|
||||
* [Bootstrap](http://getbootstrap.com/): Apache License 2.0
|
||||
* [Bootstrap Modal](http://jschr.github.io/bootstrap-modal/): Apache License 2.0
|
||||
* [Bootstrap Slider Knockout Bindings](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
|
||||
* [Bootstrap Slider Knockout Binding](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
|
||||
* [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0
|
||||
* [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
|
||||
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
|
||||
@@ -36,6 +36,8 @@
|
||||
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
|
||||
* [chainmap](https://bitbucket.org/jeunice/chainmap): Python
|
||||
* [Click](http://click.pocoo.org/): BSD
|
||||
* [dateutil](https://dateutil.readthedocs.io/): BSD
|
||||
* [emoji](https://github.com/carpedm20/emoji/): BSD
|
||||
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
|
||||
* [Flask](http://flask.pocoo.org/): BSD
|
||||
* [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
|
||||
@@ -44,6 +46,8 @@
|
||||
* [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD
|
||||
* [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT
|
||||
* [future](https://python-future.org/): MIT
|
||||
* [futures](https://github.com/agronholm/pythonfutures): Python
|
||||
* [monotonic](https://github.com/atdt/monotonic): Apache License 2.0
|
||||
* [netaddr](https://github.com/drkjam/netaddr/): BSD
|
||||
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
|
||||
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
|
||||
@@ -60,6 +64,7 @@
|
||||
* [Tornado](http://www.tornadoweb.org/): Apache License 2.0
|
||||
* [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
|
||||
* [websocket-client](https://github.com/liris/websocket-client): LGPLv3
|
||||
* [wrapt](http://wrapt.readthedocs.org/): BSD
|
||||
|
||||
## Development (testing, documentation generation, etc)
|
||||
|
||||
@@ -69,4 +74,5 @@
|
||||
* [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
|
||||
* [sphinx_rtd_theme](https://github.com/snide/sphinx_rtd_theme/): BSD
|
||||
Vendored
+6
@@ -37,6 +37,11 @@
|
||||
vertical-align: 10%;
|
||||
}
|
||||
|
||||
.rst-content .highlight>pre,
|
||||
.rst-content .linenodiv>pre {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* make code tags non-red again */
|
||||
code,
|
||||
.rst-content tt {
|
||||
@@ -52,3 +57,4 @@ a:visited code,
|
||||
.rst-content a:visited tt {
|
||||
color: #9B59B6 !important;
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ Get connection settings
|
||||
"options": {
|
||||
"ports": ["/dev/ttyACM0", "VIRTUAL"],
|
||||
"baudrates": [250000, 230400, 115200, 57600, 38400, 19200, 9600],
|
||||
"printerProfiles": [{"name": "Default", id: "_default"}],
|
||||
"printerProfiles": [{"name": "Default", "id": "_default"}],
|
||||
"portPreference": "/dev/ttyACM0",
|
||||
"baudratePreference": 250000,
|
||||
"printerProfilePreference": "_default",
|
||||
|
||||
+16
-4
@@ -31,7 +31,7 @@ Printer State
|
||||
* - ``flags``
|
||||
- 1
|
||||
- Printer state flags
|
||||
- A couple of boolean printer state flags
|
||||
- A few boolean printer state flags
|
||||
* - ``flags.operational``
|
||||
- 1
|
||||
- Boolean
|
||||
@@ -232,12 +232,18 @@ File information
|
||||
* - ``name``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system.
|
||||
- The name of the file without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system. Currently
|
||||
this will always fit into ASCII.
|
||||
* - ``display``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file without the path, this time potentially with non-ASCII unicode characters.
|
||||
E.g. "a turtle 🐢.gco" for a file "a_turtle_turtle.gco" located anywhere in the file system.
|
||||
* - ``path``
|
||||
- 1
|
||||
- String
|
||||
- The path to the file within the location. E.g. "folder/subfolder/file.gco" for a file "file.gco" located within
|
||||
"folder" and "subfolder" relative to the root of the location.
|
||||
"folder" and "subfolder" relative to the root of the location. Currently this will always fit into ASCII.
|
||||
* - ``type``
|
||||
- 1
|
||||
- String
|
||||
@@ -329,11 +335,17 @@ Abridged file or folder information
|
||||
- 1
|
||||
- String
|
||||
- The name of the file or folder without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system.
|
||||
Currently this will always fit into ASCII.
|
||||
* - ``display``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file without the path, this potentially with non-ASCII unicode characters.
|
||||
E.g. "a turtle 🐢.gco" for a file "a_turtle_turtle.gco" located anywhere in the file system.
|
||||
* - ``path``
|
||||
- 1
|
||||
- String
|
||||
- The path to the file or folder within the location. E.g. "folder/subfolder/file.gco" for a file "file.gco" located within
|
||||
"folder" and "subfolder" relative to the root of the location.
|
||||
"folder" and "subfolder" relative to the root of the location. Currently this will always fit into ASCII.
|
||||
* - ``origin``
|
||||
- 1
|
||||
- String, either ``local`` or ``sdcard``
|
||||
|
||||
@@ -192,6 +192,7 @@ Retrieve all files
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/folderA/subfolder",
|
||||
}
|
||||
}
|
||||
],
|
||||
"size": 1334,
|
||||
"refs": {
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
Job operations
|
||||
**************
|
||||
|
||||
Use these operations to query the currently selected file and start/cancel/restart/pause the
|
||||
actual print job.
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-jobs-command:
|
||||
|
||||
@@ -39,9 +39,7 @@ Retrieve installed language packs
|
||||
"_core": {
|
||||
"identifier": "_core",
|
||||
"name": "Core",
|
||||
"languages": [
|
||||
...
|
||||
]
|
||||
"languages": []
|
||||
},
|
||||
"some_plugin": {
|
||||
"identifier": "some_plugin",
|
||||
@@ -61,7 +59,6 @@ Retrieve installed language packs
|
||||
"last_update": 1470859680,
|
||||
"author": "The italian Transifex Team"
|
||||
}
|
||||
...
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -124,9 +121,7 @@ Delete a language pack
|
||||
"_core": {
|
||||
"identifier": "_core",
|
||||
"name": "Core",
|
||||
"languages": [
|
||||
...
|
||||
]
|
||||
"languages": []
|
||||
},
|
||||
"some_plugin": {
|
||||
"identifier": "some_plugin",
|
||||
@@ -138,8 +133,7 @@ Delete a language pack
|
||||
"locale_english": "German",
|
||||
"last_update": 1474574597,
|
||||
"author": "Gina Häußge"
|
||||
},
|
||||
...
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
+24
-3
@@ -62,12 +62,30 @@ Save settings
|
||||
|
||||
{
|
||||
"api": {
|
||||
"enabled": true,
|
||||
// ...
|
||||
"enabled": true
|
||||
},
|
||||
// ...
|
||||
"appearance": {
|
||||
"color": "black"
|
||||
}
|
||||
}
|
||||
|
||||
.. _sec-api-settings-generateapikey:
|
||||
|
||||
Regenerate the system wide API key
|
||||
==================================
|
||||
|
||||
.. http:post:: /api/settings/apikey
|
||||
|
||||
Generates a new system wide API key.
|
||||
|
||||
Does not expect a body. Will return the generated API key as ``apikey``
|
||||
property in the JSON object contained in the response body.
|
||||
|
||||
Requires admin rights.
|
||||
|
||||
:status 200: No error
|
||||
:status 403: No admin rights
|
||||
|
||||
.. _sec-api-settings-datamodel:
|
||||
|
||||
Data model
|
||||
@@ -87,6 +105,9 @@ 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
|
||||
possible through `config.yaml`.
|
||||
* - ``api.allowCrossOrigin``
|
||||
-
|
||||
* - ``appearance.name``
|
||||
|
||||
@@ -58,11 +58,9 @@ List All Slicers and Slicing Profiles
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
},
|
||||
...
|
||||
}
|
||||
}
|
||||
},
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
@@ -104,8 +102,7 @@ List Slicing Profiles of a Specific Slicer
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
},
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to list the available profiles.
|
||||
@@ -147,8 +144,7 @@ Retrieve Specific Profile
|
||||
"brim_line_count": 20,
|
||||
"cool_head_lift": false,
|
||||
"cool_min_feedrate": 10.0,
|
||||
"cool_min_layer_time": 5.0,
|
||||
...
|
||||
"cool_min_layer_time": 5.0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+7
-7
@@ -39,7 +39,7 @@ List all registered system commands
|
||||
"action": "shutdown",
|
||||
"name": "Shutdown",
|
||||
"command": "sudo shutdown -h now",
|
||||
"confirm": "You are about to shutdown the system.",
|
||||
"confirm": "<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
@@ -49,7 +49,7 @@ List all registered system commands
|
||||
"action": "reboot",
|
||||
"name": "Reboot",
|
||||
"command": "sudo reboot",
|
||||
"confirm": "You are about to reboot the system.",
|
||||
"confirm": "<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
@@ -59,7 +59,7 @@ List all registered system commands
|
||||
"action": "restart",
|
||||
"name": "Restart OctoPrint",
|
||||
"command": "sudo service octoprint restart",
|
||||
"confirm": "You are about to restart the OctoPrint server.",
|
||||
"confirm": "<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
@@ -100,7 +100,7 @@ List all registered system commands for a source
|
||||
"action": "shutdown",
|
||||
"name": "Shutdown",
|
||||
"command": "sudo shutdown -h now",
|
||||
"confirm": "You are about to shutdown the system.",
|
||||
"confirm": "<b>You are about to shutdown the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
@@ -110,7 +110,7 @@ List all registered system commands for a source
|
||||
"action": "reboot",
|
||||
"name": "Reboot",
|
||||
"command": "sudo reboot",
|
||||
"confirm": "You are about to reboot the system.",
|
||||
"confirm": "<b>You are about to reboot the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
@@ -120,7 +120,7 @@ List all registered system commands for a source
|
||||
"action": "restart",
|
||||
"name": "Restart OctoPrint",
|
||||
"command": "sudo service octoprint restart",
|
||||
"confirm": "You are about to restart the OctoPrint server.",
|
||||
"confirm": "<b>You are about to restart the OctoPrint server.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
|
||||
"async": true,
|
||||
"ignore": true,
|
||||
"source": "core",
|
||||
@@ -154,7 +154,7 @@ Execute a registered system command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
204 No Content
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:param source: The source for which to list commands, currently either ``core`` or ``custom``
|
||||
:param action: The identifier of the command, ``action`` from its definition
|
||||
|
||||
+84
-1
@@ -68,6 +68,21 @@ Test paths or URLs
|
||||
when the test could be performed. The status code of the response does NOT reflect the
|
||||
test result!
|
||||
|
||||
.. _sec-api-util-test-server:
|
||||
|
||||
server
|
||||
Tests whether a provided server identified by host and port can be reached. Protocol can optionally be specified
|
||||
as well. Supported parameters are:
|
||||
|
||||
* ``host``: The host to test. IP or host name. Mandatory.
|
||||
* ``port``: The port to test. Integer. Mandatory.
|
||||
* ``protocol``: The protocol to test with. ``tcp`` or ``udp``. Optional, defaults to ``tcp``.
|
||||
* ``timeout``: A timeout for the test, in seconds. If no successful connection to the server could be established
|
||||
within this time frame, the check will be considered a failure. Optional, defaults to 3.05 seconds.
|
||||
|
||||
The ``server`` command returns :http:statuscode:`200` with a :ref:`Server test result <sec-api-util-datamodel-servertestresult>`
|
||||
when the test could be performed. The status code of the response does NOT reflect the test result!
|
||||
|
||||
Requires admin rights.
|
||||
|
||||
**Example 1**
|
||||
@@ -226,6 +241,35 @@ Test paths or URLs
|
||||
}
|
||||
}
|
||||
|
||||
**Example 6**
|
||||
|
||||
Test whether a server is reachable on a given port via TCP.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/util/test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"command": "server",
|
||||
"host": "8.8.8.8",
|
||||
"port": 53
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"host": "8.8.8.8",
|
||||
"port": 53,
|
||||
"protocol": "tcp",
|
||||
"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``
|
||||
@@ -233,8 +277,11 @@ Test paths or URLs
|
||||
: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`` command only: the timeout for the HTTP request
|
||||
: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:
|
||||
@@ -244,6 +291,9 @@ Data model
|
||||
|
||||
.. _sec-api-util-datamodel-pathtestresult:
|
||||
|
||||
Path test result
|
||||
----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
@@ -275,6 +325,9 @@ Data model
|
||||
|
||||
.. _sec-api-util-datamodel-urltestresult:
|
||||
|
||||
URL test result
|
||||
---------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
@@ -306,3 +359,33 @@ Data model
|
||||
- object
|
||||
- A dictionary with all headers of the checked URL's response. Only present if ``response`` in the
|
||||
request was set.
|
||||
|
||||
.. _sec-api-util-datamodel-servertestresult:
|
||||
|
||||
Server test result
|
||||
------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``host``
|
||||
- 1
|
||||
- string
|
||||
- The host that was tested.
|
||||
* - ``port``
|
||||
- 1
|
||||
- int
|
||||
- The port that was tested
|
||||
* - ``protocol``
|
||||
- 1
|
||||
- string
|
||||
- The protocol that was tested, ``tcp`` or ``udp``
|
||||
* - ``result``
|
||||
- 1
|
||||
- bool
|
||||
- ``true`` if the check passed.
|
||||
@@ -45,7 +45,7 @@ Installing CuraEngine
|
||||
|
||||
You'll need a build of ``legacy`` branch of `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_
|
||||
in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch
|
||||
`here <https://github.com/ultimaker/curaengine/tree/legacy>`_.
|
||||
`here <https://github.com/ultimaker/curaengine/tree/legacy>`__.
|
||||
|
||||
If you previously used the `old variant of the Cura integration <https://github.com/foosel/OctoPrint/wiki/Cura-Integration>`_,
|
||||
you probably still have a fully functional binary lying around in the
|
||||
@@ -60,7 +60,7 @@ Compiling for Raspbian
|
||||
.. note::
|
||||
|
||||
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
|
||||
`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.
|
||||
|
||||
@@ -54,6 +54,12 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
|
||||
# Time to live for the repository cache
|
||||
repository_ttl: 1440
|
||||
|
||||
# The URL of the plugin notices feed to use
|
||||
notices: http://plugins.octoprint.org/notices.json
|
||||
|
||||
# Time to live for the notices feed cache
|
||||
notices_ttl: 360
|
||||
|
||||
# Additional arguments to use with pip. Defaults to unset,
|
||||
# you normally shouldn't need to modify this
|
||||
pip_args: --some --additional --pip --arguments
|
||||
@@ -76,6 +82,36 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
|
||||
- hidden
|
||||
- plugins
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-hooks:
|
||||
|
||||
Hooks
|
||||
-----
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-hooks-reconnect_hooks:
|
||||
|
||||
octoprint.plugin.pluginmanager.reconnect_hooks
|
||||
++++++++++++++++++++++++++++++++++++++++++++++
|
||||
|
||||
.. py:function:: reconnect_hooks_hook(*args, **kwargs)
|
||||
|
||||
Returns additional hooks defined by the plugin for which the plugin manager
|
||||
should display the "You should reconnect to your printer" message on plugin
|
||||
install/uninstall/enabling/disabling.
|
||||
|
||||
Handlers should return a Python list containing the affected hook names.
|
||||
|
||||
**Example**
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def reconnect_hooks_hook(*args, **kwargs):
|
||||
return ["octoprint.plugin.exampleplugin.some_custom_hook",
|
||||
"octoprint.plugin.exampleplugin.some_other_custom_hook"]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook
|
||||
}
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-sourcecode:
|
||||
|
||||
Source Code
|
||||
|
||||
@@ -14,14 +14,14 @@ First Steps
|
||||
|
||||
Out of the box the Software Update Plugin will be able to notify you of any
|
||||
updates that might be available for your OctoPrint installation or any plugins
|
||||
that registered themselves with it. In order to also be able to update
|
||||
your OctoPrint installation, you'll need to configure
|
||||
at least OctoPrint's checkout folder, and you also should
|
||||
configure the restart commands for OctoPrint and the whole server.
|
||||
that registered themselves with it. In order for automatic restarts after updates
|
||||
to work, you should configure the restart commands for OctoPrint and the whole server.
|
||||
|
||||
For configuring the plugin you'll need to go into OctoPrint's Settings Dialog, navigate to the
|
||||
Software Upda.. _section therein and once you are there click on the little wrench icon in the
|
||||
upper right corner.
|
||||
Out of the box the plugin should already be ready to update your OctoPrint installation to current
|
||||
stable release versions, but you can also switch to one of the available release candidate channels
|
||||
or outright git commit tracking via the plugin's configuration dialog. To open this dialog, fire up OctoPrint's
|
||||
Settings Dialog, navigate to the Software Update section therein and once you are there click on the little
|
||||
wrench icon in the upper right corner.
|
||||
|
||||
.. _fig-bundledplugins-softwareupdate-plugin-configuration:
|
||||
.. figure:: ../images/bundledplugins-softwareupdate-plugin-configuration.png
|
||||
@@ -32,31 +32,16 @@ upper right corner.
|
||||
|
||||
There you can adjust the following settings:
|
||||
|
||||
* **OctoPrint checkout folder**: This should be the path to OctoPrint's git checkout folder (``/home/pi/OctoPrint``
|
||||
for OctoPi or `manual installs following the Raspberry Pi setup guide <https://github.com/foosel/OctoPrint/wiki/Setup-on-a-Raspberry-Pi-running-Raspbian>`_).
|
||||
This must be set to allow updating from within OctoPrint
|
||||
|
||||
.. note::
|
||||
|
||||
OctoPi releases 0.12.0 and later ship with this already setup for you.
|
||||
|
||||
.. note::
|
||||
|
||||
**OctoPi 0.11.0 users**: Please also take a look at
|
||||
`the note at the very end of this FAQ entry <https://github.com/foosel/OctoPrint/wiki/FAQ#how-can-i-update-the-octoprint-installation-on-my-octopi-image>`_.
|
||||
Due to a little issue in that OctoPi release 0.11.0 you might have to fix
|
||||
the URL your OctoPrint checkout is using for updating. This can easily be
|
||||
done by SSHing into your OctoPi instance and doing this::
|
||||
|
||||
cd ~/OctoPrint
|
||||
git remote set-url origin https://github.com/foosel/OctoPrint.git
|
||||
|
||||
* **OctoPrint version tracking**: Whether you want to track OctoPrint *releases* or every *commit*. Usually you want to
|
||||
select "Release" here which is also the default, unless you are a developer.
|
||||
* **OctoPrint Release Channel**: The release channel of OctoPrint to track for updates. If you only want stable versions,
|
||||
* **OctoPrint Release Channel** (if tracking releases): The release channel of OctoPrint to track for updates. If you only want stable versions,
|
||||
select "Stable" here which is also the default. "Maintenance RCs" will also allow you to update to maintenance release
|
||||
candidates, "Devel RCs" will also allow you to update to development release candidates. If in doubt, leave it at
|
||||
"Stable". `Read more about Release Channels here <https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels>`_.
|
||||
* **OctoPrint checkout folder** (if tracking git commits): This must be the path to OctoPrint's git checkout folder
|
||||
(``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide <https://github.com/foosel/OctoPrint/wiki/Setup-on-a-Raspberry-Pi-running-Raspbian>`_).
|
||||
Note that since OctoPrint 1.3.6 you will no longer need to set this to be able to update to releases, only if you
|
||||
want to be able to update against some bleeding edge git branch.
|
||||
* **Version cache TTL**: The "time to live" of the cache OctoPrint will use to temporarily persist the version information
|
||||
for the various components registered with the plugin, so that they don't have to be queried from the internet every time
|
||||
you load the page. Defaults to 24h, you usually shouldn't need to change that value.
|
||||
@@ -132,30 +117,29 @@ Configuring the Plugin
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
plugins:
|
||||
softwareupdate:
|
||||
# the time-to-live of the version cache, in minutes
|
||||
cache_ttl: 60
|
||||
plugins:
|
||||
softwareupdate:
|
||||
# the time-to-live of the version cache, in minutes
|
||||
cache_ttl: 60
|
||||
|
||||
# configured version check and update methods
|
||||
checks:
|
||||
# "octoprint" is reserved for OctoPrint
|
||||
octoprint:
|
||||
# this defines an version check that will check against releases
|
||||
# published on OctoPrint's Github repository and an update method
|
||||
# utilizing an (included) update script that will be run on
|
||||
# OctoPrint's checkout folder
|
||||
type: github_release
|
||||
user: foosel
|
||||
repo: OctoPrint
|
||||
update_script: '{python} "/path/to/octoprint-update.py" --python="{python}" "{folder}" "{target}"'
|
||||
update_folder: /path/to/octoprint/checkout/folder
|
||||
# configured version check and update methods
|
||||
checks:
|
||||
# "octoprint" is reserved for OctoPrint
|
||||
octoprint:
|
||||
# this defines an version check that will check against releases
|
||||
# published on OctoPrint's Github repository and pip as update method
|
||||
# against the release archives on Github - this is the default
|
||||
type: github_release
|
||||
user: foosel
|
||||
repo: OctoPrint
|
||||
method: pip
|
||||
pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip'
|
||||
|
||||
# further checks may be define here
|
||||
# further checks may be define here
|
||||
|
||||
# pip command, if another one than the automatically detected one should be
|
||||
# used - should normally NOT be necessary and hence set
|
||||
pip_command: /path/to/pip
|
||||
# pip command, if another one than the automatically detected one should be
|
||||
# used - should normally NOT be necessary and hence set
|
||||
pip_command: /path/to/pip
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-configuration-versionchecks:
|
||||
|
||||
@@ -188,6 +172,23 @@ Version checks
|
||||
* ``repo``: (mandatory) Github repository to check
|
||||
* ``branch``: Branch of the Github repository to check, defaults to
|
||||
``master`` if not set.
|
||||
* ``current``: Current commit hash. Will be updated automatically.
|
||||
|
||||
* ``bitbucket_commit``: Checks against commits pushed to Bitbucket. Additional
|
||||
config parameters:
|
||||
|
||||
* ``user``: (mandatory) Bitbucket user the repository to check belongs to
|
||||
* ``repo``: (mandatory) Bitbucket repository to check
|
||||
* ``branch``: Branch of the Bitbucket repository to check, defaults to
|
||||
``master`` if not set.
|
||||
* ``current``: Current commit hash. Will be updated automatically.
|
||||
* ``api_user``: (mandatory only for private repositories) Bitbucket user name (not email address).
|
||||
Requires ``api_password`` to be set. Hint: This is used for the check only. For the actual
|
||||
download you might register your public SSH key as access key for the according repo and
|
||||
configure this as pip URL in ``config.yaml``: ``git+ssh://git@bitbucket.org/my_user/my_repo.git@{target_version}``
|
||||
* ``api_password``: (mandatory only for private repositories) App password. Requires
|
||||
``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate
|
||||
a new app password. App passwords are user specific on Bitbucket.
|
||||
|
||||
* ``git_commit``: Checks a local git repository for new commits on its
|
||||
configured remote. Additional config parameters:
|
||||
@@ -232,6 +233,32 @@ Update methods
|
||||
:ref:`hook <sec-bundledplugins-softwareupdate-hooks>`. A python callable
|
||||
which performs the update, see below for details.
|
||||
|
||||
.. note::
|
||||
|
||||
To allow default configurations for multiple update methods, if more than one of
|
||||
the above update method specific settings is set the one to use can be selected
|
||||
by setting the property ``method`` to the method specific setting in question.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example defines both ``pip`` and ``update_script``. By setting to
|
||||
``method`` to ``pip``, the Software Update plugin is instructed to use that as
|
||||
update method.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
plugins:
|
||||
softwareupdate:
|
||||
checks:
|
||||
octoprint:
|
||||
type: github_release
|
||||
user: foosel
|
||||
repo: OctoPrint
|
||||
method: pip
|
||||
pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip'
|
||||
update_script: '{python} "/path/to/octoprint-update.py" --python="{python}" "{folder}" "{target}"'
|
||||
checkout_folder: /path/to/octoprint/checkout/folder
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-configuration-patterns:
|
||||
|
||||
Common configuration patterns
|
||||
@@ -251,6 +278,7 @@ plugin itself):
|
||||
user: foosel
|
||||
repo: OctoPrint
|
||||
branch: devel
|
||||
method: update_script
|
||||
update_folder: /home/pi/OctoPrint
|
||||
|
||||
Plugin installed via pip and hosted on Github under
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ needs_sphinx = '1.3'
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
|
||||
'sphinx.ext.napoleon']
|
||||
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid']
|
||||
todo_include_todos = True
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
|
||||
@@ -285,9 +285,13 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# to false.
|
||||
okWithLinenumber: false
|
||||
|
||||
# Number of extruders to simulate on the virtual printer.
|
||||
# Number of extruders to simulate on the virtual printer. Map from tool id (0, 1, ...) to temperature
|
||||
# in °C
|
||||
numExtruders: 1
|
||||
|
||||
# Allows pinning certain hotends to a fixed temperature
|
||||
pinnedExtruders: null
|
||||
|
||||
# Whether to include the current tool temperature in the M105 output as separate T segment or not.
|
||||
#
|
||||
# True: > M105
|
||||
@@ -304,13 +308,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# > File opened
|
||||
includeFilenameInOpened: true
|
||||
|
||||
# The maximum movement speeds of the simulated printer's axes, in mm/s
|
||||
movementSpeed:
|
||||
x: 6000
|
||||
y: 6000
|
||||
z: 200
|
||||
e: 300
|
||||
|
||||
# Whether the simulated printer should also simulate a heated bed or not
|
||||
hasBed: true
|
||||
|
||||
@@ -331,6 +328,18 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# to make sure nothing gets lost on the line
|
||||
repetierStyleResends: false
|
||||
|
||||
# If enabled, ok will be sent before a commands output, otherwise after or inline (M105)
|
||||
#
|
||||
# True: > M20
|
||||
# < ok
|
||||
# < Begin file list
|
||||
# < End file list
|
||||
# False: > M20
|
||||
# < Begin file list
|
||||
# < End file list
|
||||
# < ok
|
||||
okBeforeCommandOutput: false
|
||||
|
||||
# If enabled, reports the first extruder in M105 responses as T instead of T0
|
||||
#
|
||||
# True: > M105
|
||||
@@ -358,7 +367,8 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# side will block
|
||||
rxBuffer: 64
|
||||
|
||||
# Size of simulated command buffer
|
||||
# Size of simulated command buffer, number of commands. If full, buffered commands will block
|
||||
# until a slot frees up
|
||||
commandBuffer: 4
|
||||
|
||||
# Whether to support the M112 command with simulated kill
|
||||
@@ -370,6 +380,58 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# Whether to simulate broken M29 behaviour (missing ok after response)
|
||||
brokenM29: true
|
||||
|
||||
# Whether F is supported as individual command
|
||||
supportF: false
|
||||
|
||||
# Firmware name to report (useful for testing firmware detection)
|
||||
firmwareName: Virtual Marlin 1.0
|
||||
|
||||
# Simulate a shared nozzle
|
||||
sharedNozzle: false
|
||||
|
||||
# Send "busy" messages if busy processing something
|
||||
sendBusy: false
|
||||
|
||||
# Simulate a reset on connect
|
||||
simulateReset: true
|
||||
|
||||
# Lines to send on simulated reset
|
||||
resetLines:
|
||||
- start
|
||||
- Marlin: Virtual Marlin!
|
||||
- "\x80"
|
||||
- "SD card ok"
|
||||
|
||||
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
|
||||
# mis-sent oks). Can also be filled at runtime via the debug command prepare_ok
|
||||
preparedOks: []
|
||||
|
||||
# Format string for ok response.
|
||||
#
|
||||
# Placeholders:
|
||||
# - lastN: last acknowledged line number
|
||||
# - buffer: empty slots in internal command buffer
|
||||
#
|
||||
# Example format string for "extended" ok format:
|
||||
# ok N{lastN} P{buffer}
|
||||
okFormatString: ok
|
||||
|
||||
# Format string for M115 output.
|
||||
#
|
||||
# Placeholders:
|
||||
# - firmare_name: The firmware name as defined in firmwareName
|
||||
m115FormatString: "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0"
|
||||
|
||||
# Whether to include capability report in M115 output
|
||||
m115ReportCapabilites: false
|
||||
|
||||
# Capabilities to report if capability report is enabled
|
||||
capabilities:
|
||||
AUTOREPORT_TEMP: true
|
||||
|
||||
# Simulated ambient temperature in °C
|
||||
ambientTemperature: 21.3
|
||||
|
||||
.. _sec-configuration-config_yaml-estimation:
|
||||
|
||||
Estimation
|
||||
@@ -793,7 +855,12 @@ Use the following settings to configure the serial connection to the printer:
|
||||
# Command to send in order to initiate a handshake with the printer.
|
||||
# Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
|
||||
# should be acknowledged with a simple "ok".
|
||||
helloCommand: M110 N0
|
||||
helloCommand:
|
||||
- M110 N0
|
||||
|
||||
# Commands that should never be auto-uppercased when sent to the printer. Defaults to only M117.
|
||||
autoUppercaseBlacklist:
|
||||
- M117
|
||||
|
||||
# Whether to disconnect on errors or not
|
||||
disconnectOnErrors: true
|
||||
@@ -909,6 +976,31 @@ Use the following settings to configure the server:
|
||||
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||
systemShutdownCommand: sudo shutdown -h now
|
||||
|
||||
# Configuration of the regular online connectivity check
|
||||
onlineCheck:
|
||||
# whether the online check is enabled, defaults to false due to valid privacy concerns
|
||||
enabled: false
|
||||
|
||||
# interval in which to check for online connectivity (in seconds)
|
||||
interval: 300
|
||||
|
||||
# DNS host against which to check (default: 8.8.8.8 aka Google's DNS)
|
||||
host: 8.8.8.8
|
||||
|
||||
# DNS port against which to check (default: 53 - the default DNS port)
|
||||
port: 53
|
||||
|
||||
# Configuration of the plugin blacklist
|
||||
pluginBlacklist:
|
||||
# whether use of the blacklist is enabled, defaults to false
|
||||
enabled: false
|
||||
|
||||
# the URL from which to fetch the blacklist
|
||||
url: http://plugins.octoprint.org/blacklist.json
|
||||
|
||||
# time to live of the cached blacklist, in seconds (default: 15 minutes)
|
||||
ttl: 15 * 60
|
||||
|
||||
# Settings of when to display what disk space warning
|
||||
diskspace:
|
||||
|
||||
@@ -943,8 +1035,8 @@ Use the following settings to configure the server:
|
||||
* ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https``
|
||||
|
||||
If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look
|
||||
`into OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ for a couple
|
||||
of examples on how to configure this.
|
||||
`into OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ for some
|
||||
examples on how to configure this.
|
||||
|
||||
.. _sec-configuration-config_yaml-slicing:
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
.. _sec-development-environment:
|
||||
|
||||
Setting up a Development environment
|
||||
====================================
|
||||
|
||||
.. _sec-development-environment-source:
|
||||
|
||||
Obtaining, building and running the source
|
||||
------------------------------------------
|
||||
|
||||
This describes the general steps in obtaining, building and running. OS specific instructions can be found
|
||||
below.
|
||||
|
||||
* Prerequisites:
|
||||
|
||||
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Git <https://git-scm.com>`_
|
||||
|
||||
* Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
|
||||
* Enter the checked out source folder: ``cd OctoPrint``
|
||||
* Create a virtual environment in the checked out source folder to use for installing and running OctoPrint and its
|
||||
dependencies (this avoids potential versioning issues for the dependencies with system wide installed
|
||||
instances): ``virtualenv venv``
|
||||
* Activate the virtual environment: ``source venv/bin/activate`` (Linux, MacOS) or
|
||||
``source venv/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
* Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
|
||||
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
|
||||
including its regular *and* development and plugin development dependencies: ``pip install -e .[develop,plugins]``
|
||||
|
||||
When the virtual environment is activated you can then:
|
||||
|
||||
* run the OctoPrint server via ``octoprint serve``
|
||||
* run the test suite from the checked out source folder via ``nosetests --with-doctest``
|
||||
* build the documentation from the ``docs`` sub folder of the checked out sources via ``sphinx-build -b html . _build``
|
||||
|
||||
.. _sec-development-environment-source-linux:
|
||||
|
||||
Linux
|
||||
.....
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
First make sure you have python including its header files, pip, setuptools, virtualenv, git and some build requirements
|
||||
installed:
|
||||
|
||||
* On apt based distributions (e.g. Debian, Ubuntu, ...):
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential
|
||||
|
||||
* On zypper based distributions (example below for SLES 12 SP2):
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
sudo zypper ar https://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP2/ python_devel
|
||||
sudo zypper ref
|
||||
sudo zypper in python python-pip python-devel python-setuptools python-virtualenv git libyaml-devel
|
||||
sudo zypper in -t pattern Basis-Devel
|
||||
|
||||
.. todo::
|
||||
|
||||
Using a Linux distribution that doesn't use ``apt`` or ``zypper``? Please send a
|
||||
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
|
||||
steps into this guide!
|
||||
|
||||
Then:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
cd ~/devel
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source ./venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop,plugins]
|
||||
|
||||
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
environment.
|
||||
|
||||
.. _sec-development-environment-windows:
|
||||
|
||||
Windows
|
||||
.......
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
First download & install:
|
||||
|
||||
* `Python 2.7.12 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2712/>`_
|
||||
|
||||
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
|
||||
|
||||
* `Microsoft Visual C++ Compiler for Python 2.7 <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_
|
||||
* `Git for Windows <https://git-for-windows.github.io/>`_
|
||||
|
||||
Open the Git Bash you just installed and in that:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
pip install virtualenv
|
||||
cd /c/Devel
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source ./venv/Scripts/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop,plugins]
|
||||
|
||||
.. _sec-development-environment-mac:
|
||||
|
||||
Mac OS X
|
||||
........
|
||||
|
||||
.. note::
|
||||
|
||||
This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Setup-on-Mac/>`_.
|
||||
Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
You'll need a user account with administrator privileges.
|
||||
|
||||
* Install the latest version of Xcode suitable for your OS. For example, OS X 10.11 (El Capitan) requires Xcode 7.
|
||||
* Install Xcode's command line tools:
|
||||
|
||||
* ``xcode-select --install``
|
||||
* ``sudo xcodebuild`` (ensure the license was accepted)
|
||||
* If you have more than one Xcode installed: ``sudo xcode-select -s /Applications/Xcode.app/Contents/Developer``
|
||||
|
||||
* Install Homebrew and use that to install Python:
|
||||
|
||||
* ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
|
||||
* ``brew install python``
|
||||
|
||||
* Install `virtualenv <https://virtualenv.pypa.io/>`_
|
||||
|
||||
* ``pip install virtualenv``
|
||||
|
||||
* Install OctoPrint
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
cd ~/devel
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop,plugins]
|
||||
|
||||
.. _sec-development-environment-ides:
|
||||
|
||||
IDE Setup
|
||||
---------
|
||||
|
||||
.. todo::
|
||||
|
||||
Using another IDE than the ones below? Please send a
|
||||
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
|
||||
steps into this guide!
|
||||
|
||||
.. _sec-development-environment-ides-pycharm:
|
||||
|
||||
PyCharm
|
||||
.......
|
||||
|
||||
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
|
||||
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
|
||||
- Right click "src" in project tree, mark as source folder
|
||||
- Add Run/Debug Configuration, select "Python":
|
||||
|
||||
* Name: OctoPrint server
|
||||
* Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``)
|
||||
* Script parameters: ``serve --debug``
|
||||
* Project: ``OctoPrint``
|
||||
* Python interpreter: the ``venv`` local virtual environment
|
||||
* Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
* If you want dependencies to auto-update on run if necessary: "Before Launch" > "+" > "Run external tool" > "+"
|
||||
|
||||
* Name: Update OctoPrint dependencies
|
||||
* Program: ``$PyInterpreterDirectory$/pip`` (or ``$PyInterpreterDirectory$/pip.exe`` on Windows)
|
||||
* Parameters: ``install -e .[develop,plugins]``
|
||||
* Working directory: ``$ProjectFileDir$``
|
||||
|
||||
- Add Run/Debug Configuration, select "Python tests" and therein "Nosetests":
|
||||
|
||||
* Name: OctoPrint nosetests
|
||||
* Target: Path, ``.``
|
||||
* Project: ``OctoPrint``
|
||||
* Python interpreter: the ``venv`` local virtual environment
|
||||
* Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
* Just like with the run configuration for the server you can also have the dependencies auto-update on run of
|
||||
the tests, see above on how to set this up.
|
||||
|
||||
- Add Run/Debug Configuration, select "Python docs" and therein "Sphinx task"
|
||||
|
||||
* Name: OctoPrint docs
|
||||
* Command: ``html``
|
||||
* Input: the ``docs`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs`` or
|
||||
``C:\Devel\OctoPrint\docs``)
|
||||
* Output: the ``docs/_build`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs/_build`` or
|
||||
``C:\Devel\OctoPrint\docs\_build``)
|
||||
* Project: ``OctoPrint``
|
||||
* Python interpreter: the ``venv`` local virtual environment
|
||||
* Just like with the run configuration for the server you can also have the dependencies auto-update when building
|
||||
the documentation, see above on how to set this up.
|
||||
|
||||
.. note::
|
||||
|
||||
Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
|
||||
`a debugger bug contained in earlier versions <https://youtrack.jetbrains.com/issue/PY-18365>`_ or plugin management
|
||||
will not work in your developer install when running OctoPrint from PyCharm in debug mode.
|
||||
+4
-179
@@ -4,183 +4,8 @@
|
||||
Development
|
||||
###########
|
||||
|
||||
.. contents::
|
||||
:local:
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
|
||||
.. _sec-development-environment:
|
||||
|
||||
Setting up a Development environment
|
||||
====================================
|
||||
|
||||
.. _sec-development-environment-source:
|
||||
|
||||
Obtaining, building and running the source
|
||||
------------------------------------------
|
||||
|
||||
This describes the general steps in obtaining, building and running. OS specific instructions can be found
|
||||
below.
|
||||
|
||||
* Prerequisites:
|
||||
|
||||
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Git <https://git-scm.com>`_
|
||||
|
||||
* Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
|
||||
* Create a virtual environment in the checkout folder to use for installing and running OctoPrint and its
|
||||
dependencies (this avoids potential versioning issues for the dependencies with system wide installed
|
||||
instances): ``virtualenv venv``
|
||||
* Activate the virtual environment: ``source venv/bin/activate`` (might differ per your platform/OS)
|
||||
* Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
|
||||
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
|
||||
including its regular *and* development dependencies: ``pip install -e .[develop]``
|
||||
|
||||
.. _sec-development-environment-source-linux:
|
||||
|
||||
Linux
|
||||
.....
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
First make sure you have python including its header files, pip, setuptools, virtualenv, git and some build requirements
|
||||
installed:
|
||||
|
||||
* On apt based distributions (e.g. Debian, Ubuntu, ...):
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential
|
||||
|
||||
.. todo::
|
||||
|
||||
Using a Linux distribution that doesn't use ``apt``? Please send a
|
||||
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
|
||||
steps into this guide!
|
||||
|
||||
Then:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
cd ~/devel
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source ./venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop]
|
||||
|
||||
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
environment.
|
||||
|
||||
.. _sec-development-environment-windows:
|
||||
|
||||
Windows
|
||||
.......
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
First download & install:
|
||||
|
||||
* `Python 2.7.12 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2712/>`_
|
||||
|
||||
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
|
||||
|
||||
* `Microsoft Visual C++ Compiler for Python 2.7 <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_
|
||||
* `Git for Windows <https://git-for-windows.github.io/>`_
|
||||
|
||||
Open the Git Bash you just installed and in that:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
pip install virtualenv
|
||||
cd /c/Devel
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source ./venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop]
|
||||
|
||||
You can then start OctoPrint via ``/c/Devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
environment.
|
||||
|
||||
.. _sec-development-environment-mac:
|
||||
|
||||
Mac OS X
|
||||
........
|
||||
|
||||
.. note::
|
||||
|
||||
This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Setup-on-Mac/>`_.
|
||||
Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
You'll need a user account with administrator privileges.
|
||||
|
||||
* Install the latest version of Xcode suitable for your OS. For example, OS X 10.11 (El Capitan) requires Xcode 7.
|
||||
* Install Xcode's command line tools:
|
||||
|
||||
* ``xcode-select --install``
|
||||
* ``sudo xcodebuild`` (ensure the license was accepted)
|
||||
* If you have more than one Xcode installed: ``sudo xcode-select -s /Applications/Xcode.app/Contents/Developer``
|
||||
|
||||
* Install Homebrew and use that to install Python:
|
||||
|
||||
* ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
|
||||
* ``brew install python``
|
||||
|
||||
* Install `virtualenv <https://virtualenv.pypa.io/>`_
|
||||
|
||||
* ``pip install virtualenv``
|
||||
|
||||
* Install OctoPrint
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
cd ~/devel
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source venv/bin/activate
|
||||
pip install -e .[develop]
|
||||
|
||||
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
environment.
|
||||
|
||||
.. _sec-development-environment-ides:
|
||||
|
||||
IDE Setup
|
||||
---------
|
||||
|
||||
.. todo::
|
||||
|
||||
Using another IDE than the ones below? Please send a
|
||||
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
|
||||
steps into this guide!
|
||||
|
||||
.. _sec-development-environment-ides-pycharm:
|
||||
|
||||
PyCharm
|
||||
.......
|
||||
|
||||
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
|
||||
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
|
||||
- Right click "src" in project tree, mark as source folder
|
||||
- Add Run/Debug Configuration, select "Python":
|
||||
|
||||
* Name: OctoPrint server
|
||||
* Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``)
|
||||
* Script parameters: ``--debug``
|
||||
* Project: ``OctoPrint``
|
||||
* Python interpreter: the ``venv`` local virtual environment
|
||||
* Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
|
||||
.. note::
|
||||
|
||||
Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
|
||||
`a debugger bug contained in earlier versions <https://youtrack.jetbrains.com/issue/PY-18365>`_ or plugin management
|
||||
will not work in your developer install when running OctoPrint from PyCharm in debug mode.
|
||||
environment.rst
|
||||
virtual_printer.rst
|
||||
@@ -0,0 +1,116 @@
|
||||
.. _sec-development-virtual-printer:
|
||||
|
||||
Setting up the virtual printer for debugging
|
||||
============================================
|
||||
|
||||
OctoPrint includes, by default, a virtual printer plugin. This plugin allows you to debug OctoPrint's serial
|
||||
communication without connecting to an actual printer. Furthermore, it is possible to create certain edge conditions
|
||||
that may be hard to reproduce with a real printer.
|
||||
|
||||
.. _sec-development-virtual-printer-enable:
|
||||
|
||||
Enabling the virtual printer
|
||||
----------------------------
|
||||
|
||||
The virtual printer is enabled by editing OctoPrint's config.yaml file. Details on the configuration file can
|
||||
be found in the full :ref:`config.yaml documentation <sec-configuration-config_yaml>`.
|
||||
|
||||
The steps to take are as follows:
|
||||
|
||||
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on MacOS.
|
||||
* Add or extend the ``devel`` section with:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
devel:
|
||||
virtualPrinter:
|
||||
enabled: true
|
||||
|
||||
* Restart OctoPrint.
|
||||
* In the connection panel, a new option will appear in the Serial Port dropdown labeled ``VIRTUAL``.
|
||||
* Select this option and click ``connect``.
|
||||
* The virtual printer is now active.
|
||||
|
||||
.. _sec-development-virtual-printer-config:
|
||||
|
||||
Virtual printer configuration options
|
||||
-------------------------------------
|
||||
|
||||
The config.yaml file has many configuration options for the virtual printer that allow you to fine-tune its behavior.
|
||||
|
||||
Please see the relevant :ref:`config.yaml section <sec-configuration-config_yaml-devel>` for the full details.
|
||||
|
||||
.. _sec-development-virtual-printer-log:
|
||||
|
||||
Log file
|
||||
--------
|
||||
|
||||
Once activated, the virtual printer will log all serial communication in the ``plugin_virtual_printer_serial.log`` file
|
||||
that can be found in the OctoPrint settings folder.
|
||||
|
||||
.. _sec-development-virtual-printer-debug:
|
||||
|
||||
Debug commands
|
||||
--------------
|
||||
|
||||
You can simulate certain conditions and communications through the terminal tab in OctoPrint's interface.
|
||||
|
||||
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.
|
||||
|
||||
Action Triggers
|
||||
...............
|
||||
|
||||
``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
|
||||
....................
|
||||
|
||||
``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
|
||||
|
||||
``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"
|
||||
|
||||
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>
|
||||
+79
-7
@@ -110,6 +110,14 @@ ClientClosed
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
|
||||
ConnectivityChanged
|
||||
The server's internet connectivity changed
|
||||
|
||||
Payload:
|
||||
|
||||
* ``old``: Old connectivity value (true for online, false for offline)
|
||||
* ``new``: New connectivity value (true for online, false for offline)
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
@@ -152,7 +160,7 @@ File handling
|
||||
-------------
|
||||
|
||||
Upload
|
||||
A file has been uploaded.
|
||||
A file has been uploaded through the web interface.
|
||||
|
||||
Payload:
|
||||
* ``name``: the file's name
|
||||
@@ -165,19 +173,74 @@ Upload
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
FileAdded
|
||||
A file has been added to a storage.
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``name``: the file's name
|
||||
* ``type``: the file's type, a list of the path within the type hierarchy, e.g. ``["machinecode", "gcode"]`` or
|
||||
``["model", "stl"]``
|
||||
|
||||
.. note::
|
||||
|
||||
A copied file triggers this for its new path. A moved file first triggers ``FileRemoved`` for its original
|
||||
path and then ``FileAdded`` for the new one.
|
||||
|
||||
FileRemoved
|
||||
A file has been removed from a storage.
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``name``: the file's name
|
||||
* ``type``: the file's type, a list of the path within the type hierarchy, e.g. ``["machinecode", "gcode"]`` or
|
||||
``["model", "stl"]``
|
||||
|
||||
.. note::
|
||||
|
||||
A moved file first triggers ``FileRemoved`` for its original path and then ``FileAdded`` for the new one.
|
||||
|
||||
FolderAdded
|
||||
A folder has been added to a storage.
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the folders's path within its storage location
|
||||
* ``name``: the folders's name
|
||||
|
||||
.. note::
|
||||
|
||||
A copied folder triggers this for its new path. A moved folder first triggers ``FolderRemoved`` for its original
|
||||
path and then ``FolderAdded`` for the new one.
|
||||
|
||||
FolderRemoved
|
||||
A folder has been removed from a storage.
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the folders's path within its storage location
|
||||
* ``name``: the folders's name
|
||||
|
||||
.. note::
|
||||
|
||||
A moved folder first triggers ``FolderRemoved`` for its original path and then ``FolderAdded`` for the new one.
|
||||
|
||||
UpdatedFiles
|
||||
A file list was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``type``: the type of file list that was modified. Currently only ``printables`` and ``gcode`` (DEPRECATED) are supported here.
|
||||
* ``type``: the type of file list that was modified. Only ``printables`` is supported here. See the deprecation
|
||||
note below.
|
||||
|
||||
.. note::
|
||||
.. deprecated:: 1.2.0
|
||||
|
||||
The ``gcode`` modification type has been superseded by ``printables``. It is currently still available for
|
||||
reasons of backwards compatibility and will also be sent on modification of ``printables``. It will however
|
||||
be removed with 1.4.0.
|
||||
|
||||
The type ``gcode`` has been renamed to ``printables`` with the introduction of a new file management layer that
|
||||
supports STL files as first class citizens as well. For reasons of backwards compatibility the ``UpdatedFiles``
|
||||
event for printable files will be fired twice, once with ``type`` set to ``gcode``, once set to ``printables``.
|
||||
Support for the ``gcode`` type will be removed in the next release after version 1.2.0.
|
||||
|
||||
MetadataAnalysisStarted
|
||||
The metadata analysis of a file has started.
|
||||
@@ -422,6 +485,15 @@ PositionUpdate
|
||||
* ``t``: last tool selected *through OctoPrint*
|
||||
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
|
||||
|
||||
ToolChange
|
||||
A tool change command was sent to the printer. The payload contains the former current tool index and the
|
||||
new current tool index.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``old``: old tool index
|
||||
* ``new``: new tool index
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
|
||||
+108
-12
@@ -13,11 +13,19 @@ Unless :ref:`configured otherwise <sec-configuration-config_yaml-folder>`, OctoP
|
||||
the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint``
|
||||
on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS).
|
||||
|
||||
These GCODE scripts are backed by the templating engine `Jinja2 <http://jinja.pocoo.org/>`_, allowing more than just
|
||||
These GCODE scripts are backed by the templating engine Jinja2, allowing more than just
|
||||
simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To
|
||||
this end, OctoPrint injects a couple of variables into the :ref:`template rendering context <sec-features-gcode_scripts-context>`
|
||||
this end, OctoPrint injects some variables into the :ref:`template rendering context <sec-features-gcode_scripts-context>`
|
||||
as described below.
|
||||
|
||||
You can find the docs on the Jinja templating engine as used in OctoPrint at `jinja.octoprint.org <http://jinja.octoprint.org/templates.html>`_.
|
||||
|
||||
.. note::
|
||||
|
||||
Due to backwards compatibility issues with Jinja versions 2.9+, OctoPrint currently only supports Jinja 2.8. For this
|
||||
reason use the template documentation at `jinja.octoprint.org <http://jinja.octoprint.org/templates.html>`_ instead of the
|
||||
documentation of current stable Jinja versions.
|
||||
|
||||
.. _sec-features-gcode_scripts-predefined:
|
||||
|
||||
Predefined Scripts
|
||||
@@ -60,23 +68,41 @@ All GCODE scripts have access to the following template variables through the te
|
||||
|
||||
* ``printer_profile``: The currently selected Printer Profile, including
|
||||
information such as the extruder count, the build volume size, the filament diameter etc.
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!)
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!).
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
|
||||
position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
|
||||
* ``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
|
||||
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``
|
||||
and ``script.name`` respectively.
|
||||
|
||||
There are a couple of additional template variables available for the following specific scripts:
|
||||
There are a few additional template variables available for the following specific scripts:
|
||||
|
||||
* ``afterPrintPaused`` and ``beforePrintResumed``
|
||||
|
||||
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
|
||||
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
|
||||
``t`` taken from commands sent through OctoPrint.
|
||||
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See
|
||||
``last_position`` above for the structure to expect here.
|
||||
|
||||
**Please note:** This will not be available if you disable
|
||||
"Log position on pause" under Settings > Serial > Advanced options!
|
||||
* ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
* ``afterPrintCancelled``
|
||||
|
||||
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
current tool ``t`` taken from commands sent through OctoPrint.
|
||||
See ``last_position`` above for the structure to expect here.
|
||||
|
||||
**Please note:** This will not be available if you disable
|
||||
"Log position on cancel" under Settings > Serial > Advanced options!
|
||||
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
|
||||
.. warning::
|
||||
|
||||
@@ -120,7 +146,7 @@ Out of the box, OctoPrint defaults to the following script setup for ``afterPrin
|
||||
|
||||
;disable all heaters
|
||||
{% snippet 'disable_hotends' %}
|
||||
[% snippet 'disable_bed' %}
|
||||
{% snippet 'disable_bed' %}
|
||||
|
||||
;disable fan
|
||||
M106 S0
|
||||
@@ -148,8 +174,78 @@ As you can see, the ``disable_hotends`` and ``disable_bed`` snippets utilize the
|
||||
extruders and set their temperature to 0, and to also set the bed temperature
|
||||
to 0 if a heated bed is configured.
|
||||
|
||||
.. _sec-features-gcode_scripts-examples:
|
||||
|
||||
Examples
|
||||
--------
|
||||
|
||||
.. _sec-features-gcode_scripts-examples-more_nifty_pause_and_resume:
|
||||
|
||||
More nifty pause and resume
|
||||
...........................
|
||||
|
||||
If you do not have a multi-extruder setup, aren't printing from SD and have "Log position on pause" enabled under
|
||||
Settings > Serial > Advanced options, the following ``afterPrintPaused`` and
|
||||
``beforePrintResumed`` scripts might be interesting for you. With something like them in place, OctoPrint will move your print head
|
||||
out of the way to a safe rest position (here ``G1 X0 Y0``, you might want to adjust that) on pause and move it back
|
||||
to the persisted pause position on resume, making sure to also reset the extruder and feedrate.
|
||||
|
||||
.. code-block:: jinja
|
||||
:caption: ``afterPrintPaused`` script
|
||||
|
||||
{% if pause_position.x is not none %}
|
||||
; relative XYZE
|
||||
G91
|
||||
M83
|
||||
|
||||
; retract filament, move Z slightly upwards
|
||||
G1 Z+5 E-5 F4500
|
||||
|
||||
; absolute XYZE
|
||||
M82
|
||||
G90
|
||||
|
||||
; move to a safe rest position, adjust as necessary
|
||||
G1 X0 Y0
|
||||
{% endif %}
|
||||
|
||||
.. code-block:: jinja
|
||||
:caption: ``beforePrintResumed`` script
|
||||
|
||||
{% if pause_position.x is not none %}
|
||||
; relative extruder
|
||||
M83
|
||||
|
||||
; prime nozzle
|
||||
G1 E-5 F4500
|
||||
G1 E5 F4500
|
||||
G1 E5 F4500
|
||||
|
||||
; absolute E
|
||||
M82
|
||||
|
||||
; absolute XYZ
|
||||
G90
|
||||
|
||||
; reset E
|
||||
G92 E{{ pause_position.e }}
|
||||
|
||||
; move back to pause position XYZ
|
||||
G1 X{{ pause_position.x }} Y{{ pause_position.y }} Z{{ pause_position.z }} F4500
|
||||
|
||||
; reset to feed rate before pause if available
|
||||
{% if pause_position.f is not none %}G1 F{{ pause_position.f }}{% endif %}
|
||||
{% endif %}
|
||||
|
||||
.. warning::
|
||||
|
||||
As mentioned in the warning above and the description of the example itself, this will *only* work if you are
|
||||
not printing from SD and not using multiple extruders since OctoPrint will only then be able to track the
|
||||
necessary position data and print parameters due to firmware limitations.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Jinja Template Designer Documentation <http://jinja.pocoo.org/docs/dev/templates/>`_
|
||||
`Jinja Template Designer Documentation <http://jinja.octoprint.org/templates.html>`_
|
||||
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
|
||||
also by OctoPrint's GCODE scripts.
|
||||
also by OctoPrint's GCODE scripts. Linked here are the docs for Jinja 2.8.1, which OctoPrint still
|
||||
relies on for backwards compatibility reasons.
|
||||
@@ -16,6 +16,9 @@ Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recov
|
||||
a third party plugin causes the server to not start up or the web interface to not render or function
|
||||
correctly anymore.
|
||||
|
||||
Whenever reporting an issue with OctoPrint, please always attempt to reproduce it in safe mode as well to
|
||||
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party plugins.
|
||||
|
||||
.. _sec-features-safemode-how:
|
||||
|
||||
How to start OctoPrint in safe mode
|
||||
@@ -23,15 +26,37 @@ How to start OctoPrint in safe mode
|
||||
|
||||
There exist three ways to start OctoPrint in safe mode:
|
||||
|
||||
* since OctoPrint 1.3.2: by selecting "Restart OctoPrint in safe mode" from the "System" menu,
|
||||
if the "Restart OctoPrint" server command has been correctly configured (see :numref:`fig-features-safemode-systemmenu`).
|
||||
* by starting OctoPrint with the command line parameter ``--safe``, e.g. ``octoprint serve --safe``
|
||||
* by setting the option ``server.startOnceInSafeMode`` in :ref:`config.yaml <sec-configuration-config_yaml>`
|
||||
to ``true`` and restarting
|
||||
* by selecting "Restart OctoPrint in safe mode" from the "System" menu,
|
||||
if the "Restart OctoPrint" server command has been correctly configured (since OctoPrint 1.3.2,
|
||||
see :numref:`fig-features-safemode-systemmenu`)
|
||||
* by setting the flag ``server.startOnceInSafeMode`` in :ref:`config.yaml <sec-configuration-config_yaml>`
|
||||
to ``true`` and restarting. To set this flag you have the following options:
|
||||
|
||||
* from command line run ``octoprint safemode`` (since OctoPrint 1.3.6)
|
||||
* from command line run ``octoprint config set --bool server.startOnceInSafeMode true`` (fixed in OctoPrint 1.3.6)
|
||||
* use the `Yamlpatcher Plugin <http://plugins.octoprint.org/plugins/yamlpatcher/>`_ and enter & apply the patch
|
||||
``[["set", "server.startOnceInSafeMode", true]]``
|
||||
* edit ``config.yaml`` manually with a text editor, locate the ``server`` block if it already exists or create it
|
||||
if it doesn't and add ``startOnceInSafeMode: true`` to it:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# ...
|
||||
server:
|
||||
startOnceInSafeMode: true
|
||||
# ...
|
||||
|
||||
Please also refer to the :ref:`YAML primer <sec-configuration-yaml>`.
|
||||
* by starting OctoPrint with the command line parameter ``--safe``, e.g. ``octoprint serve --safe`` (don't forget to
|
||||
shutdown OctoPrint first before doing this)
|
||||
|
||||
The last two options will have OctoPrint enable safe mode only for the next server start - once you
|
||||
restart OctoPrint again, safe mode will be disabled again.
|
||||
|
||||
.. note::
|
||||
|
||||
**OctoPi users**: For you that's ``~/oprint/bin/octoprint`` wherever it says just ``octoprint``.
|
||||
|
||||
.. _fig-features-safemode-systemmenu:
|
||||
.. figure:: ../images/features-safemode-systemmenu.png
|
||||
:align: center
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 24 KiB |
@@ -119,7 +119,7 @@
|
||||
:param string method: The HTTP method to use for the request (optional)
|
||||
:param string url: The URL to perform the request against (optional)
|
||||
:param object data: The data to send in the request body (optional)
|
||||
:param object opts: Additonal options to use for the request (optional)
|
||||
:param object opts: Additional options to use for the request (optional)
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.get(url, opts)
|
||||
|
||||
@@ -14,7 +14,7 @@ If you are using it from a web page hosted on OctoPrint as a Jinja2 template, yo
|
||||
methods to embed it instead of manually entering the URL, in order to have OctoPrint take care of setting the
|
||||
correct URL prefix:
|
||||
|
||||
.. code-block:: html
|
||||
.. code-block:: html+jinja
|
||||
|
||||
<!--
|
||||
full client library or all individual files, depending
|
||||
@@ -35,7 +35,7 @@ correct URL prefix:
|
||||
Regardless of which way you use to include the library, you'll also need to make sure you included JQuery and lodash,
|
||||
because the library depends on those to be available (as ``$`` and ``_``). You can embed those like this:
|
||||
|
||||
.. code-block:: html
|
||||
.. code-block:: html+jinja
|
||||
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
@@ -35,6 +35,13 @@
|
||||
: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.settings.generateApiKey(opts)
|
||||
|
||||
Generate a new system wide API key.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ref:`Settings API <sec-api-settings>`
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
.. js:function:: OctoPrintClient.util.testPath(path, additional, opts)
|
||||
|
||||
Test the provided ``path`` for existance. More test criteria supported by the :ref:`path test command <sec-api-util-test-path>`
|
||||
Test the provided ``path`` for existence. More test criteria supported by the :ref:`path test command <sec-api-util-test-path>`
|
||||
can be provided via the ``additional`` object.
|
||||
|
||||
**Example 1**
|
||||
@@ -126,8 +126,16 @@
|
||||
.done(function(response) {
|
||||
if (response.result) {
|
||||
// check passed
|
||||
var content = response.response.content;
|
||||
var mimeType = "image/jpeg";
|
||||
|
||||
var headers = response.response.headers;
|
||||
if (headers && headers["content-type"]) {
|
||||
mimeType = headers["content-type"].split(";")[0];
|
||||
}
|
||||
|
||||
var image = $("#someimage");
|
||||
image.
|
||||
image.src = "data:" + mimeType + ";base64," + content;
|
||||
} else {
|
||||
// check failed
|
||||
}
|
||||
@@ -153,6 +161,48 @@
|
||||
: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.util.testServer(host, port, additional, opts)
|
||||
|
||||
Test if a server is reachable. More options supported by the :ref:`server test command <sec-api-util-test-server>`
|
||||
can be provided via the ``additional`` object.
|
||||
|
||||
**Example 1**
|
||||
|
||||
Test if ``8.8.8.8`` is reachable on port 53 within the default timeout.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.util.testServer("8.8.8.8", 53)
|
||||
.done(function(response) {
|
||||
if (response.result) {
|
||||
// check passed
|
||||
} else {
|
||||
// check failed
|
||||
}
|
||||
});
|
||||
|
||||
**Example 2**
|
||||
|
||||
Test if ``127.0.0.1`` is reachable on port 1234 and UDP.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.util.testUrl("127.0.0.1", 1234, {"protocol": "udp"})
|
||||
.done(function(response) {
|
||||
if (response.result) {
|
||||
// check passed
|
||||
} else {
|
||||
// check failed
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
:param string url: Host to test
|
||||
:param int port: Port to test
|
||||
:param object additional: Additional parameters for the test command
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ref:`Util API <sec-api-util>`
|
||||
|
||||
@@ -14,4 +14,5 @@ Internal Modules
|
||||
server.rst
|
||||
settings.rst
|
||||
slicing.rst
|
||||
users.rst
|
||||
util.rst
|
||||
@@ -0,0 +1,9 @@
|
||||
.. _sec-modules-users:
|
||||
|
||||
octoprint.users
|
||||
---------------
|
||||
|
||||
.. automodule:: octoprint.users
|
||||
:members:
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ development environment::
|
||||
$ virtualenv venv
|
||||
[...]
|
||||
$ source venv/bin/activate
|
||||
(venv) $ pip install -e[develop]
|
||||
(venv) $ pip install -e .[develop,plugins]
|
||||
[...]
|
||||
(venv) $ octoprint --help
|
||||
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
|
||||
@@ -41,7 +41,15 @@ development environment::
|
||||
|
||||
[...]
|
||||
|
||||
We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code:
|
||||
.. important::
|
||||
|
||||
This tutorial assumes you are running OctoPrint 1.3.0 and up. Please make sure your version of
|
||||
OctoPrint is up to date before proceeding. If you did a fresh checkout, that should already
|
||||
be the case but if not you might have to update first. You can check your version of OctoPrint
|
||||
by running ``octoprint --version`` or by taking a look into the lower left corner in OctoPrint's
|
||||
web interface.
|
||||
|
||||
We'll start at the most basic form a plugin can take - just a few simple lines of Python code:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
@@ -108,7 +116,7 @@ used :func:`~octoprint.plugin.StartupPlugin.on_startup` instead, in which case o
|
||||
up and ready to serve requests.
|
||||
|
||||
You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system
|
||||
injects :ref:`a couple of useful objects <sec-plugins-mixins-injectedproperties>` into our plugin implementation classes,
|
||||
injects :ref:`a some useful objects <sec-plugins-mixins-injectedproperties>` into our plugin implementation classes,
|
||||
one of those being a fully instantiated `python logger <https://docs.python.org/2/library/logging.html>`_ ready to be
|
||||
used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld``
|
||||
for our little plugin here, or more generally ``octoprint.plugins.<plugin identifier>``.
|
||||
@@ -130,10 +138,11 @@ best way possible, meaning we want to make our plugin a fully installable python
|
||||
install directly via `OctoPrint's built-in Plugin Manager <https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager>`_
|
||||
or alternatively manually utilizing Python's standard package manager ``pip`` directly.
|
||||
|
||||
So let's begin. We'll use the `cookiecutter <https://github.com/audreyr/cookiecutter>`_ template for OctoPrint plugins here,
|
||||
so we'll first need to install that::
|
||||
So let's begin. We'll use the `cookiecutter <https://github.com/audreyr/cookiecutter>`_ template for OctoPrint plugins
|
||||
here. This should already be installed if you used the ``plugins`` extra while installing OctoPrint. However,
|
||||
you may install it with::
|
||||
|
||||
(venv) $ pip install cookiecutter
|
||||
(venv) $ pip install "cookiecutter>=1.4,<1.7"
|
||||
|
||||
Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a new OctoPrint plugin skeleton for us::
|
||||
|
||||
@@ -482,7 +491,7 @@ Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
|
||||
|
||||
OctoPrint injects the template variables that your plugin defines prefixed with ``plugin_<plugin identifier>_`` into
|
||||
the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple
|
||||
`Jinja2 Variable <http://jinja.pocoo.org/docs/dev/templates/#variables>`_ in your plugin's template.
|
||||
`Jinja2 Variable <http://jinja.octoprint.org/templates.html#variables>`_ in your plugin's template.
|
||||
|
||||
Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should
|
||||
still work and point to the URL we defined as default.
|
||||
@@ -811,12 +820,10 @@ Put something like the following into ``helloworld.css``:
|
||||
.. code-block:: css
|
||||
:linenos:
|
||||
|
||||
#tab_plugin_helloworld {
|
||||
iframe {
|
||||
width: 100%;
|
||||
height: 600px;
|
||||
border: 1px solid #808080;
|
||||
}
|
||||
#tab_plugin_helloworld iframe {
|
||||
width: 100%;
|
||||
height: 600px;
|
||||
border: 1px solid #808080;
|
||||
}
|
||||
|
||||
Don't forget to remove the ``style`` attribute from the ``iframe`` tag in ``helloworld_tab.jinja2``:
|
||||
@@ -1070,8 +1077,14 @@ For some insight on how to create plugins that react to various events within Oc
|
||||
add support for a slicer, OctoPrint's own bundled `CuraEngine plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_
|
||||
might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin <https://github.com/imrahil/OctoPrint-NavbarTemp>`_
|
||||
might show what's possible with a few lines of code already. Finally, just take a look at the
|
||||
`list of available plugins <https://github.com/foosel/OctoPrint/wiki#plugins>`_ on the OctoPrint wiki if you are
|
||||
looking for examples.
|
||||
`official Plugin Repository <http://plugins.octoprint.org>`_ if you are looking for examples.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Jinja Template Designer Documentation <http://jinja.octoprint.org/templates.html>`_
|
||||
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
|
||||
by OctoPrint's frontend. Linked here are the docs for Jinja 2.8.1, which OctoPrint still
|
||||
relies on for backwards compatibility reasons [#f3]_.
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
@@ -1084,3 +1097,7 @@ looking for examples.
|
||||
.. [#f2] Refer to the `LESS documentation <http://lesscss.org/#using-less>`_ on how to do that. If you are developing
|
||||
your plugin under Windows you might also want to give `WinLESS <http://winless.org/>`_ a look which will run
|
||||
in the background and keep your CSS files up to date with your various project's LESS files automatically.
|
||||
.. [#f3] Please always consult the Jinja documentation at `jinja.octoprint.org <http://jinja.octoprint.org>`_ instead of
|
||||
the current stable documentation available at Jinja's project page. The reason for that is that for backwards
|
||||
compatibility reasons OctoPrint currently sadly has to rely on an older version of Jinja. The documentation
|
||||
available at `jinja.octoprint.org <http://jinja.octoprint.org>`_ matches that older version.
|
||||
@@ -6,7 +6,7 @@ Helpers
|
||||
Helpers are methods that plugin can exposed 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 a couple of helper functions to the system can be found in the
|
||||
An example for providing some helper functions to the system can be found in the
|
||||
`Discovery Plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_,
|
||||
which provides it's SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
|
||||
|
||||
|
||||
+121
-5
@@ -79,7 +79,7 @@ property instead, manually instantiate your implementation instance and then add
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_action_command.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_action_command.py>`_
|
||||
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_action_command.py>`__
|
||||
:name: sec-plugin-concepts-hooks-example
|
||||
|
||||
.. _sec-plugins-hooks-ordering:
|
||||
@@ -226,6 +226,37 @@ octoprint.accesscontrol.appkey
|
||||
:return: A list of 3-tuples as described above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-accesscontrol-keyvalidator:
|
||||
|
||||
octoprint.accesscontrol.keyvalidator
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: acl_keyvalidator_hook(apikey, *args, **kwargs)
|
||||
|
||||
Via this hook plugins may validate their own customized API keys to be used to access OctoPrint's API.
|
||||
|
||||
``apikey`` will be the API key as read from the request headers.
|
||||
|
||||
Hook handlers are expected to return a :class:`~octoprint.users.User` instance here that will then be considered that
|
||||
user making the request. By returning ``None`` or nothing at all, hook handlers signal that they do not handle the
|
||||
provided key.
|
||||
|
||||
**Example:**
|
||||
|
||||
Allows using a user's id as their API key (for obvious reasons this is NOT recommended in production environments
|
||||
and merely provided for educational purposes):
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_keyvalidator.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_keyvalidator.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_keyvalidator.py>`_
|
||||
|
||||
.. versionadded:: 1.3.6
|
||||
|
||||
:param str apikey: The API key to validate
|
||||
:return: The user in whose name the request will be processed further
|
||||
:rtype: :class:`~octoprint.users.User`
|
||||
|
||||
.. _sec-plugins-hook-cli-commands:
|
||||
|
||||
octoprint.cli.commands
|
||||
@@ -370,7 +401,7 @@ octoprint.comm.protocol.action
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_action_command.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_action_command.py>`_
|
||||
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_action_command.py>`__
|
||||
|
||||
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str line: The complete line as received from the printer, format ``// action:<command>``
|
||||
@@ -389,14 +420,15 @@ This describes actually four hooks:
|
||||
* ``octoprint.comm.protocol.gcode.sending``
|
||||
* ``octoprint.comm.protocol.gcode.sent``
|
||||
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs)
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs)
|
||||
|
||||
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
|
||||
are the following:
|
||||
|
||||
* ``queuing``: This phase is triggered just before the command is added to the send queue of the communication layer. This
|
||||
corresponds to the moment a command is being read from a file that is currently being printed. Handlers
|
||||
may suppress or change commands or their command type here.
|
||||
may suppress or change commands or their command type here. This is the only phase that supports multi command
|
||||
expansion by having the handler return a list, see below for details.
|
||||
* ``queued``: This phase is triggered just after the command was added to the send queue of the communication layer.
|
||||
No manipulation is possible here anymore (returned values will be ignored).
|
||||
* ``sending``: This phase is triggered just before the command is actually being sent to the printer. Right afterwards
|
||||
@@ -425,7 +457,7 @@ This describes actually four hooks:
|
||||
|
||||
* ``None``: Don't change anything. 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. Hence, the following
|
||||
examples are all falling into this category:
|
||||
examples are all falling into this category and equivalent:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -450,6 +482,27 @@ This describes actually four hooks:
|
||||
should use this option.
|
||||
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
|
||||
Handlers which wish to rewrite both the command and the command type should use this option.
|
||||
* **"queuing" phase only**: A list of any of the above to allow for expanding one command into
|
||||
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
|
||||
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
|
||||
does not make a lot of sense to be quite honest):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
|
||||
if gcode or not cmd.startswith("@foo"):
|
||||
return
|
||||
|
||||
return [("M105", "temperature_poll"), # 2-tuple, command & command type
|
||||
("M110",), # 1-tuple, just the command
|
||||
"M117 echo foo: {}".format(cmd)] # string, just the command
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.comm.protocol.gcode.queuing": rewrite_foo
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
**Example**
|
||||
|
||||
@@ -469,6 +522,8 @@ This describes actually four hooks:
|
||||
:param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD
|
||||
printing status polling.
|
||||
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
|
||||
:param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided
|
||||
or no command could be parsed.
|
||||
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-gcode-received:
|
||||
@@ -531,6 +586,32 @@ octoprint.comm.protocol.scripts
|
||||
:return: A 2-tuple in the form ``(prefix, postfix)`` or None
|
||||
:rtype: tuple or None
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-temperatures-received:
|
||||
|
||||
octoprint.comm.protocol.temperatures.received
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: protocol_temperatures_received_hook(comm_instance, parsed_temperatures, *args, **kwargs)
|
||||
|
||||
Get the parsed temperatures returned by the printer, allowing handlers to modify them prior to handing them off
|
||||
to the system. Handlers are expected to either return ``parsed_temperatures`` as-is or a modified copy thereof.
|
||||
|
||||
``parsed_temperatures`` is a dictionary mapping from tool/bed identifier (``B``, ``T0``, ``T1``) to a 2-tuple of
|
||||
actual and target temperature, e.g. ``{'B': (45.2, 50.0), 'T0': (178.9, 210.0), 'T1': (21.3, 0.0)}``.
|
||||
|
||||
This hook can be useful in cases where a printer e.g. is prone to returning garbage data from time to time, allowing
|
||||
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.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/sanitize_temperatures.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `sanitize_temperatures.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/sanitize_temperatures.py>`_
|
||||
|
||||
.. _sec-plugins-hook-comm-transport-serial-factory:
|
||||
|
||||
octoprint.comm.transport.serial.factory
|
||||
@@ -922,3 +1003,38 @@ octoprint.ui.web.templatetypes
|
||||
:param dict template_sorting: read-only dictionary of currently configured template sorting specifications
|
||||
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
|
||||
Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
If no of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
@@ -45,6 +45,8 @@ An overview of these properties follows.
|
||||
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
|
||||
``self._user_manager``
|
||||
OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`.
|
||||
``self._connectivity_checker``
|
||||
OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
|
||||
@@ -299,6 +299,130 @@ on your view model, taking a list of all bound view models:
|
||||
});
|
||||
})
|
||||
|
||||
.. _sec-plugins-viewmodels-livecycle:
|
||||
|
||||
Lifecycle diagrams
|
||||
------------------
|
||||
|
||||
.. _sec-plugins-viewmodels-startup:
|
||||
|
||||
Web interface startup
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant Main
|
||||
participant onServerConnect
|
||||
participant fetchSettings
|
||||
participant bindViewModels
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
|
||||
Note right of DataUpdater: connectCallback = undefined
|
||||
|
||||
activate Main
|
||||
|
||||
Main->>+DataUpdater: connect
|
||||
Note right of DataUpdater: initialized = false
|
||||
DataUpdater-->>Main: ok
|
||||
deactivate Main
|
||||
DataUpdater->>DataUpdater: asynchronous connect to server...
|
||||
activate DataUpdater
|
||||
Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...)
|
||||
DataUpdater-X+Main: done
|
||||
deactivate DataUpdater
|
||||
deactivate DataUpdater
|
||||
|
||||
Main->>+DataUpdater: connectCallback = onServerConnect
|
||||
Note right of DataUpdater: connectCallback = onServerConnect
|
||||
DataUpdater-->>-Main: ok
|
||||
Main->>+onServerConnect: call
|
||||
onServerConnect->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>onServerConnect: ok
|
||||
onServerConnect-->>Main: ok
|
||||
deactivate onServerConnect
|
||||
deactivate Main
|
||||
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over Main,LoginStateViewModel: Session available!
|
||||
LoginStateViewModel-X+onServerConnect: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
Note right of DataUpdater: initialized = true
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>-onServerConnect: ok
|
||||
onServerConnect-X+Main: done
|
||||
deactivate onServerConnect
|
||||
|
||||
Main->>+fetchSettings: call
|
||||
Note right of fetchSettings: trigger onStartup
|
||||
|
||||
fetchSettings-->>Main: ok
|
||||
deactivate Main
|
||||
|
||||
fetchSettings->>+fetchSettings: asynchronous settings fetch
|
||||
fetchSettings->>+bindViewModels: call
|
||||
|
||||
loop for each view model
|
||||
bindViewModels->bindViewModels: trigger onBeforeBinding
|
||||
bindViewModels->bindViewModels: trigger onBoundTo
|
||||
bindViewModels->bindViewModels: trigger onAfterBinding
|
||||
end
|
||||
|
||||
bindViewModels->bindViewModels: trigger onAllBound
|
||||
opt User is logged in
|
||||
bindViewModels->>+LoginStateViewModel: onAllBound
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
LoginStateViewModel-->>-bindViewModels: ok
|
||||
end
|
||||
bindViewModels->bindViewModels: trigger onStartupComplete
|
||||
bindViewModels-->>-fetchSettings: ok
|
||||
|
||||
deactivate fetchSettings
|
||||
deactivate fetchSettings
|
||||
|
||||
|
||||
.. _sec-plugins-viewmodels-reconnect:
|
||||
|
||||
Web interface reconnect
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant onServerConnect
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
|
||||
activate DataUpdater
|
||||
DataUpdater->>DataUpdater: call connectCallback
|
||||
DataUpdater->>+onServerConnect: call
|
||||
onServerConnect-->>DataUpdater: ok
|
||||
deactivate DataUpdater
|
||||
|
||||
onServerConnect->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>onServerConnect: ok
|
||||
deactivate onServerConnect
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over onServerConnect,LoginStateViewModel: Session available!
|
||||
opt User is logged in
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
end
|
||||
|
||||
activate onServerConnect
|
||||
LoginStateViewModel-XonServerConnect: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>onServerConnect: ok
|
||||
deactivate DataUpdater
|
||||
deactivate onServerConnect
|
||||
|
||||
.. seealso::
|
||||
|
||||
`OctoPrint's core viewmodels <https://github.com/foosel/OctoPrint/tree/devel/src/octoprint/static/js/app/viewmodels>`_
|
||||
|
||||
@@ -7,41 +7,99 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the
|
||||
|
||||
|
||||
import codecs
|
||||
import urllib2
|
||||
import requests
|
||||
from contextlib import closing
|
||||
|
||||
from sphinx.directives import LiteralInclude, dedent_lines
|
||||
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
|
||||
nodes, set_source_info, parselinenos, logger, container_wrapper
|
||||
|
||||
if False:
|
||||
# For type annotation
|
||||
from typing import Any, List # NOQA
|
||||
|
||||
cache = dict()
|
||||
|
||||
class OnlineIncludeReader(LiteralIncludeReader):
|
||||
|
||||
def read_file(self, filename, location=None):
|
||||
# type: (unicode, Any) -> List[unicode]
|
||||
|
||||
global cache
|
||||
try:
|
||||
if filename in cache:
|
||||
lines = cache[filename]
|
||||
else:
|
||||
with closing(requests.get(filename, stream=True)) as r:
|
||||
r.encoding = self.encoding
|
||||
lines = r.text.splitlines(True)
|
||||
cache[filename] = lines
|
||||
|
||||
if 'tab-width' in self.options:
|
||||
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
|
||||
|
||||
return lines
|
||||
except (IOError, OSError):
|
||||
raise IOError(_('Include file %r not found or reading it failed') % filename)
|
||||
except UnicodeError:
|
||||
raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
|
||||
'be wrong, try giving an :encoding: option') %
|
||||
(self.encoding, filename))
|
||||
|
||||
|
||||
class OnlineIncludeDirective(LiteralInclude):
|
||||
|
||||
def read_with_encoding(self, filename, document, codec_info, encoding):
|
||||
global cache
|
||||
def run(self):
|
||||
# type: () -> List[nodes.Node]
|
||||
document = self.state.document
|
||||
if not document.settings.file_insertion_enabled:
|
||||
return [document.reporter.warning('File insertion disabled',
|
||||
line=self.lineno)]
|
||||
env = document.settings.env
|
||||
|
||||
# convert options['diff'] to absolute path
|
||||
if 'diff' in self.options:
|
||||
_, path = env.relfn2path(self.options['diff'])
|
||||
self.options['diff'] = path
|
||||
|
||||
f = None
|
||||
try:
|
||||
if not self.arguments[0] in cache:
|
||||
f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2],
|
||||
codec_info[3], 'strict')
|
||||
lines = f.readlines()
|
||||
cache[self.arguments[0]] = lines
|
||||
else:
|
||||
lines = cache[self.arguments[0]]
|
||||
location = self.state_machine.get_source_and_line(self.lineno)
|
||||
url = self.arguments[0]
|
||||
|
||||
reader = OnlineIncludeReader(url, self.options, env.config)
|
||||
text, lines = reader.read(location=location)
|
||||
|
||||
retnode = nodes.literal_block(text, text, source=url)
|
||||
set_source_info(self, retnode)
|
||||
if self.options.get('diff'): # if diff is set, set udiff
|
||||
retnode['language'] = 'udiff'
|
||||
elif 'language' in self.options:
|
||||
retnode['language'] = self.options['language']
|
||||
retnode['linenos'] = ('linenos' in self.options or
|
||||
'lineno-start' in self.options or
|
||||
'lineno-match' in self.options)
|
||||
retnode['classes'] += self.options.get('class', [])
|
||||
extra_args = retnode['highlight_args'] = {}
|
||||
if 'emphasize-lines' in self.options:
|
||||
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
|
||||
if any(i >= lines for i in hl_lines):
|
||||
logger.warning('line number spec is out of range(1-%d): %r' %
|
||||
(lines, self.options['emphasize-lines']),
|
||||
location=location)
|
||||
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
|
||||
extra_args['linenostart'] = reader.lineno_start
|
||||
|
||||
if 'caption' in self.options:
|
||||
caption = self.options['caption'] or self.arguments[0]
|
||||
retnode = container_wrapper(self, retnode, caption)
|
||||
|
||||
# retnode will be note_implicit_target that is linked from caption and numref.
|
||||
# when options['name'] is provided, it should be primary ID.
|
||||
self.add_name(retnode)
|
||||
|
||||
return [retnode]
|
||||
except Exception as exc:
|
||||
return [document.reporter.warning(str(exc), line=self.lineno)]
|
||||
|
||||
lines = dedent_lines(lines, self.options.get('dedent'))
|
||||
return lines
|
||||
except (IOError, OSError, urllib2.URLError):
|
||||
return [document.reporter.warning(
|
||||
'Include file %r not found or reading it failed' % self.arguments[0],
|
||||
line=self.lineno)]
|
||||
except UnicodeError:
|
||||
return [document.reporter.warning(
|
||||
'Encoding %r used for reading included file %r seems to '
|
||||
'be wrong, try giving an :encoding: option' %
|
||||
(encoding, self.arguments[0]))]
|
||||
finally:
|
||||
if f is not None:
|
||||
f.close()
|
||||
|
||||
def visit_onlineinclude(translator, node):
|
||||
translator.visit_literal_block(node)
|
||||
@@ -53,4 +111,4 @@ def setup(app):
|
||||
app.add_directive("onlineinclude", OnlineIncludeDirective)
|
||||
|
||||
handler = (visit_onlineinclude, depart_onlineinclude)
|
||||
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
|
||||
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
|
||||
@@ -7,4 +7,6 @@
|
||||
# variables INSTALL_REQUIRES and EXTRA_REQUIRES.
|
||||
###
|
||||
|
||||
# let's force the regular pypi URL, with https, just to be sure
|
||||
-i https://pypi.python.org/simple
|
||||
.
|
||||
@@ -3,7 +3,7 @@ description-file = README.md
|
||||
|
||||
[versioneer]
|
||||
VCS = git
|
||||
style = pep440-post
|
||||
style = pep440-tag
|
||||
versionfile_source = src/octoprint/_version.py
|
||||
versionfile_build = octoprint/_version.py
|
||||
tag_prefix =
|
||||
|
||||
@@ -23,7 +23,7 @@ INSTALL_REQUIRES = [
|
||||
# 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.2,<1.1",
|
||||
"sockjs-tornado>=1.0.3,<1.1",
|
||||
"PyYAML>=3.10,<3.11",
|
||||
"Flask-Login>=0.2.2,<0.3",
|
||||
"Flask-Principal>=0.3.5,<0.4",
|
||||
@@ -38,16 +38,21 @@ INSTALL_REQUIRES = [
|
||||
"pylru>=1.0.9,<1.1",
|
||||
"rsa>=3.2,<3.3",
|
||||
"pkginfo>=1.2.1,<1.3",
|
||||
"requests>=2.7,<2.8",
|
||||
"requests>=2.18.4,<3",
|
||||
"semantic_version>=2.4.2,<2.5",
|
||||
"psutil>=3.2.1,<3.3",
|
||||
"psutil>=5.4.1,<6",
|
||||
"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",
|
||||
"scandir>=1.3,<1.4",
|
||||
"websocket-client>=0.40,<0.41"
|
||||
"websocket-client>=0.40,<0.41",
|
||||
"python-dateutil>=2.6,<2.7",
|
||||
"wrapt>=1.10.10,<1.11",
|
||||
"futures>=3.1.1,<3.2",
|
||||
"emoji>=0.4.5,<0.5",
|
||||
"monotonic>=1.3,<1.4"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
@@ -58,13 +63,14 @@ EXTRA_REQUIRES = dict(
|
||||
# Dependencies for developing OctoPrint
|
||||
develop=[
|
||||
# Testing dependencies
|
||||
"mock>=1.0.1,<1.1",
|
||||
"mock>=2.0.0,<3",
|
||||
"nose>=1.3.0,<1.4",
|
||||
"ddt",
|
||||
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.3,<1.4",
|
||||
"sphinx>=1.6,<1.7",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid>=0.3",
|
||||
"sphinx_rtd_theme",
|
||||
|
||||
# PyPi upload related
|
||||
@@ -73,7 +79,7 @@ EXTRA_REQUIRES = dict(
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
plugins=[
|
||||
"cookiecutter>=1.4,<1.5"
|
||||
"cookiecutter>=1.4,<1.7"
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
+174
-11
@@ -12,7 +12,7 @@ versions = get_versions()
|
||||
|
||||
__version__ = versions['version']
|
||||
__branch__ = versions.get('branch', None)
|
||||
__display_version__ = "{} ({} branch)".format(__version__, __branch__) if __branch__ else __version__
|
||||
__display_version__ = __version__
|
||||
__revision__ = versions.get('full-revisionid', versions.get('full', None))
|
||||
|
||||
del versions
|
||||
@@ -57,9 +57,10 @@ class FatalStartupError(BaseException):
|
||||
|
||||
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, after_preinit_logging=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_plugin_manager=None):
|
||||
after_event_manager=None, after_connectivity_checker=None,
|
||||
after_plugin_manager=None, after_environment_detector=None):
|
||||
kwargs = dict()
|
||||
|
||||
logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler)
|
||||
@@ -94,13 +95,34 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
if callable(after_safe_mode):
|
||||
after_safe_mode(**kwargs)
|
||||
|
||||
plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode)
|
||||
event_manager = init_event_manager(settings)
|
||||
|
||||
kwargs["event_manager"] = event_manager
|
||||
if callable(after_event_manager):
|
||||
after_event_manager(**kwargs)
|
||||
|
||||
connectivity_checker = init_connectivity_checker(settings, event_manager)
|
||||
|
||||
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
|
||||
|
||||
if callable(after_plugin_manager):
|
||||
after_plugin_manager(**kwargs)
|
||||
|
||||
return settings, logger, safe_mode, plugin_manager
|
||||
environment_detector = init_environment_detector(plugin_manager)
|
||||
kwargs["environment_detector"] = environment_detector
|
||||
|
||||
if callable(after_environment_detector):
|
||||
after_environment_detector(**kwargs)
|
||||
|
||||
return settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector
|
||||
|
||||
|
||||
def init_settings(basedir, configfile):
|
||||
@@ -194,12 +216,13 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
"level": "DEBUG",
|
||||
"formatter": "serial",
|
||||
"backupCount": 3,
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log")
|
||||
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
|
||||
"delay": True
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
"SERIAL": {
|
||||
"level": "CRITICAL",
|
||||
"level": "INFO",
|
||||
"handlers": ["serialFile"],
|
||||
"propagate": False
|
||||
},
|
||||
@@ -280,18 +303,22 @@ def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handl
|
||||
return logger
|
||||
|
||||
|
||||
def init_pluginsystem(settings, safe_mode=False):
|
||||
def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connectivity_checker=None):
|
||||
"""Initializes the plugin manager based on the settings."""
|
||||
|
||||
import os
|
||||
|
||||
logger = log.getLogger(__name__)
|
||||
logger = log.getLogger(__name__ + ".startup")
|
||||
|
||||
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
|
||||
settings.getBaseFolder("plugins")]
|
||||
plugin_entry_points = ["octoprint.plugin"]
|
||||
plugin_disabled_list = settings.get(["plugins", "_disabled"])
|
||||
|
||||
plugin_blacklist = []
|
||||
if not ignore_blacklist and settings.getBoolean(["server", "pluginBlacklist", "enabled"]):
|
||||
plugin_blacklist = get_plugin_blacklist(settings, connectivity_checker=connectivity_checker)
|
||||
|
||||
plugin_validators = []
|
||||
if safe_mode:
|
||||
def validator(phase, plugin_info):
|
||||
@@ -310,13 +337,14 @@ def init_pluginsystem(settings, safe_mode=False):
|
||||
plugin_folders=plugin_folders,
|
||||
plugin_entry_points=plugin_entry_points,
|
||||
plugin_disabled_list=plugin_disabled_list,
|
||||
plugin_blacklist=plugin_blacklist,
|
||||
plugin_validators=plugin_validators)
|
||||
|
||||
settings_overlays = dict()
|
||||
disabled_from_overlays = dict()
|
||||
|
||||
def handle_plugin_loaded(name, plugin):
|
||||
if hasattr(plugin.instance, "__plugin_settings_overlay__"):
|
||||
if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"):
|
||||
plugin.needs_restart = True
|
||||
|
||||
# plugin has a settings overlay, inject it
|
||||
@@ -355,7 +383,7 @@ def init_pluginsystem(settings, safe_mode=False):
|
||||
|
||||
if not addon in already_processed and not addon in disabled_list:
|
||||
disabled_list.append(addon)
|
||||
logger.info("Disabling plugin {} as defined by plugin {} through settings overlay".format(addon, name))
|
||||
logger.info("Disabling plugin {} as defined by plugin {}".format(addon, name))
|
||||
already_processed.append(name)
|
||||
|
||||
def handle_plugin_enabled(name, plugin):
|
||||
@@ -369,6 +397,141 @@ def init_pluginsystem(settings, safe_mode=False):
|
||||
pm.reload_plugins(startup=True, initialize_implementations=False)
|
||||
return pm
|
||||
|
||||
|
||||
def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
import requests
|
||||
import os
|
||||
import time
|
||||
import yaml
|
||||
|
||||
from octoprint.util import bom_aware_open
|
||||
from octoprint.util.version import is_octoprint_compatible
|
||||
|
||||
logger = log.getLogger(__name__ + ".startup")
|
||||
|
||||
if connectivity_checker is not None and not connectivity_checker.online:
|
||||
logger.info("We don't appear to be online, not fetching plugin blacklist")
|
||||
return []
|
||||
|
||||
def format_blacklist(entries):
|
||||
format_entry = lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 \
|
||||
else "{} (any)".format(x)
|
||||
return ", ".join(map(format_entry, entries))
|
||||
|
||||
def process_blacklist(entries):
|
||||
result = []
|
||||
|
||||
if not isinstance(entries, list):
|
||||
return result
|
||||
|
||||
for entry in entries:
|
||||
if not "plugin" in entry:
|
||||
continue
|
||||
|
||||
if "octoversions" in entry and not is_octoprint_compatible(*entry["octoversions"]):
|
||||
continue
|
||||
|
||||
if "version" in entry:
|
||||
logger.debug("Blacklisted plugin: {}, version: {}".format(entry["plugin"], entry["version"]))
|
||||
result.append((entry["plugin"], entry["version"]))
|
||||
elif "versions" in entry:
|
||||
logger.debug("Blacklisted plugin: {}, versions: {}".format(entry["plugin"], ", ".join(entry["versions"])))
|
||||
for version in entry["versions"]:
|
||||
result.append((entry["plugin"], version))
|
||||
else:
|
||||
logger.debug("Blacklisted plugin: {}".format(entry["plugin"]))
|
||||
result.append(entry["key"])
|
||||
|
||||
return result
|
||||
|
||||
def fetch_blacklist_from_cache(path, ttl):
|
||||
if not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
if os.stat(path).st_mtime + ttl < time.time():
|
||||
return None
|
||||
|
||||
with bom_aware_open(path, encoding="utf-8", mode="r") as f:
|
||||
result = yaml.safe_load(f)
|
||||
|
||||
if isinstance(result, list):
|
||||
return result
|
||||
|
||||
def fetch_blacklist_from_url(url, timeout=3, cache=None):
|
||||
result = []
|
||||
try:
|
||||
r = requests.get(url, timeout=timeout)
|
||||
result = process_blacklist(r.json())
|
||||
|
||||
if cache is not None:
|
||||
try:
|
||||
with bom_aware_open(cache, encoding="utf-8", mode="w") as f:
|
||||
yaml.safe_dump(result, f)
|
||||
except:
|
||||
logger.info("Fetched plugin blacklist but couldn't write it to its cache file.")
|
||||
except:
|
||||
logger.info("Unable to fetch plugin blacklist from {}, proceeding without it.".format(url))
|
||||
return result
|
||||
|
||||
try:
|
||||
# first attempt to fetch from cache
|
||||
cache_path = os.path.join(settings.getBaseFolder("data"), "plugin_blacklist.yaml")
|
||||
ttl = settings.getInt(["server", "pluginBlacklist", "ttl"])
|
||||
blacklist = fetch_blacklist_from_cache(cache_path, ttl)
|
||||
|
||||
if blacklist is None:
|
||||
# no result from the cache, let's fetch it fresh
|
||||
url = settings.get(["server", "pluginBlacklist", "url"])
|
||||
timeout = settings.getFloat(["server", "pluginBlacklist", "timeout"])
|
||||
blacklist = fetch_blacklist_from_url(url, timeout=timeout, cache=cache_path)
|
||||
|
||||
if blacklist is None:
|
||||
# still now result, so no blacklist
|
||||
blacklist = []
|
||||
|
||||
if blacklist:
|
||||
logger.info("Blacklist processing done, "
|
||||
"adding {} blacklisted plugin versions: {}".format(len(blacklist),
|
||||
format_blacklist(blacklist)))
|
||||
else:
|
||||
logger.info("Blacklist processing done")
|
||||
|
||||
return blacklist
|
||||
except:
|
||||
logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.")
|
||||
|
||||
|
||||
def init_event_manager(settings):
|
||||
from octoprint.events import eventManager
|
||||
return eventManager()
|
||||
|
||||
|
||||
def init_connectivity_checker(settings, event_manager):
|
||||
from octoprint.events import Events
|
||||
from octoprint.util import ConnectivityChecker
|
||||
|
||||
# start regular check if we are connected to the internet
|
||||
connectivityEnabled = settings.getBoolean(["server", "onlineCheck", "enabled"])
|
||||
connectivityInterval = settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = settings.getInt(["server", "onlineCheck", "port"])
|
||||
|
||||
def on_connectivity_change(old_value, new_value):
|
||||
event_manager.fire(Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
|
||||
|
||||
connectivityChecker = ConnectivityChecker(connectivityInterval,
|
||||
connectivityHost,
|
||||
port=connectivityPort,
|
||||
enabled=connectivityEnabled,
|
||||
on_change=on_connectivity_change)
|
||||
|
||||
return connectivityChecker
|
||||
|
||||
|
||||
def init_environment_detector(plugin_manager):
|
||||
from octoprint.environment import EnvironmentDetector
|
||||
return EnvironmentDetector(plugin_manager)
|
||||
|
||||
#~~ server main method
|
||||
|
||||
def main():
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env python2
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
if __name__ == "__main__":
|
||||
import octoprint
|
||||
octoprint.main()
|
||||
@@ -102,13 +102,13 @@ def standard_options(hidden=False):
|
||||
|
||||
options = [
|
||||
factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
||||
help="Specify the basedir to use for uploads, timelapses etc."),
|
||||
help="Specify the basedir to use for configs, uploads, timelapses etc."),
|
||||
factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
||||
help="Specify the config file to use."),
|
||||
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
||||
help="Increase logging verbosity"),
|
||||
help="Increase logging verbosity."),
|
||||
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
||||
help="Enable safe mode; disables all third party plugins")
|
||||
help="Enable safe mode; disables all third party plugins.")
|
||||
]
|
||||
|
||||
return bulk_options(options)
|
||||
@@ -123,6 +123,7 @@ legacy_options = bulk_options([
|
||||
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option),
|
||||
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option),
|
||||
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option),
|
||||
hidden_option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option)
|
||||
])
|
||||
"""Legacy options available directly on the "octoprint" command in earlier versions.
|
||||
Kept available for reasons of backwards compatibility, but hidden from the
|
||||
@@ -135,9 +136,10 @@ from .plugins import plugin_commands
|
||||
from .dev import dev_commands
|
||||
from .client import client_commands
|
||||
from .config import config_commands
|
||||
from .analysis import analysis_commands
|
||||
|
||||
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands])
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
|
||||
@standard_options()
|
||||
@legacy_options
|
||||
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
|
||||
@@ -160,11 +162,11 @@ def octo(ctx, **kwargs):
|
||||
"start|stop|restart\" is deprecated, please use "
|
||||
"\"octoprint daemon start|stop|restart\" from now on")
|
||||
|
||||
if sys.platform == "linux2":
|
||||
if sys.platform == "win32" or sys.platform == "darwin":
|
||||
click.echo("Sorry, daemon mode is not supported under your operating system right now")
|
||||
else:
|
||||
from octoprint.cli.server import daemon_command
|
||||
ctx.invoke(daemon_command, command=daemon, **kwargs)
|
||||
else:
|
||||
click.echo("Sorry, daemon mode is only supported under Linux right now")
|
||||
else:
|
||||
click.echo("Starting the server via \"octoprint\" is deprecated, "
|
||||
"please use \"octoprint serve\" from now on.")
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import click
|
||||
|
||||
#~~ "octoprint util" commands
|
||||
|
||||
@click.group()
|
||||
def analysis_commands():
|
||||
pass
|
||||
|
||||
@analysis_commands.group(name="analysis")
|
||||
def util():
|
||||
"""Analysis tools."""
|
||||
pass
|
||||
|
||||
|
||||
@util.command(name="gcode")
|
||||
@click.option("--throttle", "throttle", type=float, default=None)
|
||||
@click.option("--throttle-lines", "throttle_lines", type=int, default=None)
|
||||
@click.option("--speed-x", "speedx", type=float, default=6000)
|
||||
@click.option("--speed-y", "speedy", type=float, default=6000)
|
||||
@click.option("--speed-z", "speedz", type=float, default=300)
|
||||
@click.option("--offset", "offset", type=(float, float), multiple=True)
|
||||
@click.option("--max-t", "maxt", type=int, default=10)
|
||||
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
|
||||
@click.option("--progress", "progress", is_flag=True)
|
||||
@click.argument("path", type=click.Path())
|
||||
def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
|
||||
"""Runs a GCODE file analysis."""
|
||||
|
||||
import time
|
||||
import yaml
|
||||
from octoprint.util.gcodeInterpreter import gcode
|
||||
|
||||
throttle_callback = None
|
||||
if throttle:
|
||||
def throttle_callback(filePos, readBytes):
|
||||
if filePos % throttle_lines == 0:
|
||||
# only apply throttle every $throttle_lines lines
|
||||
time.sleep(throttle)
|
||||
|
||||
offsets = offset
|
||||
if offsets is None:
|
||||
offsets = []
|
||||
elif isinstance(offset, tuple):
|
||||
offsets = list(offsets)
|
||||
offsets = [(0, 0)] + offsets
|
||||
if len(offsets) < maxt:
|
||||
offsets += [(0, 0)] * (maxt - len(offsets))
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
progress_callback = None
|
||||
if progress:
|
||||
def progress_callback(percentage):
|
||||
click.echo("PROGRESS:{}".format(percentage))
|
||||
interpreter = gcode(progress_callback=progress_callback)
|
||||
|
||||
interpreter.load(path,
|
||||
speedx=speedx,
|
||||
speedy=speedy,
|
||||
offsets=offsets,
|
||||
throttle=throttle_callback,
|
||||
max_extruders=maxt,
|
||||
g90_extruder=g90_extruder)
|
||||
|
||||
click.echo("DONE:{}s".format(time.time() - start_time))
|
||||
click.echo("RESULTS:")
|
||||
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
|
||||
+90
-32
@@ -9,7 +9,7 @@ import json
|
||||
|
||||
import octoprint_client
|
||||
|
||||
from octoprint.cli import get_ctx_obj_option
|
||||
from octoprint.cli import get_ctx_obj_option, bulk_options
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
|
||||
|
||||
@@ -23,24 +23,66 @@ class JsonStringParamType(click.ParamType):
|
||||
self.fail("%s is not a valid json string" % value, param, ctx)
|
||||
|
||||
|
||||
def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None):
|
||||
assert(host is not None or settings is not None)
|
||||
assert(port is not None or settings is not None)
|
||||
assert(apikey is not None or settings is not None)
|
||||
|
||||
if not host:
|
||||
host = settings.get(["server", "host"])
|
||||
host = host if host != "0.0.0.0" else "127.0.0.1"
|
||||
if not port:
|
||||
port = settings.getInt(["server", "port"])
|
||||
|
||||
if not apikey:
|
||||
apikey = settings.get(["api", "key"])
|
||||
|
||||
baseurl = octoprint_client.build_base_url(https=https,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
host=host,
|
||||
port=port,
|
||||
prefix=prefix)
|
||||
|
||||
return octoprint_client.Client(baseurl, apikey)
|
||||
|
||||
|
||||
client_options = bulk_options([
|
||||
click.option("--apikey", "-a", type=click.STRING),
|
||||
click.option("--host", "-h", type=click.STRING),
|
||||
click.option("--port", "-p", type=click.INT),
|
||||
click.option("--httpuser", type=click.STRING),
|
||||
click.option("--httppass", type=click.STRING),
|
||||
click.option("--https", is_flag=True),
|
||||
click.option("--prefix", type=click.STRING)
|
||||
])
|
||||
"""Common options to configure an API client."""
|
||||
|
||||
|
||||
@click.group()
|
||||
def client_commands():
|
||||
pass
|
||||
|
||||
|
||||
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
|
||||
@click.option("--host", "-h", type=click.STRING)
|
||||
@click.option("--port", "-p", type=click.INT)
|
||||
@click.option("--httpuser", type=click.STRING)
|
||||
@click.option("--httppass", type=click.STRING)
|
||||
@click.option("--https", is_flag=True)
|
||||
@click.option("--prefix", type=click.STRING)
|
||||
@client_options
|
||||
@click.pass_context
|
||||
def client(ctx, host, port, httpuser, httppass, https, prefix):
|
||||
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
"""Basic API client."""
|
||||
try:
|
||||
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
octoprint_client.init_client(ctx.obj.settings, https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix)
|
||||
settings = None
|
||||
if not host or not port or not apikey:
|
||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
|
||||
ctx.obj.client = create_client(settings=settings,
|
||||
apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the client.", err=True)
|
||||
@@ -60,27 +102,33 @@ def log_response(response, status_code=True, body=True, headers=False):
|
||||
|
||||
@client.command("get")
|
||||
@click.argument("path")
|
||||
def get(path):
|
||||
@click.option("--timeout", type=float, default=None)
|
||||
@click.pass_context
|
||||
def get(ctx, path, timeout):
|
||||
"""Performs a GET request against the specified server path."""
|
||||
r = octoprint_client.get(path)
|
||||
r = ctx.obj.client.get(path, timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("post_json")
|
||||
@click.argument("path")
|
||||
@click.argument("data", type=JsonStringParamType())
|
||||
def post_json(path, data):
|
||||
@click.option("--timeout", type=float, default=None)
|
||||
@click.pass_context
|
||||
def post_json(ctx, path, data, timeout):
|
||||
"""POSTs JSON data to the specified server path."""
|
||||
r = octoprint_client.post_json(path, data)
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("patch_json")
|
||||
@click.argument("path")
|
||||
@click.argument("data", type=JsonStringParamType())
|
||||
def patch_json(path, data):
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def patch_json(ctx, path, data, timeout):
|
||||
"""PATCHes JSON data to the specified server path."""
|
||||
r = octoprint_client.patch(path, data, encoding="json")
|
||||
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@@ -89,8 +137,10 @@ def patch_json(path, data):
|
||||
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
|
||||
@click.option("--json", is_flag=True)
|
||||
@click.option("--yaml", is_flag=True)
|
||||
def post_from_file(path, file_path, json_flag, yaml_flag):
|
||||
"""POSTs JSON data to the specified server path."""
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
||||
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
|
||||
if json_flag or yaml_flag:
|
||||
if json_flag:
|
||||
with open(file_path, "rb") as fp:
|
||||
@@ -100,12 +150,12 @@ def post_from_file(path, file_path, json_flag, yaml_flag):
|
||||
with open(file_path, "rb") as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
|
||||
r = octoprint_client.post_json(path, data)
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
else:
|
||||
with open(file_path, "rb") as fp:
|
||||
data = fp.read()
|
||||
|
||||
r = octoprint_client.post(path, data)
|
||||
r = ctx.obj.client.post(path, data, timeout=timeout)
|
||||
|
||||
log_response(r)
|
||||
|
||||
@@ -117,13 +167,15 @@ def post_from_file(path, file_path, json_flag, yaml_flag):
|
||||
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
|
||||
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
|
||||
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
|
||||
def command(path, command, str_params, int_params, float_params, bool_params):
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
|
||||
"""Sends a JSON command to the specified server path."""
|
||||
data = dict()
|
||||
params = str_params + int_params + float_params + bool_params
|
||||
for param in params:
|
||||
data[param[0]] = param[1]
|
||||
r = octoprint_client.post_command(path, command, additional=data)
|
||||
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
|
||||
log_response(r, body=False)
|
||||
|
||||
|
||||
@@ -133,26 +185,32 @@ def command(path, command, str_params, int_params, float_params, bool_params):
|
||||
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
|
||||
@click.option("--file-name", type=click.STRING)
|
||||
@click.option("--content-type", type=click.STRING)
|
||||
def upload(path, file_path, params, file_name, content_type):
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
|
||||
"""Uploads the specified file to the specified server path."""
|
||||
data = dict()
|
||||
for param in params:
|
||||
data[param[0]] = param[1]
|
||||
|
||||
r = octoprint_client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type)
|
||||
r = ctx.obj.client.upload(path, file_path,
|
||||
additional=data, file_name=file_name, content_type=content_type, timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("delete")
|
||||
@click.argument("path")
|
||||
def delete(path):
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def delete(ctx, path, timeout):
|
||||
"""Sends a DELETE request to the specified server path."""
|
||||
r = octoprint_client.delete(path)
|
||||
r = ctx.obj.client.delete(path, timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("listen")
|
||||
def listen():
|
||||
@click.pass_context
|
||||
def listen(ctx):
|
||||
def on_connect(ws):
|
||||
click.echo(">>> Connected!")
|
||||
|
||||
@@ -168,11 +226,11 @@ def listen():
|
||||
def on_message(ws, message_type, message_payload):
|
||||
click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload)))
|
||||
|
||||
socket = octoprint_client.connect_socket(on_connect=on_connect,
|
||||
on_close=on_close,
|
||||
on_error=on_error,
|
||||
on_heartbeat=on_heartbeat,
|
||||
on_message=on_message)
|
||||
socket = ctx.obj.client.create_socket(on_connect=on_connect,
|
||||
on_close=on_close,
|
||||
on_error=on_error,
|
||||
on_heartbeat=on_heartbeat,
|
||||
on_message=on_message)
|
||||
|
||||
click.echo(">>> Waiting for client to exit")
|
||||
try:
|
||||
|
||||
@@ -9,7 +9,7 @@ import click
|
||||
import logging
|
||||
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
from octoprint.cli import pass_octoprint_ctx, standard_options, bulk_options, get_ctx_obj_option
|
||||
from octoprint.cli import standard_options, bulk_options, get_ctx_obj_option
|
||||
|
||||
import yaml
|
||||
import json
|
||||
@@ -54,7 +54,7 @@ def config(ctx):
|
||||
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the client.", err=True)
|
||||
click.echo("There was a fatal error initializing the settings manager.", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
|
||||
@@ -70,7 +70,6 @@ def config(ctx):
|
||||
help="Interpret value as int")
|
||||
@click.option("--json", "as_json", is_flag=True,
|
||||
help="Parse value from json")
|
||||
@pass_octoprint_ctx
|
||||
@click.pass_context
|
||||
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
|
||||
"""Sets a config path to the provided value."""
|
||||
@@ -163,7 +162,6 @@ def insert_value_command(ctx, path, index, value, as_json=False):
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("value", type=click.STRING)
|
||||
@click.option("--json", "as_json", is_flag=True)
|
||||
@pass_octoprint_ctx
|
||||
@click.pass_context
|
||||
def remove_value_command(ctx, path, value, as_json=False):
|
||||
"""Removes value from list at config path."""
|
||||
@@ -216,3 +214,28 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
||||
output = pprint.pformat(value)
|
||||
|
||||
click.echo(output)
|
||||
|
||||
|
||||
@config.command(name="effective")
|
||||
@click.option("--json", "as_json", is_flag=True,
|
||||
help="Output value formatted as JSON")
|
||||
@click.option("--yaml", "as_yaml", is_flag=True,
|
||||
help="Output value formatted as YAML")
|
||||
@click.option("--raw", "as_raw", is_flag=True,
|
||||
help="Output value as raw string representation")
|
||||
@standard_options(hidden=True)
|
||||
@click.pass_context
|
||||
def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
|
||||
"""Retrieves the full effective config."""
|
||||
value = ctx.obj.settings.effective
|
||||
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
output = pprint.pformat(value)
|
||||
|
||||
click.echo(output)
|
||||
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import click
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
class OctoPrintDevelCommands(click.MultiCommand):
|
||||
"""
|
||||
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
|
||||
@@ -204,7 +206,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
click.echo("This doesn't look like an OctoPrint plugin folder")
|
||||
sys.exit(1)
|
||||
|
||||
self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path)
|
||||
self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path)
|
||||
|
||||
return command
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
if self._initialized:
|
||||
return
|
||||
|
||||
click.echo("Initializing settings & plugin subsystem...")
|
||||
if ctx.obj is None:
|
||||
ctx.obj = OctoPrintContext()
|
||||
|
||||
@@ -51,7 +52,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
from octoprint import init_settings, init_pluginsystem, FatalStartupError
|
||||
try:
|
||||
self.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
self.plugin_manager = init_pluginsystem(self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False))
|
||||
self.plugin_manager = init_pluginsystem(self.settings,
|
||||
safe_mode=get_ctx_obj_option(ctx, "safe_mode", False))
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the settings or the plugin system.", err=True)
|
||||
@@ -60,6 +62,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
# fetch registered hooks
|
||||
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARN)
|
||||
|
||||
self._initialized = True
|
||||
|
||||
def list_commands(self, ctx):
|
||||
@@ -88,14 +92,14 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
continue
|
||||
result[name + self.sep + command.name] = command
|
||||
except:
|
||||
self._logger.exception("Error while retrieving cli commants for plugin {}".format(name))
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
|
||||
|
||||
return result
|
||||
|
||||
@click.group()
|
||||
@pass_octoprint_ctx
|
||||
def plugin_commands(obj):
|
||||
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
|
||||
pass
|
||||
|
||||
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
|
||||
def plugins():
|
||||
|
||||
+58
-22
@@ -11,7 +11,8 @@ import sys
|
||||
|
||||
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
|
||||
|
||||
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, octoprint_daemon=None):
|
||||
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode,
|
||||
ignore_blacklist, octoprint_daemon=None):
|
||||
"""Initializes the environment and starts up the server."""
|
||||
|
||||
from octoprint import init_platform, __display_version__, FatalStartupError
|
||||
@@ -19,7 +20,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
def log_startup(recorder=None, safe_mode=None, **kwargs):
|
||||
from octoprint.logging import get_divider_line
|
||||
|
||||
logger = logging.getLogger("octoprint.server")
|
||||
logger = logging.getLogger("octoprint.startup")
|
||||
|
||||
logger.info(get_divider_line("*"))
|
||||
logger.info("Starting OctoPrint {}".format(__display_version__))
|
||||
@@ -47,7 +48,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
|
||||
logger.info(get_divider_line("*"))
|
||||
|
||||
def log_register_rollover(safe_mode=None, plugin_manager=None, **kwargs):
|
||||
def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs):
|
||||
from octoprint.logging import get_handler, log_to_handler, get_divider_line
|
||||
from octoprint.logging.handlers import OctoPrintLogHandler
|
||||
|
||||
@@ -66,20 +67,24 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
if safe_mode:
|
||||
_log("SAFE MODE is active. Third party plugins are disabled!")
|
||||
plugin_manager.log_all_plugins(only_to_handler=handler)
|
||||
environment_detector.log_detected_environment(only_to_handler=handler)
|
||||
_log(get_divider_line("-"))
|
||||
|
||||
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
|
||||
|
||||
try:
|
||||
settings, _, safe_mode, plugin_manager = init_platform(basedir,
|
||||
configfile,
|
||||
logging_file=logging_config,
|
||||
debug=debug,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=__name__,
|
||||
safe_mode=safe_mode,
|
||||
after_safe_mode=log_startup,
|
||||
after_plugin_manager=log_register_rollover)
|
||||
components = init_platform(basedir, configfile,
|
||||
logging_file=logging_config,
|
||||
debug=debug,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=__name__,
|
||||
safe_mode=safe_mode,
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
after_safe_mode=log_startup,
|
||||
after_environment_detector=log_register_rollover)
|
||||
|
||||
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
|
||||
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error starting up OctoPrint.", err=True)
|
||||
@@ -87,6 +92,9 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
from octoprint.server import Server
|
||||
octoprint_server = Server(settings=settings,
|
||||
plugin_manager=plugin_manager,
|
||||
event_manager=event_manager,
|
||||
connectivity_checker=connectivity_checker,
|
||||
environment_detector=environment_detector,
|
||||
host=host,
|
||||
port=port,
|
||||
debug=debug,
|
||||
@@ -107,7 +115,9 @@ server_options = bulk_options([
|
||||
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Allow OctoPrint to run as user root."),
|
||||
click.option("--debug", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Enable debug mode.")
|
||||
help="Enable debug mode."),
|
||||
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Disable processing of the plugin blacklist.")
|
||||
])
|
||||
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
|
||||
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
|
||||
@@ -125,9 +135,30 @@ def server_commands():
|
||||
pass
|
||||
|
||||
|
||||
@server_commands.command(name="safemode")
|
||||
@standard_options()
|
||||
@click.pass_context
|
||||
def enable_safemode(ctx, **kwargs):
|
||||
"""Sets the safe mode flag for the next start."""
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
|
||||
try:
|
||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the settings manager.", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
settings.setBoolean(["server", "startOnceInSafeMode"], True)
|
||||
settings.save()
|
||||
|
||||
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
|
||||
|
||||
|
||||
@server_commands.command(name="serve")
|
||||
@standard_options()
|
||||
@server_options
|
||||
@standard_options(hidden=True)
|
||||
@click.pass_context
|
||||
def serve_command(ctx, **kwargs):
|
||||
"""Starts the OctoPrint server."""
|
||||
@@ -145,18 +176,20 @@ def serve_command(ctx, **kwargs):
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = get_value("safe_mode")
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
run_server(basedir, configfile, host, port, debug,
|
||||
allow_root, logging, verbosity, safe_mode)
|
||||
allow_root, logging, verbosity, safe_mode,
|
||||
ignore_blacklist)
|
||||
|
||||
|
||||
if sys.platform == "linux2":
|
||||
# we only support daemon mode under Linux
|
||||
if sys.platform != "win32" and sys.platform != "darwin":
|
||||
# we do not support daemon mode under windows or macosx
|
||||
|
||||
@server_commands.command(name="daemon")
|
||||
@standard_options()
|
||||
@server_options
|
||||
@daemon_options
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
|
||||
metavar="start|stop|restart|status")
|
||||
@click.pass_context
|
||||
@@ -164,7 +197,7 @@ if sys.platform == "linux2":
|
||||
"""
|
||||
Starts, stops or restarts in daemon mode.
|
||||
|
||||
Please note that daemon mode is only supported under Linux right now.
|
||||
Please note that daemon mode is not supported under Windows and MacOSX right now.
|
||||
"""
|
||||
|
||||
def get_value(key):
|
||||
@@ -181,6 +214,7 @@ if sys.platform == "linux2":
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = get_value("safe_mode")
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
if pid is None:
|
||||
click.echo("No path to a pidfile set",
|
||||
@@ -189,7 +223,8 @@ if sys.platform == "linux2":
|
||||
|
||||
from octoprint.daemon import Daemon
|
||||
class OctoPrintDaemon(Daemon):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity,
|
||||
safe_mode, ignore_blacklist):
|
||||
Daemon.__init__(self, pidfile)
|
||||
|
||||
self._basedir = basedir
|
||||
@@ -201,14 +236,15 @@ if sys.platform == "linux2":
|
||||
self._logging_config = logging_config
|
||||
self._verbosity = verbosity
|
||||
self._safe_mode = safe_mode
|
||||
self._ignore_blacklist = ignore_blacklist
|
||||
|
||||
def run(self):
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
|
||||
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
|
||||
octoprint_daemon=self)
|
||||
self._ignore_blacklist, octoprint_daemon=self)
|
||||
|
||||
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
|
||||
safe_mode)
|
||||
safe_mode, ignore_blacklist)
|
||||
|
||||
if command == "start":
|
||||
octoprint_daemon.start()
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import threading
|
||||
import yaml
|
||||
|
||||
import psutil
|
||||
|
||||
from octoprint.plugin import EnvironmentDetectionPlugin
|
||||
from octoprint.util.platform import get_os
|
||||
|
||||
class EnvironmentDetector(object):
|
||||
|
||||
def __init__(self, plugin_manager):
|
||||
self._plugin_manager = plugin_manager
|
||||
|
||||
self._cache = None
|
||||
self._cache_lock = threading.RLock()
|
||||
|
||||
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
@property
|
||||
def environment(self):
|
||||
with self._cache_lock:
|
||||
if self._cache is None:
|
||||
self.run_detection()
|
||||
return copy.deepcopy(self._cache)
|
||||
|
||||
def run_detection(self, notify_plugins=True):
|
||||
try:
|
||||
environment = dict()
|
||||
environment["os"] = self._detect_os()
|
||||
environment["python"] = self._detect_python()
|
||||
environment["hardware"] = self._detect_hardware()
|
||||
|
||||
plugin_result = self._detect_from_plugins()
|
||||
if plugin_result:
|
||||
environment["plugins"] = plugin_result
|
||||
|
||||
with self._cache_lock:
|
||||
self._cache = environment
|
||||
|
||||
if notify_plugins:
|
||||
self.notify_plugins()
|
||||
|
||||
return environment
|
||||
except:
|
||||
self._logger.exception("Unexpected error while detecting environment")
|
||||
with self._cache_lock:
|
||||
self._cache = dict()
|
||||
return self._cache
|
||||
|
||||
def _detect_os(self):
|
||||
return dict(id=get_os(),
|
||||
platform=sys.platform)
|
||||
|
||||
def _detect_python(self):
|
||||
result = dict(version="unknown",
|
||||
pip="unknown")
|
||||
|
||||
# determine python version
|
||||
try:
|
||||
result["version"] = platform.python_version()
|
||||
except:
|
||||
self._logger.exception("Error detecting python version")
|
||||
|
||||
# determine if we are running from a virtual environment
|
||||
try:
|
||||
if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
|
||||
result["virtualenv"] = sys.prefix
|
||||
except:
|
||||
self._logger.exception("Error detecting whether we are running in a virtual environment")
|
||||
|
||||
# try to find pip version
|
||||
try:
|
||||
import pip
|
||||
result["pip"] = pip.__version__
|
||||
except:
|
||||
self._logger.exception("Error detecting pip version")
|
||||
|
||||
return result
|
||||
|
||||
def _detect_hardware(self):
|
||||
result = dict(cores="unknown",
|
||||
freq="unknown",
|
||||
ram="unknown")
|
||||
|
||||
try:
|
||||
cores = psutil.cpu_count()
|
||||
cpu_freq = psutil.cpu_freq()
|
||||
ram = psutil.virtual_memory()
|
||||
if cores:
|
||||
result["cores"] = cores
|
||||
if cpu_freq and hasattr(cpu_freq, "max"):
|
||||
result["freq"] = cpu_freq.max
|
||||
if ram and hasattr(ram, "total"):
|
||||
result["ram"] = ram.total
|
||||
except:
|
||||
self._logger.exception("Error while detecting hardware environment")
|
||||
|
||||
return result
|
||||
|
||||
def _detect_from_plugins(self):
|
||||
result = dict()
|
||||
|
||||
for implementation in self._environment_plugins:
|
||||
try:
|
||||
additional = implementation.get_additional_environment()
|
||||
if additional is not None and isinstance(additional, dict) and len(additional):
|
||||
result[implementation._identifier] = additional
|
||||
except:
|
||||
self._logger.exception("Error while fetching additional "
|
||||
"environment data from plugin {}".format(implementation._identifier))
|
||||
|
||||
return result
|
||||
|
||||
def log_detected_environment(self, only_to_handler=None):
|
||||
def _log(message, level=logging.INFO):
|
||||
if only_to_handler is not None:
|
||||
import octoprint.logging
|
||||
octoprint.logging.log_to_handler(self._logger, only_to_handler, level, message, [])
|
||||
else:
|
||||
self._logger.log(level, message)
|
||||
|
||||
try:
|
||||
_log(self._format())
|
||||
except:
|
||||
self._logger.exception("Error logging detected environment")
|
||||
|
||||
def _format(self):
|
||||
with self._cache_lock:
|
||||
if self._cache is None:
|
||||
self.run_detection()
|
||||
environment = copy.deepcopy(self._cache)
|
||||
|
||||
dumped_environment = yaml.safe_dump(environment,
|
||||
default_flow_style=False,
|
||||
indent=" ",
|
||||
allow_unicode=True).strip()
|
||||
environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n")))
|
||||
return u"Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
|
||||
environment["os"]["id"].title(),
|
||||
environment["os"]["platform"],
|
||||
environment_lines)
|
||||
|
||||
def notify_plugins(self):
|
||||
with self._cache_lock:
|
||||
if self._cache is None:
|
||||
self.run_detection(notify_plugins=False)
|
||||
environment = copy.deepcopy(self._cache)
|
||||
|
||||
for implementation in self._environment_plugins:
|
||||
try:
|
||||
implementation.on_environment_detected(environment)
|
||||
except:
|
||||
self._logger.exception("Error while sending environment "
|
||||
"detection result to plugin {}".format(implementation._identifier))
|
||||
+44
-6
@@ -27,9 +27,10 @@ def all_events():
|
||||
|
||||
|
||||
class Events(object):
|
||||
# application startup
|
||||
# server
|
||||
STARTUP = "Startup"
|
||||
SHUTDOWN = "Shutdown"
|
||||
CONNECTIVITY_CHANGED = "ConnectivityChanged"
|
||||
|
||||
# connect/disconnect to printer
|
||||
CONNECTING = "Connecting"
|
||||
@@ -39,6 +40,7 @@ class Events(object):
|
||||
|
||||
# State changes
|
||||
PRINTER_STATE_CHANGED = "PrinterStateChanged"
|
||||
PRINTER_RESET = "PrinterReset"
|
||||
|
||||
# connect/disconnect by client
|
||||
CLIENT_OPENED = "ClientOpened"
|
||||
@@ -53,9 +55,15 @@ class Events(object):
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||
|
||||
FILE_ADDED = "FileAdded"
|
||||
FILE_REMOVED = "FileRemoved"
|
||||
FOLDER_ADDED = "FolderAdded"
|
||||
FOLDER_REMOVED = "FolderRemoved"
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
TRANSFER_DONE = "TransferDone"
|
||||
TRANSFER_FAILED = "TransferFailed"
|
||||
|
||||
# print job
|
||||
PRINT_STARTED = "PrintStarted"
|
||||
@@ -79,6 +87,7 @@ class Events(object):
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
POSITION_UPDATE = "PositionUpdate"
|
||||
TOOL_CHANGE = "ToolChange"
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
|
||||
# Timelapse
|
||||
@@ -125,9 +134,11 @@ class EventManager(object):
|
||||
self._registeredListeners = collections.defaultdict(list)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._startup_signaled = False
|
||||
self._shutdown_signaled = False
|
||||
|
||||
self._queue = queue.Queue()
|
||||
self._held_back = queue.Queue()
|
||||
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
@@ -154,7 +165,8 @@ class EventManager(object):
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=(event, payload))
|
||||
args=(event, payload),
|
||||
initialized=True)
|
||||
self._logger.info("Event loop shut down")
|
||||
except:
|
||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
||||
@@ -170,7 +182,30 @@ class EventManager(object):
|
||||
payload being a payload object specific to the event.
|
||||
"""
|
||||
|
||||
self._queue.put((event, payload))
|
||||
send_held_back = False
|
||||
if event == Events.STARTUP:
|
||||
self._logger.info("Processing startup event, this is our first event")
|
||||
self._startup_signaled = True
|
||||
send_held_back = True
|
||||
|
||||
self._enqueue(event, payload)
|
||||
|
||||
if send_held_back:
|
||||
self._logger.info("Adding {} events to queue that "
|
||||
"were held back before startup event".format(self._held_back.qsize()))
|
||||
while True:
|
||||
try:
|
||||
self._queue.put(self._held_back.get(block=False))
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
def _enqueue(self, event, payload):
|
||||
if self._startup_signaled:
|
||||
q = self._queue
|
||||
else:
|
||||
q = self._held_back
|
||||
|
||||
q.put((event, payload))
|
||||
|
||||
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
|
||||
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
|
||||
@@ -178,7 +213,7 @@ class EventManager(object):
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
self._queue.put((event, legacy_payload))
|
||||
q.put((event, legacy_payload))
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
@@ -350,7 +385,10 @@ class CommandTrigger(GenericEventListener):
|
||||
else:
|
||||
commandExecutioner(command)
|
||||
except subprocess.CalledProcessError as e:
|
||||
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, str(e)))
|
||||
if debug:
|
||||
self._logger.warn("Command failed with return code {}: {}".format(e.returncode, str(e)))
|
||||
else:
|
||||
self._logger.warn("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
|
||||
except:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
@@ -368,7 +406,7 @@ class CommandTrigger(GenericEventListener):
|
||||
|
||||
def _processCommand(self, command, payload):
|
||||
"""
|
||||
Performs string substitutions in the command string based on a couple of current parameters.
|
||||
Performs string substitutions in the command string based on a few current parameters.
|
||||
|
||||
The following substitutions are currently supported:
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
|
||||
|
||||
@@ -38,13 +40,47 @@ def full_extension_tree():
|
||||
)
|
||||
)
|
||||
|
||||
def leaf_merger(a, b):
|
||||
supported_leaf_types = (ContentTypeMapping, ContentTypeDetector, list)
|
||||
if not isinstance(a, supported_leaf_types) or not isinstance(b, supported_leaf_types):
|
||||
raise ValueError()
|
||||
|
||||
if isinstance(a, ContentTypeDetector) and isinstance(b, ContentTypeMapping):
|
||||
raise ValueError()
|
||||
|
||||
if isinstance(a, ContentTypeMapping) and isinstance(b, ContentTypeDetector):
|
||||
raise ValueError()
|
||||
|
||||
a_list = a if isinstance(a, list) else a.extensions
|
||||
b_list = b if isinstance(b, list) else b.extensions
|
||||
merged = a_list + b_list
|
||||
|
||||
content_type = None
|
||||
if isinstance(b, ContentTypeMapping):
|
||||
content_type = b.content_type
|
||||
elif isinstance(a, ContentTypeMapping):
|
||||
content_type = a.content_type
|
||||
|
||||
detector = None
|
||||
if isinstance(b, ContentTypeDetector):
|
||||
detector = b.detector
|
||||
elif isinstance(a, ContentTypeDetector):
|
||||
detector = a.detector
|
||||
|
||||
if content_type is not None:
|
||||
return ContentTypeMapping(merged, content_type)
|
||||
elif detector is not None:
|
||||
return ContentTypeDetector(merged, detector)
|
||||
else:
|
||||
return merged
|
||||
|
||||
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
|
||||
for name, hook in extension_tree_hooks.items():
|
||||
try:
|
||||
hook_result = hook()
|
||||
if hook_result is None or not isinstance(hook_result, dict):
|
||||
continue
|
||||
result = octoprint.util.dict_merge(result, hook_result)
|
||||
result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger)
|
||||
except:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name))
|
||||
|
||||
@@ -178,9 +214,12 @@ class FileManager(object):
|
||||
import octoprint.settings
|
||||
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
|
||||
|
||||
def initialize(self):
|
||||
def initialize(self, process_backlog=False):
|
||||
self.reload_plugins()
|
||||
if process_backlog:
|
||||
self.process_backlog()
|
||||
|
||||
def process_backlog(self):
|
||||
def worker():
|
||||
self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals()))
|
||||
for storage_type, storage_manager in self._storage_managers.items():
|
||||
@@ -251,11 +290,33 @@ class FileManager(object):
|
||||
def default_slicer(self):
|
||||
return self._slicing_manager.default_slicer
|
||||
|
||||
def analyse(self, destination, path, printer_profile_id=None):
|
||||
if not self.file_exists(destination, path):
|
||||
return
|
||||
|
||||
if printer_profile_id is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
else:
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path, printer_profile=printer_profile)
|
||||
if queue_entry:
|
||||
return self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
|
||||
return False
|
||||
|
||||
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, display=None,
|
||||
callback=None, callback_args=None):
|
||||
absolute_source_path = self.path_on_disk(source_location, source_path)
|
||||
|
||||
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time,
|
||||
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
|
||||
@@ -280,7 +341,9 @@ class FileManager(object):
|
||||
io.FileIO(tmp_path, "rb"))
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
|
||||
self.add_file(dest_location, dest_path, file_obj,
|
||||
display=display, links=links, allow_overwrite=True,
|
||||
printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = time.time()
|
||||
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
|
||||
@@ -392,7 +455,7 @@ class FileManager(object):
|
||||
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
|
||||
return result
|
||||
|
||||
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None):
|
||||
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None, display=None):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
@@ -409,30 +472,47 @@ class FileManager(object):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
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, file_path, printer_profile=printer_profile)
|
||||
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)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return file_path
|
||||
return path_in_storage
|
||||
|
||||
def remove_file(self, destination, path):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
self._storage(destination).remove_file(path)
|
||||
|
||||
_, name = self._storage(destination).split_path(path)
|
||||
eventManager().fire(Events.FILE_REMOVED, dict(storage=destination,
|
||||
path=path,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def copy_file(self, destination, source, dst):
|
||||
path = self._storage(destination).copy_file(source, dst)
|
||||
if not self.has_analysis(destination, path):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
path_in_storage = self._storage(destination).copy_file(source, dst)
|
||||
if not self.has_analysis(destination, path_in_storage):
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def move_file(self, destination, source, dst):
|
||||
@@ -443,31 +523,71 @@ class FileManager(object):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry)
|
||||
|
||||
source_path_in_storage = self._storage(destination).path_in_storage(source)
|
||||
_, source_name = self._storage(destination).split_path(source_path_in_storage)
|
||||
dst_path_in_storage = self._storage(destination).path_in_storage(dst)
|
||||
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
|
||||
|
||||
eventManager().fire(Events.FILE_REMOVED, dict(storage=destination,
|
||||
path=source_path_in_storage,
|
||||
name=source_name,
|
||||
type=get_file_type(source_name)))
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=dst_path_in_storage,
|
||||
name=dst_name,
|
||||
type=get_file_type(dst_name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def add_folder(self, destination, path, ignore_existing=True):
|
||||
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
|
||||
def add_folder(self, destination, path, ignore_existing=True, display=None):
|
||||
path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing, display=display)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return folder_path
|
||||
return path_in_storage
|
||||
|
||||
def remove_folder(self, destination, path, recursive=True):
|
||||
self._analysis_queue.dequeue_folder(destination, path)
|
||||
self._analysis_queue.pause()
|
||||
self._storage(destination).remove_folder(path, recursive=recursive)
|
||||
self._analysis_queue.resume()
|
||||
|
||||
_, name = self._storage(destination).split_path(path)
|
||||
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
|
||||
path=path,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def copy_folder(self, destination, source, dst):
|
||||
self._storage(destination).copy_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
|
||||
path_in_storage = self._storage(destination).copy_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=path_in_storage)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def move_folder(self, destination, source, dst):
|
||||
self._analysis_queue.dequeue_folder(destination, source)
|
||||
self._analysis_queue.pause()
|
||||
self._storage(destination).move_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
|
||||
dst_path_in_storage = self._storage(destination).move_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=dst_path_in_storage)
|
||||
self._analysis_queue.resume()
|
||||
|
||||
source_path_in_storage = self._storage(destination).path_in_storage(source)
|
||||
_, source_name = self._storage(destination).split_path(source_path_in_storage)
|
||||
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
|
||||
|
||||
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
|
||||
path=source_path_in_storage,
|
||||
name=source_name))
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=dst_path_in_storage,
|
||||
name=dst_name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def has_analysis(self, destination, path):
|
||||
@@ -539,6 +659,9 @@ class FileManager(object):
|
||||
def path_on_disk(self, destination, path):
|
||||
return self._storage(destination).path_on_disk(path)
|
||||
|
||||
def canonicalize(self, destination, path):
|
||||
return self._storage(destination).canonicalize(path)
|
||||
|
||||
def sanitize(self, destination, path):
|
||||
return self._storage(destination).sanitize(path)
|
||||
|
||||
|
||||
@@ -19,8 +19,6 @@ import time
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
|
||||
"""
|
||||
@@ -305,39 +303,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
* The extruded volume in cm³
|
||||
"""
|
||||
|
||||
def _do_analysis(self, high_priority=False):
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||
if throttle > 0:
|
||||
def throttle_callback(filePos, readBytes):
|
||||
if filePos % throttle_lines == 0:
|
||||
# only apply throttle every 100 lines
|
||||
time.sleep(throttle)
|
||||
else:
|
||||
throttle_callback = None
|
||||
def __init__(self, finished_callback):
|
||||
AbstractAnalysisQueue.__init__(self, finished_callback)
|
||||
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback)
|
||||
self._aborted = False
|
||||
self._reenqueue = False
|
||||
|
||||
def _do_analysis(self, high_priority=False):
|
||||
import sarge
|
||||
import sys
|
||||
import yaml
|
||||
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
|
||||
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
|
||||
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
|
||||
speedx = self._current.printer_profile["axes"]["x"]["speed"]
|
||||
speedy = self._current.printer_profile["axes"]["y"]["speed"]
|
||||
offsets = self._current.printer_profile["extruder"]["offsets"]
|
||||
|
||||
command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
|
||||
"--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
|
||||
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
|
||||
"--throttle-lines={}".format(throttle_lines)]
|
||||
for offset in offsets[1:]:
|
||||
command += ["--offset", str(offset[0]), str(offset[1])]
|
||||
if g90_extruder:
|
||||
command += ["--g90-extruder"]
|
||||
command.append(self._current.absolute_path)
|
||||
|
||||
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
|
||||
|
||||
self._aborted = False
|
||||
p = sarge.run(command, async=True, stdout=sarge.Capture())
|
||||
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
# the events might not be all set if an exception
|
||||
# by sarge is triggered within the async process
|
||||
# thread
|
||||
time.sleep(0.01)
|
||||
|
||||
# by now we should have a command, let's wait for its
|
||||
# process to have been prepared
|
||||
p.commands[0].process_ready.wait()
|
||||
|
||||
if not p.commands[0].process:
|
||||
# the process might have been set to None in case of any exception
|
||||
raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command)))
|
||||
|
||||
try:
|
||||
# let's wait for stuff to finish
|
||||
while p.returncode is None:
|
||||
if self._aborted:
|
||||
# oh, we shall abort, let's do so!
|
||||
p.commands[0].terminate()
|
||||
raise AnalysisAborted(reenqueue=self._reenqueue)
|
||||
|
||||
# else continue
|
||||
p.commands[0].poll()
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
output = p.stdout.text
|
||||
self._logger.debug("Got output: {!r}".format(output))
|
||||
|
||||
if not "RESULTS:" in output:
|
||||
raise RuntimeError("No analysis result found")
|
||||
|
||||
_, output = output.split("RESULTS:")
|
||||
analysis = yaml.safe_load(output)
|
||||
|
||||
result = dict()
|
||||
result["printingArea"] = self._gcode.printing_area
|
||||
result["dimensions"] = self._gcode.dimensions
|
||||
if self._gcode.totalMoveTimeMinute:
|
||||
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
|
||||
if self._gcode.extrusionAmount:
|
||||
result["printingArea"] = analysis["printing_area"]
|
||||
result["dimensions"] = analysis["dimensions"]
|
||||
if analysis["total_time"]:
|
||||
result["estimatedPrintTime"] = analysis["total_time"] * 60
|
||||
if analysis["extrusion_length"]:
|
||||
result["filament"] = dict()
|
||||
for i in range(len(self._gcode.extrusionAmount)):
|
||||
for i in range(len(analysis["extrusion_length"])):
|
||||
result["filament"]["tool%d" % i] = {
|
||||
"length": self._gcode.extrusionAmount[i],
|
||||
"volume": self._gcode.extrusionVolume[i]
|
||||
"length": analysis["extrusion_length"][i],
|
||||
"volume": analysis["extrusion_volume"][i]
|
||||
}
|
||||
return result
|
||||
except gcodeInterpreter.AnalysisAborted as ex:
|
||||
raise AnalysisAborted(reenqueue=ex.reenqueue)
|
||||
finally:
|
||||
self._gcode = None
|
||||
|
||||
def _do_abort(self, reenqueue=True):
|
||||
if self._gcode:
|
||||
self._gcode.abort(reenqueue=reenqueue)
|
||||
self._aborted = True
|
||||
self._reenqueue = reenqueue
|
||||
@@ -10,6 +10,7 @@ import logging
|
||||
import os
|
||||
import pylru
|
||||
import shutil
|
||||
import re
|
||||
|
||||
try:
|
||||
from os import scandir, walk
|
||||
@@ -20,16 +21,20 @@ from octoprint.util import atomic_write
|
||||
from contextlib import contextmanager
|
||||
from copy import deepcopy
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from emoji import demojize
|
||||
from slugify import Slugify
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util import is_hidden_path, to_unicode
|
||||
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
Interface of storage adapters for OctoPrint.
|
||||
"""
|
||||
|
||||
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
"""
|
||||
@@ -153,19 +158,22 @@ class StorageInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_folder(self, path, ignore_existing=True):
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
"""
|
||||
Adds a folder as ``path``. The ``path`` will be sanitized.
|
||||
Adds a folder as ``path``
|
||||
|
||||
The ``path`` will be sanitized.
|
||||
|
||||
:param string path: the path of the new folder
|
||||
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
|
||||
:param unicode display: display name of the folder
|
||||
:return: the sanitized name of the new folder to be used for future references to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
"""
|
||||
Removes the folder at ``path``.
|
||||
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
|
||||
@@ -195,7 +203,7 @@ class StorageInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
"""
|
||||
Adds the file ``file_object`` as ``path``
|
||||
|
||||
@@ -206,13 +214,16 @@ class StorageInterface(object):
|
||||
:param list links: any links to add with the file
|
||||
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
|
||||
and its metadata will just be silently overwritten
|
||||
:param unicode display: display name of the file
|
||||
:return: the sanitized name of the file to be used for future references to it
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_file(self, path):
|
||||
"""
|
||||
Removes the file at ``path``. Will also take care of deleting the corresponding entries
|
||||
Removes the file at ``path``
|
||||
|
||||
Will also take care of deleting the corresponding entries
|
||||
in the metadata and deleting all links pointing to the file.
|
||||
|
||||
:param string path: path of the file to remove
|
||||
@@ -322,6 +333,23 @@ class StorageInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def canonicalize(self, path):
|
||||
"""
|
||||
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
|
||||
implementation must separate those if necessary.
|
||||
|
||||
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
|
||||
of stripping any invalid characters.
|
||||
|
||||
Args:
|
||||
path: the path to canonicalize
|
||||
|
||||
Returns:
|
||||
a 2-tuple containing the canonicalized path and file name
|
||||
|
||||
"""
|
||||
return self.sanitize(path)
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
|
||||
@@ -398,6 +426,7 @@ class StorageError(Exception):
|
||||
INVALID_DESTINATION = "invalid_destination"
|
||||
DOES_NOT_EXIST = "does_not_exist"
|
||||
ALREADY_EXISTS = "already_exists"
|
||||
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
|
||||
NOT_EMPTY = "not_empty"
|
||||
|
||||
def __init__(self, message, code=None, cause=None):
|
||||
@@ -420,6 +449,22 @@ class LocalFileStorage(StorageInterface):
|
||||
This storage type implements :func:`path_on_disk`.
|
||||
"""
|
||||
|
||||
_UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]")
|
||||
|
||||
@classmethod
|
||||
def _no_unicode_variations(cls, text):
|
||||
return cls._UNICODE_VARIATIONS.sub(u"", text)
|
||||
|
||||
_SLUGIFY = Slugify()
|
||||
_SLUGIFY.safe_chars = "-_.()[] "
|
||||
|
||||
@classmethod
|
||||
def _slugify(cls, text):
|
||||
text = to_unicode(text)
|
||||
text = cls._no_unicode_variations(text)
|
||||
text = demojize(text, delimiters=(u"", u""))
|
||||
return cls._SLUGIFY(text)
|
||||
|
||||
def __init__(self, basefolder, create=False):
|
||||
"""
|
||||
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
|
||||
@@ -430,7 +475,7 @@ class LocalFileStorage(StorageInterface):
|
||||
"""
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
|
||||
self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder)))
|
||||
if not os.path.exists(self.basefolder) and create:
|
||||
os.makedirs(self.basefolder)
|
||||
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
|
||||
@@ -442,10 +487,6 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
self._metadata_cache = pylru.lrucache(10)
|
||||
|
||||
from slugify import Slugify
|
||||
self._slugify = Slugify()
|
||||
self._slugify.safe_chars = "-_.()[] "
|
||||
|
||||
self._old_metadata = None
|
||||
self._initialize_metadata()
|
||||
|
||||
@@ -486,6 +527,9 @@ class LocalFileStorage(StorageInterface):
|
||||
return self.analysis_backlog_for_path()
|
||||
|
||||
def analysis_backlog_for_path(self, path=None):
|
||||
if path:
|
||||
path = self.sanitize_path(path)
|
||||
|
||||
for entry in self._analysis_backlog_generator(path):
|
||||
yield entry
|
||||
|
||||
@@ -549,17 +593,22 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def list_files(self, path=None, filter=None, recursive=True):
|
||||
if path:
|
||||
path = self.sanitize_path(path)
|
||||
path = self.sanitize_path(to_unicode(path))
|
||||
base = self.path_in_storage(path)
|
||||
if base:
|
||||
base += "/"
|
||||
base += u"/"
|
||||
else:
|
||||
path = self.basefolder
|
||||
base = ""
|
||||
base = u""
|
||||
return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive)
|
||||
|
||||
def add_folder(self, path, ignore_existing=True):
|
||||
path, name = self.sanitize(path)
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
display_path, display_name = self.canonicalize(path)
|
||||
path = self.sanitize_path(display_path)
|
||||
name = self.sanitize_name(display_name)
|
||||
|
||||
if display is not None:
|
||||
display_name = display
|
||||
|
||||
folder_path = os.path.join(path, name)
|
||||
if os.path.exists(folder_path):
|
||||
@@ -568,6 +617,11 @@ class LocalFileStorage(StorageInterface):
|
||||
else:
|
||||
os.mkdir(folder_path)
|
||||
|
||||
if display_name != name:
|
||||
metadata = self._get_metadata_entry(path, name, default=dict())
|
||||
metadata["display"] = display_name
|
||||
self._update_metadata_entry(path, name, metadata)
|
||||
|
||||
return self.path_in_storage((path, name))
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
@@ -590,12 +644,15 @@ class LocalFileStorage(StorageInterface):
|
||||
import shutil
|
||||
shutil.rmtree(folder_path)
|
||||
|
||||
self._delete_metadata(folder_path)
|
||||
self._remove_metadata_entry(path, name)
|
||||
|
||||
def _get_source_destination_data(self, source, destination):
|
||||
def _get_source_destination_data(self, source, destination, must_not_equal=False):
|
||||
"""Prepares data dicts about source and destination for copy/move."""
|
||||
source_path, source_name = self.sanitize(source)
|
||||
destination_path, destination_name = self.sanitize(destination)
|
||||
|
||||
destination_canon_path, destination_canon_name = self.canonicalize(destination)
|
||||
destination_path = self.sanitize_path(destination_canon_path)
|
||||
destination_name = self.sanitize_name(destination_canon_name)
|
||||
|
||||
source_fullpath = os.path.join(source_path, source_name)
|
||||
destination_fullpath = os.path.join(destination_path, destination_name)
|
||||
@@ -605,45 +662,88 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
if not os.path.isdir(destination_path):
|
||||
raise StorageError("Destination path {} does not exist or is not a folder".format(destination_path), code=StorageError.INVALID_DESTINATION)
|
||||
if os.path.exists(destination_fullpath):
|
||||
if os.path.exists(destination_fullpath) and source_fullpath != destination_fullpath:
|
||||
raise StorageError("{} does already exist in {}".format(destination_name, destination_path), code=StorageError.INVALID_DESTINATION)
|
||||
|
||||
source_meta = self._get_metadata_entry(source_path, source_name)
|
||||
if source_meta:
|
||||
source_display = source_meta.get("display", source_name)
|
||||
else:
|
||||
source_display = source_name
|
||||
|
||||
if (must_not_equal or source_display == destination_canon_name) and source_fullpath == destination_fullpath:
|
||||
raise StorageError("Source {} and destination {} are the same folder".format(source_path, destination_path), code=StorageError.SOURCE_EQUALS_DESTINATION)
|
||||
|
||||
source_data = dict(
|
||||
path=source_path,
|
||||
name=source_name,
|
||||
display=source_display,
|
||||
fullpath=source_fullpath,
|
||||
)
|
||||
destination_data = dict(
|
||||
path=destination_path,
|
||||
name=destination_name,
|
||||
display=destination_canon_name,
|
||||
fullpath=destination_fullpath,
|
||||
)
|
||||
return source_data, destination_data
|
||||
|
||||
def _set_display_metadata(self, destination_data, source_data=None):
|
||||
if source_data and destination_data["name"] == source_data["name"] and source_data["name"] != source_data["display"]:
|
||||
display = source_data["display"]
|
||||
elif destination_data["name"] != destination_data["display"]:
|
||||
display = destination_data["display"]
|
||||
else:
|
||||
display = None
|
||||
|
||||
destination_meta = self._get_metadata_entry(destination_data["path"], destination_data["name"],
|
||||
default=dict())
|
||||
if display:
|
||||
destination_meta["display"] = display
|
||||
self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
|
||||
elif "display" in destination_meta:
|
||||
del destination_meta["display"]
|
||||
self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
|
||||
|
||||
def copy_folder(self, source, destination):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True)
|
||||
|
||||
try:
|
||||
shutil.copytree(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
|
||||
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def move_folder(self, source, destination):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
|
||||
# only a display rename? Update that and bail early
|
||||
if source_data["fullpath"] == destination_data["fullpath"]:
|
||||
self._set_display_metadata(destination_data)
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
try:
|
||||
shutil.move(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
|
||||
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
self._remove_metadata_entry(source_data["path"], source_data["name"])
|
||||
self._delete_metadata(source_data["fullpath"])
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
|
||||
path, name = self.sanitize(path)
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
display_path, display_name = self.canonicalize(path)
|
||||
path = self.sanitize_path(display_path)
|
||||
name = self.sanitize_name(display_name)
|
||||
|
||||
if display:
|
||||
display_name = display
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(name):
|
||||
raise StorageError("{name} is an unrecognized file type".format(**locals()), code=StorageError.INVALID_FILE)
|
||||
|
||||
@@ -655,6 +755,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
# make sure folders exist
|
||||
if not os.path.exists(path):
|
||||
# TODO persist display names of path segments!
|
||||
os.makedirs(path)
|
||||
|
||||
# save the file
|
||||
@@ -665,10 +766,13 @@ class LocalFileStorage(StorageInterface):
|
||||
metadata = self._get_metadata_entry(path, name, default=dict())
|
||||
metadata_dirty = False
|
||||
if not "hash" in metadata or metadata["hash"] != file_hash:
|
||||
metadata["hash"] = file_hash
|
||||
# hash changed -> throw away old metadata
|
||||
metadata = dict(hash=file_hash)
|
||||
metadata_dirty = True
|
||||
if "analysis" in metadata:
|
||||
del metadata["analysis"]
|
||||
|
||||
if not "display" in metadata and display_name != name:
|
||||
# display name is not the same as file name -> store in metadata
|
||||
metadata["display"] = display_name
|
||||
metadata_dirty = True
|
||||
|
||||
if metadata_dirty:
|
||||
@@ -705,7 +809,7 @@ class LocalFileStorage(StorageInterface):
|
||||
self._remove_metadata_entry(path, name)
|
||||
|
||||
def copy_file(self, source, destination):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True)
|
||||
|
||||
try:
|
||||
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
|
||||
@@ -714,12 +818,18 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
self._copy_metadata_entry(source_data["path"], source_data["name"],
|
||||
destination_data["path"], destination_data["name"])
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def move_file(self, source, destination, allow_overwrite=False):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
|
||||
# only a display rename? Update that and bail early
|
||||
if source_data["fullpath"] == destination_data["fullpath"]:
|
||||
self._set_display_metadata(destination_data)
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
try:
|
||||
shutil.move(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
@@ -728,7 +838,8 @@ class LocalFileStorage(StorageInterface):
|
||||
self._copy_metadata_entry(source_data["path"], source_data["name"],
|
||||
destination_data["path"], destination_data["name"],
|
||||
delete_source=True)
|
||||
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def has_analysis(self, path):
|
||||
@@ -761,7 +872,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def remove_history(self, path, index):
|
||||
path, name = self.sanitize(path)
|
||||
self._update_history(name, path, index)
|
||||
self._delete_history(name, path, index)
|
||||
|
||||
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
|
||||
path, name = self.sanitize(path)
|
||||
@@ -799,14 +910,15 @@ class LocalFileStorage(StorageInterface):
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def split_path(self, path):
|
||||
split = path.split("/")
|
||||
path = to_unicode(path)
|
||||
split = path.split(u"/")
|
||||
if len(split) == 1:
|
||||
return "", split[0]
|
||||
return u"", split[0]
|
||||
else:
|
||||
return self.join_path(*split[:-1]), split[-1]
|
||||
|
||||
def join_path(self, *path):
|
||||
return "/".join(path)
|
||||
return u"/".join(map(to_unicode, path))
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
@@ -823,40 +935,48 @@ class LocalFileStorage(StorageInterface):
|
||||
hence be returned at second position. If you only need to convert a folder path, be sure to
|
||||
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
|
||||
"""
|
||||
name = None
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, "/")
|
||||
path = path.split("/")
|
||||
if isinstance(path, (list, tuple)):
|
||||
if len(path) == 1:
|
||||
name = path[0]
|
||||
path = "/"
|
||||
else:
|
||||
name = path[-1]
|
||||
path = "/" + self.join_path(*path[:-1])
|
||||
if not path:
|
||||
path = "/"
|
||||
|
||||
path, name = self.canonicalize(path)
|
||||
name = self.sanitize_name(name)
|
||||
path = self.sanitize_path(path)
|
||||
return path, name
|
||||
|
||||
def canonicalize(self, path):
|
||||
name = None
|
||||
if isinstance(path, basestring):
|
||||
path = to_unicode(path)
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, u"/")
|
||||
path = path.split(u"/")
|
||||
if isinstance(path, (list, tuple)):
|
||||
if len(path) == 1:
|
||||
name = to_unicode(path[0])
|
||||
path = u""
|
||||
else:
|
||||
name = to_unicode(path[-1])
|
||||
path = self.join_path(*map(to_unicode, path[:-1]))
|
||||
if not path:
|
||||
path = u""
|
||||
|
||||
return path, name
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
|
||||
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
|
||||
``(``, and ``)`` as is.
|
||||
"""
|
||||
name = to_unicode(name)
|
||||
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
if u"/" in name or u"\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
result = self._slugify(name).replace(" ", "_")
|
||||
if result and result != "." and result != ".." and result[0] == ".":
|
||||
result = self._slugify(name).replace(u" ", u"_")
|
||||
if result and result != u"." and result != u".." and result[0] == u".":
|
||||
# hidden files under *nix
|
||||
result = result[1:]
|
||||
return result
|
||||
@@ -867,12 +987,15 @@ class LocalFileStorage(StorageInterface):
|
||||
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
|
||||
absolute path including leading ``basefolder`` path.
|
||||
"""
|
||||
if path[0] == "/":
|
||||
path = path[1:]
|
||||
elif path[0] == "." and path[1] == "/":
|
||||
path = path[2:]
|
||||
path = to_unicode(path)
|
||||
|
||||
if len(path):
|
||||
if path[0] == u"/":
|
||||
path = path[1:]
|
||||
elif path[0] == u"." and path[1] == u"/":
|
||||
path = path[2:]
|
||||
|
||||
path_elements = path.split("/")
|
||||
path_elements = path.split(u"/")
|
||||
joined_path = self.basefolder
|
||||
for path_element in path_elements:
|
||||
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
|
||||
@@ -882,6 +1005,7 @@ class LocalFileStorage(StorageInterface):
|
||||
return path
|
||||
|
||||
def _sanitize_entry(self, entry, path, entry_path):
|
||||
entry = to_unicode(entry)
|
||||
sanitized = self.sanitize_name(entry)
|
||||
if sanitized != entry:
|
||||
# entry is not sanitized yet, let's take care of that
|
||||
@@ -891,16 +1015,16 @@ class LocalFileStorage(StorageInterface):
|
||||
counter = 1
|
||||
while os.path.exists(sanitized_path):
|
||||
counter += 1
|
||||
sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
|
||||
sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext))
|
||||
sanitized_path = os.path.join(path, sanitized)
|
||||
|
||||
try:
|
||||
shutil.move(entry_path, sanitized_path)
|
||||
|
||||
self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
|
||||
self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
|
||||
return sanitized, sanitized_path
|
||||
except:
|
||||
self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
|
||||
self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
|
||||
raise
|
||||
|
||||
return entry, entry_path
|
||||
@@ -909,10 +1033,11 @@ class LocalFileStorage(StorageInterface):
|
||||
if isinstance(path, (tuple, list)):
|
||||
path = self.join_path(*path)
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
path = to_unicode(path)
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, "/")
|
||||
if path.startswith("/"):
|
||||
path = path.replace(os.path.sep, u"/")
|
||||
if path.startswith(u"/"):
|
||||
path = path[1:]
|
||||
|
||||
return path
|
||||
@@ -1168,7 +1293,7 @@ class LocalFileStorage(StorageInterface):
|
||||
continue
|
||||
|
||||
try:
|
||||
entry_name = entry.name
|
||||
entry_name = entry_display = entry.name
|
||||
entry_path = entry.path
|
||||
entry_is_file = entry.is_file()
|
||||
entry_is_dir = entry.is_dir()
|
||||
@@ -1181,6 +1306,7 @@ class LocalFileStorage(StorageInterface):
|
||||
try:
|
||||
new_entry_name, new_entry_path = self._sanitize_entry(entry_name, path, entry_path)
|
||||
if entry_name != new_entry_name or entry_path != new_entry_path:
|
||||
entry_display = to_unicode(entry_name)
|
||||
entry_name = new_entry_name
|
||||
entry_path = new_entry_path
|
||||
entry_stat = os.stat(entry_path)
|
||||
@@ -1200,18 +1326,26 @@ class LocalFileStorage(StorageInterface):
|
||||
file_type = type_path[0]
|
||||
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_data = metadata[entry_name]
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
else:
|
||||
entry_data = self._add_basic_metadata(path, entry_name, save=False, metadata=metadata)
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
|
||||
# TODO extract model hash from source if possible to recreate link
|
||||
|
||||
if not entry_filter or entry_filter(entry_name, entry_data):
|
||||
if not entry_filter or entry_filter(entry_name, entry_metadata):
|
||||
# only add files passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_data)
|
||||
extended_entry_data.update(entry_metadata)
|
||||
extended_entry_data["name"] = entry_name
|
||||
extended_entry_data["display"] = entry_metadata.get("display", entry_name)
|
||||
extended_entry_data["path"] = path_in_location
|
||||
extended_entry_data["type"] = file_type
|
||||
extended_entry_data["typePath"] = type_path
|
||||
@@ -1224,11 +1358,27 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
# folder recursion
|
||||
elif entry_is_dir:
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
elif entry_name != entry_display:
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
else:
|
||||
entry_metadata = dict()
|
||||
|
||||
entry_data = dict(
|
||||
name=entry_name,
|
||||
display=entry_metadata.get("display", entry_name),
|
||||
path=path_in_location,
|
||||
type="folder",
|
||||
type_path=["folder"]
|
||||
typePath=["folder"]
|
||||
)
|
||||
if recursive:
|
||||
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
|
||||
@@ -1260,22 +1410,33 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
return result
|
||||
|
||||
def _add_basic_metadata(self, path, entry, additional_metadata=None, save=True, metadata=None):
|
||||
def _add_basic_metadata(self, path, entry, display_name=None, additional_metadata=None, save=True, metadata=None):
|
||||
if additional_metadata is None:
|
||||
additional_metadata = dict()
|
||||
|
||||
if metadata is None:
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
entry_data = dict(
|
||||
hash=self._create_hash(os.path.join(path, entry)),
|
||||
links=[],
|
||||
notes=[]
|
||||
)
|
||||
entry_path = os.path.join(path, entry)
|
||||
|
||||
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
|
||||
# if there is still old metadata available and that contains an analysis for this file, use it!
|
||||
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
|
||||
if os.path.isfile(entry_path):
|
||||
entry_data = dict(
|
||||
hash=self._create_hash(os.path.join(path, entry)),
|
||||
links=[],
|
||||
notes=[]
|
||||
)
|
||||
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
|
||||
# if there is still old metadata available and that contains an analysis for this file, use it!
|
||||
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
|
||||
|
||||
elif os.path.isdir(entry_path):
|
||||
entry_data = dict()
|
||||
|
||||
else:
|
||||
return
|
||||
|
||||
if display_name is not None and not display_name == entry:
|
||||
entry_data["display"] = display_name
|
||||
|
||||
entry_data.update(additional_metadata)
|
||||
metadata[entry] = entry_data
|
||||
@@ -1326,7 +1487,7 @@ class LocalFileStorage(StorageInterface):
|
||||
metadata[name] = data
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False):
|
||||
def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False, updates=None):
|
||||
with self._get_metadata_lock(source_path):
|
||||
source_data = self._get_metadata_entry(source_path, source_name, default=dict())
|
||||
if not source_data:
|
||||
@@ -1335,6 +1496,9 @@ class LocalFileStorage(StorageInterface):
|
||||
if delete_source:
|
||||
self._remove_metadata_entry(source_path, source_name)
|
||||
|
||||
if updates is not None:
|
||||
source_data.update(updates)
|
||||
|
||||
with self._get_metadata_lock(destination_path):
|
||||
self._update_metadata_entry(destination_path, destination_name, source_data)
|
||||
|
||||
@@ -1352,8 +1516,9 @@ class LocalFileStorage(StorageInterface):
|
||||
except:
|
||||
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
|
||||
else:
|
||||
self._metadata_cache[path] = deepcopy(metadata)
|
||||
return metadata
|
||||
if isinstance(metadata, dict):
|
||||
self._metadata_cache[path] = deepcopy(metadata)
|
||||
return metadata
|
||||
return dict()
|
||||
|
||||
def _save_metadata(self, path, metadata):
|
||||
|
||||
@@ -135,3 +135,16 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
|
||||
else:
|
||||
return c * indent + " " + message
|
||||
|
||||
|
||||
def prefix_multilines(text, prefix=": "):
|
||||
lines = text.splitlines()
|
||||
if not lines:
|
||||
return ""
|
||||
|
||||
if len(lines) == 1:
|
||||
return lines[0]
|
||||
|
||||
return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line,
|
||||
lines[1:]))
|
||||
|
||||
@@ -27,7 +27,7 @@ class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
|
||||
def doRollover(self):
|
||||
CleaningTimedRotatingFileHandler.doRollover(self)
|
||||
|
||||
for rcb in self.__class__.rollover_callbacks:
|
||||
for rcb in self.rollover_callbacks:
|
||||
callback, args, kwargs = rcb
|
||||
callback(*args, **kwargs)
|
||||
|
||||
|
||||
@@ -44,8 +44,9 @@ def _validate_plugin(phase, plugin_info):
|
||||
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
|
||||
return True
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
|
||||
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None,
|
||||
plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
|
||||
plugin_validators=None):
|
||||
"""
|
||||
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
|
||||
singleton.
|
||||
@@ -58,13 +59,13 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for
|
||||
potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and
|
||||
``src/plugins`` within OctoPrint's code base.
|
||||
plugin_types (list): A list of recognized plugin types for which to look for provided implementations. If not
|
||||
provided this defaults to the plugin types found in :mod:`octoprint.plugin.types` without
|
||||
:class:`~octoprint.plugin.OctoPrintPlugin`.
|
||||
plugin_bases (list): A list of recognized plugin base classes for which to look for provided implementations. If not
|
||||
provided this defaults to :class:`~octoprint.plugin.OctoPrintPlugin`.
|
||||
plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided
|
||||
this defaults to the entry point ``octoprint.plugin``.
|
||||
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
|
||||
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
|
||||
plugin_blacklist (list): A list of plugin identifiers/identifier-version tuples that are currently blacklisted.
|
||||
plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order
|
||||
be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar
|
||||
to logging handlers
|
||||
@@ -88,23 +89,12 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
|
||||
else:
|
||||
if init:
|
||||
if plugin_types is None:
|
||||
plugin_types = [StartupPlugin,
|
||||
ShutdownPlugin,
|
||||
TemplatePlugin,
|
||||
SettingsPlugin,
|
||||
SimpleApiPlugin,
|
||||
AssetPlugin,
|
||||
BlueprintPlugin,
|
||||
EventHandlerPlugin,
|
||||
SlicerPlugin,
|
||||
AppPlugin,
|
||||
ProgressPlugin,
|
||||
WizardPlugin,
|
||||
UiPlugin]
|
||||
if plugin_bases is None:
|
||||
plugin_bases = [OctoPrintPlugin]
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http"]
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
"octoprint.printer.factory"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
|
||||
@@ -115,10 +105,11 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
plugin_validators.append(_validate_plugin)
|
||||
|
||||
_instance = PluginManager(plugin_folders,
|
||||
plugin_types,
|
||||
plugin_bases,
|
||||
plugin_entry_points,
|
||||
logging_prefix="octoprint.plugins.",
|
||||
plugin_disabled_list=plugin_disabled_list,
|
||||
plugin_blacklist=plugin_blacklist,
|
||||
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
|
||||
plugin_obsolete_hooks=plugin_obsolete_hooks,
|
||||
plugin_validators=plugin_validators)
|
||||
@@ -176,7 +167,7 @@ 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):
|
||||
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
|
||||
@@ -212,6 +203,8 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
|
||||
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
|
||||
is determined be presence of injected ``_identifier`` property.
|
||||
|
||||
"""
|
||||
|
||||
@@ -224,6 +217,9 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||
for plugin in plugins:
|
||||
if initialized and not hasattr(plugin, "_identifier"):
|
||||
continue
|
||||
|
||||
if hasattr(plugin, method):
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
@@ -239,7 +235,7 @@ class PluginSettings(object):
|
||||
"""
|
||||
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
|
||||
|
||||
It provides a couple of convenience methods for directly accessing plugin settings via the regular
|
||||
It provides some convenience methods for directly accessing plugin settings via the regular
|
||||
:class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations.
|
||||
|
||||
All getter and setter methods will ensure that plugin settings are stored in their correct location within the
|
||||
@@ -263,13 +259,17 @@ class PluginSettings(object):
|
||||
:returns: The retrieved settings value.
|
||||
:rtype: object
|
||||
|
||||
.. method:: get_int(path)
|
||||
.. method:: get_int(path, min=None, max=None)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``int``.
|
||||
Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved
|
||||
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
|
||||
the value is greater than it.
|
||||
|
||||
.. method:: get_float(path)
|
||||
.. method:: get_float(path, min=None, max=None)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``float``.
|
||||
Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved
|
||||
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
|
||||
the value is greater than it.
|
||||
|
||||
.. method:: get_boolean(path)
|
||||
|
||||
@@ -285,13 +285,19 @@ class PluginSettings(object):
|
||||
:param boolean force: If set to True, the modified configuration will even be written back to disk if
|
||||
the value didn't change.
|
||||
|
||||
.. method:: set_int(path, value, force=False)
|
||||
.. method:: set_int(path, value, force=False, min=None, max=None)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
|
||||
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
|
||||
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
|
||||
that, ``max`` if greater than that) will be set instead.
|
||||
|
||||
.. method:: set_float(path, value, force=False)
|
||||
.. method:: set_float(path, value, force=False, min=None, max=None)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
|
||||
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
|
||||
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
|
||||
that, ``max`` if greater than that) will be set instead.
|
||||
|
||||
.. method:: set_boolean(path, value, force=False)
|
||||
|
||||
|
||||
+287
-121
@@ -31,10 +31,14 @@ import os
|
||||
import imp
|
||||
from collections import defaultdict, namedtuple, OrderedDict
|
||||
import logging
|
||||
import fnmatch
|
||||
import inspect
|
||||
|
||||
import pkg_resources
|
||||
import pkginfo
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
@@ -56,7 +60,7 @@ class PluginInfo(object):
|
||||
Arguments:
|
||||
key (str): Identifier of the plugin
|
||||
location (str): Installation folder of the plugin
|
||||
instance (module): Plugin module instance
|
||||
instance (module): Plugin module instance - this may be ``None`` if the plugin has been blacklisted!
|
||||
name (str): Human readable name of the plugin
|
||||
version (str): Version of the plugin
|
||||
description (str): Description of the plugin
|
||||
@@ -71,6 +75,9 @@ class PluginInfo(object):
|
||||
attr_description = '__plugin_description__'
|
||||
""" Module attribute from which to retrieve the plugin's description. """
|
||||
|
||||
attr_disabling_discouraged = '__plugin_disabling_discouraged__'
|
||||
""" Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """
|
||||
|
||||
attr_version = '__plugin_version__'
|
||||
""" Module attribute from which to retrieve the plugin's version. """
|
||||
|
||||
@@ -136,6 +143,7 @@ class PluginInfo(object):
|
||||
self.instance = instance
|
||||
self.origin = None
|
||||
self.enabled = True
|
||||
self.blacklisted = False
|
||||
self.bundled = False
|
||||
self.loaded = False
|
||||
self.managable = True
|
||||
@@ -197,7 +205,7 @@ class PluginInfo(object):
|
||||
|
||||
def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""),
|
||||
show_location=False, location_str=" - {location}",
|
||||
show_enabled=False, enabled_strs=("* ", " ")):
|
||||
show_enabled=False, enabled_strs=("* ", " ", "X ")):
|
||||
"""
|
||||
Long string representation of the plugin's information. Will return a string of the format ``<enabled><str(self)><bundled><location>``.
|
||||
|
||||
@@ -205,8 +213,8 @@ class PluginInfo(object):
|
||||
The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows:
|
||||
|
||||
``enabled_str``
|
||||
a 2-tuple, the first entry being the string to insert when the plugin is enabled, the second
|
||||
entry the string to insert when it is not.
|
||||
a 3-tuple, the first entry being the string to insert when the plugin is enabled, the second
|
||||
entry the string to insert when it is not, the third entry the string when it is blacklisted.
|
||||
``bundled_str``
|
||||
a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second
|
||||
entry the string to insert when it is not.
|
||||
@@ -226,7 +234,7 @@ class PluginInfo(object):
|
||||
str: The long string representation of the plugin as described above
|
||||
"""
|
||||
if show_enabled:
|
||||
ret = enabled_strs[0] if self.enabled else enabled_strs[1]
|
||||
ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1])
|
||||
else:
|
||||
ret = ""
|
||||
|
||||
@@ -294,6 +302,19 @@ class PluginInfo(object):
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=self._description)
|
||||
|
||||
@property
|
||||
def disabling_discouraged(self):
|
||||
"""
|
||||
Reason why disabling of this plugin is discouraged. Only evaluated for bundled plugins! Will be taken from
|
||||
the disabling_discouraged attribute of the plugin module as defined in :attr:`attr_disabling_discouraged` if
|
||||
available. False if unset or plugin not bundled.
|
||||
|
||||
Returns:
|
||||
str or None: Reason why disabling this plugin is discouraged (only for bundled plugins)
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_disabling_discouraged, default=False) if self.bundled \
|
||||
else False
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
"""
|
||||
@@ -428,7 +449,7 @@ class PluginInfo(object):
|
||||
return self._get_instance_attribute(self.__class__.attr_disable, default=lambda: True)
|
||||
|
||||
def _get_instance_attribute(self, attr, default=None, defaults=None):
|
||||
if not hasattr(self.instance, attr):
|
||||
if self.instance is None or not hasattr(self.instance, attr):
|
||||
if defaults is not None:
|
||||
for value in defaults:
|
||||
if value is not None:
|
||||
@@ -445,26 +466,29 @@ class PluginManager(object):
|
||||
It is able to discover plugins both through possible file system locations as well as customizable entry points.
|
||||
"""
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None,
|
||||
plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
|
||||
plugin_validators=None):
|
||||
def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None,
|
||||
plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None,
|
||||
plugin_obsolete_hooks=None, plugin_validators=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if logging_prefix is None:
|
||||
logging_prefix = ""
|
||||
if plugin_folders is None:
|
||||
plugin_folders = []
|
||||
if plugin_types is None:
|
||||
plugin_types = []
|
||||
if plugin_bases is None:
|
||||
plugin_bases = []
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = []
|
||||
if plugin_disabled_list is None:
|
||||
plugin_disabled_list = []
|
||||
if plugin_blacklist is None:
|
||||
plugin_blacklist = []
|
||||
|
||||
self.plugin_folders = plugin_folders
|
||||
self.plugin_types = plugin_types
|
||||
self.plugin_bases = plugin_bases
|
||||
self.plugin_entry_points = plugin_entry_points
|
||||
self.plugin_disabled_list = plugin_disabled_list
|
||||
self.plugin_blacklist = plugin_blacklist
|
||||
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
|
||||
self.plugin_obsolete_hooks = plugin_obsolete_hooks
|
||||
self.plugin_validators = plugin_validators
|
||||
@@ -526,56 +550,76 @@ class PluginManager(object):
|
||||
if existing is None:
|
||||
existing = dict(self.plugins)
|
||||
|
||||
result = dict()
|
||||
result = OrderedDict()
|
||||
if self.plugin_folders:
|
||||
result.update(self._find_plugins_from_folders(self.plugin_folders, existing, ignored_uninstalled=ignore_uninstalled))
|
||||
try:
|
||||
result.update(self._find_plugins_from_folders(self.plugin_folders,
|
||||
existing,
|
||||
ignored_uninstalled=ignore_uninstalled))
|
||||
except:
|
||||
self.logger.exception("Error fetching plugins from folders")
|
||||
if self.plugin_entry_points:
|
||||
existing.update(result)
|
||||
result.update(self._find_plugins_from_entry_points(self.plugin_entry_points, existing, ignore_uninstalled=ignore_uninstalled))
|
||||
try:
|
||||
result.update(self._find_plugins_from_entry_points(self.plugin_entry_points,
|
||||
existing,
|
||||
ignore_uninstalled=ignore_uninstalled))
|
||||
except:
|
||||
self.logger.exception("Error fetching plugins from entry points")
|
||||
return result
|
||||
|
||||
def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True):
|
||||
result = dict()
|
||||
result = OrderedDict()
|
||||
|
||||
for folder in folders:
|
||||
flagged_readonly = False
|
||||
if isinstance(folder, (list, tuple)):
|
||||
if len(folder) == 2:
|
||||
folder, flagged_readonly = folder
|
||||
else:
|
||||
continue
|
||||
actual_readonly = not os.access(folder, os.W_OK)
|
||||
try:
|
||||
flagged_readonly = False
|
||||
if isinstance(folder, (list, tuple)):
|
||||
if len(folder) == 2:
|
||||
folder, flagged_readonly = folder
|
||||
else:
|
||||
continue
|
||||
actual_readonly = not os.access(folder, os.W_OK)
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
for entry in scandir(folder):
|
||||
if entry.is_dir() and os.path.isfile(os.path.join(entry.path, "__init__.py")):
|
||||
key = entry.name
|
||||
elif entry.is_file() and entry.name.endswith(".py"):
|
||||
key = entry.name[:-3] # strip off the .py extension
|
||||
else:
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
for entry in scandir(folder):
|
||||
try:
|
||||
if entry.is_dir() and os.path.isfile(os.path.join(entry.path, "__init__.py")):
|
||||
key = entry.name
|
||||
elif entry.is_file() and entry.name.endswith(".py"):
|
||||
key = entry.name[:-3] # strip off the .py extension
|
||||
if key.startswith("__"):
|
||||
# might be an __init__.py in our plugins folder, or something else we don't want
|
||||
# to handle
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
|
||||
plugin = self._import_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.bundled = flagged_readonly
|
||||
if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin.enabled = False
|
||||
plugin = self._import_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.bundled = flagged_readonly
|
||||
|
||||
result[key] = plugin
|
||||
plugin.enabled = False
|
||||
|
||||
result[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
|
||||
|
||||
def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True):
|
||||
result = dict()
|
||||
result = OrderedDict()
|
||||
|
||||
# let's make sure we have a current working set ...
|
||||
working_set = pkg_resources.WorkingSet()
|
||||
@@ -592,51 +636,64 @@ class PluginManager(object):
|
||||
if not isinstance(groups, (list, tuple)):
|
||||
groups = [groups]
|
||||
|
||||
for group in groups:
|
||||
for entry_point in working_set.iter_entry_points(group=group, name=None):
|
||||
key = entry_point.name
|
||||
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"]):
|
||||
# plugin is already defined or marked as uninstalled, ignore it
|
||||
continue
|
||||
|
||||
kwargs = dict(module_name=module_name, version=version)
|
||||
package_name = None
|
||||
def wrapped(gen):
|
||||
# to protect against some issues in installed packages that make iteration over entry points
|
||||
# fall on its face - e.g. https://groups.google.com/forum/#!msg/octoprint/DyXdqhR0U7c/kKMUsMmIBgAJ
|
||||
for entry in gen:
|
||||
try:
|
||||
module_pkginfo = InstalledEntryPoint(entry_point)
|
||||
yield entry
|
||||
except:
|
||||
self.logger.exception("Something went wrong while retrieving package info data for module %s" % 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
|
||||
))
|
||||
package_name = module_pkginfo.name
|
||||
self.logger.exception("Something went wrong while processing the entry points of a package in the "
|
||||
"Python environment - broken entry_points.txt in some package?")
|
||||
|
||||
plugin = self._import_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
|
||||
for group in groups:
|
||||
for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)):
|
||||
try:
|
||||
key = entry_point.name
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
# plugin is manageable if its location is writable and OctoPrint
|
||||
# is either not running from a virtual env or the plugin is
|
||||
# installed in that virtual env - the virtual env's pip will not
|
||||
# allow us to uninstall stuff that is installed outside
|
||||
# of the virtual env, so this check is necessary
|
||||
plugin.managable = os.access(plugin.location, os.W_OK) \
|
||||
and (not self._python_virtual_env
|
||||
or is_sub_path_of(plugin.location, self._python_prefix)
|
||||
or is_editable_install(self._python_install_dir,
|
||||
package_name,
|
||||
module_name,
|
||||
plugin.location))
|
||||
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined or marked as uninstalled, ignore it
|
||||
continue
|
||||
|
||||
plugin.enabled = False
|
||||
result[key] = plugin
|
||||
kwargs = dict(module_name=module_name, version=version)
|
||||
package_name = None
|
||||
try:
|
||||
module_pkginfo = InstalledEntryPoint(entry_point)
|
||||
except:
|
||||
self.logger.exception("Something went wrong while retrieving package info data for module %s" % 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
|
||||
))
|
||||
package_name = module_pkginfo.name
|
||||
|
||||
plugin = self._import_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
|
||||
|
||||
# plugin is manageable if its location is writable and OctoPrint
|
||||
# is either not running from a virtual env or the plugin is
|
||||
# installed in that virtual env - the virtual env's pip will not
|
||||
# allow us to uninstall stuff that is installed outside
|
||||
# of the virtual env, so this check is necessary
|
||||
plugin.managable = os.access(plugin.location, os.W_OK) \
|
||||
and (not self._python_virtual_env
|
||||
or is_sub_path_of(plugin.location, self._python_prefix)
|
||||
or is_editable_install(self._python_install_dir,
|
||||
package_name,
|
||||
module_name,
|
||||
plugin.location))
|
||||
|
||||
plugin.enabled = False
|
||||
result[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
|
||||
|
||||
return result
|
||||
|
||||
@@ -653,6 +710,12 @@ class PluginManager(object):
|
||||
self.logger.warn("Could not locate plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
if self._is_plugin_blacklisted(key) or (version is not None and self._is_plugin_version_blacklisted(key, version)):
|
||||
plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author, url=url, license=license)
|
||||
plugin.blacklisted = True
|
||||
self.logger.warn("Plugin {} is blacklisted. Not importing it, only registering a dummy entry.".format(plugin))
|
||||
return plugin
|
||||
|
||||
plugin = self._import_plugin(key, *module, name=name, version=version, summary=summary, author=author, url=url, license=license)
|
||||
if plugin is None:
|
||||
return None
|
||||
@@ -675,6 +738,19 @@ class PluginManager(object):
|
||||
def _is_plugin_disabled(self, key):
|
||||
return key in self.plugin_disabled_list or key.endswith('disabled')
|
||||
|
||||
def _is_plugin_blacklisted(self, key):
|
||||
return key in self.plugin_blacklist
|
||||
|
||||
def _is_plugin_version_blacklisted(self, key, version):
|
||||
def matches_plugin(entry):
|
||||
if isinstance(entry, (tuple, list)) and len(entry) == 2:
|
||||
entry_key, entry_version = entry
|
||||
return entry_key == key and entry_version == version
|
||||
return False
|
||||
|
||||
return any(map(lambda entry: matches_plugin(entry),
|
||||
self.plugin_blacklist))
|
||||
|
||||
def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None):
|
||||
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(
|
||||
folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders))
|
||||
@@ -689,7 +765,8 @@ class PluginManager(object):
|
||||
# 1st pass: loading the plugins
|
||||
for name, plugin in plugins.items():
|
||||
try:
|
||||
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
|
||||
if not plugin.blacklisted:
|
||||
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
|
||||
except PluginNeedsRestart:
|
||||
pass
|
||||
except PluginLifecycleException as e:
|
||||
@@ -703,6 +780,9 @@ class PluginManager(object):
|
||||
for name, plugin in plugins.items():
|
||||
try:
|
||||
if plugin.loaded and not self._is_plugin_disabled(name):
|
||||
if plugin.blacklisted:
|
||||
self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
continue
|
||||
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
|
||||
except PluginNeedsRestart:
|
||||
pass
|
||||
@@ -759,6 +839,11 @@ class PluginManager(object):
|
||||
|
||||
plugin.loaded = True
|
||||
|
||||
# we might only now have a version, so check again if we are blacklisted
|
||||
if not plugin.blacklisted and plugin.version and self._is_plugin_version_blacklisted(plugin.key,
|
||||
plugin.version):
|
||||
plugin.blacklisted = True
|
||||
|
||||
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
@@ -890,9 +975,9 @@ class PluginManager(object):
|
||||
|
||||
# evaluate registered implementation
|
||||
if plugin.implementation:
|
||||
for plugin_type in self.plugin_types:
|
||||
if isinstance(plugin.implementation, plugin_type):
|
||||
self.plugin_implementations_by_type[plugin_type].append((name, plugin.implementation))
|
||||
mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases)
|
||||
for mixin in mixins:
|
||||
self.plugin_implementations_by_type[mixin].append((name, plugin.implementation))
|
||||
|
||||
self.plugin_implementations[name] = plugin.implementation
|
||||
|
||||
@@ -915,9 +1000,10 @@ class PluginManager(object):
|
||||
if name in self.plugin_implementations:
|
||||
del self.plugin_implementations[name]
|
||||
|
||||
for plugin_type in self.plugin_types:
|
||||
mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases)
|
||||
for mixin in mixins:
|
||||
try:
|
||||
self.plugin_implementations_by_type[plugin_type].remove((name, plugin.implementation))
|
||||
self.plugin_implementations_by_type[mixin].remove((name, plugin.implementation))
|
||||
except ValueError:
|
||||
# that's ok, the plugin was just not registered for the type
|
||||
pass
|
||||
@@ -926,45 +1012,118 @@ class PluginManager(object):
|
||||
return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin)
|
||||
|
||||
def has_restart_needing_implementation(self, plugin):
|
||||
if not plugin.implementation:
|
||||
return False
|
||||
|
||||
return isinstance(plugin.implementation, RestartNeedingPlugin)
|
||||
return self.has_any_of_mixins(plugin, RestartNeedingPlugin)
|
||||
|
||||
def has_restart_needing_hooks(self, plugin):
|
||||
if not plugin.hooks:
|
||||
return False
|
||||
|
||||
hooks = plugin.hooks.keys()
|
||||
for hook in hooks:
|
||||
if self.is_restart_needing_hook(hook):
|
||||
return True
|
||||
return False
|
||||
return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks)
|
||||
|
||||
def has_obsolete_hooks(self, plugin):
|
||||
if not plugin.hooks:
|
||||
return False
|
||||
|
||||
hooks = plugin.hooks.keys()
|
||||
for hook in hooks:
|
||||
if self.is_obsolete_hook(hook):
|
||||
return True
|
||||
return False
|
||||
return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks)
|
||||
|
||||
def is_restart_needing_hook(self, hook):
|
||||
if self.plugin_restart_needing_hooks is None:
|
||||
return False
|
||||
|
||||
for h in self.plugin_restart_needing_hooks:
|
||||
if hook.startswith(h):
|
||||
return True
|
||||
|
||||
return False
|
||||
return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks)
|
||||
|
||||
def is_obsolete_hook(self, hook):
|
||||
if self.plugin_obsolete_hooks is None:
|
||||
return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks)
|
||||
|
||||
@staticmethod
|
||||
def has_any_of_hooks(plugin, *hooks):
|
||||
"""
|
||||
Tests if the ``plugin`` contains any of the provided ``hooks``.
|
||||
|
||||
Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`.
|
||||
|
||||
Args:
|
||||
plugin: plugin to test hooks for
|
||||
*hooks: hooks to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if any of the plugin's hooks match the provided hooks,
|
||||
False otherwise.
|
||||
"""
|
||||
|
||||
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
|
||||
hooks = hooks[0]
|
||||
|
||||
hooks = filter(lambda hook: hook is not None, hooks)
|
||||
if not hooks:
|
||||
return False
|
||||
return hook in self.plugin_obsolete_hooks
|
||||
if not plugin or not plugin.hooks:
|
||||
return False
|
||||
|
||||
plugin_hooks = plugin.hooks.keys()
|
||||
|
||||
return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks),
|
||||
plugin_hooks))
|
||||
|
||||
@staticmethod
|
||||
def hook_matches_hooks(hook, *hooks):
|
||||
"""
|
||||
Tests if ``hook`` matches any of the provided ``hooks`` to test for.
|
||||
|
||||
``hook`` is expected to be an exact hook name.
|
||||
|
||||
``hooks`` is expected to be a list containing one or more hook names or
|
||||
patterns. That can be either an exact hook name or an
|
||||
:func:`fnmatch.fnmatch` pattern.
|
||||
|
||||
Args:
|
||||
hook: the hook to test
|
||||
hooks: the hook name patterns to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if the ``hook`` matches any of the ``hooks``, False otherwise.
|
||||
|
||||
"""
|
||||
|
||||
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
|
||||
hooks = hooks[0]
|
||||
|
||||
hooks = filter(lambda hook: hook is not None, hooks)
|
||||
if not hooks:
|
||||
return False
|
||||
if not hook:
|
||||
return False
|
||||
|
||||
return any(map(lambda h: fnmatch.fnmatch(hook, h),
|
||||
hooks))
|
||||
|
||||
@staticmethod
|
||||
def mixins_matching_bases(klass, *bases):
|
||||
result = set()
|
||||
for c in inspect.getmro(klass):
|
||||
if c == klass or c in bases:
|
||||
# ignore the exact class and our bases
|
||||
continue
|
||||
if issubclass(c, bases):
|
||||
result.add(c)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def has_any_of_mixins(plugin, *mixins):
|
||||
"""
|
||||
Tests if the ``plugin`` has an implementation implementing any
|
||||
of the provided ``mixins``.
|
||||
|
||||
Args:
|
||||
plugin: plugin for which to check the implementation
|
||||
*mixins: mixins to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if the plugin's implementation implements any of the
|
||||
provided mixins, False otherwise.
|
||||
"""
|
||||
|
||||
if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)):
|
||||
mixins = mixins[0]
|
||||
|
||||
mixins = filter(lambda mixin: mixin is not None, mixins)
|
||||
if not mixins:
|
||||
return False
|
||||
if not plugin or not plugin.implementation:
|
||||
return False
|
||||
|
||||
return isinstance(plugin.implementation, tuple(mixins))
|
||||
|
||||
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
for name, plugin in self.enabled_plugins.items():
|
||||
@@ -1063,7 +1222,7 @@ class PluginManager(object):
|
||||
|
||||
|
||||
def log_all_plugins(self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True,
|
||||
location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!"),
|
||||
location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#"),
|
||||
only_to_handler=None):
|
||||
all_plugins = self.enabled_plugins.values() + self.disabled_plugins.values()
|
||||
|
||||
@@ -1406,6 +1565,13 @@ class Plugin(object):
|
||||
initialization of the implementation.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._identifier = None
|
||||
self._plugin_name = None
|
||||
self._plugin_version = None
|
||||
self._basefolder = None
|
||||
self._logger = None
|
||||
|
||||
def initialize(self):
|
||||
"""
|
||||
Called by the plugin core after performing all injections. Override this to initialize your implementation.
|
||||
|
||||
+101
-12
@@ -8,9 +8,11 @@ Please note that the plugin implementation types are documented in the section
|
||||
|
||||
.. autoclass:: OctoPrintPlugin
|
||||
:show-inheritance:
|
||||
:members:
|
||||
|
||||
.. autoclass:: ReloadNeedingPlugin
|
||||
:show-inheritance:
|
||||
:members:
|
||||
|
||||
"""
|
||||
|
||||
@@ -23,6 +25,8 @@ __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):
|
||||
"""
|
||||
@@ -73,16 +77,39 @@ class OctoPrintPlugin(Plugin):
|
||||
The :class:`~octoprint.server.LifecycleManager` instance. Injected by the plugin core system upon initialization
|
||||
of the implementation.
|
||||
|
||||
.. attribute:: _user_manager
|
||||
|
||||
The :class:`~octoprint.users.UserManager` instance. Injected by the plugin core system upon initialization
|
||||
of the implementation.
|
||||
|
||||
.. attribute:: _connectivity_checker
|
||||
|
||||
The :class:`~octoprint.util.ConnectivityChecker` instance. Injected by the plugin core system upon initialization
|
||||
of the implementation.
|
||||
|
||||
.. attribute:: _data_folder
|
||||
|
||||
Path to the data folder for the plugin to use for any data it might have to persist. Should always be accessed
|
||||
through :meth:`get_plugin_data_folder` since that function will also ensure that the data folder actually exists
|
||||
and if not creating it before returning it. Injected by the plugin core system upon initialization of the
|
||||
implementation.
|
||||
|
||||
.. automethod:: get_plugin_data_folder
|
||||
"""
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._plugin_manager = None
|
||||
self._printer_profile_manager = None
|
||||
self._event_bus = None
|
||||
self._analysis_queue = None
|
||||
self._slicing_manager = None
|
||||
self._file_manager = None
|
||||
self._printer = None
|
||||
self._app_session_manager = None
|
||||
self._plugin_lifecycle_manager = None
|
||||
self._user_manager = None
|
||||
self._connectivity_checker = None
|
||||
self._data_folder = None
|
||||
|
||||
def get_plugin_data_folder(self):
|
||||
"""
|
||||
Retrieves the path to a data folder specifically for the plugin, ensuring it exists and if not creating it
|
||||
@@ -104,6 +131,16 @@ class ReloadNeedingPlugin(Plugin):
|
||||
Mixin for plugin types that need a reload of the UI after enabling/disabling them.
|
||||
"""
|
||||
|
||||
|
||||
class EnvironmentDetectionPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
def get_additional_environment(self):
|
||||
pass
|
||||
|
||||
def on_environment_detected(self, environment, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
|
||||
@@ -531,7 +568,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
|
||||
`Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object as
|
||||
parameter. If you plugin returns `True` here, OctoPrint will next call
|
||||
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like
|
||||
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like
|
||||
- again - the Flask Request object and the render keyword arguments as
|
||||
used by the default OctoPrint web interface. For more information see below.
|
||||
|
||||
@@ -582,7 +619,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
it only gets re-rendered if the request demands that (by having no-cache headers set) or if
|
||||
the cache gets invalidated otherwise.
|
||||
|
||||
In order to be able to do that, the ``UiPlugin`` offers overriding a couple of cache specific
|
||||
In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific
|
||||
methods used for figuring out the source files whose modification time to use for cache invalidation
|
||||
as well as override possibilities for ETag and LastModified calculation. Additionally there are
|
||||
methods to allow persisting call parameters to allow for preemptively caching your UI during
|
||||
@@ -591,6 +628,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
See below for details on this.
|
||||
"""
|
||||
|
||||
# noinspection PyMethodMayBeStatic,PyUnusedLocal
|
||||
def will_handle_ui(self, request):
|
||||
"""
|
||||
Called by OctoPrint to determine if the mixin implementation will be
|
||||
@@ -613,6 +651,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return False
|
||||
|
||||
# noinspection PyMethodMayBeStatic,PyUnusedLocal
|
||||
def on_ui_render(self, now, request, render_kwargs):
|
||||
"""
|
||||
Called by OctoPrint to retrieve the response to send to the client
|
||||
@@ -701,6 +740,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_additional_key_data_for_cache(self):
|
||||
"""
|
||||
Allows to return additional data to use in the cache key.
|
||||
@@ -712,6 +752,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_additional_tracked_files(self):
|
||||
"""
|
||||
Allows to return additional files to track for validating existing caches. By default OctoPrint
|
||||
@@ -724,6 +765,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_custom_tracked_files(self):
|
||||
"""
|
||||
Allows to define a complete separate set of files to track for (in)validating the cache. If this
|
||||
@@ -736,16 +778,18 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_custom_etag(self):
|
||||
"""
|
||||
Allows to use a custom way to calculate the ETag, instead of the default method (hashing
|
||||
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
|
||||
|
||||
Returns:
|
||||
basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
|
||||
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_additional_etag(self, default_additional):
|
||||
"""
|
||||
Allows to provide a list of additional fields to use for ETag generation.
|
||||
@@ -761,6 +805,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return default_additional
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_custom_lastmodified(self):
|
||||
"""
|
||||
Allows to calculate the LastModified differently than using the most recent modification
|
||||
@@ -771,6 +816,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_preemptive_caching_enabled(self):
|
||||
"""
|
||||
Allows to control whether the view provided by the plugin should be preemptively
|
||||
@@ -783,6 +829,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return True
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_data_for_preemptive_caching(self):
|
||||
"""
|
||||
Allows defining additional data to be persisted in the preemptive cache configuration, on
|
||||
@@ -793,6 +840,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_additional_request_data_for_preemptive_caching(self):
|
||||
"""
|
||||
Allows defining additional request data to persist in the preemptive cache configuration and
|
||||
@@ -808,6 +856,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_preemptive_caching_additional_unless(self):
|
||||
"""
|
||||
Allows defining additional reasons for temporarily not adding a preemptive cache record for
|
||||
@@ -821,6 +870,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
return False
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_ui_custom_template_filter(self, default_template_filter):
|
||||
"""
|
||||
Allows to specify a custom template filter to use for filtering the template contained in the
|
||||
@@ -905,6 +955,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
|
||||
"""
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_wizard_required(self):
|
||||
"""
|
||||
Allows the plugin to report whether it needs to display a wizard to the
|
||||
@@ -920,6 +971,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
"""
|
||||
return False
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_wizard_version(self):
|
||||
"""
|
||||
The version of this plugin's wizard. OctoPrint will only display a wizard
|
||||
@@ -939,6 +991,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_wizard_details(self):
|
||||
"""
|
||||
Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data
|
||||
@@ -953,6 +1006,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
"""
|
||||
return dict()
|
||||
|
||||
# noinspection PyMethodMayBeStatic,PyUnusedLocal
|
||||
def on_wizard_finish(self, handled):
|
||||
"""
|
||||
Called by OctoPrint whenever the user finishes a wizard session.
|
||||
@@ -971,6 +1025,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
"""
|
||||
pass
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
@classmethod
|
||||
def is_wizard_ignored(cls, seen_wizards, implementation):
|
||||
"""
|
||||
@@ -1038,7 +1093,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
mixin offers.
|
||||
|
||||
Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend
|
||||
and/or want to react to simple commands which boil down to a type of command and a couple of flat parameters
|
||||
and/or want to react to simple commands which boil down to a type of command and a few flat parameters
|
||||
supplied with it.
|
||||
|
||||
The simple API constructed by OctoPrint for you will be made available under ``/api/plugin/<plugin identifier>/``.
|
||||
@@ -1121,6 +1176,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
}
|
||||
"""
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_api_commands(self):
|
||||
"""
|
||||
Return a dictionary here with the keys representing the accepted commands and the values being lists of
|
||||
@@ -1128,12 +1184,14 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_api_adminonly(self):
|
||||
"""
|
||||
Return True if the API is only available to users having the admin role.
|
||||
"""
|
||||
return False
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def on_api_command(self, command, data):
|
||||
"""
|
||||
Called by OctoPrint upon a POST request to ``/api/plugin/<plugin identifier>``. ``command`` will contain one of
|
||||
@@ -1153,6 +1211,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def on_api_get(self, request):
|
||||
"""
|
||||
Called by OctoPrint upon a GET request to ``/api/plugin/<plugin identifier>``. ``request`` will contain the
|
||||
@@ -1251,6 +1310,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
return f
|
||||
return decorator
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
def get_blueprint(self):
|
||||
"""
|
||||
Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself.
|
||||
@@ -1316,6 +1376,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
template_folder=template_folder
|
||||
)
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_blueprint_protected(self):
|
||||
"""
|
||||
Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts
|
||||
@@ -1377,15 +1438,26 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the
|
||||
default implementations do not fit your requirements.
|
||||
|
||||
.. attribute:: _settings
|
||||
|
||||
The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
|
||||
the plugin core system upon initialization of the implementation.
|
||||
.. warning::
|
||||
|
||||
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,
|
||||
therefore you **must** make sure that you specify sensitive information accordingly to limit access as required!
|
||||
"""
|
||||
|
||||
config_version_key = "_config_version"
|
||||
"""Key of the field in the settings that holds the configuration format version."""
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._settings = None
|
||||
"""
|
||||
The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
|
||||
the plugin core system upon initialization of the implementation.
|
||||
"""
|
||||
|
||||
def on_settings_load(self):
|
||||
"""
|
||||
Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from
|
||||
@@ -1418,6 +1490,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
restricted_paths = self.get_settings_restricted_paths()
|
||||
|
||||
# noinspection PyShadowingNames
|
||||
def restrict_path_unless(data, path, condition):
|
||||
if not path:
|
||||
return
|
||||
@@ -1516,6 +1589,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
return diff
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_settings_defaults(self):
|
||||
"""
|
||||
Retrieves the plugin's default settings with which the plugin's settings manager will be initialized.
|
||||
@@ -1525,6 +1599,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return dict()
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_settings_restricted_paths(self):
|
||||
"""
|
||||
Retrieves the list of paths in the plugin's settings which be restricted on the REST API.
|
||||
@@ -1548,8 +1623,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
field="field"),
|
||||
path=dict(to=dict(never=dict(return="return"))))
|
||||
|
||||
def get_settings_restricted_path(self):
|
||||
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],
|
||||
def get_settings_restricted_paths(self):
|
||||
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],],
|
||||
user=[["some", "user_only", "path"],],
|
||||
never=[["path", "to", "never", "return"],])
|
||||
|
||||
@@ -1579,6 +1654,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return dict()
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_settings_preprocessors(self):
|
||||
"""
|
||||
Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting
|
||||
@@ -1616,6 +1692,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return dict(), dict()
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_settings_version(self):
|
||||
"""
|
||||
Retrieves the settings format version of the plugin.
|
||||
@@ -1630,6 +1707,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def on_settings_migrate(self, target, current):
|
||||
"""
|
||||
Called by OctoPrint if it detects that the installed version of the plugin necessitates a higher settings version
|
||||
@@ -1716,6 +1794,7 @@ class EventHandlerPlugin(OctoPrintPlugin):
|
||||
videos rendering etc.
|
||||
"""
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def on_event(self, event, payload):
|
||||
"""
|
||||
Called by OctoPrint upon processing of a fired event on the platform.
|
||||
@@ -1734,6 +1813,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
|
||||
"""
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_slicer_configured(self):
|
||||
"""
|
||||
Unless the return value of this method is ``True``, OctoPrint will not register the slicer within the slicing
|
||||
@@ -1743,6 +1823,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return False
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_slicer_properties(self):
|
||||
"""
|
||||
Plugins should override this method to return a ``dict`` containing a bunch of meta data about the implemented slicer.
|
||||
@@ -1780,6 +1861,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
destination_extensions=["gco", "gcode", "g"]
|
||||
)
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_slicer_default_profile(self):
|
||||
"""
|
||||
Should return a :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile to use with
|
||||
@@ -1791,6 +1873,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_slicer_profile(self, path):
|
||||
"""
|
||||
Should return a :class:`~octoprint.slicing.SlicingProfile` parsed from the slicing profile stored at the
|
||||
@@ -1804,6 +1887,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return None
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
|
||||
"""
|
||||
Should save the provided :class:`~octoprint.slicing.SlicingProfile` to the indicated ``path``, after applying
|
||||
@@ -1820,6 +1904,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
pass
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
"""
|
||||
Called by OctoPrint to slice ``model_path`` for the indicated ``printer_profile``. If the ``machinecode_path`` is ``None``,
|
||||
@@ -1876,6 +1961,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
pass
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def cancel_slicing(self, machinecode_path):
|
||||
"""
|
||||
Cancels the slicing to the indicated file.
|
||||
@@ -1892,16 +1978,18 @@ class ProgressPlugin(OctoPrintPlugin):
|
||||
limited to minimally 1% steps.
|
||||
"""
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def on_print_progress(self, storage, path, progress):
|
||||
"""
|
||||
Called by OctoPrint on minimally 1% increments during a running print job.
|
||||
|
||||
:param string location: Location of the file
|
||||
:param string storage: Location of the file
|
||||
:param string path: Path of the file
|
||||
:param int progress: Current progress as a value between 0 and 100
|
||||
"""
|
||||
pass
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def on_slicing_progress(self, slicer, source_location, source_path, destination_location, destination_path, progress):
|
||||
"""
|
||||
Called by OctoPrint on minimally 1% increments during a running slicing job.
|
||||
@@ -1927,6 +2015,7 @@ class AppPlugin(OctoPrintPlugin):
|
||||
|
||||
"""
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_additional_apps(self):
|
||||
return []
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# make our plugins testable
|
||||
@@ -18,16 +18,22 @@ import threading
|
||||
import feedparser
|
||||
import flask
|
||||
|
||||
from collections import OrderedDict
|
||||
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify
|
||||
from flask.ext.babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
|
||||
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._cached_channel_configs = None
|
||||
self._cached_channel_configs_mutex = threading.RLock()
|
||||
@@ -39,40 +45,75 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
# StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
self._fetch_all_channels()
|
||||
# decouple channel fetching from server startup
|
||||
def fetch_data():
|
||||
self._fetch_all_channels()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
# SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(channels=dict(_important=dict(name="Important OctoPrint Announcements",
|
||||
priority=1,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/important.xml"),
|
||||
_news=dict(name="OctoPrint News",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/news.xml"),
|
||||
_releases=dict(name="OctoPrint Release Announcements",
|
||||
settings = dict(channels=dict(_important=dict(name="Important Announcements",
|
||||
description="Important announcements about OctoPrint.",
|
||||
priority=1,
|
||||
type="rss",
|
||||
url="https://octoprint.org/feeds/important.xml"),
|
||||
_releases=dict(name="Release Announcements",
|
||||
description="Announcements of new releases and release candidates of OctoPrint.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="https://octoprint.org/feeds/releases.xml"),
|
||||
_blog=dict(name="On the OctoBlog",
|
||||
description="Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/releases.xml"),
|
||||
_spotlight=dict(name="OctoPrint Community Spotlights",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/spotlight.xml"),
|
||||
_octopi=dict(name="OctoPi Announcements",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/octopi.xml"),
|
||||
_plugins=dict(name="New Plugins in the Repository",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://plugins.octoprint.org/feed.xml")),
|
||||
enabled_channels=[],
|
||||
forced_channels=["_important"],
|
||||
ttl=6*60,
|
||||
display_limit=3,
|
||||
summary_limit=300)
|
||||
url="https://octoprint.org/feeds/octoblog.xml"),
|
||||
_plugins=dict(name="New Plugins in the Repository",
|
||||
description="Announcements of new plugins released on the official Plugin Repository.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="https://plugins.octoprint.org/feed.xml"),
|
||||
_octopi=dict(name="OctoPi News",
|
||||
description="News around OctoPi, the Raspberry Pi image including OctoPrint.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="https://octoprint.org/feeds/octopi.xml")),
|
||||
enabled_channels=[],
|
||||
forced_channels=["_important"],
|
||||
channel_order=["_important", "_releases", "_blog", "_plugins", "_octopi"],
|
||||
ttl=6*60,
|
||||
display_limit=3,
|
||||
summary_limit=300)
|
||||
settings["enabled_channels"] = settings["channels"].keys()
|
||||
return settings
|
||||
|
||||
def get_settings_version(self):
|
||||
return 1
|
||||
|
||||
def on_settings_migrate(self, target, current):
|
||||
if current is None:
|
||||
# first version had different default feeds and only _important enabled by default
|
||||
channels = self._settings.get(["channels"])
|
||||
if "_news" in channels:
|
||||
del channels["_news"]
|
||||
if "_spotlight" in channels:
|
||||
del channels["_spotlight"]
|
||||
self._settings.set(["channels"], channels)
|
||||
|
||||
enabled = self._settings.get(["enabled_channels"])
|
||||
add_blog = False
|
||||
if "_news" in enabled:
|
||||
add_blog = True
|
||||
enabled.remove("_news")
|
||||
if "_spotlight" in enabled:
|
||||
add_blog = True
|
||||
enabled.remove("_spotlight")
|
||||
if add_blog and not "_blog" in enabled:
|
||||
enabled.append("_blog")
|
||||
self._settings.set(["enabled_channels"], enabled)
|
||||
|
||||
# AssetPlugin
|
||||
|
||||
@@ -97,7 +138,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
def get_channel_data(self):
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
|
||||
result = dict()
|
||||
result = []
|
||||
|
||||
force = flask.request.values.get("force", "false") in valid_boolean_trues
|
||||
|
||||
@@ -118,21 +159,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
last = entries[0]["published"]
|
||||
self._mark_read_until(key, last)
|
||||
|
||||
result[key] = dict(channel=data["name"],
|
||||
result.append(dict(key=key,
|
||||
channel=data["name"],
|
||||
url=data["url"],
|
||||
description=data.get("description", ""),
|
||||
priority=data.get("priority", 2),
|
||||
enabled=key in enabled or key in forced,
|
||||
forced=key in forced,
|
||||
data=entries,
|
||||
unread=unread)
|
||||
unread=unread))
|
||||
|
||||
return flask.jsonify(result)
|
||||
return flask.jsonify(channels=result)
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
hash.update(repr(sorted(enabled)))
|
||||
hash.update(repr(sorted(forced)))
|
||||
hash.update(OCTOPRINT_VERSION)
|
||||
|
||||
for channel in sorted(channel_configs.keys()):
|
||||
hash.update(repr(channel_configs[channel]))
|
||||
@@ -141,11 +185,12 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
return check_etag(etag())
|
||||
# noinspection PyShadowingNames
|
||||
def condition(lm, etag):
|
||||
return check_etag(etag)
|
||||
|
||||
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
condition=lambda lm, etag: condition(lm, etag),
|
||||
unless=lambda: force)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
|
||||
@@ -171,6 +216,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
self._fetch_all_channels_async()
|
||||
|
||||
# Internal Tools
|
||||
|
||||
def _mark_read_until(self, channel, until):
|
||||
@@ -208,9 +261,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
with self._cached_channel_configs_mutex:
|
||||
if self._cached_channel_configs is None or force:
|
||||
configs = self._settings.get(["channels"], merged=True)
|
||||
result = dict()
|
||||
for key, config in configs.items():
|
||||
if "url" not in config or "name" not in config:
|
||||
order = self._settings.get(["channel_order"])
|
||||
all_keys = order + [key for key in sorted(configs.keys()) if not key in order]
|
||||
|
||||
result = OrderedDict()
|
||||
for key in all_keys:
|
||||
config = configs.get(key)
|
||||
if config is None or "url" not in config or "name" not in config:
|
||||
# strip invalid entries
|
||||
continue
|
||||
result[self._slugify(key)] = config
|
||||
@@ -223,6 +280,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
safe_key = self._slugify(key)
|
||||
return self._get_channel_configs(force=force).get(safe_key)
|
||||
|
||||
def _fetch_all_channels_async(self, force=False):
|
||||
thread = threading.Thread(target=self._fetch_all_channels, kwargs=dict(force=force))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def _fetch_all_channels(self, force=False):
|
||||
"""Fetch all channel feeds from cache or network."""
|
||||
|
||||
@@ -255,7 +317,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
if data is None:
|
||||
# cache not allowed or empty, fetch from network
|
||||
data = self._get_channel_data_from_network(key, config)
|
||||
if self._connectivity_checker.online:
|
||||
data = self._get_channel_data_from_network(key, config)
|
||||
else:
|
||||
self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key))
|
||||
|
||||
return data
|
||||
|
||||
@@ -287,7 +352,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
url = config["url"]
|
||||
try:
|
||||
start = time.time()
|
||||
r = requests.get(url)
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
@@ -322,10 +388,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return dict(title=entry["title"],
|
||||
title_without_tags=_strip_tags(entry["title"]),
|
||||
summary=entry["summary"],
|
||||
summary=_lazy_images(entry["summary"]),
|
||||
summary_without_images=_strip_images(entry["summary"]),
|
||||
published=published,
|
||||
link=entry["link"],
|
||||
link=utmify(entry["link"], source="octoprint", medium="announcements", content=OCTOPRINT_VERSION),
|
||||
read=read)
|
||||
|
||||
def _get_channel_cache_path(self, key):
|
||||
@@ -337,8 +403,57 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
_image_tag_re = re.compile(r'<img.*?/?>')
|
||||
def _strip_images(text):
|
||||
"""
|
||||
>>> _strip_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
|
||||
u"<a href='test.html'>I'm a link</a> and this is an image: "
|
||||
>>> _strip_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">")
|
||||
u'One and two and three and four '
|
||||
>>> _strip_images(u"No images here")
|
||||
u'No images here'
|
||||
"""
|
||||
return _image_tag_re.sub('', text)
|
||||
|
||||
def _replace_images(text, callback):
|
||||
"""
|
||||
>>> callback = lambda img: "foobar"
|
||||
>>> _replace_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback)
|
||||
u"<a href='test.html'>I'm a link</a> and this is an image: foobar"
|
||||
>>> _replace_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback)
|
||||
u'One foobar and two foobar and three foobar and four foobar'
|
||||
"""
|
||||
result = text
|
||||
for match in _image_tag_re.finditer(text):
|
||||
tag = match.group(0)
|
||||
replaced = callback(tag)
|
||||
result = result.replace(tag, replaced)
|
||||
return result
|
||||
|
||||
_image_src_re = re.compile(r'src=(?P<quote>[\'"]*)(?P<src>.*?)(?P=quote)(?=\s+|>)')
|
||||
def _lazy_images(text, placeholder=None):
|
||||
"""
|
||||
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
|
||||
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
|
||||
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png")
|
||||
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
|
||||
>>> _lazy_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png")
|
||||
u'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="four">'
|
||||
>>> _lazy_images(u"No images here")
|
||||
u'No images here'
|
||||
"""
|
||||
if placeholder is None:
|
||||
# 1px transparent gif
|
||||
placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
|
||||
|
||||
def callback(img_tag):
|
||||
match = _image_src_re.search(img_tag)
|
||||
if match is not None:
|
||||
src = match.group("src")
|
||||
quote = match.group("quote")
|
||||
quoted_src = quote + src + quote
|
||||
img_tag = img_tag.replace(match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src))
|
||||
return img_tag
|
||||
|
||||
return _replace_images(text, callback)
|
||||
|
||||
def _strip_tags(text):
|
||||
"""
|
||||
@@ -374,4 +489,9 @@ def _strip_tags(text):
|
||||
|
||||
|
||||
__plugin_name__ = "Announcement Plugin"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Announcements all around OctoPrint"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin you might miss important announcements "
|
||||
"regarding security or other critical issues concerning OctoPrint.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = AnnouncementPlugin()
|
||||
@@ -1 +1 @@
|
||||
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}
|
||||
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
|
||||
@@ -40,7 +40,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = data.enabled ? "icon-circle" : "icon-circle-blank";
|
||||
var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -54,6 +54,18 @@ $(function() {
|
||||
return !data.forced;
|
||||
};
|
||||
|
||||
self.cleanedLink = function(data) {
|
||||
// Strips any query parameters from the link and returns it
|
||||
var link = data.link;
|
||||
if (!link) return link;
|
||||
|
||||
var queryPos = link.indexOf("?");
|
||||
if (queryPos !== -1) {
|
||||
link = link.substr(0, queryPos);
|
||||
}
|
||||
return link;
|
||||
};
|
||||
|
||||
self.markRead = function(channel, until) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
@@ -120,12 +132,13 @@ $(function() {
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
|
||||
|
||||
var unread = 0;
|
||||
var channels = [];
|
||||
_.each(data, function(value, key) {
|
||||
value.key = key;
|
||||
_.each(data.channels, function(value) {
|
||||
value.last = value.data.length ? value.data[0].published : undefined;
|
||||
value.count = value.data.length;
|
||||
unread += value.unread;
|
||||
@@ -140,6 +153,11 @@ $(function() {
|
||||
};
|
||||
|
||||
self.showAnnouncementDialog = function(channel) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
// lazy load images that still need lazy-loading
|
||||
$("#plugin_announcements_dialog_content article img").lazyload();
|
||||
|
||||
self.announcementDialogContent.scrollTop(0);
|
||||
|
||||
if (!self.announcementDialog.hasClass("in")) {
|
||||
@@ -172,6 +190,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.displayAnnouncements = function(channels) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
|
||||
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
|
||||
|
||||
@@ -222,7 +242,7 @@ $(function() {
|
||||
}
|
||||
var rest = newItems.length - displayedItems.length;
|
||||
|
||||
var text = "<ul>";
|
||||
var text = "<ul style='margin-top: 10px; margin-bottom: 10px'>";
|
||||
_.each(displayedItems, function(item) {
|
||||
var limitedSummary = stripParagraphs(item.summary_without_images.trim());
|
||||
if (limitedSummary.length > maxLength) {
|
||||
@@ -239,6 +259,8 @@ $(function() {
|
||||
text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest}));
|
||||
}
|
||||
|
||||
text += "<small>" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + "</small>";
|
||||
|
||||
var options = {
|
||||
title: channel,
|
||||
text: text,
|
||||
@@ -248,22 +270,22 @@ $(function() {
|
||||
buttons: [{
|
||||
text: gettext("Later"),
|
||||
click: function(notice) {
|
||||
self.hiddenChannels.push(key);
|
||||
notice.remove();
|
||||
self.hiddenChannels.push(key);
|
||||
}
|
||||
}, {
|
||||
text: gettext("Mark read"),
|
||||
click: function(notice) {
|
||||
self.markRead(key, value.last);
|
||||
notice.remove();
|
||||
self.markRead(key, value.last);
|
||||
}
|
||||
}, {
|
||||
text: gettext("Read..."),
|
||||
addClass: "btn-primary",
|
||||
click: function(notice) {
|
||||
notice.remove();
|
||||
self.showAnnouncementDialog(key);
|
||||
self.markRead(key, value.last);
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
},
|
||||
@@ -284,21 +306,41 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.hideAnnouncements = function() {
|
||||
_.each(self.channelNotifications, function(notification, key) {
|
||||
notification.remove();
|
||||
});
|
||||
self.channelNotifications = {};
|
||||
};
|
||||
|
||||
self.configureAnnouncements = function() {
|
||||
self.settings.show("settings_plugin_announcements");
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.retrieveData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.hideAnnouncements();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.announcementDialog = $("#plugin_announcements_dialog");
|
||||
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
|
||||
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
if (!payload || !payload.new) return;
|
||||
self.retrieveData();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([
|
||||
AnnouncementsViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: AnnouncementsViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
|
||||
});
|
||||
});
|
||||
@@ -53,4 +53,10 @@ table {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
.configurelink {
|
||||
float: left;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
<!-- ko foreach: {data: channels.items, afterAdd: setupTabLink} -->
|
||||
<!-- ko if: $data.enabled || $data.forced -->
|
||||
<li>
|
||||
<a data-toggle="tab" target="_blank" data-bind="text: $data.channel + ' (' + $data.unread + '/' + $data.count + ')', attr: {href: '#plugin_announcements_dialog_channel_' + $data.key}, css: {unread: $data.unread}"></a>
|
||||
<a data-toggle="tab" target="_blank" data-bind="text: $data.channel, attr: {href: '#plugin_announcements_dialog_channel_' + $data.key, title: $data.description}, css: {unread: $data.unread}"></a>
|
||||
</li>
|
||||
<!-- /ko -->
|
||||
<!-- /ko -->
|
||||
@@ -27,8 +27,8 @@
|
||||
<h3><a data-bind="text: $data.title, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a> <small data-bind="text: formatTimeAgo($data.published), attr: {title: formatDate($data.published)}"></small></h3>
|
||||
<div class="content" data-bind="html: $data.summary"></div>
|
||||
<div class="actions">
|
||||
<span class="articlelink"><small><a data-bind="text: $data.link, 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="icon-eye-open"></i> {{ _('Mark as last read') }}</a></small></span>
|
||||
<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>
|
||||
</div>
|
||||
</article>
|
||||
<!-- /ko -->
|
||||
@@ -40,6 +40,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-block" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
<button class="btn configurelink" data-bind="click: configureAnnouncements"><i class="fa fa-wrench"></i></button>
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,3 +1,3 @@
|
||||
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
|
||||
<i data-bind="css: {'icon-bell': !unread(), 'icon-bell-alt': unread()}"></i>
|
||||
<i class="fa" data-bind="css: {'fa-bell-o': !unread(), 'fa-bell': unread()}"></i>
|
||||
</a>
|
||||
@@ -10,7 +10,8 @@
|
||||
<tbody data-bind="foreach: channels.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_announcements_channels_name">
|
||||
<div data-bind="text: channel, css: {muted: !enabled}"></div>
|
||||
<div data-bind="css: {muted: !enabled}"><strong data-bind="text: channel"></strong></div>
|
||||
<div data-bind="text: description, css: {muted: !enabled}"></div>
|
||||
<div><small class="muted" data-bind="text: url"> </small></div>
|
||||
</td>
|
||||
<td class="settings_plugin_announcements_channels_actions">
|
||||
@@ -31,4 +32,4 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="icon-refresh"></i> {{ _('Refresh Announcements') }}</button>
|
||||
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="fa fa-refresh"></i> {{ _('Refresh Announcements') }}</button>
|
||||
@@ -1,22 +1,21 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
|
||||
from flask.ext.babel import gettext
|
||||
from .subwizards import Subwizards
|
||||
|
||||
|
||||
class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.WizardPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
Subwizards):
|
||||
|
||||
#~~ TemplatePlugin API
|
||||
|
||||
@@ -25,8 +24,18 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
names = self._get_subwizard_attrs("_get_", "_wizard_name")
|
||||
additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data")
|
||||
|
||||
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
|
||||
firstrun = self._settings.global_get(["server", "firstRun"])
|
||||
|
||||
if not firstrun:
|
||||
required = dict((key, value) for key, value in required.items()
|
||||
if not firstrunonly.get(key, lambda: False)())
|
||||
|
||||
result = list()
|
||||
for key, method in required.items():
|
||||
if not callable(method):
|
||||
continue
|
||||
|
||||
if not method():
|
||||
continue
|
||||
|
||||
@@ -37,7 +46,11 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
if not name:
|
||||
continue
|
||||
|
||||
config = dict(type="wizard", name=name, template="corewizard_{}_wizard.jinja2".format(key), div="wizard_plugin_corewizard_{}".format(key))
|
||||
config = dict(type="wizard",
|
||||
name=name,
|
||||
template="corewizard_{}_wizard.jinja2".format(key),
|
||||
div="wizard_plugin_corewizard_{}".format(key),
|
||||
suffix="_{}".format(key))
|
||||
if key in additional:
|
||||
additional_result = additional[key]()
|
||||
if additional_result:
|
||||
@@ -49,15 +62,27 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~~ AssetPlugin API
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/corewizard.js"]
|
||||
)
|
||||
if self.is_wizard_required():
|
||||
return dict(
|
||||
js=["js/corewizard.js"],
|
||||
css=["css/corewizard.css"]
|
||||
)
|
||||
else:
|
||||
return dict()
|
||||
|
||||
#~~ WizardPlugin API
|
||||
|
||||
def is_wizard_required(self):
|
||||
methods = self._get_subwizard_attrs("_is_", "_wizard_required")
|
||||
return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values()))
|
||||
required = self._get_subwizard_attrs("_is_", "_wizard_required")
|
||||
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
|
||||
firstrun = self._settings.global_get(["server", "firstRun"])
|
||||
|
||||
if not firstrun:
|
||||
required = dict((key, value) for key, value in required.items()
|
||||
if not firstrunonly.get(key, lambda: False)())
|
||||
any_required = any(map(lambda m: m(), required.values()))
|
||||
|
||||
return any_required
|
||||
|
||||
def get_wizard_details(self):
|
||||
result = dict()
|
||||
@@ -68,87 +93,8 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return result
|
||||
|
||||
#~~ ACL subwizard
|
||||
|
||||
def _is_acl_wizard_required(self):
|
||||
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
|
||||
|
||||
def _get_acl_wizard_details(self):
|
||||
return dict()
|
||||
|
||||
def _get_acl_wizard_name(self):
|
||||
return gettext("Access Control")
|
||||
|
||||
def _get_acl_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_acl_wizard_required())
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
|
||||
def acl_wizard_api(self):
|
||||
from flask import request
|
||||
from octoprint.server.api import valid_boolean_trues, NO_CONTENT
|
||||
|
||||
data = request.values
|
||||
if hasattr(request, "json") and request.json:
|
||||
data = request.json
|
||||
|
||||
if "ac" in data and data["ac"] in valid_boolean_trues and \
|
||||
"user" in data.keys() and "pass1" in data.keys() and \
|
||||
"pass2" in data.keys() and data["pass1"] == data["pass2"]:
|
||||
# configure access control
|
||||
self._settings.global_set_boolean(["accessControl", "enabled"], True)
|
||||
self._user_manager.enable()
|
||||
self._user_manager.addUser(data["user"], data["pass1"], True, ["user", "admin"], overwrite=True)
|
||||
elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues:
|
||||
# disable access control
|
||||
self._settings.global_set_boolean(["accessControl", "enabled"], False)
|
||||
|
||||
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
|
||||
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
|
||||
|
||||
self._user_manager.disable()
|
||||
self._settings.save()
|
||||
return NO_CONTENT
|
||||
|
||||
#~~ Webcam subwizard
|
||||
|
||||
def _is_webcam_wizard_required(self):
|
||||
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
|
||||
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
|
||||
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
|
||||
|
||||
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
|
||||
|
||||
def _get_webcam_wizard_details(self):
|
||||
return dict()
|
||||
|
||||
def _get_webcam_wizard_name(self):
|
||||
return gettext("Webcam & Timelapse")
|
||||
|
||||
#~~ Server commands subwizard
|
||||
|
||||
def _is_servercommands_wizard_required(self):
|
||||
system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
|
||||
system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
return not (system_shutdown_command and system_restart_command and server_restart_command)
|
||||
|
||||
def _get_servercommands_wizard_details(self):
|
||||
return dict()
|
||||
|
||||
def _get_servercommands_wizard_name(self):
|
||||
return gettext("Server Commands")
|
||||
|
||||
#~~ Printer profile subwizard
|
||||
|
||||
def _is_printerprofile_wizard_required(self):
|
||||
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
|
||||
|
||||
def _get_printerprofile_wizard_details(self):
|
||||
return dict()
|
||||
|
||||
def _get_printerprofile_wizard_name(self):
|
||||
return gettext("Default Printer Profile")
|
||||
def get_wizard_version(self):
|
||||
return 3
|
||||
|
||||
#~~ helpers
|
||||
|
||||
@@ -172,5 +118,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
|
||||
__plugin_name__ = "Core Wizard"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Provides wizard dialogs for core components and functionality"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to perform "
|
||||
"setup steps that might be required after an update.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CoreWizardPlugin()
|
||||
@@ -0,0 +1,4 @@
|
||||
#wizard_plugin_corewizard_pluginblacklist p {
|
||||
line-height: 1.5;
|
||||
margin-bottom: 1.5em;
|
||||
}
|
||||
@@ -11,6 +11,8 @@ $(function() {
|
||||
self.setup = ko.observable(false);
|
||||
self.decision = ko.observable();
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.passwordMismatch = ko.pureComputed(function() {
|
||||
return self.password() != self.confirmedPassword();
|
||||
});
|
||||
@@ -72,6 +74,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
@@ -82,7 +86,13 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
|
||||
if (!self.decision()) {
|
||||
return "reload";
|
||||
}
|
||||
@@ -94,7 +104,14 @@ $(function() {
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
if (self.settingsViewModel.webcam_streamUrl()
|
||||
|| (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
|
||||
return "reload";
|
||||
@@ -108,23 +125,195 @@ $(function() {
|
||||
self.settingsViewModel = parameters[0];
|
||||
}
|
||||
|
||||
function CoreWizardOnlineCheckViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
|
||||
self.setup = ko.observable(false);
|
||||
|
||||
self.decision = ko.observable();
|
||||
self.required = false;
|
||||
self.active = false;
|
||||
|
||||
self.enableOnlineCheck = function() {
|
||||
self.settingsViewModel.server_onlineCheck_enabled(true);
|
||||
self.decision(true);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.disableOnlineCheck = function() {
|
||||
self.settingsViewModel.server_onlineCheck_enabled(false);
|
||||
self.decision(false);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function() {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function() {
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up the online connectivity check"),
|
||||
message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.")
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function() {
|
||||
var data = {
|
||||
server: {
|
||||
onlineCheck: {
|
||||
enabled: self.settingsViewModel.server_onlineCheck_enabled(),
|
||||
interval: self.settingsViewModel.server_onlineCheck_interval(),
|
||||
host: self.settingsViewModel.server_onlineCheck_host(),
|
||||
port: self.settingsViewModel.server_onlineCheck_port()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.active = true;
|
||||
self.settingsViewModel.saveData(data)
|
||||
.done(function() {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
function CoreWizardPluginBlacklistViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
|
||||
self.setup = ko.observable(false);
|
||||
|
||||
self.decision = ko.observable();
|
||||
self.required = false;
|
||||
self.active = false;
|
||||
|
||||
self.enablePluginBlacklist = function() {
|
||||
self.settingsViewModel.server_pluginBlacklist_enabled(true);
|
||||
self.decision(true);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.disablePluginBlacklist = function() {
|
||||
self.settingsViewModel.server_pluginBlacklist_enabled(false);
|
||||
self.decision(false);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function() {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required;
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function() {
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up the plugin blacklist processing"),
|
||||
message: gettext("You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing.")
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function() {
|
||||
var data = {
|
||||
server: {
|
||||
pluginBlacklist: {
|
||||
enabled: self.settingsViewModel.server_pluginBlacklist_enabled()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.active = true;
|
||||
self.settingsViewModel.saveData(data)
|
||||
.done(function() {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
function CoreWizardPrinterProfileViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.printerProfiles = parameters[0];
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.editor = self.printerProfiles.createProfileEditor();
|
||||
self.editorLoaded = ko.observable(false);
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required;
|
||||
if (!self.required) return;
|
||||
|
||||
OctoPrint.printerprofiles.get("_default")
|
||||
.done(function(data) {
|
||||
self.editor.fromProfileData(data);
|
||||
self.editorLoaded(true);
|
||||
})
|
||||
.fail(function() {
|
||||
self.editor.fromProfileData();
|
||||
self.editorLoaded(true);
|
||||
});
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
|
||||
OctoPrint.printerprofiles.update("_default", self.editor.toProfileData())
|
||||
.done(function() {
|
||||
self.printerProfiles.requestData();
|
||||
@@ -132,21 +321,29 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
CoreWizardAclViewModel,
|
||||
["loginStateViewModel"],
|
||||
"#wizard_plugin_corewizard_acl"
|
||||
], [
|
||||
CoreWizardWebcamViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_webcam"
|
||||
], [
|
||||
CoreWizardServerCommandsViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_servercommands"
|
||||
], [
|
||||
CoreWizardPrinterProfileViewModel,
|
||||
["printerProfilesViewModel"],
|
||||
"#wizard_plugin_corewizard_printerprofile"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: CoreWizardAclViewModel,
|
||||
dependencies: ["loginStateViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_acl"]
|
||||
}, {
|
||||
construct: CoreWizardWebcamViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_webcam"]
|
||||
}, {
|
||||
construct: CoreWizardServerCommandsViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_servercommands"]
|
||||
}, {
|
||||
construct: CoreWizardOnlineCheckViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_onlinecheck"]
|
||||
}, {
|
||||
construct: CoreWizardPluginBlacklistViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_pluginblacklist"]
|
||||
}, {
|
||||
construct: CoreWizardPrinterProfileViewModel,
|
||||
dependencies: ["printerProfilesViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_printerprofile"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
# 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import sys
|
||||
import inspect
|
||||
from flask.ext.babel import gettext
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
class ServerCommandsSubwizard(object):
|
||||
def _is_servercommands_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_servercommands_wizard_required(self):
|
||||
system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
|
||||
system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
return not (system_shutdown_command and system_restart_command and server_restart_command)
|
||||
|
||||
def _get_servercommands_wizard_details(self):
|
||||
return dict(required=self._is_servercommands_wizard_required())
|
||||
|
||||
def _get_servercommands_wizard_name(self):
|
||||
return gettext("Server Commands")
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
class WebcamSubwizard(object):
|
||||
def _is_webcam_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_webcam_wizard_required(self):
|
||||
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
|
||||
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
|
||||
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
|
||||
|
||||
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
|
||||
|
||||
def _get_webcam_wizard_details(self):
|
||||
return dict(required=self._is_webcam_wizard_required())
|
||||
|
||||
def _get_webcam_wizard_name(self):
|
||||
return gettext("Webcam & Timelapse")
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
class AclSubwizard(object):
|
||||
def _is_acl_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_acl_wizard_required(self):
|
||||
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
|
||||
|
||||
def _get_acl_wizard_details(self):
|
||||
return dict(required=self._is_acl_wizard_required())
|
||||
|
||||
def _get_acl_wizard_name(self):
|
||||
return gettext("Access Control")
|
||||
|
||||
def _get_acl_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_acl_wizard_required())
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
|
||||
def acl_wizard_api(self):
|
||||
from flask import request, abort
|
||||
from octoprint.server.api import valid_boolean_trues, NO_CONTENT
|
||||
|
||||
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.hasBeenCustomized():
|
||||
abort(404)
|
||||
|
||||
data = request.values
|
||||
if hasattr(request, "json") and request.json:
|
||||
data = request.json
|
||||
|
||||
if "ac" in data and data["ac"] in valid_boolean_trues and \
|
||||
"user" in data.keys() and "pass1" in data.keys() and \
|
||||
"pass2" in data.keys() and data["pass1"] == data["pass2"]:
|
||||
# configure access control
|
||||
self._settings.global_set_boolean(["accessControl", "enabled"], True)
|
||||
self._user_manager.enable()
|
||||
self._user_manager.addUser(data["user"], data["pass1"], True, ["user", "admin"], overwrite=True)
|
||||
elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues:
|
||||
# disable access control
|
||||
self._settings.global_set_boolean(["accessControl", "enabled"], False)
|
||||
|
||||
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
|
||||
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
|
||||
|
||||
self._user_manager.disable()
|
||||
self._settings.save()
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
class OnlineCheckSubwizard(object):
|
||||
def _is_onlinecheck_wizard_firstrunonly(self):
|
||||
return False
|
||||
|
||||
def _is_onlinecheck_wizard_required(self):
|
||||
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
|
||||
|
||||
def _get_onlinecheck_wizard_details(self):
|
||||
return dict(required=self._is_onlinecheck_wizard_required())
|
||||
|
||||
def _get_onlinecheck_wizard_name(self):
|
||||
return gettext("Online connectivity check")
|
||||
|
||||
def _get_onlinecheck_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_onlinecheck_wizard_required())
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
class PluginBlacklistSubwizard(object):
|
||||
def _is_pluginblacklist_wizard_firstrunonly(self):
|
||||
return False
|
||||
|
||||
def _is_pluginblacklist_wizard_required(self):
|
||||
return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None
|
||||
|
||||
def _get_pluginblacklist_wizard_details(self):
|
||||
return dict(required=self._is_pluginblacklist_wizard_required())
|
||||
|
||||
def _get_pluginblacklist_wizard_name(self):
|
||||
return gettext("Plugin blacklist")
|
||||
|
||||
def _get_pluginblacklist_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_pluginblacklist_wizard_required())
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
class PrinterProfileSubwizard(object):
|
||||
def _is_printerprofile_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_printerprofile_wizard_required(self):
|
||||
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
|
||||
|
||||
def _get_printerprofile_wizard_details(self):
|
||||
return dict(required=self._is_printerprofile_wizard_required())
|
||||
|
||||
def _get_printerprofile_wizard_name(self):
|
||||
return gettext("Default Printer Profile")
|
||||
|
||||
|
||||
Subwizards = type("Subwizwards",
|
||||
tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
|
||||
if clsname.endswith("Subwizard")),
|
||||
dict())
|
||||
@@ -0,0 +1,47 @@
|
||||
<h3>{{ _('Configure the connectivity check') }}</h3>
|
||||
|
||||
{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
|
||||
|
||||
<p>{% trans %}
|
||||
If it is disabled OctoPrint will always assume to have a working connection to the internet.
|
||||
If that should not actually be the case, server startups, update checks and the like might take longer.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<p>{% trans %}
|
||||
OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
|
||||
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
|
||||
</form>
|
||||
|
||||
<p>{% trans %}
|
||||
OctoPrint comes preconfigured to utilize Google's DNS server <code>8.8.8.8</code>, port 53 for the connectivity check (if
|
||||
it's enabled). If you have concerns about using that, define the IP and port of a different online server that you
|
||||
trust and that has a high availability.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
|
||||
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckTest.jinja2" %}
|
||||
</form>
|
||||
|
||||
<p>{% trans %}
|
||||
Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at
|
||||
any time to a later date through Settings > Server right from within OctoPrint.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<div class="row-fluid">
|
||||
<a href="#" class="btn span6" data-bind="click: function() { if(!setup()){disableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Connectivity Check') }}</a>
|
||||
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Connectivity Check') }}</a>
|
||||
</div>
|
||||
|
||||
<div class="onlinecheck_decision" style="display: none" data-bind="visible: setup()">
|
||||
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
|
||||
Connectivity check is <strong class="text-success">enabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
|
||||
Connectivity check is <strong class="text-danger">disabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
</div>
|
||||
@@ -0,0 +1,31 @@
|
||||
<h3>{{ _('Configure plugin blacklist processing') }}</h3>
|
||||
|
||||
<p>{% trans %}
|
||||
To protect against known severe issues with certain versions of third party plugins, OctoPrint supports the use
|
||||
of a centralized plugin version blacklist to automatically disable such plugin versions before they can interfere with
|
||||
normal operation, allowing you to uninstall or update them to a newer version.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<p>{% trans url="https://plugins.octoprint.org/blacklist/" %}
|
||||
By default, OctoPrint will use the blacklist hosted at <code>plugins.octoprint.org/blacklist.json</code> which you
|
||||
can also take a look at in a more human readable format <a href="{{ url }}" target="_blank">here</a>.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<p>{% trans %}
|
||||
Please decide whether to allow fetch and use of this centralized blacklist starting with the next server start.
|
||||
You may also change your decision at any time through Settings > Server right from within OctoPrint.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<div class="row-fluid">
|
||||
<a href="#" class="btn btn-danger span6" data-bind="click: function() { if(!setup()){disablePluginBlacklist()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Plugin Blacklist Processing') }}</a>
|
||||
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enablePluginBlacklist()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Plugin Blacklist Processing') }}</a>
|
||||
</div>
|
||||
|
||||
<div class="pluginblacklist_decision" style="display: none" data-bind="visible: setup()">
|
||||
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
|
||||
Plugin blacklist processing is <strong class="text-success">enabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
|
||||
Plugin blacklist processing is <strong class="text-danger">disabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
</div>
|
||||
@@ -17,6 +17,7 @@ import octoprint.slicing
|
||||
import octoprint.settings
|
||||
|
||||
from octoprint.util.paths import normalize as normalize_path
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
from .profile import Profile
|
||||
from .profile import GcodeFlavors
|
||||
@@ -30,6 +31,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.WizardPlugin):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger("octoprint.plugins.cura")
|
||||
self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine")
|
||||
@@ -79,6 +81,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL)
|
||||
self._cura_logger.propagate = False
|
||||
|
||||
engine = self._settings.get(["cura_engine"])
|
||||
if not self._is_engine_configured(cura_engine=engine):
|
||||
self._logger.info("Path to CuraEngine has not been configured or does not exist (currently set to %r), "
|
||||
"Cura will not be selectable for slicing" % engine)
|
||||
|
||||
##~~ BlueprintPlugin API
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
|
||||
@@ -167,11 +174,18 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
##~~ SettingsPlugin API
|
||||
|
||||
def on_settings_save(self, data):
|
||||
old_engine = self._settings.get(["cura_engine"])
|
||||
old_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
|
||||
new_engine = self._settings.get(["cura_engine"])
|
||||
new_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
|
||||
if old_engine != new_engine and not self._is_engine_configured(new_engine):
|
||||
self._logger.info("Path to CuraEngine has not been configured or does not exist (currently set to %r), "
|
||||
"Cura will not be selectable for slicing" % new_engine)
|
||||
|
||||
if old_debug_logging != new_debug_logging:
|
||||
if new_debug_logging:
|
||||
self._cura_logger.setLevel(logging.DEBUG)
|
||||
@@ -189,11 +203,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
def is_slicer_configured(self):
|
||||
cura_engine = normalize_path(self._settings.get(["cura_engine"]))
|
||||
if self._is_engine_configured(cura_engine=cura_engine):
|
||||
return True
|
||||
else:
|
||||
self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
|
||||
return False
|
||||
return self._is_engine_configured(cura_engine=cura_engine)
|
||||
|
||||
def get_slicer_properties(self):
|
||||
return dict(
|
||||
@@ -236,7 +246,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None,
|
||||
on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
try:
|
||||
with self._job_mutex:
|
||||
if not profile_path:
|
||||
@@ -258,7 +269,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
if not on_progress_kwargs:
|
||||
on_progress_kwargs = dict()
|
||||
|
||||
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
|
||||
self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}"
|
||||
.format(to_unicode(model_path, errors="replace"),
|
||||
to_unicode(machinecode_path, errors="replace"),
|
||||
to_unicode(profile_path, errors="replace")))
|
||||
|
||||
executable = normalize_path(self._settings.get(["cura_engine"]))
|
||||
if not executable:
|
||||
@@ -293,7 +307,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
args += ["-s", "%s=%s" % (k, str(v))]
|
||||
args += ["-o", machinecode_path, model_path]
|
||||
|
||||
self._logger.info(u"Running %r in %s" % (" ".join(args), working_dir))
|
||||
self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"),
|
||||
args)),
|
||||
working_dir))
|
||||
|
||||
import sarge
|
||||
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
@@ -314,7 +330,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
p.commands[0].poll()
|
||||
continue
|
||||
|
||||
line = octoprint.util.to_unicode(line, errors="replace")
|
||||
line = to_unicode(line, errors="replace")
|
||||
self._cura_logger.debug(line.strip())
|
||||
|
||||
if on_progress is not None:
|
||||
@@ -437,7 +453,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
command = self._slicing_commands[machinecode_path]
|
||||
if command is not None:
|
||||
command.terminate()
|
||||
self._logger.info(u"Cancelled slicing of %s" % machinecode_path)
|
||||
self._logger.info(u"Cancelled slicing of {}"
|
||||
.format(to_unicode(machinecode_path, errors="replace")))
|
||||
|
||||
def _load_profile(self, path):
|
||||
import yaml
|
||||
@@ -503,9 +520,10 @@ def _get_usage_from_length(filament_length, filament_diameter):
|
||||
|
||||
return usage
|
||||
|
||||
|
||||
__plugin_name__ = "CuraEngine (<= 15.04)"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CuraPlugin()
|
||||
|
||||
@@ -7,7 +7,11 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import re
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from builtins import range
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
class SupportLocationTypes(object):
|
||||
NONE = "none"
|
||||
|
||||
@@ -24,12 +24,37 @@ $(function() {
|
||||
self.profileDescription = ko.observable();
|
||||
self.profileAllowOverwrite = ko.observable(true);
|
||||
self.profileMakeDefault = ko.observable(false);
|
||||
self.profileFirst = ko.observable(false);
|
||||
|
||||
// make sure to update form data if any of the metadata changes
|
||||
self.profileName.subscribe(function() { self.copyProfileMetadata(); });
|
||||
self.profileDisplayName.subscribe(function() {
|
||||
if (self.profileDisplayName()) {
|
||||
self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase());
|
||||
}
|
||||
self.copyProfileMetadata();
|
||||
});
|
||||
self.profileDescription.subscribe(function() { self.copyProfileMetadata(); });
|
||||
self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); });
|
||||
self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); });
|
||||
|
||||
self.unconfiguredCuraEngine = ko.observable();
|
||||
self.unconfiguredSlicingProfile = ko.observable();
|
||||
|
||||
self.uploadDialog = $("#settings_plugin_cura_import");
|
||||
self.uploadElement = $("#settings-cura-import");
|
||||
self.uploadButton = $("#settings-cura-import-start");
|
||||
self.uploadData = ko.observable(undefined);
|
||||
self.uploadBusy = ko.observable(false);
|
||||
|
||||
self.uploadEnabled = ko.pureComputed(function() {
|
||||
return self.fieldsEnabled();
|
||||
});
|
||||
self.fieldsEnabled = ko.pureComputed(function() {
|
||||
return self.uploadData() && !self.uploadBusy()
|
||||
&& (self.profileName() || self.placeholderName())
|
||||
&& (self.profileDisplayName() || self.placeholderDisplayName())
|
||||
&& (self.profileDescription() || self.placeholderDescription());
|
||||
});
|
||||
|
||||
self.profiles = new ItemListHelper(
|
||||
"plugin_cura_profiles",
|
||||
@@ -66,6 +91,56 @@ $(function() {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.performUpload = function() {
|
||||
if (self.uploadData()) {
|
||||
self.uploadData().submit();
|
||||
}
|
||||
};
|
||||
|
||||
self.copyProfileMetadata = function(form) {
|
||||
form = form || (self.uploadData() ? self.uploadData().formData : {});
|
||||
|
||||
if (self.profileName() !== undefined) {
|
||||
form["name"] = self.profileName();
|
||||
} else if (self.placeholderName() !== undefined) {
|
||||
form["name"] = self.placeholderName();
|
||||
}
|
||||
|
||||
if (self.profileDisplayName() !== undefined) {
|
||||
form["displayName"] = self.profileDisplayName();
|
||||
} else if (self.placeholderDisplayName() !== undefined) {
|
||||
form["displayName"] = self.placeholderDisplayName();
|
||||
}
|
||||
|
||||
if (self.profileDescription() !== undefined) {
|
||||
form["description"] = self.profileDescription();
|
||||
} else if (self.placeholderDescription() !== undefined) {
|
||||
form["description"] = self.placeholderDescription();
|
||||
}
|
||||
|
||||
if (self.profileMakeDefault()) {
|
||||
form["default"] = true;
|
||||
}
|
||||
|
||||
return form;
|
||||
};
|
||||
|
||||
self.clearUpload = function() {
|
||||
self.uploadData(undefined);
|
||||
self.fileName(undefined);
|
||||
self.placeholderName(undefined);
|
||||
self.placeholderDisplayName(undefined);
|
||||
self.placeholderDescription(undefined);
|
||||
self.profileName(undefined);
|
||||
self.profileDisplayName(undefined);
|
||||
self.profileDescription(undefined);
|
||||
self.profileAllowOverwrite(true);
|
||||
|
||||
var firstProfile = self.profiles.items().length === 0;
|
||||
self.profileMakeDefault(firstProfile);
|
||||
self.profileFirst(firstProfile);
|
||||
};
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
@@ -73,6 +148,11 @@ $(function() {
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
if (data.files.length == 0) {
|
||||
// no files? ignore
|
||||
return false;
|
||||
}
|
||||
if (self.uploadData()) {
|
||||
// data already defined? ignore (should never happen)
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -83,41 +163,22 @@ $(function() {
|
||||
self.placeholderDisplayName(name);
|
||||
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
|
||||
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadButton.on("click", function() {
|
||||
var form = {
|
||||
allowOverwrite: self.profileAllowOverwrite()
|
||||
};
|
||||
var form = {
|
||||
allowOverwrite: self.profileAllowOverwrite()
|
||||
};
|
||||
data.formData = self.copyProfileMetadata(form);
|
||||
|
||||
if (self.profileName() !== undefined) {
|
||||
form["name"] = self.profileName();
|
||||
}
|
||||
if (self.profileDisplayName() !== undefined) {
|
||||
form["displayName"] = self.profileDisplayName();
|
||||
}
|
||||
if (self.profileDescription() !== undefined) {
|
||||
form["description"] = self.profileDescription();
|
||||
}
|
||||
if (self.profileMakeDefault()) {
|
||||
form["default"] = true;
|
||||
}
|
||||
|
||||
data.formData = form;
|
||||
data.submit();
|
||||
});
|
||||
self.uploadData(data);
|
||||
},
|
||||
submit: function(e, data) {
|
||||
self.copyProfileMetadata();
|
||||
self.uploadBusy(true);
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.fileName(undefined);
|
||||
self.placeholderName(undefined);
|
||||
self.placeholderDisplayName(undefined);
|
||||
self.placeholderDescription(undefined);
|
||||
self.profileName(undefined);
|
||||
self.profileDisplayName(undefined);
|
||||
self.profileDescription(undefined);
|
||||
self.profileAllowOverwrite(true);
|
||||
self.profileMakeDefault(false);
|
||||
self.uploadBusy(false);
|
||||
self.clearUpload();
|
||||
|
||||
$("#settings_plugin_cura_import").modal("hide");
|
||||
self.uploadDialog.modal("hide");
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
}
|
||||
@@ -160,12 +221,9 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.showImportProfileDialog = function(makeDefault) {
|
||||
if (makeDefault == undefined) {
|
||||
makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0;
|
||||
}
|
||||
self.profileMakeDefault(makeDefault);
|
||||
$("#settings_plugin_cura_import").modal("show");
|
||||
self.showImportProfileDialog = function() {
|
||||
self.clearUpload();
|
||||
self.uploadDialog.modal("show");
|
||||
};
|
||||
|
||||
self.testEnginePath = function() {
|
||||
@@ -207,7 +265,18 @@ $(function() {
|
||||
|
||||
self.onBeforeBinding = function () {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
//self.requestData();
|
||||
};
|
||||
|
||||
self.onAllBound = function() {
|
||||
self.uploadDialog.on("hidden", function(event) {
|
||||
if (event.target.id == "settings_plugin_cura_import") {
|
||||
self.clearUpload();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onSettingsHidden = function() {
|
||||
@@ -242,10 +311,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
CuraViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
|
||||
["#settings_plugin_cura", "#wizard_plugin_cura"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: CuraViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
|
||||
elements: ["#settings_plugin_cura", "#wizard_plugin_cura"]
|
||||
});
|
||||
});
|
||||
@@ -20,32 +20,32 @@
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, valueUpdate: 'afterkeydown', attr: {placeholder: placeholderDisplayName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Description') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: profileMakeDefault"> {{ _('Make default profile') }}
|
||||
<input type="checkbox" data-bind="checked: profileMakeDefault, enable: fieldsEnabled() && !profileFirst(), css: {disabled: !fieldsEnabled() || profileFirst()}"> {{ _('Make default profile') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
|
||||
<input type="checkbox" data-bind="checked: profileAllowOverwrite, enable: fieldsEnabled() && !profileFirst(), css: {disabled: !fieldsEnabled() || profileFirst()}"> {{ _('Overwrite existing file') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -59,6 +59,6 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: performUpload, enable: uploadEnabled, css: {disabled: !uploadEnabled()}" id="settings-cura-import-start"><i class="fa fa-spinner fa-spin" data-bind="visible: uploadBusy"></i> {{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -12,10 +12,10 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: profiles.paginatedItems">
|
||||
<tr data-bind="attr: {title: description}">
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="fa fa-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_cura_profiles_actions">
|
||||
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
<a href="#" class="fa fa-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -10,8 +10,10 @@ The SSDP/UPNP implementations has been largely inspired by https://gist.github.c
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import flask
|
||||
from flask.ext.babel import gettext
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from builtins import range
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -23,12 +25,6 @@ except:
|
||||
pybonjour = False
|
||||
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery"
|
||||
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
def __plugin_load__():
|
||||
if not pybonjour:
|
||||
# no pybonjour available, we can't use that
|
||||
@@ -59,6 +55,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
ssdp_multicast_port = 1900
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self.host = None
|
||||
self.port = None
|
||||
@@ -682,3 +679,12 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
else:
|
||||
import socket
|
||||
return u"OctoPrint instance on {}".format(socket.gethostname())
|
||||
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html"
|
||||
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin your OctoPrint instance will no longer be "
|
||||
"discoverable on the network via Bonjour and uPnP.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
@@ -0,0 +1,175 @@
|
||||
# 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import flask
|
||||
import os
|
||||
|
||||
from flask.ext.babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
|
||||
_CPUINFO_PATH = "/proc/cpuinfo"
|
||||
|
||||
# based on https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F
|
||||
_RPI_REVISION_MAP = {
|
||||
"Beta": "1B (Beta)",
|
||||
"0002": "1B",
|
||||
"0003": "1B",
|
||||
"0004": "1B",
|
||||
"0005": "1B",
|
||||
"0006": "1B",
|
||||
"0007": "1A",
|
||||
"0008": "1A",
|
||||
"0009": "1A",
|
||||
"000d": "1B",
|
||||
"000e": "1B",
|
||||
"000f": "1B",
|
||||
"0010": "B+",
|
||||
"0011": "CM1",
|
||||
"0012": "A+",
|
||||
"0013": "B+",
|
||||
"0014": "CM1",
|
||||
"0015": "A+",
|
||||
"a01040": "2B",
|
||||
"a01041": "2B",
|
||||
"a21041": "2B",
|
||||
"a22042": "2B",
|
||||
"900021": "A+",
|
||||
"900032": "B+",
|
||||
"900092": "Zero",
|
||||
"900093": "Zero",
|
||||
"920093": "Zero",
|
||||
"9000c1": "Zero W",
|
||||
"a02082": "3B",
|
||||
"a020a0": "CM3",
|
||||
"a22082": "3B",
|
||||
"a32082": "3B",
|
||||
}
|
||||
|
||||
|
||||
def get_octopi_version():
|
||||
with open(_OCTOPI_VERSION_PATH, "r") as f:
|
||||
version_line = f.readline()
|
||||
return version_line.strip()
|
||||
|
||||
|
||||
def get_pi_cpuinfo():
|
||||
fields = dict(revision="Revision",
|
||||
hardware="Hardware",
|
||||
serial="Serial")
|
||||
|
||||
result = dict()
|
||||
with open(_CPUINFO_PATH) as f:
|
||||
for line in f:
|
||||
if not line:
|
||||
continue
|
||||
|
||||
for key, prefix in fields.items():
|
||||
if line.startswith(prefix):
|
||||
result[key] = line[line.index(":") + 1:].strip()
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_pi_model(hardware, revision):
|
||||
if hardware not in ("BCM2835",):
|
||||
return "unknown"
|
||||
|
||||
if revision.startswith("1000"):
|
||||
# strip flag for over-volted (https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F)
|
||||
revision = revision[4:]
|
||||
|
||||
return _RPI_REVISION_MAP.get(revision.lower(), "unknown")
|
||||
|
||||
|
||||
class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._version = None
|
||||
self._cpuinfo = None
|
||||
self._model = None
|
||||
|
||||
#~~ EnvironmentDetectionPlugin
|
||||
|
||||
def get_additional_environment(self):
|
||||
return dict(version=self._get_version(),
|
||||
revision=self._get_cpuinfo().get("revision", "unknown"),
|
||||
model=self._get_model())
|
||||
|
||||
#~~ SimpleApiPlugin
|
||||
|
||||
def on_api_get(self, request):
|
||||
return flask.jsonify(version=self._get_version())
|
||||
|
||||
#~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/octopi_support.js"],
|
||||
css=["css/octopi_support.css"]
|
||||
)
|
||||
|
||||
#~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="about", name="About OctoPi", template="octopi_support_about.jinja2")
|
||||
]
|
||||
|
||||
def get_template_vars(self):
|
||||
return dict(version=self._get_version())
|
||||
|
||||
#~~ Helpers
|
||||
|
||||
def _get_version(self):
|
||||
if self._version is None:
|
||||
try:
|
||||
self._version = get_octopi_version()
|
||||
except:
|
||||
self._logger.exception("Error while reading OctoPi version from file {}".format(_OCTOPI_VERSION_PATH))
|
||||
self._version = "unknown"
|
||||
return self._version
|
||||
|
||||
def _get_model(self):
|
||||
if self._model is None:
|
||||
try:
|
||||
cpuinfo = self._get_cpuinfo()
|
||||
self._model = get_pi_model(cpuinfo.get("hardware", "unknown"),
|
||||
cpuinfo.get("revision", "unknown"))
|
||||
except:
|
||||
self._logger.exception("Error while detecting RPi model")
|
||||
self._model = "unknown"
|
||||
return self._model
|
||||
|
||||
def _get_cpuinfo(self):
|
||||
if self._cpuinfo is None:
|
||||
try:
|
||||
self._cpuinfo = get_pi_cpuinfo()
|
||||
except:
|
||||
self._logger.exception("Error while fetching cpu info")
|
||||
self._cpuinfo = dict()
|
||||
return self._cpuinfo
|
||||
|
||||
__plugin_name__ = "OctoPi Support Plugin"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Provides additional information about your OctoPi instance in the UI."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"provide additional information about your OctoPi instance,"
|
||||
"which will make it more tricky to help you if you need support.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
def __plugin_check__():
|
||||
from octoprint.util.platform import get_os
|
||||
return get_os() == "linux" and os.path.exists(_OCTOPI_VERSION_PATH)
|
||||
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = OctoPiSupportPlugin()
|
||||
@@ -0,0 +1,3 @@
|
||||
#octopi_support_footer {
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintOctoPiSupportClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintOctoPiSupportClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("octopi_support"));
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("octopi_support", OctoPrintOctoPiSupportClient);
|
||||
return OctoPrintOctoPiSupportClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
|
||||
function OctoPiSupportViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.octopi_support.get()
|
||||
.done(function(response) {
|
||||
$("#octopi_support_footer").remove();
|
||||
if (!response.version) return;
|
||||
|
||||
var octoPrintVersion = $(".footer span.version");
|
||||
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
|
||||
+ " <span class='octopi_version'>" + response.version + "</span></span>")
|
||||
$(octoPiVersion).insertAfter(octoPrintVersion);
|
||||
})
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onServerReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: OctoPiSupportViewModel
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
<h3>{{ _('About OctoPi') }}</h3>
|
||||
|
||||
<h4>The ready-to-go Raspberry Pi image with OctoPrint</h4>
|
||||
|
||||
<p>Version <span class="plugin_octopi_support_version">{{ plugin_octopi_support_version }}</span></p>
|
||||
|
||||
<ul>
|
||||
<li>Website: <a href="https://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a> & <a href="https://octopi.octoprint.org" target="_blank" rel="noreferrer noopener">octopi.octoprint.org</a></li>
|
||||
<li>Source Code: <a href="https://github.com/guysoft/OctoPi" target="_blank" rel="noreferrer noopener">github.com/guysoft/OctoPi</a></li>
|
||||
</ul>
|
||||
|
||||
<p>
|
||||
© 2013-{{ now.strftime("%Y") }} <a href="https://github.com/guysoft/OctoPi/graphs/contributors" target="_blank" rel="noreferrer noopener">The OctoPi Authors</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
OctoPi is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
</p>
|
||||
<p>
|
||||
OctoPi is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
</p>
|
||||
<p>
|
||||
For a copy of the GNU General Public License, see
|
||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html" target="_blank" rel="noreferrer noopener">www.gnu.org/licenses/gpl-3.0.en.html</a>.
|
||||
</p>
|
||||
|
||||
@@ -5,14 +5,17 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import admin_permission, VERSION
|
||||
from octoprint.util.pip import LocalPipCaller, UnknownPip
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import get_os
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask.ext.babel import gettext
|
||||
@@ -23,23 +26,40 @@ import sys
|
||||
import requests
|
||||
import re
|
||||
import os
|
||||
import pkg_resources
|
||||
import copy
|
||||
import dateutil.parser
|
||||
import time
|
||||
import threading
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
|
||||
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
|
||||
|
||||
# valid pip install URL schemes according to https://pip.pypa.io/en/stable/reference/pip_install/
|
||||
URL_SCHEMES = ("http", "https", "git",
|
||||
"git+http", "git+https", "git+ssh", "git+git",
|
||||
"hg+http", "hg+https", "hg+static-http", "hg+ssh",
|
||||
"svn", "svn+svn", "svn+http", "svn+https", "svn+ssh",
|
||||
"bzr+http", "bzr+https", "bzr+ssh", "bzr+sftp", "bzr+ftp", "bzr+lp")
|
||||
|
||||
OPERATING_SYSTEMS = dict(windows=["win32"],
|
||||
linux=["linux2"],
|
||||
macos=["darwin"])
|
||||
linux=lambda x: x.startswith("linux"),
|
||||
macos=["darwin"],
|
||||
freebsd=lambda x: x.startswith("freebsd"))
|
||||
|
||||
pip_inapplicable_arguments = dict(uninstall=["--user"])
|
||||
PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"])
|
||||
|
||||
RECONNECT_HOOKS = ["octoprint.comm.protocol.*",]
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._pending_enable = set()
|
||||
self._pending_disable = set()
|
||||
@@ -53,12 +73,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._repository_cache_path = None
|
||||
self._repository_cache_ttl = 0
|
||||
|
||||
self._notices = dict()
|
||||
self._notices_available = False
|
||||
self._notices_cache_path = None
|
||||
self._notices_cache_ttl = 0
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
def initialize(self):
|
||||
self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console")
|
||||
self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json")
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
self._notices_cache_path = os.path.join(self.get_plugin_data_folder(), "notices.json")
|
||||
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
|
||||
|
||||
self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"]))
|
||||
self._pip_caller.on_log_call = self._log_call
|
||||
@@ -73,7 +100,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
def on_startup(self, host, port):
|
||||
def on_after_startup(self):
|
||||
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
|
||||
console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3)
|
||||
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
@@ -83,14 +110,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._console_logger.setLevel(logging.DEBUG)
|
||||
self._console_logger.propagate = False
|
||||
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
# decouple repository fetching from server startup
|
||||
self._fetch_all_data(async=True)
|
||||
|
||||
##~~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(
|
||||
repository="http://plugins.octoprint.org/plugins.json",
|
||||
repository="https://plugins.octoprint.org/plugins.json",
|
||||
repository_ttl=24*60,
|
||||
notices="https://plugins.octoprint.org/notices.json",
|
||||
notices_ttl=6*60,
|
||||
pip_args=None,
|
||||
pip_force_user=False,
|
||||
dependency_links=False,
|
||||
@@ -101,6 +131,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
|
||||
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
|
||||
|
||||
##~~ AssetPlugin
|
||||
@@ -171,6 +202,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
self._fetch_all_data(async=True)
|
||||
|
||||
##~~ SimpleApiPlugin
|
||||
|
||||
def get_api_commands(self):
|
||||
@@ -192,14 +231,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if refresh_repository:
|
||||
self._repository_available = self._refresh_repository()
|
||||
|
||||
refresh_notices = request.values.get("refresh_notices", "false") in valid_boolean_trues
|
||||
if refresh_notices:
|
||||
self._notices_available = self._refresh_notices()
|
||||
|
||||
def view():
|
||||
return jsonify(plugins=self._get_plugins(),
|
||||
repository=dict(
|
||||
available=self._repository_available,
|
||||
plugins=self._repository_plugins
|
||||
),
|
||||
os=self._get_os(),
|
||||
octoprint=self._get_octoprint_version_string(),
|
||||
os=get_os(),
|
||||
octoprint=get_octoprint_version_string(),
|
||||
pip=dict(
|
||||
available=self._pip_caller.available,
|
||||
version=self._pip_caller.version_string,
|
||||
@@ -209,7 +252,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
additional_args=self._settings.get(["pip_args"]),
|
||||
python=sys.executable
|
||||
),
|
||||
safe_mode=safe_mode)
|
||||
safe_mode=safe_mode,
|
||||
online=self._connectivity_checker.online)
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
@@ -217,7 +261,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
hash.update(repr(self._get_plugins()))
|
||||
hash.update(str(self._repository_available))
|
||||
hash.update(repr(self._repository_plugins))
|
||||
hash.update(str(self._notices_available))
|
||||
hash.update(repr(self._notices))
|
||||
hash.update(repr(safe_mode))
|
||||
hash.update(repr(self._connectivity_checker.online))
|
||||
hash.update(repr(_DATA_FORMAT_VERSION))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -225,7 +273,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
unless=lambda: refresh_repository)(view)()
|
||||
unless=lambda: refresh_repository or refresh_notices)(view)()
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not admin_permission.can():
|
||||
@@ -240,7 +288,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
return self.command_install(url=url,
|
||||
force="force" in data and data["force"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data
|
||||
and data["dependency_links"] in valid_boolean_trues,
|
||||
reinstall=plugin_name)
|
||||
|
||||
elif command == "uninstall":
|
||||
@@ -261,37 +310,87 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
|
||||
if url is not None:
|
||||
pip_args = ["install", sarge.shell_quote(url)]
|
||||
if not any(map(lambda scheme: url.startswith(scheme + "://"), self.URL_SCHEMES)):
|
||||
raise ValueError("Invalid URL to pip install from")
|
||||
|
||||
source = url
|
||||
source_type = "url"
|
||||
already_installed_check = lambda line: url in line
|
||||
|
||||
elif path is not None:
|
||||
pip_args = ["install", sarge.shell_quote(path)]
|
||||
path = os.path.abspath(path)
|
||||
path_url = "file://" + path
|
||||
if os.sep != "/":
|
||||
# windows gets special handling
|
||||
path = path.replace(os.sep, "/").lower()
|
||||
path_url = "file:///" + path
|
||||
|
||||
source = path
|
||||
source_type = "path"
|
||||
already_installed_check = lambda line: path_url in line.lower() # lower case in case of windows
|
||||
|
||||
else:
|
||||
raise ValueError("Either URL or path must be provided")
|
||||
|
||||
self._logger.info("Installing plugin from {}".format(source))
|
||||
pip_args = ["install", sarge.shell_quote(source)]
|
||||
|
||||
if dependency_links or self._settings.get_boolean(["dependency_links"]):
|
||||
pip_args.append("--process-dependency-links")
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins()
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing=dict())
|
||||
|
||||
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
|
||||
success_string = "Successfully installed"
|
||||
failure_string = "Could not install"
|
||||
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
|
||||
# pip's output for a package that is already installed looks something like any of these:
|
||||
#
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# https://example.com/foobar.zip in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# file:///tmp/foobar.zip in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# file:///C:/Temp/foobar.zip in <lib>
|
||||
#
|
||||
# If we detect any of these matching what we just tried to install, we'll need to trigger a second
|
||||
# install with reinstall flags.
|
||||
|
||||
if not force and any(map(lambda x: x.strip().startswith(already_installed_string) and already_installed_check(x),
|
||||
stdout)):
|
||||
self._logger.info("Plugin to be installed from {} was already installed, forcing a reinstall".format(source))
|
||||
self._log_message("Looks like the plugin was already installed. Forcing a reinstall.")
|
||||
force = True
|
||||
except:
|
||||
self._logger.exception("Could not install plugin from %s" % url)
|
||||
return make_response("Could not install plugin from URL, see the log for more details", 500)
|
||||
else:
|
||||
if force:
|
||||
# We don't use --upgrade here because that will also happily update all our dependencies - we'd rather
|
||||
# do that in a controlled manner
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
except:
|
||||
self._logger.exception("Could not install plugin from %s" % url)
|
||||
return make_response("Could not install plugin from URL, see the log for more details", 500)
|
||||
self._logger.exception("Could not install plugin from {}".format(source))
|
||||
return make_response("Could not install plugin from source {}, see the log for more details"
|
||||
.format(source), 500)
|
||||
|
||||
try:
|
||||
result_line = filter(lambda x: x.startswith(success_string) or x.startswith(failure_string), stdout)[-1]
|
||||
result_line = filter(lambda x: x.startswith(success_string) or x.startswith(failure_string),
|
||||
stdout)[-1]
|
||||
except IndexError:
|
||||
result = dict(result=False, reason="Could not parse output from pip")
|
||||
self._logger.error("Installing the plugin from {} failed, could not parse output from pip. "
|
||||
"See plugin_pluginmanager_console.log for generated output".format(source))
|
||||
result = dict(result=False,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
reason="Could not parse output from pip, see plugin_pluginmanager_console.log "
|
||||
"for generated output")
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -304,8 +403,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
# Successfully installed OctoPrint-Plugin Dependency-One Dependency-Two
|
||||
# Cleaning up...
|
||||
#
|
||||
# So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split by whitespace
|
||||
# and strip to get all installed packages.
|
||||
# So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split
|
||||
# by whitespace and strip to get all installed packages.
|
||||
#
|
||||
# We then need to iterate over all known plugins and see if either the package name or the package name plus
|
||||
# version number matches one of our installed packages. If it does, that's our installed plugin.
|
||||
@@ -317,58 +416,57 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
result_line = result_line.strip()
|
||||
if not result_line.startswith(success_string):
|
||||
result = dict(result=False, reason="Pip did not report successful installation")
|
||||
self._logger.error("Installing the plugin from {} failed, pip did not report successful installation"
|
||||
.format(source))
|
||||
result = dict(result=False,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
reason="Pip did not report successful installation")
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
installed = map(lambda x: x.strip(), result_line[len(success_string):].split(" "))
|
||||
all_plugins_after = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
|
||||
|
||||
for key, plugin in all_plugins_after.items():
|
||||
if plugin.origin is None or plugin.origin.type != "entry_point":
|
||||
continue
|
||||
|
||||
package_name = plugin.origin.package_name
|
||||
package_version = plugin.origin.package_version
|
||||
versioned_package = "{package_name}-{package_version}".format(**locals())
|
||||
|
||||
if package_name in installed or versioned_package in installed:
|
||||
# exact match, we are done here
|
||||
new_plugin_key = key
|
||||
new_plugin = plugin
|
||||
break
|
||||
|
||||
else:
|
||||
# it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a
|
||||
found = False
|
||||
|
||||
for inst in installed:
|
||||
if inst.startswith(versioned_package):
|
||||
found = True
|
||||
break
|
||||
|
||||
if found:
|
||||
new_plugin_key = key
|
||||
new_plugin = plugin
|
||||
break
|
||||
else:
|
||||
self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to initialize properly during runtime. Please restart OctoPrint.")
|
||||
result = dict(result=True, url=url, needs_restart=True, needs_refresh=True, was_reinstalled=False, plugin="unknown")
|
||||
new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after)
|
||||
if new_plugin is None:
|
||||
self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to "
|
||||
"initialize properly during runtime. Please restart OctoPrint.")
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
was_reinstalled=False,
|
||||
plugin="unknown")
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
self._plugin_manager.reload_plugins()
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) or new_plugin_key in all_plugins_before or reinstall is not None
|
||||
needs_refresh = new_plugin.implementation and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) \
|
||||
or new_plugin.key in all_plugins_before \
|
||||
or reinstall is not None
|
||||
needs_refresh = new_plugin.implementation \
|
||||
and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin_key, "uninstalled")
|
||||
self._plugin_manager.mark_plugin(new_plugin_key,
|
||||
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled")
|
||||
self._plugin_manager.mark_plugin(new_plugin.key,
|
||||
uninstalled=False,
|
||||
installed=not is_reinstall and needs_restart)
|
||||
|
||||
self._plugin_manager.log_all_plugins()
|
||||
|
||||
result = dict(result=True, url=url, needs_restart=needs_restart, needs_refresh=needs_refresh, was_reinstalled=new_plugin_key in all_plugins_before or reinstall is not None, plugin=self._to_external_representation(new_plugin))
|
||||
self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version))
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None,
|
||||
plugin=self._to_external_plugin(new_plugin))
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -423,6 +521,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed")
|
||||
self._plugin_manager.mark_plugin(plugin.key,
|
||||
@@ -431,7 +530,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
if not needs_restart:
|
||||
try:
|
||||
self._plugin_manager.disable_plugin(plugin.key, plugin=plugin)
|
||||
if plugin.enabled:
|
||||
self._plugin_manager.disable_plugin(plugin.key, plugin=plugin)
|
||||
except octoprint.plugin.core.PluginLifecycleException as e:
|
||||
self._logger.exception(u"Problem disabling plugin {name}".format(name=plugin.key))
|
||||
result = dict(result=False, uninstalled=True, disabled=False, unloaded=False, reason=e.reason)
|
||||
@@ -439,7 +539,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return jsonify(result)
|
||||
|
||||
try:
|
||||
self._plugin_manager.unload_plugin(plugin.key)
|
||||
if plugin.loaded:
|
||||
self._plugin_manager.unload_plugin(plugin.key)
|
||||
except octoprint.plugin.core.PluginLifecycleException as e:
|
||||
self._logger.exception(u"Problem unloading plugin {name}".format(name=plugin.key))
|
||||
result = dict(result=False, uninstalled=True, disabled=True, unloaded=False, reason=e.reason)
|
||||
@@ -448,7 +549,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
self._plugin_manager.reload_plugins()
|
||||
|
||||
result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_representation(plugin))
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
self._send_result_notification("uninstall", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -458,11 +563,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
|
||||
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
|
||||
needs_restart_api = (needs_restart or safe_mode_victim) and not pending
|
||||
needs_refresh_api = needs_refresh and not pending
|
||||
needs_reconnect_api = needs_reconnect and not pending
|
||||
|
||||
try:
|
||||
if command == "disable":
|
||||
@@ -473,13 +580,51 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._logger.exception(u"Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason))
|
||||
result = dict(result=False, reason=e.reason)
|
||||
except octoprint.plugin.core.PluginNeedsRestart:
|
||||
result = dict(result=True, needs_restart=True, needs_refresh=True, plugin=self._to_external_representation(plugin))
|
||||
result = dict(result=True,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
else:
|
||||
result = dict(result=True, needs_restart=needs_restart_api, needs_refresh=needs_refresh_api, plugin=self._to_external_representation(plugin))
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart_api,
|
||||
needs_refresh=needs_refresh_api,
|
||||
needs_reconnect=needs_reconnect_api,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
|
||||
self._send_result_notification(command, result)
|
||||
return jsonify(result)
|
||||
|
||||
def _find_installed_plugin(self, packages, plugins=None):
|
||||
if plugins is None:
|
||||
plugins = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
|
||||
|
||||
for key, plugin in plugins.items():
|
||||
if plugin.origin is None or plugin.origin.type != "entry_point":
|
||||
continue
|
||||
|
||||
package_name = plugin.origin.package_name
|
||||
package_version = plugin.origin.package_version
|
||||
versioned_package = "{package_name}-{package_version}".format(**locals())
|
||||
|
||||
if package_name in packages or versioned_package in packages:
|
||||
# exact match, we are done here
|
||||
return plugin
|
||||
|
||||
else:
|
||||
# it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a
|
||||
found = False
|
||||
|
||||
for inst in packages:
|
||||
if inst.startswith(versioned_package):
|
||||
found = True
|
||||
break
|
||||
|
||||
if found:
|
||||
return plugin
|
||||
|
||||
return None
|
||||
|
||||
def _send_result_notification(self, action, result):
|
||||
notification = dict(type="result", action=action)
|
||||
notification.update(result)
|
||||
@@ -496,7 +641,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
if additional_args is not None:
|
||||
|
||||
inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list())
|
||||
inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list())
|
||||
for inapplicable_argument in inapplicable_arguments:
|
||||
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
|
||||
|
||||
@@ -555,6 +700,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable:
|
||||
self._pending_disable.add(plugin.key)
|
||||
|
||||
def _fetch_all_data(self, async=False):
|
||||
def run():
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
|
||||
if async:
|
||||
thread = threading.Thread(target=run)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
else:
|
||||
run()
|
||||
|
||||
def _fetch_repository_from_disk(self):
|
||||
repo_data = None
|
||||
if os.path.isfile(self._repository_cache_path):
|
||||
@@ -572,10 +729,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return self._refresh_repository(repo_data=repo_data)
|
||||
|
||||
def _fetch_repository_from_url(self):
|
||||
import requests
|
||||
if not self._connectivity_checker.online:
|
||||
self._logger.info("Looks like we are offline, can't fetch repository from network")
|
||||
return None
|
||||
|
||||
repository_url = self._settings.get(["repository"])
|
||||
try:
|
||||
r = requests.get(repository_url)
|
||||
r = requests.get(repository_url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info("Loaded plugin repository data from {}".format(repository_url))
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
|
||||
@@ -598,11 +759,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if repo_data is None:
|
||||
return False
|
||||
|
||||
current_os = self._get_os()
|
||||
octoprint_version = self._get_octoprint_version(base=True)
|
||||
current_os = get_os()
|
||||
octoprint_version = get_octoprint_version(base=True)
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = dict(entry)
|
||||
result = copy.deepcopy(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
@@ -614,7 +775,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
|
||||
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"])
|
||||
result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"],
|
||||
octoprint_version=octoprint_version)
|
||||
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
|
||||
@@ -624,88 +786,132 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._repository_plugins = map(map_repository_entry, repo_data)
|
||||
return True
|
||||
|
||||
def _is_octoprint_compatible(self, octoprint_version, compatibility_entries):
|
||||
"""
|
||||
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
|
||||
"""
|
||||
def _fetch_notices_from_disk(self):
|
||||
notice_data = None
|
||||
if os.path.isfile(self._notices_cache_path):
|
||||
import time
|
||||
mtime = os.path.getmtime(self._notices_cache_path)
|
||||
if mtime + self._notices_cache_ttl >= time.time() > mtime:
|
||||
try:
|
||||
import json
|
||||
with open(self._notices_cache_path) as f:
|
||||
notice_data = json.load(f)
|
||||
self._logger.info("Loaded notice data from disk, was still valid")
|
||||
except:
|
||||
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
|
||||
|
||||
return self._refresh_notices(notice_data=notice_data)
|
||||
|
||||
def _fetch_notices_from_url(self):
|
||||
if not self._connectivity_checker.online:
|
||||
self._logger.info("Looks like we are offline, can't fetch notices from network")
|
||||
return None
|
||||
|
||||
notices_url = self._settings.get(["notices"])
|
||||
try:
|
||||
r = requests.get(notices_url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info("Loaded plugin notices data from {}".format(notices_url))
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not fetch notices from {notices_url}: {message}".format(notices_url=notices_url, message=str(e)))
|
||||
return None
|
||||
|
||||
notice_data = r.json()
|
||||
|
||||
try:
|
||||
import json
|
||||
with octoprint.util.atomic_write(self._notices_cache_path, "wb") as f:
|
||||
json.dump(notice_data, f)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e)))
|
||||
return notice_data
|
||||
|
||||
def _refresh_notices(self, notice_data=None):
|
||||
if notice_data is None:
|
||||
notice_data = self._fetch_notices_from_url()
|
||||
if notice_data is None:
|
||||
return False
|
||||
|
||||
notices = dict()
|
||||
for notice in notice_data:
|
||||
if not "plugin" in notice or not "text" in notice or not "date" in notice:
|
||||
continue
|
||||
|
||||
key = notice["plugin"]
|
||||
|
||||
for octo_compat in compatibility_entries:
|
||||
try:
|
||||
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
|
||||
octo_compat = ">={}".format(octo_compat)
|
||||
parsed_date = dateutil.parser.parse(notice["date"])
|
||||
notice["timestamp"] = parsed_date.timetuple()
|
||||
except Exception as e:
|
||||
self._logger.warn("Error while parsing date {!r} for plugin notice "
|
||||
"of plugin {}, ignoring notice: {}".format(notice["date"], key, str(e)))
|
||||
continue
|
||||
|
||||
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
|
||||
if octoprint_version in s:
|
||||
break
|
||||
except:
|
||||
self._logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat))
|
||||
else:
|
||||
return False
|
||||
if not key in notices:
|
||||
notices[key] = []
|
||||
notices[key].append(notice)
|
||||
|
||||
self._notices = notices
|
||||
return True
|
||||
|
||||
def _is_os_compatible(self, current_os, compatibility_entries):
|
||||
@staticmethod
|
||||
def _is_os_compatible(current_os, compatibility_entries):
|
||||
"""
|
||||
Tests if the ``current_os`` matches any of the provided ``compatibility_entries``.
|
||||
Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries``
|
||||
"""
|
||||
return current_os in filter(lambda x: x in self.__class__.OPERATING_SYSTEMS.keys(), compatibility_entries)
|
||||
if len(compatibility_entries) == 0:
|
||||
# shortcut - no compatibility info means we are compatible
|
||||
return True
|
||||
|
||||
def _get_os(self):
|
||||
for identifier, platforms in self.__class__.OPERATING_SYSTEMS.items():
|
||||
if sys.platform in platforms:
|
||||
return identifier
|
||||
else:
|
||||
return "unknown"
|
||||
negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries))
|
||||
positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries)
|
||||
|
||||
def _get_octoprint_version_string(self):
|
||||
return VERSION
|
||||
negative_match = False
|
||||
if negative_entries:
|
||||
# check if we are blacklisted
|
||||
negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries))
|
||||
|
||||
def _get_octoprint_version(self, base=False):
|
||||
octoprint_version_string = self._get_octoprint_version_string()
|
||||
positive_match = True
|
||||
if positive_entries:
|
||||
# check if we are whitelisted
|
||||
positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries))
|
||||
|
||||
if "-" in octoprint_version_string:
|
||||
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
|
||||
return positive_match and not negative_match
|
||||
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
|
||||
@property
|
||||
def _reconnect_hooks(self):
|
||||
reconnect_hooks = self.__class__.RECONNECT_HOOKS
|
||||
|
||||
# A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's
|
||||
# versions should never contains such a prefix, we'll make sure to have stuff behave the same
|
||||
# regardless of setuptools version anyhow.
|
||||
if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v":
|
||||
octoprint_version = octoprint_version[1:]
|
||||
reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks")
|
||||
for name, hook in reconnect_hook_provider_hooks.items():
|
||||
try:
|
||||
result = hook()
|
||||
if isinstance(result, (list, tuple)):
|
||||
reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result))
|
||||
except:
|
||||
self._logger.exception("Error while retrieving additional hooks for which a "
|
||||
"reconnect is required from plugin {name}".format(**locals()))
|
||||
|
||||
if base:
|
||||
if isinstance(octoprint_version, tuple):
|
||||
# old setuptools
|
||||
base_version = []
|
||||
for part in octoprint_version:
|
||||
if part.startswith("*"):
|
||||
break
|
||||
base_version.append(part)
|
||||
base_version.append("*final")
|
||||
octoprint_version = tuple(base_version)
|
||||
else:
|
||||
# new setuptools
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
|
||||
return octoprint_version
|
||||
return reconnect_hooks
|
||||
|
||||
def _get_plugins(self):
|
||||
plugins = self._plugin_manager.plugins
|
||||
|
||||
hidden = self._settings.get(["hidden"])
|
||||
result = []
|
||||
for name, plugin in plugins.items():
|
||||
if name in hidden:
|
||||
for key, plugin in plugins.items():
|
||||
if key in hidden:
|
||||
continue
|
||||
result.append(self._to_external_representation(plugin))
|
||||
result.append(self._to_external_plugin(plugin))
|
||||
|
||||
return result
|
||||
|
||||
def _to_external_representation(self, plugin):
|
||||
def _to_external_plugin(self, plugin):
|
||||
return dict(
|
||||
key=plugin.key,
|
||||
name=plugin.name,
|
||||
description=plugin.description,
|
||||
disabling_discouraged=gettext(plugin.disabling_discouraged) if plugin.disabling_discouraged else False,
|
||||
author=plugin.author,
|
||||
version=plugin.version,
|
||||
url=plugin.url,
|
||||
@@ -713,18 +919,53 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
bundled=plugin.bundled,
|
||||
managable=plugin.managable,
|
||||
enabled=plugin.enabled,
|
||||
blacklisted=plugin.blacklisted,
|
||||
safe_mode_victim=getattr(plugin, "safe_mode_victim", False),
|
||||
safe_mode_enabled=getattr(plugin, "safe_mode_enabled", False),
|
||||
pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False) and plugin.key in self._pending_enable),
|
||||
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable),
|
||||
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
|
||||
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
|
||||
origin=plugin.origin.type
|
||||
origin=plugin.origin.type,
|
||||
notifications = self._get_notifications(plugin)
|
||||
)
|
||||
|
||||
def _get_notifications(self, plugin):
|
||||
key = plugin.key
|
||||
if not plugin.enabled:
|
||||
return
|
||||
|
||||
if key not in self._notices:
|
||||
return
|
||||
|
||||
octoprint_version = get_octoprint_version(base=True)
|
||||
plugin_notifications = self._notices.get(key, [])
|
||||
|
||||
def filter_relevant(notification):
|
||||
return "text" in notification and "date" in notification and \
|
||||
("versions" not in notification or plugin.version in notification["versions"]) and \
|
||||
("octoversions" not in notification or is_octoprint_compatible(*notification["octoversions"],
|
||||
octoprint_version=octoprint_version))
|
||||
|
||||
def map_notification(notification):
|
||||
return self._to_external_notification(key, notification)
|
||||
|
||||
return filter(lambda x: x is not None,
|
||||
map(map_notification,
|
||||
filter(filter_relevant,
|
||||
plugin_notifications)))
|
||||
|
||||
def _to_external_notification(self, key, notification):
|
||||
return dict(key=key,
|
||||
date=time.mktime(notification["timestamp"]),
|
||||
text=notification["text"],
|
||||
link=notification.get("link"),
|
||||
versions=notification.get("versions", []),
|
||||
important=notification.get("important", False))
|
||||
|
||||
__plugin_name__ = "Plugin Manager"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
|
||||
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
table th.settings_plugin_plugin_manager_plugins_name,table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_plugin_manager_plugins_actions,table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table th.settings_plugin_plugin_manager_plugins_actions a,table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table th.settings_plugin_plugin_manager_plugins_actions a.disabled,table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px;padding-right:10px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url("../img/repo_unavailable.png");text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px;padding-right:10px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:bold}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px;padding-right:12px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
@@ -10,7 +10,20 @@
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts);
|
||||
var refresh_repo, refresh_notices;
|
||||
if (_.isPlainObject(refresh)) {
|
||||
refresh_repo = refresh.repo || false;
|
||||
refresh_notices = refresh.notices || false;
|
||||
} else {
|
||||
refresh_repo = refresh;
|
||||
refresh_notices = false;
|
||||
}
|
||||
|
||||
var query = [];
|
||||
if (refresh_repo) query.push("refresh_repository=true");
|
||||
if (refresh_notices) query.push("refresh_notices=true");
|
||||
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
|
||||
@@ -79,6 +92,8 @@ $(function() {
|
||||
|
||||
self.config_repositoryUrl = ko.observable();
|
||||
self.config_repositoryTtl = ko.observable();
|
||||
self.config_noticesUrl = ko.observable();
|
||||
self.config_noticesTtl = ko.observable();
|
||||
self.config_pipAdditionalArgs = ko.observable();
|
||||
self.config_pipForceUser = ko.observable();
|
||||
|
||||
@@ -159,6 +174,7 @@ $(function() {
|
||||
self.pipPython = ko.observable();
|
||||
|
||||
self.safeMode = ko.observable();
|
||||
self.online = ko.observable();
|
||||
|
||||
self.pipUseUserString = ko.pureComputed(function() {
|
||||
return self.pipUseUser() ? "yes" : "no";
|
||||
@@ -185,6 +201,20 @@ $(function() {
|
||||
});
|
||||
|
||||
self.notifications = [];
|
||||
self.noticeNotifications = [];
|
||||
self.hiddenNoticeNotifications = {};
|
||||
self.noticeCount = ko.observable(0);
|
||||
|
||||
self.noticeCountText = ko.pureComputed(function() {
|
||||
var count = self.noticeCount();
|
||||
if (count == 0) {
|
||||
return gettext("There are no plugin notices. Great!");
|
||||
} else if (count == 1) {
|
||||
return gettext("There is a plugin notice for one of your installed plugins.");
|
||||
} else {
|
||||
return _.sprintf(gettext("There are %(count)d plugin notices for one or more of your installed plugins."), {count: count});
|
||||
}
|
||||
});
|
||||
|
||||
self.enableManagement = ko.pureComputed(function() {
|
||||
return !self.printerState.isPrinting();
|
||||
@@ -192,7 +222,9 @@ $(function() {
|
||||
|
||||
self.enableToggle = function(data) {
|
||||
var command = self._getToggleCommand(data);
|
||||
return self.enableManagement() && (command == "disable" || !data.safe_mode_victim || data.safe_mode_enabled) && data.key != 'pluginmanager';
|
||||
var not_safemode_victim = !data.safe_mode_victim || data.safe_mode_enabled;
|
||||
var not_blacklisted = !data.blacklisted;
|
||||
return self.enableManagement() && (command == "disable" || (not_safemode_victim && not_blacklisted)) && data.key != 'pluginmanager';
|
||||
};
|
||||
|
||||
self.enableUninstall = function(data) {
|
||||
@@ -205,27 +237,61 @@ $(function() {
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data);
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.invalidUrl = ko.pureComputed(function() {
|
||||
// supported pip install URL schemes, according to https://pip.pypa.io/en/stable/reference/pip_install/
|
||||
var allowedUrlSchemes = ["http", "https",
|
||||
"git", "git+http", "git+https", "git+ssh", "git+git",
|
||||
"hg+http", "hg+https", "hg+static-http", "hg+ssh",
|
||||
"svn", "svn+svn", "svn+http", "svn+https", "svn+ssh",
|
||||
"bzr+http", "bzr+https", "bzr+ssh", "bzr+sftp", "brz+ftp", "bzr+lp"];
|
||||
|
||||
var url = self.installUrl();
|
||||
return url !== undefined && url.trim() != "" && !(_.startsWith(url.toLocaleLowerCase(), "http://") || _.startsWith(url.toLocaleLowerCase(), "https://"));
|
||||
var lowerUrl = url !== undefined ? url.toLocaleLowerCase() : undefined;
|
||||
|
||||
var lowerUrlStartsWithScheme = function(scheme) {
|
||||
return _.startsWith(lowerUrl, scheme + "://");
|
||||
};
|
||||
|
||||
return url !== undefined && url.trim() !== ""
|
||||
&& !(_.any(allowedUrlSchemes, lowerUrlStartsWithScheme));
|
||||
});
|
||||
|
||||
self.enableUrlInstall = ko.pureComputed(function() {
|
||||
var url = self.installUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
return self.enableManagement()
|
||||
&& self.pipAvailable()
|
||||
&& !self.safeMode()
|
||||
&& self.online()
|
||||
&& url !== undefined
|
||||
&& url.trim() !== ""
|
||||
&& !self.invalidUrl();
|
||||
});
|
||||
|
||||
self.invalidArchive = ko.pureComputed(function() {
|
||||
var allowedArchiveExtensions = [".zip", ".tar.gz", ".tgz", ".tar"];
|
||||
|
||||
var name = self.uploadFilename();
|
||||
return name !== undefined && !(_.endsWith(name.toLocaleLowerCase(), ".zip") || _.endsWith(name.toLocaleLowerCase(), ".tar.gz") || _.endsWith(name.toLocaleLowerCase(), ".tgz") || _.endsWith(name.toLocaleLowerCase(), ".tar"));
|
||||
var lowerName = name !== undefined ? name.toLocaleLowerCase() : undefined;
|
||||
|
||||
var lowerNameHasExtension = function(extension) {
|
||||
return _.endsWith(lowerName, extension);
|
||||
};
|
||||
|
||||
return name !== undefined
|
||||
&& !(_.any(allowedArchiveExtensions, lowerNameHasExtension));
|
||||
});
|
||||
|
||||
self.enableArchiveInstall = ko.pureComputed(function() {
|
||||
var name = self.uploadFilename();
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
return self.enableManagement()
|
||||
&& self.pipAvailable()
|
||||
&& !self.safeMode()
|
||||
&& name !== undefined
|
||||
&& name.trim() !== ""
|
||||
&& !self.invalidArchive();
|
||||
});
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
@@ -250,7 +316,13 @@ $(function() {
|
||||
});
|
||||
},
|
||||
done: function(e, data) {
|
||||
self._markDone();
|
||||
var response = data.result;
|
||||
if (response.result) {
|
||||
self._markDone();
|
||||
} else {
|
||||
self._markDone(response.reason);
|
||||
}
|
||||
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadFilename(undefined);
|
||||
},
|
||||
@@ -261,7 +333,7 @@ $(function() {
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
self._markDone();
|
||||
self._markDone("Could not install plugin, unknown error.");
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadFilename(undefined);
|
||||
}
|
||||
@@ -280,19 +352,37 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self._fromPluginsResponse(data.plugins);
|
||||
self._fromRepositoryResponse(data.repository);
|
||||
self._fromPipResponse(data.pip);
|
||||
self.fromResponse = function(data, options) {
|
||||
self._fromPluginsResponse(data.plugins, options);
|
||||
self._fromRepositoryResponse(data.repository, options);
|
||||
self._fromPipResponse(data.pip, options);
|
||||
|
||||
self.safeMode(data.safe_mode || false);
|
||||
self.online(data.online !== undefined ? data.online : true);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function(data) {
|
||||
self._fromPluginsResponse = function(data, options) {
|
||||
var evalNotices = options.eval_notices || false;
|
||||
var ignoreNoticeHidden = options.ignore_notice_hidden || false;
|
||||
var ignoreNoticeIgnored = options.ignore_notice_ignored || false;
|
||||
|
||||
if (evalNotices) self._removeAllNoticeNotifications();
|
||||
|
||||
var installedPlugins = [];
|
||||
var noticeCount = 0;
|
||||
_.each(data, function(plugin) {
|
||||
installedPlugins.push(plugin.key);
|
||||
|
||||
if (evalNotices && plugin.notifications && plugin.notifications.length) {
|
||||
_.each(plugin.notifications, function(notification) {
|
||||
noticeCount++;
|
||||
if (!ignoreNoticeIgnored && self._isNoticeNotificationIgnored(plugin.key, notification.date)) return;
|
||||
if (!ignoreNoticeHidden && self._isNoticeNotificationHidden(plugin.key, notification.date)) return;
|
||||
self._showPluginNotification(plugin, notification);
|
||||
});
|
||||
}
|
||||
});
|
||||
if (evalNotices) self.noticeCount(noticeCount);
|
||||
self.installedPlugins(installedPlugins);
|
||||
self.plugins.updateItems(data);
|
||||
};
|
||||
@@ -324,13 +414,28 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.requestData = function(includeRepo) {
|
||||
self.requestData = function(options) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.plugins.pluginmanager.get(includeRepo)
|
||||
.done(self.fromResponse);
|
||||
if (!_.isPlainObject(options)) {
|
||||
options = {
|
||||
refresh_repo: options,
|
||||
refresh_notices: false,
|
||||
eval_notices: false
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
options.refresh_repo = options.refresh_repo || false;
|
||||
options.refresh_notices = options.refresh_notices || false;
|
||||
options.eval_notices = options.eval_notices || false;
|
||||
|
||||
OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices})
|
||||
.done(function(data) {
|
||||
self.fromResponse(data, options);
|
||||
});
|
||||
};
|
||||
|
||||
self.togglePlugin = function(data) {
|
||||
@@ -344,7 +449,9 @@ $(function() {
|
||||
|
||||
if (data.key == "pluginmanager") return;
|
||||
|
||||
var onSuccess = self.requestData,
|
||||
var onSuccess = function() {
|
||||
self.requestData();
|
||||
},
|
||||
onError = function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
@@ -360,9 +467,26 @@ $(function() {
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
} else {
|
||||
OctoPrint.plugins.pluginmanager.disable(data.key)
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.pluginmanager.disable(data.key)
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
};
|
||||
|
||||
if (data.disabling_discouraged) {
|
||||
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: data.name})
|
||||
+ "</p><p>" + data.disabling_discouraged;
|
||||
showConfirmationDialog({
|
||||
title: gettext("This is not recommended"),
|
||||
message: message,
|
||||
question: gettext("Do you still want to disable it?"),
|
||||
cancel: gettext("Keep enabled"),
|
||||
proceed: gettext("Disable anyway"),
|
||||
onproceed: perform
|
||||
})
|
||||
} else {
|
||||
perform();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -418,32 +542,33 @@ $(function() {
|
||||
}
|
||||
self._markWorking(workTitle, workText);
|
||||
|
||||
var onSuccess = function() {
|
||||
var onSuccess = function(response) {
|
||||
if (response.result) {
|
||||
self._markDone();
|
||||
} else {
|
||||
self._markDone(response.reason)
|
||||
}
|
||||
self.requestData();
|
||||
self.installUrl("");
|
||||
},
|
||||
onError = function() {
|
||||
self._markDone("Could not install plugin, unknown error, please consult octoprint.log for details");
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Please consult octoprint.log for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
},
|
||||
onAlways = function() {
|
||||
self._markDone();
|
||||
};
|
||||
|
||||
if (reinstall) {
|
||||
OctoPrint.plugins.pluginmanager.reinstall(reinstall, url, followDependencyLinks)
|
||||
.done(onSuccess)
|
||||
.fail(onError)
|
||||
.always(onAlways);
|
||||
.fail(onError);
|
||||
} else {
|
||||
OctoPrint.plugins.pluginmanager.install(url, followDependencyLinks)
|
||||
.done(onSuccess)
|
||||
.fail(onError)
|
||||
.always(onAlways);
|
||||
.fail(onError);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -462,7 +587,9 @@ $(function() {
|
||||
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
|
||||
|
||||
OctoPrint.plugins.pluginmanager.uninstall(data.key)
|
||||
.done(self.requestData)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
@@ -480,8 +607,23 @@ $(function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
self.requestData({refresh_repo: true});
|
||||
};
|
||||
|
||||
self.requestData(true);
|
||||
self.refreshNotices = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.requestData({refresh_notices: true, eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true});
|
||||
};
|
||||
|
||||
self.reshowNotices = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.requestData({eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true});
|
||||
};
|
||||
|
||||
self.showPluginSettings = function() {
|
||||
@@ -502,6 +644,18 @@ $(function() {
|
||||
repositoryTtl = null;
|
||||
}
|
||||
|
||||
var notices = self.config_noticesUrl();
|
||||
if (notices != undefined && notices.trim() == "") {
|
||||
notices = null;
|
||||
}
|
||||
|
||||
var noticesTtl;
|
||||
try {
|
||||
noticesTtl = parseInt(self.config_noticesTtl());
|
||||
} catch (ex) {
|
||||
noticesTtl = null;
|
||||
}
|
||||
|
||||
var pipArgs = self.config_pipAdditionalArgs();
|
||||
if (pipArgs != undefined && pipArgs.trim() == "") {
|
||||
pipArgs = null;
|
||||
@@ -512,6 +666,8 @@ $(function() {
|
||||
pluginmanager: {
|
||||
repository: repository,
|
||||
repository_ttl: repositoryTtl,
|
||||
notices: notices,
|
||||
notices_ttl: noticesTtl,
|
||||
pip_args: pipArgs,
|
||||
pip_force_user: self.config_pipForceUser()
|
||||
}
|
||||
@@ -520,13 +676,15 @@ $(function() {
|
||||
self.settingsViewModel.saveData(data, function() {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.refreshRepository();
|
||||
self.requestData({refresh_repo: true, refresh_notices: true, eval_notices: true});
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
|
||||
self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
|
||||
self.config_noticesUrl(self.settingsViewModel.settings.plugins.pluginmanager.notices());
|
||||
self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl());
|
||||
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
|
||||
self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());
|
||||
};
|
||||
@@ -540,10 +698,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.installButtonText = function(data) {
|
||||
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : gettext("Incompatible");
|
||||
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible"));
|
||||
};
|
||||
|
||||
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) {
|
||||
self._displayNotification = function(response, action, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) {
|
||||
var notification;
|
||||
|
||||
var beforeClose = function(notification) {
|
||||
@@ -551,7 +709,17 @@ $(function() {
|
||||
};
|
||||
|
||||
if (response.result) {
|
||||
if (response.needs_restart) {
|
||||
if (action == "install" && response.plugin && response.plugin.blacklisted) {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
text: textSuccess,
|
||||
type: "warning",
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else if (response.needs_restart) {
|
||||
var options = {
|
||||
title: titleSuccess,
|
||||
text: textRestart,
|
||||
@@ -565,17 +733,21 @@ $(function() {
|
||||
hide: false
|
||||
};
|
||||
|
||||
var restartClicked = false;
|
||||
if (self.restartCommandSpec) {
|
||||
options.confirm = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Restart now"),
|
||||
click: function () {
|
||||
click: function (notice) {
|
||||
if (restartClicked) return;
|
||||
restartClicked = true;
|
||||
showConfirmationDialog({
|
||||
message: gettext("This will restart your OctoPrint server."),
|
||||
message: gettext("<strong>This will restart your OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
|
||||
onproceed: function() {
|
||||
OctoPrint.system.executeCommand("core", "restart")
|
||||
.done(function() {
|
||||
notice.remove();
|
||||
new PNotify({
|
||||
title: gettext("Restart in progress"),
|
||||
text: gettext("The server is now being restarted in the background")
|
||||
@@ -587,6 +759,9 @@ $(function() {
|
||||
text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")
|
||||
})
|
||||
});
|
||||
},
|
||||
onclose: function() {
|
||||
restartClicked = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -596,6 +771,7 @@ $(function() {
|
||||
|
||||
notification = PNotify.singleButtonNotify(options);
|
||||
} else if (response.needs_refresh) {
|
||||
var refreshClicked = false;
|
||||
notification = PNotify.singleButtonNotify({
|
||||
title: titleSuccess,
|
||||
text: textReload,
|
||||
@@ -604,6 +780,8 @@ $(function() {
|
||||
buttons: [{
|
||||
text: gettext("Reload now"),
|
||||
click: function () {
|
||||
if (refreshClicked) return;
|
||||
refreshClicked = true;
|
||||
location.reload(true);
|
||||
}
|
||||
}]
|
||||
@@ -617,6 +795,15 @@ $(function() {
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else if (response.needs_reconnect) {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
text: textReconnect,
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
@@ -654,9 +841,14 @@ $(function() {
|
||||
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
};
|
||||
|
||||
self._markDone = function() {
|
||||
self._markDone = function(error) {
|
||||
self.working(false);
|
||||
self.loglines.push({line: gettext("Done!"), stream: "message"});
|
||||
if (error) {
|
||||
self.loglines.push({line: gettext("Error!"), stream: "error"});
|
||||
self.loglines.push({line: error, stream: "error"})
|
||||
} else {
|
||||
self.loglines.push({line: gettext("Done!"), stream: "message"});
|
||||
}
|
||||
self._scrollWorkingOutputToEnd();
|
||||
};
|
||||
|
||||
@@ -670,7 +862,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "icon-circle-blank" : "icon-circle";
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -679,7 +871,9 @@ $(function() {
|
||||
self.toggleButtonTitle = function(data) {
|
||||
var command = self._getToggleCommand(data);
|
||||
if (command == "enable") {
|
||||
if (data.safe_mode_victim && !data.safe_mode_enabled) {
|
||||
if (data.blacklisted) {
|
||||
return gettext("Blacklisted");
|
||||
} else if (data.safe_mode_victim && !data.safe_mode_enabled) {
|
||||
return gettext("Disabled due to active safe mode");
|
||||
} else {
|
||||
return gettext("Enable Plugin");
|
||||
@@ -689,13 +883,184 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.showPluginNotifications = function(plugin) {
|
||||
if (!plugin.notifications || plugin.notifications.length == 0) return;
|
||||
|
||||
self._removeAllNoticeNotificationsForPlugin(plugin.key);
|
||||
_.each(plugin.notifications, function(notification) {
|
||||
self._showPluginNotification(plugin, notification);
|
||||
});
|
||||
};
|
||||
|
||||
self.showPluginNotificationsLinkText = function(plugins) {
|
||||
if (!plugins.notifications || plugins.notifications.length == 0) return;
|
||||
|
||||
var count = plugins.notifications.length;
|
||||
var importantCount = _.filter(plugins.notifications, function(notification) { return notification.important }).length;
|
||||
if (count > 1) {
|
||||
if (importantCount) {
|
||||
return _.sprintf(gettext("There are %(count)d notices (%(important)d marked as important) available regarding this plugin - click to show!"), {count: count, important: importantCount});
|
||||
} else {
|
||||
return _.sprintf(gettext("There are %(count)d notices available regarding this plugin - click to show!"), {count: count});
|
||||
}
|
||||
} else {
|
||||
if (importantCount) {
|
||||
return gettext("There is an important notice available regarding this plugin - click to show!");
|
||||
} else {
|
||||
return gettext("There is a notice available regarding this plugin - click to show!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self._showPluginNotification = function(plugin, notification) {
|
||||
var name = plugin.name;
|
||||
var version = plugin.version;
|
||||
|
||||
var important = notification.important;
|
||||
var link = notification.link;
|
||||
|
||||
var title;
|
||||
if (important) {
|
||||
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: name});
|
||||
} else {
|
||||
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: name});
|
||||
}
|
||||
|
||||
var text = "";
|
||||
|
||||
if (notification.versions && notification.versions.length > 0) {
|
||||
var versions = _.map(notification.versions, function(v) { return (v == version) ? "<strong>" + v + "</strong>" : v; }).join(", ");
|
||||
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + "</small>";
|
||||
} else {
|
||||
text += "<small>" + gettext("Affected versions: all") + "</small>";
|
||||
}
|
||||
|
||||
text += "<p>" + notification.text + "</p>";
|
||||
if (link) {
|
||||
text += "<p><a href='" + link + "' target='_blank'>" + gettext("Read more...") + "</a></p>";
|
||||
}
|
||||
|
||||
var beforeClose = function(notification) {
|
||||
if (!self.noticeNotifications[plugin.key]) return;
|
||||
self.noticeNotifications[plugin.key] = _.without(self.noticeNotifications[plugin.key], notification);
|
||||
};
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
text: text,
|
||||
type: (important) ? "error" : "notice",
|
||||
before_close: beforeClose,
|
||||
hide: false,
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Later"),
|
||||
click: function(notice) {
|
||||
self._hideNoticeNotification(plugin.key, notification.date);
|
||||
notice.remove();
|
||||
notice.get().trigger("pnotify.cancel", notice);
|
||||
}
|
||||
}, {
|
||||
text: gettext("Mark read"),
|
||||
click: function(notice) {
|
||||
self._ignoreNoticeNotification(plugin.key, notification.date);
|
||||
notice.remove();
|
||||
notice.get().trigger("pnotify.cancel", notice);
|
||||
}
|
||||
}]
|
||||
},
|
||||
buttons: {
|
||||
sticker: false,
|
||||
closer: false
|
||||
}
|
||||
};
|
||||
|
||||
if (!self.noticeNotifications[plugin.key]) {
|
||||
self.noticeNotifications[plugin.key] = [];
|
||||
}
|
||||
self.noticeNotifications[plugin.key].push(new PNotify(options));
|
||||
};
|
||||
|
||||
self._removeAllNoticeNotifications = function() {
|
||||
_.each(_.keys(self.noticeNotifications), function(key) {
|
||||
self._removeAllNoticeNotificationsForPlugin(key);
|
||||
});
|
||||
};
|
||||
|
||||
self._removeAllNoticeNotificationsForPlugin = function(key) {
|
||||
if (!self.noticeNotifications[key] || !self.noticeNotifications[key].length) return;
|
||||
_.each(self.noticeNotifications[key], function(notification) {
|
||||
notification.remove();
|
||||
});
|
||||
};
|
||||
|
||||
self._hideNoticeNotification = function(key, date) {
|
||||
if (!self.hiddenNoticeNotifications[key]) {
|
||||
self.hiddenNoticeNotifications[key] = [];
|
||||
}
|
||||
if (!_.contains(self.hiddenNoticeNotifications[key], date)) {
|
||||
self.hiddenNoticeNotifications[key].push(date);
|
||||
}
|
||||
};
|
||||
|
||||
self._isNoticeNotificationHidden = function(key, date) {
|
||||
if (!self.hiddenNoticeNotifications[key]) return false;
|
||||
return _.any(_.map(self.hiddenNoticeNotifications[key], function(d) { return date == d; }));
|
||||
};
|
||||
|
||||
var noticeLocalStorageKey = "plugin.pluginmanager.seen_notices";
|
||||
self._ignoreNoticeNotification = function(key, date) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
if (!self.loginState.isAdmin())
|
||||
return false;
|
||||
|
||||
var currentString = localStorage[noticeLocalStorageKey];
|
||||
var current;
|
||||
if (currentString === undefined) {
|
||||
current = {};
|
||||
} else {
|
||||
current = JSON.parse(currentString);
|
||||
}
|
||||
if (!current[self.loginState.username()]) {
|
||||
current[self.loginState.username()] = {};
|
||||
}
|
||||
if (!current[self.loginState.username()][key]) {
|
||||
current[self.loginState.username()][key] = [];
|
||||
}
|
||||
|
||||
if (!_.contains(current[self.loginState.username()][key], date)) {
|
||||
current[self.loginState.username()][key].push(date);
|
||||
localStorage[noticeLocalStorageKey] = JSON.stringify(current);
|
||||
}
|
||||
};
|
||||
|
||||
self._isNoticeNotificationIgnored = function(key, date) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
|
||||
if (localStorage[noticeLocalStorageKey] == undefined)
|
||||
return false;
|
||||
|
||||
var knownData = JSON.parse(localStorage[noticeLocalStorageKey]);
|
||||
|
||||
if (!self.loginState.isAdmin())
|
||||
return true;
|
||||
|
||||
var userData = knownData[self.loginState.username()];
|
||||
if (userData === undefined)
|
||||
return false;
|
||||
|
||||
return userData[key] && _.contains(userData[key], date);
|
||||
};
|
||||
|
||||
self.onBeforeBinding = function() {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function(user) {
|
||||
if (user.admin) {
|
||||
self.requestData();
|
||||
self.requestData({eval_notices: true});
|
||||
} else {
|
||||
self.onUserLoggedOut();
|
||||
}
|
||||
@@ -705,6 +1070,10 @@ $(function() {
|
||||
self._closeAllNotifications();
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
self.requestData({eval_notices: true});
|
||||
};
|
||||
|
||||
self._closeAllNotifications = function() {
|
||||
if (self.notifications) {
|
||||
_.each(self.notifications, function(notification) {
|
||||
@@ -722,15 +1091,6 @@ $(function() {
|
||||
self.workingDialog = $("#settings_plugin_pluginmanager_workingdialog");
|
||||
self.workingOutput = $("#settings_plugin_pluginmanager_workingdialog_output");
|
||||
self.repositoryDialog = $("#settings_plugin_pluginmanager_repositorydialog");
|
||||
|
||||
$("#settings_plugin_pluginmanager_repositorydialog_list").slimScroll({
|
||||
height: "306px",
|
||||
size: "5px",
|
||||
distance: "0",
|
||||
railVisible: true,
|
||||
alwaysVisible: true,
|
||||
scrollBy: "102px"
|
||||
});
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
@@ -754,7 +1114,7 @@ $(function() {
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
} else if (messageType == "result") {
|
||||
var titleSuccess, textSuccess, textRestart, textReload, titleError, textError;
|
||||
var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError;
|
||||
var action = data.action;
|
||||
|
||||
var name = "Unknown";
|
||||
@@ -774,35 +1134,69 @@ $(function() {
|
||||
textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly");
|
||||
textRestart = textSuccess;
|
||||
textReload = textSuccess;
|
||||
textReconnect = textSuccess;
|
||||
} else if (data.plugin && data.plugin.blacklisted) {
|
||||
if (data.was_reinstalled) {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
|
||||
textSuccess = gettext("The plugin was reinstalled successfully, however it is blacklisted and therefore won't be loaded.");
|
||||
} else {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
|
||||
textSuccess = gettext("The plugin was installed successfully, however it is blacklisted and therefore won't be loaded.");
|
||||
}
|
||||
textRestart = textSuccess;
|
||||
textReload = textSuccess;
|
||||
textReconnect = textSuccess;
|
||||
} else if (data.was_reinstalled) {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
|
||||
textSuccess = gettext("The plugin was reinstalled successfully");
|
||||
textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
} else {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
|
||||
textSuccess = gettext("The plugin was installed successfully");
|
||||
textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
}
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
var url = "unknown";
|
||||
if (data.hasOwnProperty("url")) {
|
||||
url = data.url;
|
||||
var source = "unknown";
|
||||
if (data.hasOwnProperty("source")) {
|
||||
source = data.source;
|
||||
}
|
||||
var sourceType = "unknown";
|
||||
if (data.hasOwnProperty("source_type")) {
|
||||
sourceType = data.source_type;
|
||||
}
|
||||
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
if (data.was_reinstalled) {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from URL \"%(url)s\" failed: %(reason)s"), {reason: data.reason, url: url});
|
||||
if (sourceType == "path") {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from file failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
|
||||
}
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from URL \"%(url)s\" failed: %(reason)s"), {reason: data.reason, url: url});
|
||||
if (sourceType == "path") {
|
||||
textError = _.sprintf(gettext("Installing the plugin from file failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (data.was_reinstalled) {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from URL \"%(url)s\" failed, please see the log for details."), {url: url});
|
||||
if (sourceType == "path") {
|
||||
textError = gettext("Reinstalling the plugin from file failed, please see the log for details.");
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
|
||||
}
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from URL \"%(url)s\" failed, please see the log for details."), {url: url});
|
||||
if (sourceType == "path") {
|
||||
textError = gettext("Installing the plugin from file failed, please see the log for details.");
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,6 +1209,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was uninstalled successfully");
|
||||
textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -832,6 +1227,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was enabled successfully.");
|
||||
textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -849,6 +1245,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was disabled successfully.");
|
||||
textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -861,24 +1258,23 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError);
|
||||
self._displayNotification(data, action, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError);
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
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)) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([
|
||||
PluginManagerViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel"],
|
||||
"#settings_plugin_pluginmanager"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PluginManagerViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel"],
|
||||
elements: ["#settings_plugin_pluginmanager"]
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,10 @@ table {
|
||||
|
||||
#settings_plugin_pluginmanager_repositorydialog {
|
||||
.slimScrollDiv {
|
||||
@scrollBar: 10px;
|
||||
|
||||
margin-bottom: 20px;
|
||||
padding-right: @scrollBar + 2px;
|
||||
}
|
||||
|
||||
h4 {
|
||||
@@ -89,6 +92,11 @@ table {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.error {
|
||||
font-weight: bold;
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.stdout {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
@@ -20,12 +20,19 @@
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_offline() %}
|
||||
<div class="alert" data-bind="visible: !online()">{% trans %}
|
||||
It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible
|
||||
to install new plugins from the plugin repository or archive URLs.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
@@ -40,17 +47,18 @@
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="icon-medkit" data-bind="visible: safe_mode_victim"></i></div>
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted') }}" data-bind="visible: blacklisted"></i></div>
|
||||
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_actions">
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="icon-trash" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -72,8 +80,8 @@
|
||||
<div class="muted" data-bind="visible: pipAvailable()">
|
||||
<div>
|
||||
<small>
|
||||
<a href="#" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow icon-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="fa toggle-arrow fa-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
@@ -86,12 +94,28 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="muted">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
<div class="hide">
|
||||
<small>
|
||||
<!-- ko if: noticeCount() > 0 --><a href="javascript:void(0)" data-bind="click: function() { reshowNotices(); }">{{ _('Reshow current notices') }}</a> ·<!-- /ko -->
|
||||
<a href="javascript:void(0)" data-bind="click: function() { refreshNotices(); }">{{ _('Refresh notices from repository') }}</a>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="terminal pre-scrollable" 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'}"></span><br></pre>
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_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.working()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
@@ -107,20 +131,21 @@
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
{{ pluginmanager_offline() }}
|
||||
<h4 style="position: relative">
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='https://plugins.octoprint.org') }}
|
||||
<div class="dropdown pull-right">
|
||||
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
|
||||
<span class="icon-wrench"></span>
|
||||
<span class="fa fa-wrench"></span>
|
||||
</a>
|
||||
<ul class="dropdown-menu pull-right">
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="fa fa-check" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="fa fa-check" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="fa fa-check" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="fa fa-check" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="icon-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="fa fa-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</h4>
|
||||
@@ -130,22 +155,23 @@
|
||||
</form>
|
||||
|
||||
<div data-bind="visible: repositoryAvailable()">
|
||||
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="slimScrolledForeach: repositoryplugins.paginatedItems">
|
||||
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="slimScrolledForeach: {data: repositoryplugins.paginatedItems, slimscroll: {height: '306px', size: '10px', distance: 0, railVisible: true, alwaysVisible: true, scrollBy: '102px'} }">
|
||||
<div class="entry">
|
||||
<div class="row-fluid">
|
||||
<div class="span9">
|
||||
<div><span data-bind="text: title"></span></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div>
|
||||
<small data-bind="visible: page"><i class="icon-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
|
||||
<small data-bind="visible: homepage"><i class="icon-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small data-bind="visible: page"><i class="fa fa-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
|
||||
<small data-bind="visible: homepage"><i class="fa fa-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span3">
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="icon-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="fa fa-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<div data-bind="visible: $data.disabled !== undefined" style="text-align: center"><small><a data-bind="attr: {href: page}" target="_blank">{{ _('"Why?"') }}</a></small></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -171,7 +197,7 @@
|
||||
</div>
|
||||
<button class="btn btn-primary span3" data-bind="enable: enableUrlInstall, css: {disabled: !enableUrlInstall()}, click: function() { if (enableUrlInstall()) { $root.installPlugin(); } }">{{ _('Install') }}</button>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: invalidUrl">{{ _('This does not look like a valid "http://" or "https://" URL.') }}</span>
|
||||
<span class="help-block" data-bind="visible: invalidUrl">{{ _('This does not look like a valid URL. Expected http, https or any of the <a href="%(url)s" target="_blank">supported VCS URLs</a>.', url='https://pip.pypa.io/en/stable/reference/pip_install/#vcs-support') }}</span>
|
||||
</form>
|
||||
|
||||
<h4>{{ _('... from an uploaded archive') }}</h4>
|
||||
@@ -191,7 +217,7 @@
|
||||
</form>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
@@ -237,6 +263,24 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('Notices configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Notices URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Notices cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_noticesTtl">
|
||||
<span class="add-on">min</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('pip configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
|
||||
|
||||
@@ -16,8 +16,12 @@ import logging
|
||||
import logging.handlers
|
||||
import hashlib
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from concurrent import futures
|
||||
|
||||
from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
from flask.ext.babel import gettext
|
||||
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
|
||||
@@ -33,19 +37,29 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.WizardPlugin):
|
||||
octoprint.plugin.WizardPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
|
||||
DATA_FORMAT_VERSION = "v2"
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._update_in_progress = False
|
||||
self._configured_checks_mutex = threading.Lock()
|
||||
self._configured_checks = None
|
||||
self._refresh_configured_checks = False
|
||||
|
||||
self._get_versions_mutex = threading.Lock()
|
||||
self._get_versions_mutex = threading.RLock()
|
||||
self._get_versions_data = None
|
||||
self._get_versions_data_ready = threading.Event()
|
||||
|
||||
self._version_cache = dict()
|
||||
self._version_cache_ttl = 0
|
||||
self._version_cache_path = None
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = None
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
@@ -73,8 +87,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._console_logger.propagate = False
|
||||
|
||||
def on_after_startup(self):
|
||||
# refresh cache now if necessary so it's faster once the user connects to the instance
|
||||
self.get_current_versions()
|
||||
# refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from
|
||||
# the server startup
|
||||
def fetch_data():
|
||||
self.get_current_versions()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def _get_configured_checks(self):
|
||||
with self._configured_checks_mutex:
|
||||
@@ -113,7 +133,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# This used to be part of the settings migration (version 2) due to a bug - it can't
|
||||
# stay there though since it interferes with manual entries to the checks not
|
||||
# originating from within a plugin. Hence we do that step now here.
|
||||
if "type" not in effective_config or effective_config["type"] != "github_commit":
|
||||
if "type" not in effective_config or effective_config["type"] not in self.COMMIT_TRACKING_TYPES:
|
||||
deletables = ["current", "displayVersion"]
|
||||
else:
|
||||
deletables = []
|
||||
@@ -152,6 +172,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
try:
|
||||
with open(self._version_cache_path) as f:
|
||||
data = yaml.safe_load(f)
|
||||
timestamp = os.stat(self._version_cache_path).st_mtime
|
||||
except:
|
||||
self._logger.exception("Error while loading version cache from disk")
|
||||
else:
|
||||
@@ -174,6 +195,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._version_cache = data
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = timestamp
|
||||
self._logger.info("Loaded version cache from disk")
|
||||
except:
|
||||
self._logger.exception("Error parsing in version cache data")
|
||||
@@ -190,29 +212,41 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = time.time()
|
||||
self._logger.info("Saved version cache to disk")
|
||||
|
||||
#~~ SettingsPlugin API
|
||||
|
||||
def get_settings_defaults(self):
|
||||
update_script = os.path.join(self._basefolder, "scripts", "update-octoprint.py")
|
||||
default_update_script = "{{python}} \"{update_script}\" --branch={{branch}} " \
|
||||
"--force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script)
|
||||
|
||||
return {
|
||||
"checks": {
|
||||
"octoprint": {
|
||||
"type": "github_release",
|
||||
"user": "foosel",
|
||||
"repo": "OctoPrint",
|
||||
"update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script),
|
||||
"method": "pip",
|
||||
"pip": "https://github.com/foosel/OctoPrint/archive/{target_version}.zip",
|
||||
"update_script": default_update_script,
|
||||
"restart": "octoprint",
|
||||
"stable_branch": dict(branch="master", name="Stable"),
|
||||
"prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"),
|
||||
dict(branch="rc/devel", name="Devel RCs")]
|
||||
"stable_branch": dict(branch="master", commitish=["master"], name="Stable"),
|
||||
"prerelease_branches": [dict(branch="rc/maintenance",
|
||||
commitish=["rc/maintenance"], # maintenance RCs
|
||||
name="Maintenance RCs"),
|
||||
dict(branch="rc/devel",
|
||||
commitish=["rc/maintenance", "rc/devel"], # devel & maintenance RCs
|
||||
name="Devel RCs")]
|
||||
},
|
||||
},
|
||||
"pip_command": None,
|
||||
"check_providers": {},
|
||||
|
||||
"cache_ttl": 24 * 60,
|
||||
|
||||
"notify_users": True
|
||||
}
|
||||
|
||||
def on_settings_load(self):
|
||||
@@ -260,7 +294,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
def on_settings_save(self, data):
|
||||
for key in self.get_settings_defaults():
|
||||
if key in ("checks", "cache_ttl", "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"):
|
||||
if key in ("checks", "cache_ttl", "notify_user", "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"):
|
||||
continue
|
||||
if key in data:
|
||||
self._settings.set([key], data[key])
|
||||
@@ -269,28 +303,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
|
||||
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
check = checks["octoprint"]
|
||||
update_type = check.get("type", None)
|
||||
checkout_folder = check.get("checkout_folder", None)
|
||||
update_folder = check.get("update_folder", None)
|
||||
prerelease = check.get("prerelease", False)
|
||||
prerelease_channel = check.get("prerelease_channel", None)
|
||||
else:
|
||||
update_type = checkout_folder = update_folder = prerelease_channel = None
|
||||
prerelease = False
|
||||
if "notify_users" in data:
|
||||
self._settings.set_boolean(["notify_users"], data["notify_users"])
|
||||
|
||||
defaults = dict(
|
||||
plugins=dict(softwareupdate=dict(
|
||||
checks=dict(
|
||||
octoprint=dict(
|
||||
type=update_type,
|
||||
checkout_folder=checkout_folder,
|
||||
update_folder=update_folder,
|
||||
prerelease=prerelease,
|
||||
prerelease_channel=prerelease_channel
|
||||
)
|
||||
octoprint=self.get_settings_defaults()["checks"]["octoprint"]
|
||||
)
|
||||
))
|
||||
)
|
||||
@@ -299,12 +318,32 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
if "octoprint_checkout_folder" in data:
|
||||
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
|
||||
if update_folder and data["octoprint_checkout_folder"]:
|
||||
if self._settings.get(["checks", "octoprint", "update_folder"]) and data["octoprint_checkout_folder"]:
|
||||
self._settings.set(["checks", "octoprint", "update_folder"], None, defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "octoprint_type" in data and data["octoprint_type"] in ("github_release", "git_commit"):
|
||||
self._settings.set(["checks", "octoprint", "type"], data["octoprint_type"], defaults=defaults, force=True)
|
||||
if "octoprint_type" in data:
|
||||
octoprint_type = data["octoprint_type"]
|
||||
|
||||
if octoprint_type == "github_release":
|
||||
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults)
|
||||
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
elif octoprint_type == "git_commit":
|
||||
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults)
|
||||
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "octoprint_release_channel" in data:
|
||||
prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"])
|
||||
if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]:
|
||||
self._settings.set(["checks", "octoprint", "prerelease"], True, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], data["octoprint_release_channel"],
|
||||
defaults=defaults, force=True)
|
||||
else:
|
||||
self._settings.set(["checks", "octoprint", "prerelease"], False, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if updated_octoprint_check_config:
|
||||
@@ -315,22 +354,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
pass
|
||||
self._version_cache_dirty = True
|
||||
|
||||
if "octoprint_release_channel" in data:
|
||||
prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"])
|
||||
if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]:
|
||||
self._settings.set(["checks", "octoprint", "prerelease"], True, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], data["octoprint_release_channel"], defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
else:
|
||||
self._settings.set(["checks", "octoprint", "prerelease"], False, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
def get_settings_version(self):
|
||||
return 5
|
||||
return 6
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
if current is None or current < 6:
|
||||
# up until & including config version 5 we didn't set the method parameter for the octoprint check
|
||||
# configuration
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is not None and "octoprint" in configured_checks:
|
||||
octoprint_check = dict(configured_checks["octoprint"])
|
||||
|
||||
if not "method" in octoprint_check and octoprint_check.get("type") == "git_commit":
|
||||
defaults = dict(plugins=dict(softwareupdate=dict(checks=dict(octoprint=dict(method="pip")))))
|
||||
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults)
|
||||
|
||||
if current == 4:
|
||||
# config version 4 didn't correctly remove the old settings for octoprint_restart_command
|
||||
# and environment_restart_command
|
||||
@@ -378,7 +418,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is not None and "octoprint" in configured_checks:
|
||||
octoprint_check = dict(configured_checks["octoprint"])
|
||||
if "type" not in octoprint_check or octoprint_check["type"] != "github_commit":
|
||||
if "type" not in octoprint_check or octoprint_check["type"] not in self.COMMIT_TRACKING_TYPES:
|
||||
deletables=["current", "displayName", "displayVersion"]
|
||||
else:
|
||||
deletables=[]
|
||||
@@ -444,17 +484,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
def view():
|
||||
try:
|
||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||
|
||||
# we don't want to transfer python_checker or python_updater values through json - replace with True
|
||||
for key, data in information.items():
|
||||
if "check" in data:
|
||||
if "python_checker" in data["check"]:
|
||||
data["check"]["python_checker"] = True
|
||||
if "python_updater" in data["check"]:
|
||||
data["check"]["python_updater"] = True
|
||||
|
||||
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
information=information))
|
||||
information=information,
|
||||
timestamp=self._version_cache_timestamp))
|
||||
except exceptions.ConfigurationInvalid as e:
|
||||
return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
|
||||
|
||||
@@ -478,8 +510,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(repr(data["information"]))
|
||||
hash.update(str(data["available"]))
|
||||
hash.update(str(data["possible"]))
|
||||
hash.update(str(data.get("online", None)))
|
||||
|
||||
hash.update(",".join(targets))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
hash.update(str(self._connectivity_checker.online))
|
||||
hash.update(self.DATA_FORMAT_VERSION)
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -539,7 +575,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
checks = self._get_configured_checks()
|
||||
check = checks.get("octoprint", None)
|
||||
checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
|
||||
return check and "update_script" in check and not checkout_folder
|
||||
return check and "method" in check and check["method"] == "update_script" and not checkout_folder
|
||||
|
||||
##~~ EventHandlerPlugin API
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
|
||||
thread = threading.Thread(target=self.get_current_versions)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
#~~ Updater
|
||||
|
||||
@@ -560,53 +607,94 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
information = dict()
|
||||
|
||||
# we don't want to do the same work twice, so let's use a lock
|
||||
with self._get_versions_mutex:
|
||||
for target, check in checks.items():
|
||||
if not target in check_targets:
|
||||
continue
|
||||
if self._get_versions_mutex.acquire(False):
|
||||
self._get_versions_data_ready.clear()
|
||||
try:
|
||||
futures_to_result = dict()
|
||||
online = self._connectivity_checker.check_immediately()
|
||||
self._logger.debug("Looks like we are {}".format("online" if online else "offline"))
|
||||
|
||||
if not check:
|
||||
continue
|
||||
with futures.ThreadPoolExecutor(max_workers=5) as executor:
|
||||
for target, check in checks.items():
|
||||
if not target in check_targets:
|
||||
continue
|
||||
|
||||
try:
|
||||
populated_check = self._populated_check(target, check)
|
||||
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
|
||||
if target_information is None:
|
||||
target_information = dict()
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
|
||||
continue
|
||||
if not check:
|
||||
continue
|
||||
|
||||
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
|
||||
try:
|
||||
populated_check = self._populated_check(target, check)
|
||||
future = executor.submit(self._get_current_version, target, populated_check, force=force)
|
||||
futures_to_result[future] = (target, populated_check)
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target,
|
||||
check.get("type",
|
||||
"<n/a>")))
|
||||
continue
|
||||
except:
|
||||
self._logger.exception("Could not check {} for updates".format(target))
|
||||
continue
|
||||
|
||||
update_available = update_available or target_update_available
|
||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||
for future in futures.as_completed(futures_to_result):
|
||||
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
target, populated_check = futures_to_result[future]
|
||||
if future.exception() is not None:
|
||||
self._logger.error("Could not check {} for updates, error: {!r}".format(target,
|
||||
future.exception()))
|
||||
continue
|
||||
|
||||
release_notes = None
|
||||
if target_information and target_information["remote"] and target_information["remote"]["value"]:
|
||||
if "release_notes" in populated_check and populated_check["release_notes"]:
|
||||
release_notes = populated_check["release_notes"]
|
||||
elif "release_notes" in target_information["remote"]:
|
||||
release_notes = target_information["remote"]["release_notes"]
|
||||
target_information, target_update_available, target_update_possible, target_online, target_error = future.result()
|
||||
|
||||
if release_notes:
|
||||
release_notes = release_notes.format(octoprint_version=VERSION,
|
||||
target_name=target_information["remote"]["name"],
|
||||
target_version=target_information["remote"]["value"])
|
||||
target_information = dict_merge(dict(local=dict(name="?", value="?"),
|
||||
remote=dict(name="?", value="?",
|
||||
release_notes=None),
|
||||
needs_online=True), target_information)
|
||||
|
||||
information[target] = dict(updateAvailable=target_update_available,
|
||||
updatePossible=target_update_possible,
|
||||
information=target_information,
|
||||
displayName=populated_check["displayName"],
|
||||
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value),
|
||||
check=populated_check,
|
||||
releaseNotes=release_notes)
|
||||
update_available = update_available or target_update_available
|
||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
|
||||
release_notes = None
|
||||
if target_information and target_information["remote"] and target_information["remote"][
|
||||
"value"]:
|
||||
if "release_notes" in populated_check and populated_check["release_notes"]:
|
||||
release_notes = populated_check["release_notes"]
|
||||
elif "release_notes" in target_information["remote"]:
|
||||
release_notes = target_information["remote"]["release_notes"]
|
||||
|
||||
if release_notes:
|
||||
release_notes = release_notes.format(octoprint_version=VERSION,
|
||||
target_name=target_information["remote"]["name"],
|
||||
target_version=target_information["remote"]["value"])
|
||||
|
||||
information[target] = dict(updateAvailable=target_update_available,
|
||||
updatePossible=target_update_possible,
|
||||
information=target_information,
|
||||
displayName=populated_check["displayName"],
|
||||
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION,
|
||||
local_name=local_name,
|
||||
local_value=local_value),
|
||||
releaseNotes=release_notes,
|
||||
online=target_online,
|
||||
error=target_error)
|
||||
|
||||
if target == "octoprint" and "released_version" in populated_check:
|
||||
information[target]["released_version"] = populated_check["released_version"]
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
|
||||
self._get_versions_data = information, update_available, update_possible
|
||||
self._get_versions_data_ready.set()
|
||||
finally:
|
||||
self._get_versions_mutex.release()
|
||||
|
||||
else: # something's already in progress, let's wait for it to complete and use its result
|
||||
self._get_versions_data_ready.wait()
|
||||
information, update_available, update_possible = self._get_versions_data
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
return information, update_available, update_possible
|
||||
|
||||
def _get_check_hash(self, check):
|
||||
@@ -625,36 +713,50 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(dict_to_sorted_repr(check))
|
||||
return hash.hexdigest()
|
||||
|
||||
def _get_current_version(self, target, check, force=False):
|
||||
def _get_current_version(self, target, check, force=False, online=None):
|
||||
"""
|
||||
Determines the current version information for one target based on its check configuration.
|
||||
"""
|
||||
|
||||
current_hash = self._get_check_hash(check)
|
||||
if online is None:
|
||||
online = self._connectivity_checker.online
|
||||
if target in self._version_cache and not force:
|
||||
data = self._version_cache[target]
|
||||
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
|
||||
if data["hash"] == current_hash \
|
||||
and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"] \
|
||||
and data.get("online", None) == online:
|
||||
# we also check that timestamp < now to not get confused too much by clock changes
|
||||
return data["information"], data["available"], data["possible"]
|
||||
return data["information"], data["available"], data["possible"], data["online"], data.get("error", None)
|
||||
|
||||
information = dict()
|
||||
update_available = False
|
||||
error = None
|
||||
|
||||
try:
|
||||
version_checker = self._get_version_checker(target, check)
|
||||
information, is_current = version_checker.get_latest(target, check)
|
||||
information, is_current = version_checker.get_latest(target, check, online=online)
|
||||
if information is not None and not is_current:
|
||||
update_available = True
|
||||
except exceptions.CannotCheckOffline:
|
||||
update_possible = False
|
||||
information["needs_online"] = True
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown check type %s for %s" % (check["type"], target))
|
||||
update_possible = False
|
||||
error = "unknown_check"
|
||||
except exceptions.NetworkError:
|
||||
self._logger.warn("Could not check %s for updates due to a network error" % target)
|
||||
update_possible = False
|
||||
error = "network"
|
||||
except:
|
||||
self._logger.exception("Could not check %s for updates" % target)
|
||||
update_possible = False
|
||||
error = "unknown"
|
||||
else:
|
||||
try:
|
||||
updater = self._get_updater(target, check)
|
||||
update_possible = updater.can_perform_update(target, check)
|
||||
update_possible = updater.can_perform_update(target, check, online=online)
|
||||
except:
|
||||
update_possible = False
|
||||
|
||||
@@ -662,9 +764,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash=current_hash,
|
||||
information=information,
|
||||
available=update_available,
|
||||
possible=update_possible)
|
||||
possible=update_possible,
|
||||
online=online,
|
||||
error=error)
|
||||
self._version_cache_dirty = True
|
||||
return information, update_available, update_possible
|
||||
return information, update_available, update_possible, online, error
|
||||
|
||||
def perform_updates(self, check_targets=None, force=False):
|
||||
"""
|
||||
@@ -776,7 +880,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._send_client_message("success", dict(results=target_results))
|
||||
|
||||
def _perform_update(self, target, check, force):
|
||||
information, update_available, update_possible = self._get_current_version(target, check)
|
||||
online = self._connectivity_checker.online
|
||||
|
||||
information, update_available, update_possible, _, _ = self._get_current_version(target, check, online=online)
|
||||
|
||||
if not update_available and not force:
|
||||
return False, None
|
||||
@@ -799,7 +905,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if updater is None:
|
||||
raise exceptions.UnknownUpdateType()
|
||||
|
||||
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log)
|
||||
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online)
|
||||
target_result = ("success", update_result)
|
||||
self._logger.info("Update of %s to %s successful!" % (target, target_version))
|
||||
|
||||
@@ -808,6 +914,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type"))
|
||||
return False, None
|
||||
|
||||
except exceptions.CannotUpdateOffline:
|
||||
self._logger.warn("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection"))
|
||||
|
||||
except Exception as e:
|
||||
self._logger.exception("Update of %s can not be performed" % target)
|
||||
if not "ignorable" in populated_check or not populated_check["ignorable"]:
|
||||
@@ -825,7 +935,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.load()
|
||||
|
||||
# persist the new version if necessary for check type
|
||||
if check["type"] == "github_commit":
|
||||
if check["type"] in self.COMMIT_TRACKING_TYPES:
|
||||
dummy_default = dict(plugins=dict())
|
||||
dummy_default["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
|
||||
@@ -847,7 +957,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._logger.info("Restarting...")
|
||||
try:
|
||||
util.execute(restart_command)
|
||||
util.execute(restart_command, evaluate_returncode=False, async=True)
|
||||
except exceptions.ScriptError as e:
|
||||
self._logger.exception("Error while restarting via command {}".format(restart_command))
|
||||
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
|
||||
@@ -863,6 +973,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if target == "octoprint":
|
||||
from flask.ext.babel import gettext
|
||||
|
||||
from octoprint.util.version import is_released_octoprint_version, is_stable_octoprint_version
|
||||
|
||||
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
|
||||
if result["displayName"] is None:
|
||||
# displayName missing or set to None
|
||||
@@ -880,50 +992,42 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
stable_branch = check["stable_branch"]["branch"]
|
||||
if "prerelease_branches" in check:
|
||||
release_branches += [x["branch"] for x in check["prerelease_branches"]]
|
||||
result["released_version"] = not release_branches or BRANCH in release_branches
|
||||
result["released_version"] = is_released_octoprint_version()
|
||||
|
||||
if check["type"] == "github_commit":
|
||||
if check["type"] in self.COMMIT_TRACKING_TYPES:
|
||||
result["current"] = REVISION if REVISION else "unknown"
|
||||
else:
|
||||
result["current"] = VERSION
|
||||
|
||||
if check["type"] == "github_release" and (check.get("prerelease", None) or BRANCH != stable_branch):
|
||||
# we are tracking github releases and are either also tracking prerelease OR are currently installed
|
||||
# from something that is not the stable (master) branch => we need to change some parameters
|
||||
if check["type"] == "github_release" and (check.get("prerelease", None) or not is_stable_octoprint_version()):
|
||||
# we are tracking github releases and are either also tracking prerelease OR are currently running
|
||||
# a non stable version => we need to change some parameters
|
||||
|
||||
# we compare versions fully, not just the base so that we see a difference
|
||||
# between RCs + stable for the same version release
|
||||
result["force_base"] = False
|
||||
|
||||
if check.get("prerelease", None):
|
||||
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
|
||||
channel = check.get("prerelease_channel", None)
|
||||
if channel:
|
||||
# if we have a release channel, we also set our update_branch here to our release channel
|
||||
# in case it's not already set
|
||||
result["update_branch"] = check.get("update_branch", channel)
|
||||
|
||||
else:
|
||||
# we are not tracking prereleases, but aren't on the stable branch either => switch back
|
||||
# to stable branch on update
|
||||
result["update_branch"] = check.get("update_branch", stable_branch)
|
||||
|
||||
if check.get("update_script", None):
|
||||
# if we are using the update_script, we need to set our update_branch and force
|
||||
# to install the exact version we requested
|
||||
# we force an exact version & python unequality check, to be able to downgrade
|
||||
result["force_exact_version"] = True
|
||||
result["release_compare"] = "python_unequal"
|
||||
|
||||
if check.get("prerelease", None):
|
||||
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
|
||||
channel = check.get("prerelease_channel", None)
|
||||
if channel:
|
||||
# if we have a release channel, we also set our update_branch here to our release channel
|
||||
# in case it's not already set
|
||||
result["update_branch"] = check.get("update_branch", channel)
|
||||
|
||||
# we also force our target version in the update
|
||||
result["force_exact_version"] = True
|
||||
|
||||
else:
|
||||
# we are not tracking prereleases, but aren't on the stable branch either => switch back
|
||||
# to stable branch on update
|
||||
result["update_branch"] = check.get("update_branch", stable_branch)
|
||||
|
||||
|
||||
if BRANCH != result.get("prerelease_channel"):
|
||||
# we force python unequality check here because that will also allow us to
|
||||
# downgrade on a prerelease channel change (rc/devel => rc/maintenance)
|
||||
#
|
||||
# we detect channel changes by comparing the current branch with the target
|
||||
# branch of the release channel - unequality means we might have to handle
|
||||
# a downgrade
|
||||
result["release_compare"] = "python_unequal"
|
||||
elif check.get("pip", None):
|
||||
# we force python unequality check for pip installs, to be able to downgrade
|
||||
result["release_compare"] = "python_unequal"
|
||||
|
||||
else:
|
||||
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
|
||||
@@ -936,7 +1040,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# displayVersion AND current missing or None
|
||||
result["displayVersion"] = u"unknown"
|
||||
|
||||
if check["type"] in ("github_commit",):
|
||||
if check["type"] in self.COMMIT_TRACKING_TYPES:
|
||||
result["current"] = check.get("current", None)
|
||||
else:
|
||||
result["current"] = check.get("current", check.get("displayVersion", None))
|
||||
@@ -968,18 +1072,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
raise exceptions.ConfigurationInvalid("no check type defined")
|
||||
|
||||
check_type = check["type"]
|
||||
if check_type == "github_release":
|
||||
return version_checks.github_release
|
||||
elif check_type == "github_commit":
|
||||
return version_checks.github_commit
|
||||
elif check_type == "git_commit":
|
||||
return version_checks.git_commit
|
||||
elif check_type == "commandline":
|
||||
return version_checks.commandline
|
||||
elif check_type == "python_checker":
|
||||
return version_checks.python_checker
|
||||
else:
|
||||
method = getattr(version_checks, check_type)
|
||||
if method is None:
|
||||
raise exceptions.UnknownCheckType()
|
||||
else:
|
||||
return method
|
||||
|
||||
def _get_update_method(self, target, check, valid_methods=None):
|
||||
"""
|
||||
@@ -1038,8 +1135,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
__plugin_name__ = "Software Update"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
|
||||
__plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"update itself or any of your installed plugins which might put "
|
||||
"your system at risk.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
|
||||
@@ -9,12 +9,14 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
import click
|
||||
import sys
|
||||
import requests.exceptions
|
||||
import octoprint_client as client
|
||||
from octoprint.cli.client import create_client, client_options
|
||||
|
||||
@click.command("check")
|
||||
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
|
||||
@click.option("--only-new", is_flag=True, help="Only show entries with updates available")
|
||||
@client_options
|
||||
@click.argument("targets", nargs=-1)
|
||||
def check_command(force, targets):
|
||||
def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets):
|
||||
"""
|
||||
Check for updates.
|
||||
|
||||
@@ -37,7 +39,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
if targets:
|
||||
params["check"] = ",".join(targets)
|
||||
|
||||
client.init_client(cli_group.settings)
|
||||
client = create_client(settings=cli_group.settings,
|
||||
apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
r = client.get("plugin/softwareupdate/check", params=params)
|
||||
try:
|
||||
r.raise_for_status()
|
||||
@@ -58,10 +68,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
status_text = "Update available"
|
||||
else:
|
||||
status_text = "Update available (manual)"
|
||||
line = "{}\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
|
||||
info["information"]["local"]["name"],
|
||||
info["information"]["remote"]["name"],
|
||||
status_text)
|
||||
|
||||
elif only_new:
|
||||
continue
|
||||
|
||||
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
|
||||
key,
|
||||
info["information"]["local"]["name"],
|
||||
info["information"]["remote"]["name"],
|
||||
status_text)
|
||||
if key == "octoprint":
|
||||
octoprint_line = line
|
||||
else:
|
||||
@@ -83,8 +98,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
|
||||
@click.command("update")
|
||||
@click.option("--force", is_flag=True, help="Update even if already up to date")
|
||||
@client_options
|
||||
@click.argument("targets", nargs=-1)
|
||||
def update_command(force, targets):
|
||||
def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets):
|
||||
"""
|
||||
Apply updates.
|
||||
|
||||
@@ -108,7 +124,13 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
if targets:
|
||||
data["check"] = targets
|
||||
|
||||
client.init_client(cli_group.settings)
|
||||
client = create_client(apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
flags = dict(
|
||||
waiting_for_restart=False,
|
||||
|
||||
@@ -18,6 +18,20 @@ class UnknownUpdateType(Exception):
|
||||
class UnknownCheckType(Exception):
|
||||
pass
|
||||
|
||||
class NetworkError(Exception):
|
||||
def __init__(self, message=None, cause=None):
|
||||
Exception.__init__(self)
|
||||
self.message = message
|
||||
self.cause = cause
|
||||
|
||||
def __str__(self):
|
||||
if self.message is not None:
|
||||
return self.message
|
||||
elif self.cause is not None:
|
||||
return "NetworkError caused by {}".format(self.cause)
|
||||
else:
|
||||
return "NetworkError"
|
||||
|
||||
class UpdateError(Exception):
|
||||
def __init__(self, message, data):
|
||||
self.message = message
|
||||
@@ -35,3 +49,8 @@ class RestartFailed(Exception):
|
||||
class ConfigurationInvalid(Exception):
|
||||
pass
|
||||
|
||||
class CannotCheckOffline(Exception):
|
||||
pass
|
||||
|
||||
class CannotUpdateOffline(Exception):
|
||||
pass
|
||||
@@ -1 +1 @@
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
@@ -108,17 +108,40 @@ $(function() {
|
||||
|
||||
self.checking = ko.observable(false);
|
||||
|
||||
self.octoprintUnconfigured = ko.observable();
|
||||
self.octoprintUnreleased = ko.observable();
|
||||
self.octoprintReleasedVersion = ko.observable();
|
||||
|
||||
self.octoprintUnconfigured = ko.pureComputed(function() {
|
||||
return self.error_checkoutFolder();
|
||||
});
|
||||
self.octoprintUnreleased = ko.pureComputed(function() {
|
||||
return self.settings.settings.plugins.softwareupdate.octoprint_type() === "github_release"
|
||||
&& !self.octoprintReleasedVersion();
|
||||
});
|
||||
|
||||
self.cacheTimestamp = ko.observable();
|
||||
self.cacheTimestampText = ko.pureComputed(function() {
|
||||
return formatDate(self.cacheTimestamp());
|
||||
});
|
||||
|
||||
self.config_cacheTtl = ko.observable();
|
||||
self.config_notifyUsers = ko.observable();
|
||||
self.config_checkoutFolder = ko.observable();
|
||||
self.config_checkType = ko.observable();
|
||||
self.config_updateMethod = ko.observable();
|
||||
self.config_releaseChannel = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
|
||||
self.error_checkoutFolder = ko.pureComputed(function() {
|
||||
return self.config_checkType() === "git_commit"
|
||||
&& (!self.config_checkoutFolder() || self.config_checkoutFolder().trim() === '');
|
||||
});
|
||||
|
||||
self.enable_configSave = ko.pureComputed(function() {
|
||||
return self.config_checkType() === "github_release"
|
||||
|| (self.config_checkType() === "git_commit" && !self.error_checkoutFolder());
|
||||
});
|
||||
|
||||
self.configurationDialog = undefined;
|
||||
self.confirmationDialog = undefined;
|
||||
self._updateClicked = false;
|
||||
|
||||
self.config_availableCheckTypes = ko.observableArray([]);
|
||||
self.config_availableReleaseChannels = ko.observableArray([]);
|
||||
@@ -130,8 +153,8 @@ $(function() {
|
||||
{
|
||||
"name": function(a, b) {
|
||||
// sorts ascending, puts octoprint first
|
||||
if (a.key.toLocaleLowerCase() == "octoprint") return -1;
|
||||
if (b.key.toLocaleLowerCase() == "octoprint") return 1;
|
||||
if (a.key.toLocaleLowerCase() === "octoprint") return -1;
|
||||
if (b.key.toLocaleLowerCase() === "octoprint") return 1;
|
||||
|
||||
if (a.displayName.toLocaleLowerCase() < b.displayName.toLocaleLowerCase()) return -1;
|
||||
if (a.displayName.toLocaleLowerCase() > b.displayName.toLocaleLowerCase()) return 1;
|
||||
@@ -153,9 +176,20 @@ $(function() {
|
||||
self.performCheck();
|
||||
};
|
||||
|
||||
self._showPopup = function(options, eventListeners) {
|
||||
self.onUserLoggedOut = function() {
|
||||
self._closePopup();
|
||||
self.popup = new PNotify(options);
|
||||
};
|
||||
|
||||
self._showPopup = function(options, eventListeners, singleButtonNotify) {
|
||||
singleButtonNotify = singleButtonNotify || false;
|
||||
|
||||
self._closePopup();
|
||||
|
||||
if (singleButtonNotify) {
|
||||
self.popup = PNotify.singleButtonNotify(options);
|
||||
} else {
|
||||
self.popup = new PNotify(options);
|
||||
}
|
||||
|
||||
if (eventListeners) {
|
||||
var popupObj = self.popup.get();
|
||||
@@ -186,15 +220,16 @@ $(function() {
|
||||
|
||||
self.savePluginSettings = function(viewModel, event) {
|
||||
var target = $(event.target);
|
||||
target.prepend('<i class="icon-spinner icon-spin"></i> ');
|
||||
target.prepend('<i class="fa fa-spinner fa-spin"></i> ');
|
||||
|
||||
var data = {
|
||||
plugins: {
|
||||
softwareupdate: {
|
||||
cache_ttl: parseInt(self.config_cacheTtl()),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder(),
|
||||
notify_users: self.config_notifyUsers(),
|
||||
octoprint_type: self.config_checkType(),
|
||||
octoprint_release_channel: self.config_releaseChannel()
|
||||
octoprint_release_channel: self.config_releaseChannel(),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder()
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -205,22 +240,15 @@ $(function() {
|
||||
self.performCheck();
|
||||
},
|
||||
complete: function() {
|
||||
$("i.icon-spinner", target).remove();
|
||||
$("i.fa-spinner", target).remove();
|
||||
},
|
||||
sending: true
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
var updateMethod = self.settings.settings.plugins.softwareupdate.octoprint_method();
|
||||
|
||||
var availableCheckTypes = [];
|
||||
if (updateMethod == "update_script" || updateMethod == "python") {
|
||||
availableCheckTypes = [{"key": "github_release", "name": gettext("Release")},
|
||||
var availableCheckTypes = [{"key": "github_release", "name": gettext("Release")},
|
||||
{"key": "git_commit", "name": gettext("Commit")}];
|
||||
} else {
|
||||
availableCheckTypes = [];
|
||||
}
|
||||
self.config_availableCheckTypes(availableCheckTypes);
|
||||
|
||||
var availableReleaseChannels = [];
|
||||
@@ -229,11 +257,12 @@ $(function() {
|
||||
});
|
||||
self.config_availableReleaseChannels(availableReleaseChannels);
|
||||
|
||||
self.config_updateMethod(updateMethod);
|
||||
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
self.config_notifyUsers(self.settings.settings.plugins.softwareupdate.notify_users());
|
||||
|
||||
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
|
||||
self.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
};
|
||||
|
||||
self._copyConfigBack = function() {
|
||||
@@ -242,17 +271,19 @@ $(function() {
|
||||
};
|
||||
|
||||
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
|
||||
self.cacheTimestamp(data.timestamp);
|
||||
|
||||
var versions = [];
|
||||
_.each(data.information, function(value, key) {
|
||||
value["key"] = key;
|
||||
|
||||
if (!value.hasOwnProperty("displayName") || value.displayName == "") {
|
||||
if (!value.hasOwnProperty("displayName") || value.displayName === "") {
|
||||
value.displayName = value.key;
|
||||
}
|
||||
if (!value.hasOwnProperty("displayVersion") || value.displayVersion == "") {
|
||||
if (!value.hasOwnProperty("displayVersion") || value.displayVersion === "") {
|
||||
value.displayVersion = value.information.local.name;
|
||||
}
|
||||
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes == "") {
|
||||
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes === "") {
|
||||
value.releaseNotes = undefined;
|
||||
}
|
||||
|
||||
@@ -270,32 +301,18 @@ $(function() {
|
||||
self.versions.updateItems(versions);
|
||||
|
||||
var octoprint = data.information["octoprint"];
|
||||
if (octoprint && octoprint.hasOwnProperty("check")) {
|
||||
var check = octoprint.check;
|
||||
if (check["released_version"] === false && check["type"] == "github_release") {
|
||||
self.octoprintUnreleased(true);
|
||||
} else {
|
||||
self.octoprintUnreleased(false);
|
||||
}
|
||||
self.octoprintReleasedVersion(!octoprint || octoprint.released_version);
|
||||
|
||||
var checkoutFolder = (check["checkout_folder"] || "").trim();
|
||||
var updateFolder = (check["update_folder"] || "").trim();
|
||||
var needsFolder = check["update_script"] || false;
|
||||
if (needsFolder && checkoutFolder == "" && updateFolder == "") {
|
||||
self.octoprintUnconfigured(true);
|
||||
} else {
|
||||
self.octoprintUnconfigured(false);
|
||||
}
|
||||
}
|
||||
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
if (data.status === "updateAvailable" || data.status === "updatePossible") {
|
||||
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
|
||||
|
||||
text += "<ul class='icons-ul'>";
|
||||
text += "<ul class='fa-ul'>";
|
||||
_.each(self.versions.items(), function(update_info) {
|
||||
if (update_info.updateAvailable) {
|
||||
text += "<li>"
|
||||
+ "<i class='icon-li " + (update_info.updatePossible ? "icon-ok" : "icon-remove")+ "'></i>"
|
||||
+ "<i class='fa fa-li " + (update_info.updatePossible ? "fa-check" : "fa-remove")+ "'></i>"
|
||||
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
|
||||
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
|
||||
+ "</li>";
|
||||
@@ -303,7 +320,11 @@ $(function() {
|
||||
});
|
||||
text += "</ul>";
|
||||
|
||||
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
text += "<p><small>" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "</small></p>";
|
||||
}
|
||||
|
||||
text += "</div>";
|
||||
|
||||
@@ -314,8 +335,9 @@ $(function() {
|
||||
};
|
||||
var eventListeners = {};
|
||||
|
||||
if (data.status == "updatePossible" && self.loginState.isAdmin()) {
|
||||
// if user is admin, add action buttons
|
||||
var singleButtonNotify = false;
|
||||
if (data.status === "updatePossible" && self.loginState.isAdmin()) {
|
||||
// if update is possible and user is admin, add action buttons for ignore and update
|
||||
options["confirm"] = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
@@ -329,23 +351,43 @@ $(function() {
|
||||
}, {
|
||||
text: gettext("Update now"),
|
||||
addClass: "btn-primary",
|
||||
click: self.update
|
||||
click: function() {
|
||||
if (self._updateClicked) return;
|
||||
self._updateClicked = true;
|
||||
self.update();
|
||||
}
|
||||
}]
|
||||
};
|
||||
options["buttons"] = {
|
||||
closer: false,
|
||||
sticker: false
|
||||
};
|
||||
} else {
|
||||
// if update is not possible or user is not admin, only add ignore button
|
||||
options["confirm"] = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Ignore"),
|
||||
click: function(notice) {
|
||||
notice.remove();
|
||||
self._markNotificationAsSeen(data.information);
|
||||
}
|
||||
}]
|
||||
};
|
||||
options["buttons"] = {
|
||||
closer: false,
|
||||
sticker: false
|
||||
};
|
||||
singleButtonNotify = true;
|
||||
}
|
||||
|
||||
if ((ignoreSeen || !self._hasNotificationBeenSeen(data.information)) && !OctoPrint.coreui.wizardOpen) {
|
||||
self._showPopup(options, eventListeners);
|
||||
self._showPopup(options, eventListeners, singleButtonNotify);
|
||||
}
|
||||
} else if (data.status == "current") {
|
||||
} else if (data.status === "current") {
|
||||
if (showIfNothingNew) {
|
||||
self._showPopup({
|
||||
title: gettext("Everything is up-to-date"),
|
||||
hide: false,
|
||||
type: "success"
|
||||
});
|
||||
} else {
|
||||
@@ -355,7 +397,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
|
||||
if (!self.loginState.isUser()) return;
|
||||
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
|
||||
self.checking(true);
|
||||
OctoPrint.plugins.softwareupdate.check(force)
|
||||
.done(function(data) {
|
||||
@@ -366,25 +409,80 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.iconTitleForEntry = function(data) {
|
||||
if (data.updatePossible) {
|
||||
return "";
|
||||
} else if (!data.online && data.information && data.information.needs_online) {
|
||||
return gettext("No internet connection");
|
||||
} else if (data.error) {
|
||||
return self.errorTextForEntry(data);
|
||||
} else {
|
||||
return gettext("Update not possible");
|
||||
}
|
||||
};
|
||||
|
||||
self.errorTextForEntry = function(data) {
|
||||
if (!data.error) {
|
||||
return "";
|
||||
}
|
||||
|
||||
switch (data.error) {
|
||||
case "unknown_check": {
|
||||
return gettext("Unknown update check, configuration ok?");
|
||||
}
|
||||
case "needs_online": {
|
||||
return gettext("Cannot check for update, need online connection");
|
||||
}
|
||||
case "network": {
|
||||
return gettext("Network error while checking for update");
|
||||
}
|
||||
case "unknown": {
|
||||
return gettext("Unknown error while checking for update, please check the logs");
|
||||
}
|
||||
default: {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self._markNotificationAsSeen = function(data) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify(self._informationToRemoteVersions(data));
|
||||
if (!self.loginState.isUser())
|
||||
return false;
|
||||
|
||||
var currentString = localStorage["plugin.softwareupdate.seen_information"];
|
||||
var current;
|
||||
if (currentString === undefined) {
|
||||
current = {};
|
||||
} else {
|
||||
current = JSON.parse(currentString);
|
||||
}
|
||||
current[self.loginState.username()] = self._informationToRemoteVersions(data);
|
||||
localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify(current);
|
||||
};
|
||||
|
||||
self._hasNotificationBeenSeen = function(data) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
|
||||
if (localStorage["plugin.softwareupdate.seen_information"] == undefined)
|
||||
if (localStorage["plugin.softwareupdate.seen_information"] === undefined)
|
||||
return false;
|
||||
|
||||
var knownData = JSON.parse(localStorage["plugin.softwareupdate.seen_information"]);
|
||||
|
||||
if (!self.loginState.isUser())
|
||||
return true;
|
||||
|
||||
var userData = knownData[self.loginState.username()];
|
||||
if (userData === undefined)
|
||||
return false;
|
||||
|
||||
var freshData = self._informationToRemoteVersions(data);
|
||||
|
||||
var hasBeenSeen = true;
|
||||
_.each(freshData, function(value, key) {
|
||||
if (!_.has(knownData, key) || knownData[key] != freshData[key]) {
|
||||
if (!_.has(userData, key) || userData[key] !== freshData[key]) {
|
||||
hasBeenSeen = false;
|
||||
}
|
||||
});
|
||||
@@ -400,12 +498,14 @@ $(function() {
|
||||
};
|
||||
|
||||
self.performUpdate = function(force, items) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
self.updateInProgress = true;
|
||||
|
||||
var options = {
|
||||
title: gettext("Updating..."),
|
||||
text: gettext("Now updating, please wait."),
|
||||
icon: "icon-cog icon-spin",
|
||||
icon: "fa fa-cog fa-spin",
|
||||
hide: false,
|
||||
buttons: {
|
||||
closer: false,
|
||||
@@ -434,8 +534,14 @@ $(function() {
|
||||
};
|
||||
|
||||
self.update = function(force) {
|
||||
if (self.updateInProgress) return;
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (self.updateInProgress) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
if (!self.loginState.isAdmin()) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.printerState.isPrinting()) {
|
||||
self._showPopup({
|
||||
@@ -443,6 +549,7 @@ $(function() {
|
||||
text: gettext("A print job is currently in progress. Updating will be prevented until it is done."),
|
||||
type: "error"
|
||||
});
|
||||
self._updateClicked = false;
|
||||
} else {
|
||||
self.forceUpdate = (force == true);
|
||||
self.confirmationDialog.modal("show");
|
||||
@@ -451,9 +558,13 @@ $(function() {
|
||||
};
|
||||
|
||||
self.confirmUpdate = function() {
|
||||
self.confirmationDialog.modal("hide");
|
||||
self.performUpdate(self.forceUpdate,
|
||||
_.map(self.availableAndPossible(), function(info) { return info.key }));
|
||||
self.confirmationDialog.modal("hide");
|
||||
};
|
||||
|
||||
self.confirmationHidden = function() {
|
||||
self._updateClicked = false;
|
||||
};
|
||||
|
||||
self._showWorkingDialog = function(title) {
|
||||
@@ -492,10 +603,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (next && _.startsWith(next, "wizard_plugin_softwareupdate")) {
|
||||
if (next && next === "#wizard_plugin_softwareupdate") {
|
||||
// switching to the plugin wizard tab
|
||||
self._copyConfig();
|
||||
} else if (current && _.startsWith(current, "wizard_plugin_softwareupdate")) {
|
||||
} else if (current && current === "#wizard_plugin_softwareupdate") {
|
||||
// switching away from the plugin wizard tab
|
||||
self._copyConfigBack();
|
||||
}
|
||||
@@ -511,6 +622,10 @@ $(function() {
|
||||
self.onStartup = function() {
|
||||
self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog");
|
||||
self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output");
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
|
||||
|
||||
self.confirmationDialog.on("hidden", self.confirmationHidden);
|
||||
};
|
||||
|
||||
self.onServerDisconnect = function() {
|
||||
@@ -520,6 +635,11 @@ $(function() {
|
||||
return true;
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
if (!payload || !payload.new) return;
|
||||
self.performCheck();
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
if (self.waitingForRestart) {
|
||||
self.waitingForRestart = false;
|
||||
@@ -531,7 +651,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin != "softwareupdate") {
|
||||
if (plugin !== "softwareupdate") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -622,7 +742,7 @@ $(function() {
|
||||
|
||||
restartType = messageData.restart_type;
|
||||
text = gettext("The update finished successfully, please restart OctoPrint now.");
|
||||
if (restartType == "environment") {
|
||||
if (restartType === "environment") {
|
||||
text = gettext("The update finished successfully, please reboot the server now.");
|
||||
}
|
||||
|
||||
@@ -643,7 +763,7 @@ $(function() {
|
||||
case "restart_failed": {
|
||||
restartType = messageData.restart_type;
|
||||
text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here.");
|
||||
if (restartType == "environment") {
|
||||
if (restartType === "environment") {
|
||||
text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult the log file on what went wrong here.");
|
||||
}
|
||||
|
||||
@@ -700,7 +820,7 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
if (options != undefined) {
|
||||
if (options !== undefined) {
|
||||
self._showPopup(options);
|
||||
}
|
||||
};
|
||||
@@ -710,17 +830,16 @@ $(function() {
|
||||
"'.*?' does not exist -- can't clean it"];
|
||||
self._forcedStdoutLine = new RegExp(self._forcedStdoutPatterns.join("|"));
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([
|
||||
SoftwareUpdateViewModel,
|
||||
["loginStateViewModel", "printerStateViewModel", "settingsViewModel"],
|
||||
["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog", "#wizard_plugin_softwareupdate"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SoftwareUpdateViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel"],
|
||||
elements: ["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog", "#wizard_plugin_softwareupdate"]
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,12 @@ td.settings_plugin_softwareupdate_column_update {
|
||||
width: 16px;
|
||||
}
|
||||
|
||||
td.settings_plugin_softwareupdate_column_information {
|
||||
.line {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_softwareupdate_workingdialog_output {
|
||||
font-size: 0.8em;
|
||||
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
<div class="control-group" data-bind="visible: config_updateMethod() == 'update_script' || config_updateMethod() == 'python_updater'">
|
||||
<div class="control-group" data-bind="visible: config_checkType() === 'git_commit', css: {error: error_checkoutFolder}">
|
||||
<label class="control-label">{{ _('OctoPrint checkout folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_checkoutFolder">
|
||||
<span class="help-block" data-bind="visible: error_checkoutFolder">{{ _('This needs to be set if you select commit based version tracking.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
Loaded 100 of 303 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user