Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
464d9c0757 | ||
|
|
94ae90ab80 | ||
|
|
33b89550a4 | ||
|
|
9661469532 | ||
|
|
b06c222a7d | ||
|
|
9f85b54681 | ||
|
|
5d1ad5d75d | ||
|
|
dc32f955b7 | ||
|
|
220592c267 | ||
|
|
0faa6879b4 | ||
|
|
71b5de91bf | ||
|
|
928d62a517 | ||
|
|
78bd3b1a52 | ||
|
|
b9bab0577b | ||
|
|
c41551a643 | ||
|
|
6c92dd1303 | ||
|
|
124f01ca2d | ||
|
|
0dece85fa7 | ||
|
|
caebf90ee9 | ||
|
|
0c77014903 | ||
|
|
231a796200 | ||
|
|
fe755405e8 | ||
|
|
2200f2186c | ||
|
|
b57b7cb606 | ||
|
|
f2b2496e58 | ||
|
|
e603b98d0d | ||
|
|
e235fc299f | ||
|
|
4f25ed546e | ||
|
|
f72b9db6a9 | ||
|
|
80e8e33283 | ||
|
|
00d0396417 | ||
|
|
59e39662f1 | ||
|
|
038e1b9a57 | ||
|
|
bbefeeeb02 | ||
|
|
2801da5c51 | ||
|
|
471dab9406 | ||
|
|
1deb247ce5 | ||
|
|
4469a2d84a | ||
|
|
2da7aa358d | ||
|
|
cbb083d7f6 | ||
|
|
d68de2c3c7 | ||
|
|
454c5e494a | ||
|
|
3b1874ea25 | ||
|
|
e0233dee13 | ||
|
|
84a99e1b53 | ||
|
|
b7e0e89bb4 | ||
|
|
d8c3063813 | ||
|
|
1485050234 | ||
|
|
6d7721f8f5 | ||
|
|
e3ae71eabd | ||
|
|
e88041c59e | ||
|
|
e17db4e1cf | ||
|
|
766a64c8f6 | ||
|
|
8485d2c9a7 | ||
|
|
397e691a6a | ||
|
|
6481f7cf6b | ||
|
|
46c527d24a | ||
|
|
5392f39cc4 | ||
|
|
4a324b4f5e | ||
|
|
2855b0e7a7 | ||
|
|
39e4cd3136 | ||
|
|
8fefa63c8c | ||
|
|
10532b9118 | ||
|
|
7f2eb470e4 | ||
|
|
8955b8e0b6 | ||
|
|
ee9d5048e2 | ||
|
|
09bb74b6c6 | ||
|
|
493dddf66e | ||
|
|
8173f8d0c4 | ||
|
|
01feec47d7 | ||
|
|
2b60dbc7e1 | ||
|
|
32f5f36e5a | ||
|
|
96294df710 | ||
|
|
ef54cbb148 | ||
|
|
9cd597a467 | ||
|
|
2263ebde72 | ||
|
|
1fd8d597ab | ||
|
|
2aec0b3a75 | ||
|
|
47d10a6d3e | ||
|
|
ee216ddc93 | ||
|
|
7756d312e2 | ||
|
|
19e03eeeb2 | ||
|
|
e73aeba03b | ||
|
|
87f3c5acce | ||
|
|
a38a3e67c9 | ||
|
|
547ae9e13e | ||
|
|
b031092f07 | ||
|
|
6e6dd2c34e | ||
|
|
759f4f8ea2 | ||
|
|
bee82bcde9 | ||
|
|
888fb97e66 | ||
|
|
9c775bd899 | ||
|
|
4bf3445eef | ||
|
|
47b3f51a3f | ||
|
|
2e6b85990d | ||
|
|
30a4b9e9ab | ||
|
|
81a259e51b | ||
|
|
e85e9661e0 | ||
|
|
1d60250942 | ||
|
|
e11463f6ce | ||
|
|
1146a1bb6f | ||
|
|
311fdd5aca | ||
|
|
6ddc55bf80 | ||
|
|
2c930ef069 | ||
|
|
3739bbc652 | ||
|
|
8d544e63f4 | ||
|
|
7e4cf6c5dc | ||
|
|
c8d162c999 | ||
|
|
017515dcc1 | ||
|
|
d8bd684f96 | ||
|
|
aad5c70eb0 | ||
|
|
ea2f0a9b17 | ||
|
|
c4131d5e4b | ||
|
|
21127bcf2a | ||
|
|
04da8afb07 | ||
|
|
c38f06cce2 | ||
|
|
968f952f69 | ||
|
|
8409fdaa48 | ||
|
|
f29e736427 | ||
|
|
ac3b6f6df8 | ||
|
|
a4444ccb68 | ||
|
|
270a0dcb1f | ||
|
|
a889bec4d8 | ||
|
|
7ee9bc32eb | ||
|
|
fd62c1fa3d | ||
|
|
a445cfe65e | ||
|
|
e20a9925dd | ||
|
|
09a4fb2515 | ||
|
|
cce7389a42 | ||
|
|
b138ea7a47 | ||
|
|
3b708ce079 | ||
|
|
4441618be5 | ||
|
|
0525c9ab40 | ||
|
|
0035e7c3ff | ||
|
|
073060d253 | ||
|
|
55980a1c2c | ||
|
|
852a2cf157 | ||
|
|
2e6ee57162 | ||
|
|
5c54f16ece | ||
|
|
04a13268ad | ||
|
|
49fdac7528 | ||
|
|
75f6ef4bae | ||
|
|
9fd608691b | ||
|
|
30d618267f | ||
|
|
204d212323 | ||
|
|
04528a635b | ||
|
|
db1c18075f | ||
|
|
3b556e9d79 | ||
|
|
8761273636 | ||
|
|
08efe80304 | ||
|
|
cc1d88c4c8 | ||
|
|
72eef3e224 | ||
|
|
84f6833597 | ||
|
|
2a94abdc49 | ||
|
|
fab5f34aaa | ||
|
|
76f79e5380 | ||
|
|
1b25029207 | ||
|
|
8df2a5436b | ||
|
|
72f005b7fe | ||
|
|
bcb6c7a1d4 | ||
|
|
dbe07af426 | ||
|
|
1c3e463ac6 | ||
|
|
4b04e8fd79 | ||
|
|
c0096c41a0 | ||
|
|
aab629d80e | ||
|
|
4e2afbc170 | ||
|
|
cf16392e18 | ||
|
|
34e4a20866 | ||
|
|
1b3a8acf0d | ||
|
|
1ed6730400 | ||
|
|
dde99736e4 | ||
|
|
334f2c35f9 | ||
|
|
aacd59ae78 | ||
|
|
058dbd0c2e | ||
|
|
54c8923087 | ||
|
|
1025f0be43 | ||
|
|
295b96f259 | ||
|
|
adea0db344 | ||
|
|
9f2821fe96 | ||
|
|
dcc1148863 | ||
|
|
e972026ad0 | ||
|
|
6592be63f8 | ||
|
|
8b5626e49c | ||
|
|
be4a931e32 | ||
|
|
548da0d64f | ||
|
|
25f26170ff | ||
|
|
b6b562399e | ||
|
|
3654512085 | ||
|
|
e7dbd804ce | ||
|
|
7fd03265d4 | ||
|
|
369679bae5 | ||
|
|
27e1f2e6e7 | ||
|
|
109cbeea6a | ||
|
|
606199dcc9 | ||
|
|
75b5fe198f | ||
|
|
3c5aa60d2b | ||
|
|
1b876f1cf3 | ||
|
|
580e5f5122 | ||
|
|
22f6a38f0a | ||
|
|
620aa4dfe0 | ||
|
|
1ccc787222 | ||
|
|
f8e7ae7436 | ||
|
|
3ae284d9a7 | ||
|
|
caf5be562e | ||
|
|
c01a34f358 | ||
|
|
deee737660 | ||
|
|
8425c7b973 | ||
|
|
1e42db040d | ||
|
|
e2d4b64510 | ||
|
|
61136edeea | ||
|
|
7614ef40d3 | ||
|
|
935639a51a | ||
|
|
ec689e3939 | ||
|
|
84f95b1099 | ||
|
|
fd8788dd34 | ||
|
|
32a8646135 | ||
|
|
09cc7cf5f7 | ||
|
|
496e9f0ec4 | ||
|
|
18b2ecd64c | ||
|
|
cc6f61c62e | ||
|
|
de149613cb | ||
|
|
a7ca374955 | ||
|
|
d7d3272905 | ||
|
|
9eb29a8ce0 | ||
|
|
bf16bd1180 | ||
|
|
7b5315383b | ||
|
|
72729ad418 | ||
|
|
e6f902cbe7 | ||
|
|
9b14f32279 | ||
|
|
7ad4d75588 | ||
|
|
5a623b486c | ||
|
|
920283cf87 | ||
|
|
becd16b892 | ||
|
|
f59c1ce804 | ||
|
|
c71972c0f8 | ||
|
|
47a9a40ec9 | ||
|
|
5c1fffc3d0 | ||
|
|
fe090cc6cc | ||
|
|
ab3c4ab66c | ||
|
|
1d6b7244b5 | ||
|
|
ea17566aba | ||
|
|
315ed57916 | ||
|
|
1014582b4b | ||
|
|
cf77053901 | ||
|
|
f040482b18 | ||
|
|
523fadd930 | ||
|
|
97d0fbd2c9 | ||
|
|
3b820f6848 | ||
|
|
e8b9f385b4 | ||
|
|
95bc1006a0 | ||
|
|
14ef17163f | ||
|
|
9a1bd8af87 | ||
|
|
a292a12c4a | ||
|
|
200a3ef4eb | ||
|
|
88582beb55 | ||
|
|
6d7c8bbda6 | ||
|
|
9a7f92174a | ||
|
|
a301fc6da9 | ||
|
|
e08dc0b5aa | ||
|
|
a368a7f1c9 | ||
|
|
6a601d4f8e | ||
|
|
7a3b370469 | ||
|
|
e676d53e9f | ||
|
|
40b231f692 | ||
|
|
86664fdb39 | ||
|
|
4ebb5cf42d | ||
|
|
e8bee435af | ||
|
|
082f977f7a | ||
|
|
237a2c0add | ||
|
|
2e47f49f7a | ||
|
|
05919363e1 | ||
|
|
7c8547555c | ||
|
|
ce0c77f0bf | ||
|
|
aec041b014 | ||
|
|
58b32803df | ||
|
|
6d447f8408 | ||
|
|
54d359f730 | ||
|
|
4d9f0fca41 | ||
|
|
41146c2b7c | ||
|
|
99d7157cb7 | ||
|
|
c8b5662ff2 | ||
|
|
b781681e0f | ||
|
|
5edeecdc8c | ||
|
|
f82ec61463 | ||
|
|
372a8d2ea8 | ||
|
|
9c5d1dec59 | ||
|
|
feff5e0978 | ||
|
|
019bf5acd4 | ||
|
|
717aafee08 | ||
|
|
67c5a5e168 | ||
|
|
6310afa261 | ||
|
|
cd6ae6e47b | ||
|
|
b01e1c269d | ||
|
|
49fb0f87d5 | ||
|
|
8956e7a173 | ||
|
|
9fa20f0e52 | ||
|
|
6bf8384c35 | ||
|
|
1dacbc35bf | ||
|
|
7522dbed1d | ||
|
|
d433c919ec | ||
|
|
a6f701802f | ||
|
|
e03feeb7ac | ||
|
|
00068114a1 | ||
|
|
6a7e11eb7c | ||
|
|
6f987577f4 | ||
|
|
819d690bc3 | ||
|
|
dbfe487f13 | ||
|
|
47e9afa811 | ||
|
|
f9edea0c2c | ||
|
|
8ef3d1dcad | ||
|
|
fcfef25c93 | ||
|
|
604d2f7811 | ||
|
|
a721256204 | ||
|
|
24d2efd3ce | ||
|
|
5e8220055f | ||
|
|
38eff3fe6f | ||
|
|
4e47ecabf8 | ||
|
|
df9617ac1e | ||
|
|
0b23417f45 | ||
|
|
828ba56952 | ||
|
|
63723baf07 | ||
|
|
b60b20d784 | ||
|
|
1e0bdc8b8c | ||
|
|
b47b39af99 | ||
|
|
6bc4d8fca4 | ||
|
|
1e01e587f3 | ||
|
|
d8f5dd701b | ||
|
|
bee609a316 | ||
|
|
5794a347f1 | ||
|
|
5d8535cb9c | ||
|
|
21d3622c2e | ||
|
|
008cde6ef6 | ||
|
|
4df57cd8fe | ||
|
|
f53380c04e | ||
|
|
8af45e2f21 | ||
|
|
0da47858fa | ||
|
|
abfffa3231 | ||
|
|
e056ccdf29 | ||
|
|
e334d8b073 | ||
|
|
f1673c148f | ||
|
|
ae5a1dc6dc | ||
|
|
7fcc3551ca | ||
|
|
f3fdac7e5a | ||
|
|
bba95e9000 | ||
|
|
fa81791c29 | ||
|
|
a4072723bf | ||
|
|
d451acdd4f | ||
|
|
a1a15e40e0 | ||
|
|
0c264ca0d2 | ||
|
|
9e4b0f83d8 | ||
|
|
2b8d831308 | ||
|
|
fcb0f877b8 | ||
|
|
c74e3a0a0b | ||
|
|
ea64c017e8 | ||
|
|
70a104e32a | ||
|
|
75a37f5ce7 | ||
|
|
e4d083028c | ||
|
|
6bab550830 | ||
|
|
f9916783e9 | ||
|
|
e00375e586 | ||
|
|
41fab8a36c | ||
|
|
c05b6572c5 | ||
|
|
1ae6b73f7a | ||
|
|
670ca15997 | ||
|
|
ea5ef34cc1 | ||
|
|
958fc7600d | ||
|
|
13d894e74b | ||
|
|
353309fc60 | ||
|
|
3501179257 | ||
|
|
f993f744ba | ||
|
|
d987cb23c1 | ||
|
|
5b4f4e3d77 | ||
|
|
c66b451efd | ||
|
|
e14cb44e13 | ||
|
|
17ad63dabf | ||
|
|
39cda08d07 | ||
|
|
3a1611e5c4 | ||
|
|
7736cf1e6d | ||
|
|
41e74df8d3 | ||
|
|
ac3b8ebfcc | ||
|
|
e0543de8ef | ||
|
|
f243a52823 | ||
|
|
94013ddb70 | ||
|
|
9cfcbd3929 | ||
|
|
6cfbdc6062 | ||
|
|
d3334b29d9 | ||
|
|
94ce6f1dd1 | ||
|
|
c623e90ebc | ||
|
|
b6e49b59a7 | ||
|
|
f416e96414 | ||
|
|
347f53baa4 | ||
|
|
9ecf39febe | ||
|
|
582b03f21f | ||
|
|
ff0b94c78d | ||
|
|
f5c8b04958 | ||
|
|
36818057a3 | ||
|
|
a5cff5bc3d | ||
|
|
a4bff305b3 | ||
|
|
6b149e2fc9 | ||
|
|
337e49208a | ||
|
|
b052925424 | ||
|
|
970c867ee4 | ||
|
|
c69f20c648 | ||
|
|
88c93a7c11 | ||
|
|
54677f96f4 | ||
|
|
e522633c98 | ||
|
|
f72f948744 | ||
|
|
3ad4818488 | ||
|
|
b3cc44cea5 | ||
|
|
9cb3631ad0 | ||
|
|
743ff35bcf | ||
|
|
df706f61db | ||
|
|
791e759b40 | ||
|
|
22fdc1d933 | ||
|
|
aa383e3ca1 | ||
|
|
472fda6645 | ||
|
|
bd35de80c3 | ||
|
|
52fe19e5f9 | ||
|
|
c2f09b1715 | ||
|
|
1ccc1fa47b | ||
|
|
2972d38cef | ||
|
|
4662606907 | ||
|
|
2c50aa789a | ||
|
|
9e62b250ac | ||
|
|
03722e5e70 | ||
|
|
7867052339 | ||
|
|
8a0252ccfe | ||
|
|
e84293c415 | ||
|
|
250e83ad7e | ||
|
|
660724741c | ||
|
|
a5f87597ad | ||
|
|
ebef35a573 | ||
|
|
44fcd4e305 | ||
|
|
90704e292b | ||
|
|
b83dd76c89 | ||
|
|
7ab4b90d07 | ||
|
|
fd4ff2bf37 | ||
|
|
76f93d8875 | ||
|
|
30359f52ab | ||
|
|
0020f029d1 | ||
|
|
d248df3826 | ||
|
|
dc19ad4c4c | ||
|
|
88a962b3ab | ||
|
|
033e567d2a | ||
|
|
d03d4b7b4c | ||
|
|
38ddd3102d | ||
|
|
6dd501217a | ||
|
|
e58387b4f2 | ||
|
|
1de58b7be1 | ||
|
|
58d8deefcd | ||
|
|
f8e6e4e3db | ||
|
|
a92372ec7e | ||
|
|
7b773f6fd2 | ||
|
|
69681a27d6 | ||
|
|
0adcfc693d | ||
|
|
b73507fd2b | ||
|
|
bea6bd013c | ||
|
|
9a881012e2 | ||
|
|
d62df7643b | ||
|
|
7d40320a5b | ||
|
|
09456b923f | ||
|
|
39e6c11c39 | ||
|
|
5aef014773 | ||
|
|
9738884ff8 | ||
|
|
27b625a614 | ||
|
|
096e9fc326 | ||
|
|
f577d6b45d | ||
|
|
bd7a28af5b | ||
|
|
104b0a504c | ||
|
|
40bfbe0d7b | ||
|
|
4bf5984ace | ||
|
|
8369d311bf | ||
|
|
d8eb57548d | ||
|
|
d8072f0e05 | ||
|
|
3d7016f500 | ||
|
|
41e3a0390f | ||
|
|
42a9a1976d | ||
|
|
569991e55c | ||
|
|
b7adf115ee | ||
|
|
7cf0f552f5 | ||
|
|
246c614635 | ||
|
|
df62f08ec3 | ||
|
|
b6f71eeb3b | ||
|
|
e2a7e07a0a | ||
|
|
b3acd36092 | ||
|
|
7a037b9c66 | ||
|
|
c1cf359b43 | ||
|
|
2d883d6d20 | ||
|
|
2fa18f5855 | ||
|
|
a4ce92c963 | ||
|
|
c84d39a803 | ||
|
|
d59eaa2a91 | ||
|
|
f7ad87449a | ||
|
|
08bfae216c | ||
|
|
64db784d8d | ||
|
|
5a91b8db48 | ||
|
|
58f73f3ed9 | ||
|
|
1852578136 | ||
|
|
fdb2ba8146 | ||
|
|
92ea6ee9aa | ||
|
|
fb4e95bf8e | ||
|
|
cedbf039d2 | ||
|
|
d1711f0376 | ||
|
|
047b9f544a | ||
|
|
8ea7528d41 | ||
|
|
43bf55d503 | ||
|
|
b9a5e1db69 | ||
|
|
03d421c629 | ||
|
|
066e7d1e39 | ||
|
|
4fd641dc74 | ||
|
|
16b690089d | ||
|
|
a77fbfe0c2 | ||
|
|
b36a776f51 | ||
|
|
9c39dd7303 | ||
|
|
eb5a3d1d36 | ||
|
|
d465f23309 | ||
|
|
987a6b3cf8 | ||
|
|
6b3d68f9aa | ||
|
|
fcd34265c8 | ||
|
|
088b0cf1e7 | ||
|
|
e6061fdd9c | ||
|
|
cf8a30cc4e | ||
|
|
6ba1e10b8b | ||
|
|
2a96864c07 | ||
|
|
48fceac0fe | ||
|
|
ad246deb9e | ||
|
|
c2509fad9c | ||
|
|
eeb216e08d | ||
|
|
2761608c1e | ||
|
|
27536388f2 | ||
|
|
21c8bd54f5 | ||
|
|
fa5619fad7 | ||
|
|
022c59a094 | ||
|
|
bc8abdfc62 | ||
|
|
d8cffc4b22 | ||
|
|
312760f86a | ||
|
|
5ea22c602c | ||
|
|
7540aa6b72 | ||
|
|
84cc89832b | ||
|
|
9554079e4b | ||
|
|
481faf8da1 | ||
|
|
fd6c7cd48f | ||
|
|
9441ea572d | ||
|
|
0414e4a6a6 | ||
|
|
158f14df89 | ||
|
|
93a80fe256 | ||
|
|
398e10588c | ||
|
|
6d1f610085 | ||
|
|
bd95dad85e | ||
|
|
bf8301bd6a | ||
|
|
231006ab26 | ||
|
|
744f4d0f42 | ||
|
|
ad269751b8 | ||
|
|
4c77f07bc9 | ||
|
|
e974cb8ec5 | ||
|
|
48c02e1018 | ||
|
|
f398ee90b0 | ||
|
|
23fcdc0365 | ||
|
|
e91da1cd8d | ||
|
|
4e0d3725cb | ||
|
|
f45cb1560f | ||
|
|
7214b9f2c2 | ||
|
|
37990996b7 | ||
|
|
024b58097e | ||
|
|
2cc1fe7fe2 | ||
|
|
e0cd48df92 | ||
|
|
d45d2f5123 | ||
|
|
eb5e2c94a3 | ||
|
|
ced74f5b45 | ||
|
|
01e557a689 | ||
|
|
b8b01558ce | ||
|
|
08c90e0909 | ||
|
|
052408982a | ||
|
|
68c57cc4eb | ||
|
|
9eb4f3f843 | ||
|
|
4ad7b38648 | ||
|
|
ce2463588d | ||
|
|
9804e3eca0 | ||
|
|
e9fb3a3ebb | ||
|
|
b65b97870f | ||
|
|
0c243e0dc2 | ||
|
|
d88b1fbec0 | ||
|
|
0781cb1d41 | ||
|
|
eb2ed341a2 | ||
|
|
e5f6824304 | ||
|
|
880124bbe0 | ||
|
|
b719fd1c15 | ||
|
|
464b431741 | ||
|
|
ff0e4f50da | ||
|
|
8ba23e84ca | ||
|
|
4cbddf66d3 | ||
|
|
9ba9c3b9c5 | ||
|
|
adbcc07bae | ||
|
|
83ed6a4297 | ||
|
|
1c07974f6c | ||
|
|
c3e430b472 | ||
|
|
a8fef06aa8 | ||
|
|
281eb346a5 | ||
|
|
15c8bd7d6d | ||
|
|
d0d1da3456 | ||
|
|
7c73ff78bc | ||
|
|
e0309dc6c0 | ||
|
|
cd6009c180 | ||
|
|
29bd4e96d6 | ||
|
|
5d5ca0d7aa | ||
|
|
e7df4b8d6d | ||
|
|
fbd8a97ffd | ||
|
|
4147ffa503 | ||
|
|
be2ef79686 | ||
|
|
120406d115 | ||
|
|
d72ae6102b | ||
|
|
4adfad8708 | ||
|
|
2e6d65378f | ||
|
|
4ec1a9af39 | ||
|
|
1109bd35e7 | ||
|
|
24dc12023b | ||
|
|
f53be57f0d | ||
|
|
9db4559b0c | ||
|
|
23a249ca0f | ||
|
|
3171958a8c | ||
|
|
422f1b2b5e | ||
|
|
fed3ec9616 | ||
|
|
751867d5b8 | ||
|
|
c4fcc59efd | ||
|
|
528bbba6ed | ||
|
|
905c05ba06 | ||
|
|
fcacf28c45 | ||
|
|
3e5d82c665 | ||
|
|
1bea7654b8 | ||
|
|
38ea778ccf | ||
|
|
31f300f6d8 | ||
|
|
4e8bb688aa | ||
|
|
563d623278 | ||
|
|
24790e8b2a | ||
|
|
58806dee68 | ||
|
|
4fda12b512 | ||
|
|
0c62465a22 | ||
|
|
785b0caaf2 | ||
|
|
3d4c50d481 | ||
|
|
c0975ed15e | ||
|
|
ce6de6efa6 | ||
|
|
561c1fc338 | ||
|
|
e94affe588 | ||
|
|
43e3648ba7 | ||
|
|
63938c6fd3 | ||
|
|
9cab4d510a | ||
|
|
41621826d8 | ||
|
|
2149030dbb | ||
|
|
8c0bd7e5e3 | ||
|
|
5283682c47 | ||
|
|
b53d20d2ee | ||
|
|
ed6bdf97d1 | ||
|
|
93cfa564f7 | ||
|
|
579b8fce96 | ||
|
|
d1d9462423 | ||
|
|
299f9c4a26 | ||
|
|
5c27e974fb | ||
|
|
53bd4b1ea9 | ||
|
|
3d10fff7de | ||
|
|
8107d65504 | ||
|
|
9a4cebfb61 | ||
|
|
5c81833415 | ||
|
|
d88ca50de0 | ||
|
|
b75b53d05a | ||
|
|
c2cae5b2fc | ||
|
|
30e962b447 | ||
|
|
f710bb535e | ||
|
|
814b02900b | ||
|
|
4958353335 | ||
|
|
9884c52c4e | ||
|
|
0cd4fc8655 | ||
|
|
5d07c5a0b2 | ||
|
|
cf20b3a3c3 | ||
|
|
dbe4acd47d | ||
|
|
b7a0f5bee5 | ||
|
|
0adb62b485 | ||
|
|
a439608fe7 | ||
|
|
e82efd24d3 | ||
|
|
3d1f3ed068 | ||
|
|
bac972de53 | ||
|
|
95310991b8 | ||
|
|
f60a759dca | ||
|
|
4f6f829dc3 | ||
|
|
8962ebd175 | ||
|
|
218b3c87db | ||
|
|
c12a0f8cdf | ||
|
|
4a41ccb4e6 | ||
|
|
0d1f53d58d | ||
|
|
fea07917fa | ||
|
|
003c2e0dca | ||
|
|
ce38ef6289 | ||
|
|
2457c58817 | ||
|
|
ab6dd66bad | ||
|
|
d430fe35c5 | ||
|
|
9650c71155 | ||
|
|
95da7551d2 | ||
|
|
667473f90e | ||
|
|
cf9e17ebfd | ||
|
|
ec55909305 | ||
|
|
3e03f7c12a | ||
|
|
edc2005b2c | ||
|
|
72f3fa6eda | ||
|
|
48c02c6f55 | ||
|
|
8b7643332b | ||
|
|
639619ff93 | ||
|
|
0a08ef0ed4 | ||
|
|
b3f35c579b | ||
|
|
bcb74d01b6 | ||
|
|
8a8b88af13 | ||
|
|
58ed405c88 | ||
|
|
a3d4f80599 | ||
|
|
7bfd55f3f0 | ||
|
|
153b5de1d4 | ||
|
|
932b7a094d | ||
|
|
47b8c661e7 | ||
|
|
3bb0f51d08 | ||
|
|
32fc5ccd3e | ||
|
|
4f3cba32da | ||
|
|
b2c60ba884 | ||
|
|
537ed2d11f | ||
|
|
f318cc5e28 | ||
|
|
1001cc607e | ||
|
|
35d480bc48 | ||
|
|
37f51ef983 | ||
|
|
943d7ce31a | ||
|
|
bc54ddf19f | ||
|
|
7d091d18ee | ||
|
|
599e24634c | ||
|
|
e998edd083 | ||
|
|
e15ca55558 | ||
|
|
23a2801284 | ||
|
|
9a6da3f46f | ||
|
|
fbb881bb42 | ||
|
|
87d65c150b | ||
|
|
bb2fcd5b00 |
No files matched your search
@@ -31,9 +31,12 @@ OctoPrint.egg-info
|
||||
*.codekit
|
||||
|
||||
venv
|
||||
venv2
|
||||
venv3
|
||||
venv26
|
||||
venv27
|
||||
venv33
|
||||
venv34
|
||||
venv35
|
||||
venv36
|
||||
venv37
|
||||
+11
-1
@@ -1,12 +1,22 @@
|
||||
---
|
||||
|
||||
language: python
|
||||
dist: xenial
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- python: '3.7'
|
||||
env: RUN_FLAKE8=true
|
||||
|
||||
python:
|
||||
- "3.7"
|
||||
- "3.6"
|
||||
- "2.7"
|
||||
install:
|
||||
- pip install -e .[develop]
|
||||
script:
|
||||
- nosetests --with-doctest
|
||||
- test -n "$RUN_FLAKE8" || pytest
|
||||
- test -z "$RUN_FLAKE8" || flake8 --ignore=D,E,W,F401 src/ tests setup.py
|
||||
sudo: false
|
||||
git:
|
||||
depth: 250
|
||||
+12
-9
@@ -18,16 +18,19 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.12
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.13
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
fix/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
improve/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
maintenance 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
fix/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
improve/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.12rc2
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.12rc4
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.12rc2 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
regressionfix/.* 1.3.12rc2 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
staging/maintenance 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 pep440-dev
|
||||
regressionfix/.* 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 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
|
||||
# staging/devel is currently the branch for preparation of 1.4.0rc3
|
||||
staging/devel 1.4.0rc3 e603b98d0dc552e570034aae52291737695dd0f6 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.5.0-dev for now
|
||||
.* 1.5.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
|
||||
+8
-1
@@ -69,12 +69,13 @@ date of first contribution):
|
||||
* [Philipp Baum](https://github.com/philphilphil)
|
||||
* [Kyle Evans](https://github.com/kevans91)
|
||||
* [Javier Martínez Arrieta](https://github.com/Javierma)
|
||||
* ["MirceaDan"](https://github.com/ByReaL)
|
||||
* [Mircea Dan Gheorghe](https://github.com/ByReaL)
|
||||
* [Ovidiu Hossu](https://github.com/MoonshineSG)
|
||||
* [Eyck Jentzsch](https://github.com/eyck)
|
||||
* [Mathias Rangel Wulff](https://github.com/mathiasrw)
|
||||
* [Clemens Niemeyer](https://github.com/clemniem)
|
||||
* ["I-am-me"](https://github.com/I-am-me)
|
||||
* [J-J Heinonen](https://github.com/jammi)
|
||||
* [Noah Martin](https://github.com/noahsmartin)
|
||||
* [Eyal Soha](https://github.com/eyal0)
|
||||
* [Greg Hulands](https://github.com/ghulands)
|
||||
@@ -91,11 +92,13 @@ date of first contribution):
|
||||
* [Ganey](https://github.com/ganey)
|
||||
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
||||
* [Andy Castille](https://github.com/klikini)
|
||||
* [Zachary Nofzinger](https://github.com/ZachNo)
|
||||
* [Gaston Dombiak](https://github.com/gdombiak)
|
||||
* [Brad Fisher](https://github.com/bradcfisher)
|
||||
* [Aldo Hoeben](https://github.com/fieldofview)
|
||||
* [Henning Groß](https://github.com/hgross)
|
||||
* [Jubaleth](https://github.com/jubaleth)
|
||||
* [Matthias Urlichs](https://github.com/smurfix)
|
||||
* [Daniel Joyce](https://github.com/DanielJoyce)
|
||||
* [Andy Qua](https://github.com/AndyQ)
|
||||
* [Fabio Santos](https://github.com/Fabi0San)
|
||||
@@ -108,6 +111,10 @@ date of first contribution):
|
||||
* [Piotr Usewicz](https://github.com/pusewicz)
|
||||
* [Aliaksei Pilko](https://github.com/aliaksei135)
|
||||
* [Ben Yarmis](https://github.com/byarmis)
|
||||
* [Florian Heilmann](https://github.com/FHeilmann)
|
||||
* [Ludovico de Nittis](https://github.com/RyuzakiKK)
|
||||
* [Dominik Paľo](https://github.com/DominikPalo)
|
||||
* [Kelly Anderson](https://github.com/cbxbiker61)
|
||||
|
||||
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
|
||||
|
||||
+3
-1293
File diff suppressed because it is too large.
Load diff
@@ -61,7 +61,7 @@ which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
The generic steps that should basically be done regardless of operating system
|
||||
and runtime environment are the following (as *regular
|
||||
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
|
||||
you already have Python 2.7, pip and virtualenv set up on your system:
|
||||
you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your system:
|
||||
|
||||
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
|
||||
2. Change into the OctoPrint folder: `cd OctoPrint`
|
||||
@@ -84,7 +84,7 @@ OctoPrint via `pip`:
|
||||
|
||||
You should do this every time after pulling from the repository, since the dependencies may have changed.
|
||||
|
||||
OctoPrint currently only supports Python 2.7.
|
||||
OctoPrint currently supports Python 2.7, 3.6 and 3.7.
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Always update to the latest version of OctoPrint to keep up with security patches.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Email to security@octoprint.org.
|
||||
|
||||
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
|
||||
+12
-8
@@ -8,34 +8,38 @@ thanks to everyone who contributed!
|
||||
|
||||
* Andre Bubel
|
||||
* Andrew Moorby
|
||||
* ANTONIO AUGUSTO DE LIMA PONTES
|
||||
* Arnljot Arntsen
|
||||
* BigTreeTech
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* COLLE+McVOY
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Dorian Gray
|
||||
* E3D BigBox
|
||||
* Eric Betts
|
||||
* Ernesto Martinez
|
||||
* Franziska Kunsmann
|
||||
* GadgetAngel
|
||||
* George Robles
|
||||
* Greg Holloway
|
||||
* Hugh Blemings
|
||||
* jean-claude migneault
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
* John Robinson (JRo)
|
||||
* Joshua Wills
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kenneth Jiang
|
||||
* Kyle Menigoz
|
||||
* LA 3D Printer Repair
|
||||
* LulzBot®
|
||||
* Lee Dohm
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Martin Majewski
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* Mosaic Manufacturing
|
||||
@@ -46,14 +50,14 @@ thanks to everyone who contributed!
|
||||
* Randy C. Will
|
||||
* Ranjib Dey
|
||||
* Robert Gusek
|
||||
* Samer Najia
|
||||
* Ronald Griehsler
|
||||
* Shawn Lewis
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Sven Mueller
|
||||
* TEVO 3D Printers
|
||||
* The3DprintingMagic.com
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
* Vladislav Kuzemchik
|
||||
|
||||
and 1587 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1678 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
@@ -9,6 +9,7 @@
|
||||
* [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
|
||||
* [css-element-queries](https://github.com/marcj/css-element-queries): MIT
|
||||
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
|
||||
* [Flot](http://www.flotcharts.org/): MIT
|
||||
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
.. _sec-api-apps:
|
||||
|
||||
****
|
||||
Apps
|
||||
****
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-apps-sessionkey:
|
||||
|
||||
Session Keys
|
||||
============
|
||||
|
||||
.. deprecated:: 1.3.11
|
||||
|
||||
This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` instead.
|
||||
|
||||
OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based
|
||||
validity and are generated by OctoPrint for requesting apps.
|
||||
|
||||
Obtaining those keys is based on a handshake procedure backed by cryptographic signatures using RSA. OctoPrint needs to
|
||||
be aware of apps and their associated public keys (this can be achieved either via entries in ``config.yaml`` or by
|
||||
installing app specific plugins which implement the ``AppPlugin`` type).
|
||||
|
||||
Apps can be registered within OctoPrint via ``config.yaml`` by adding them to the ``api`` > ``apps`` section, using the
|
||||
application's id concatenated with its version as key, with the public key provided as item ``pubkey`` (stripped of the
|
||||
``BEGIN RSA PUBLIC KEY`` and ``END RSA PUBLIC KEY`` separators and also newlines) and optionally also whether the app is
|
||||
enabled or not (defaults to enabled, so can be left out if it's not to be set to disabled explicitly).
|
||||
|
||||
Example:
|
||||
|
||||
.. sourcecode:: yaml
|
||||
|
||||
api:
|
||||
apps:
|
||||
"com.example.my_octoprint_app:0.9":
|
||||
pubkey: MEgCQQDYkr5Fv/YXK5ZL1uwRN4A61IagZaYLGqJ5JJGFo8wDrmpAMRqE9kK4+5hIDblC5DzfEr5oP7OA3tRO48Rf5yInAgMBAAE=
|
||||
enabled: false
|
||||
"com.example.my_octoprint_app:1.0":
|
||||
pubkey: MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4osvb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
|
||||
|
||||
In the example, the app ``com.example.my_octoprint_app`` in version 0.9 has been disabled (e.g. due to the key having
|
||||
leaked) whereas version 1.0 is fully registered with OctoPrint and may verify app session keys.
|
||||
|
||||
|
||||
.. _sec-api-apps-sessionkey-workflow:
|
||||
|
||||
Workflow
|
||||
--------
|
||||
|
||||
Apps perform the handshake by first requesting a temporary key with very limited validity,
|
||||
then sending a message back to OctoPrint containing their id, version, the temporary key and a signature created with their
|
||||
private key over these three pieces of data. OctoPrint then tries to verify the signature and if successful unlocks the
|
||||
key to be used as a fully recognized API key.
|
||||
|
||||
For performing the handshake a special API exists within OctoPrint for which no API key is needed which is described below.
|
||||
|
||||
.. _sec-api-apps-sessionkey-get:
|
||||
|
||||
Obtaining a temporary session key
|
||||
---------------------------------
|
||||
|
||||
.. http:get:: /apps/auth
|
||||
|
||||
Retrieve a temporary session key with a minimum validity. It can only be used as a proper API key after having been
|
||||
:ref:`verified <sec-api-apps-sessionkey-verify>`.
|
||||
|
||||
Returns the temporary session key and the timestamp until it's valid.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /apps/auth HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"unverifiedKey": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"validUntil": 1416220357.011
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-apps-sessionkey-verify:
|
||||
|
||||
Verifying a temporary session key
|
||||
---------------------------------
|
||||
|
||||
.. http:post:: /apps/auth
|
||||
|
||||
Verify a formerly :ref:`retrieved <sec-api-apps-sessionkey-get>` temporary session key by providing credentials and a
|
||||
cryptographic signature over these credentials and the temporary key.
|
||||
|
||||
Returns the now verified session key and the new validity.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /apps/auth HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"appid": "com.example.my_octoprint_app",
|
||||
"appversion": "1.0",
|
||||
"key": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"_sig": "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"key": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"validUntil": 1416227497.011
|
||||
}
|
||||
|
||||
.. _sec-api-apps-sessionkey-signature:
|
||||
|
||||
Creating the signature
|
||||
----------------------
|
||||
|
||||
The signature is created by concatenating the ``appid``, ``appversion`` and ``key`` fields, separated by a ``:`` (colon),
|
||||
signing the result with the app's private key using SHA-1 and then BASE64-encoding the result, stripping newlines.
|
||||
|
||||
Example for signature generation using Python and the `Python RSA library <https://pypi.python.org/pypi/rsa>`_:
|
||||
|
||||
.. sourcecode:: python
|
||||
|
||||
import base64
|
||||
import rsa
|
||||
|
||||
appid = "com.example.my_octoprint_app"
|
||||
version = "1.0"
|
||||
unverified_key = "F43A844750F74AD080FE9F438D47B33C"
|
||||
message_to_sign = appid + ":" + version + ":" + unverified_key
|
||||
// => "com.example.my_octoprint_app:1.0:F43A844750F74AD080FE9F438D47B33C"
|
||||
|
||||
private_key = rsa.PrivateKey.load_pkcs1("...")
|
||||
signature = base64.encodestring(rsa.sign(message_to_sign, private_key, "SHA-1")).replace("\n", "")
|
||||
// => "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
|
||||
|
||||
|
||||
.. _sec-api-apps-sessionkey-testing:
|
||||
|
||||
Testing your implementation
|
||||
---------------------------
|
||||
|
||||
If you want to use app session keys, here is the key pair with which the above examples were created, in order for you
|
||||
to verify your signature implementation::
|
||||
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIBPQIBAAJBAIhZ+Ls1zxtyd9kkm0DprhHIwL6woGUw5vbk5U00Hgva/ROIY7va
|
||||
NUpHiiy9vijO2VtFbkaR2JjRPYslx8Ni+QkCAwEAAQJARK4lFo+FEcs3yR2iQjEy
|
||||
p+yaAbNQJ4hZXlVvltLAYICzOM3kyKx53/eKU59NjskLz9q6QxfleymYPWAgl4NW
|
||||
fQIjAJVH8MjwNcaAquTM9z2OiFi3OC8WgaKOi5W/T+r2+B70wG8CHwDp08dqOZ/u
|
||||
xcBiy4Wzpcme9bckqoVuS3gWMm+YqgcCIwCMFU07kkY0NyumtzxPdIA4F/7OGSWf
|
||||
IHqWFEfvasAddHlbAh8A5UgkB3Zf7Bt+7aFSBnlvve6FWm/XDPL12xYztYgrAiIa
|
||||
W3miN6FjIm+8TDowrk+nyYXG2GZefeY7QXOjYr6tlDn0
|
||||
-----END RSA PRIVATE KEY-----
|
||||
|
||||
-----BEGIN RSA PUBLIC KEY-----
|
||||
MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4os
|
||||
vb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
|
||||
-----END RSA PUBLIC KEY-----
|
||||
|
||||
@@ -148,8 +148,14 @@ Login
|
||||
via the ``passive`` flag.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
|
||||
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`403` in
|
||||
case of a username/password mismatch, unknown user or a deactivated account.
|
||||
|
||||
.. warning::
|
||||
|
||||
Previous versions of this API endpoint did return a :http:statuscode:`401` in case of a username/password
|
||||
mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of
|
||||
the :http:statuscode:`401` code and got therefore changed as part of a bug fix.
|
||||
|
||||
:json passive: If present, performs a passive login only, returning information about the current user that's
|
||||
active either through an existing session or the used API key
|
||||
@@ -157,8 +163,7 @@ Login
|
||||
:json pass: (active login only) Password
|
||||
:json remember: (active login only) Whether to set a "remember me" cookie on the session
|
||||
:status 200: Successful login
|
||||
:status 401: Username/password mismatch or unknown user
|
||||
:status 403: Deactivated account
|
||||
:status 403: Username/password mismatch, unknown user or deactivated account
|
||||
|
||||
.. _sec-api-general-logout:
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ REST API
|
||||
|
||||
general.rst
|
||||
version.rst
|
||||
apps.rst
|
||||
connection.rst
|
||||
files.rst
|
||||
job.rst
|
||||
|
||||
@@ -514,6 +514,8 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
-
|
||||
* - ``webcam.ffmpegThreads``
|
||||
-
|
||||
* - ``webcam.ffmpegVideoCodec``
|
||||
-
|
||||
* - ``webcam.watermark``
|
||||
-
|
||||
* - ``webcam.flipH``
|
||||
|
||||
+47
-23
@@ -38,30 +38,21 @@ List all registered system commands
|
||||
{
|
||||
"action": "shutdown",
|
||||
"name": "Shutdown",
|
||||
"command": "sudo shutdown -h now",
|
||||
"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",
|
||||
"resource": "http://example.com/api/system/commands/core/shutdown"
|
||||
},
|
||||
{
|
||||
"action": "reboot",
|
||||
"name": "Reboot",
|
||||
"command": "sudo reboot",
|
||||
"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",
|
||||
"resource": "http://example.com/api/system/commands/core/reboot"
|
||||
},
|
||||
{
|
||||
"action": "restart",
|
||||
"name": "Restart OctoPrint",
|
||||
"command": "sudo service octoprint restart",
|
||||
"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",
|
||||
"resource": "http://example.com/api/system/commands/core/restart"
|
||||
}
|
||||
@@ -99,30 +90,21 @@ List all registered system commands for a source
|
||||
{
|
||||
"action": "shutdown",
|
||||
"name": "Shutdown",
|
||||
"command": "sudo shutdown -h now",
|
||||
"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,
|
||||
"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).",
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/shutdown"
|
||||
},
|
||||
{
|
||||
"action": "reboot",
|
||||
"name": "Reboot",
|
||||
"command": "sudo reboot",
|
||||
"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,
|
||||
"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).",
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/reboot"
|
||||
},
|
||||
{
|
||||
"action": "restart",
|
||||
"name": "Restart OctoPrint",
|
||||
"command": "sudo service octoprint restart",
|
||||
"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,
|
||||
"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).",
|
||||
"source": "core",
|
||||
"resource": "http://example.com/api/system/commands/core/restart"
|
||||
}
|
||||
@@ -184,18 +166,60 @@ List all response
|
||||
- Description
|
||||
* - ``core``
|
||||
- 0..n
|
||||
- List of :ref:`command definitions <sec-api-system-commands-definiton>`
|
||||
- List of :ref:`client command definitions <sec-api-client-system-commands-definiton>`
|
||||
- List of all core commands defined.
|
||||
* - ``custom``
|
||||
- 0..n
|
||||
- List of :ref:`command definitions <sec-api-system-commands-definiton>`
|
||||
- List of :ref:`client command definitions <sec-api-client-system-commands-definiton>`
|
||||
- List of all custom commands defined in ``config.yaml``.
|
||||
|
||||
.. _sec-api-client-system-commands-definiton:
|
||||
|
||||
Client command definitions
|
||||
--------------------------
|
||||
|
||||
A restricted form of the full :ref:`command definition <sec-api-system-commands-definiton>`.
|
||||
For exposing via the API.
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The name of the command to display in the System menu.
|
||||
* - ``action``
|
||||
- 1
|
||||
- string
|
||||
- An identifier to refer to the command programmatically. The special ``action`` string
|
||||
``divider`` signifies a divider in the menu.
|
||||
* - ``confirm``
|
||||
- 0..1
|
||||
- string
|
||||
- If present and set, this text will be displayed to the user in a confirmation dialog
|
||||
they have to acknowledge in order to really execute the command.
|
||||
* - ``source``
|
||||
- 1
|
||||
- string
|
||||
- Source of the command definition, currently either ``core`` (for system actions defined by
|
||||
OctoPrint itself) or ``custom`` (for custom system commands defined by the user through ``config.yaml``).
|
||||
* - ``resource``
|
||||
- 1
|
||||
- string
|
||||
- The URL of the command to use for executing it.
|
||||
|
||||
.. _sec-api-system-commands-definiton:
|
||||
|
||||
Command definition
|
||||
------------------
|
||||
|
||||
The full command definition is not available via the API.
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
@@ -27,7 +27,7 @@ Command line usage
|
||||
------------------
|
||||
|
||||
The Backup Plugin implements a command line interface that allows creation and restoration of backups.
|
||||
It adds two new commands, ``backup:backup`` and ``backup_restore``.
|
||||
It adds two new commands, ``backup:backup`` and ``backup:restore``.
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ network running Microsoft Windows. You will be able to just double click on the
|
||||
OctoPrint instance icon in "Networks > Other Devices" in your Windows Explorer,
|
||||
which will take you directly to the web frontend.
|
||||
|
||||
The ZeroConf support allows OctoPrint to announce itself to Safari on MacOS X
|
||||
The ZeroConf support allows OctoPrint to announce itself to Safari on macOS
|
||||
on the same network.
|
||||
|
||||
Linux users should install `Avahi <http://avahi.org>`_ and can then use one
|
||||
|
||||
@@ -196,6 +196,10 @@ Version checks
|
||||
* ``checkout_folder``: (mandatory) The full path to the folder with a valid git
|
||||
repository to check.
|
||||
|
||||
* ``pypi_release``: Checks `pypi.org <https://pypi.org>`_ for new releases of a specified package.
|
||||
|
||||
* ``package``: (mandatory) Name of the package which to check.
|
||||
|
||||
* ``command_line``: Uses a provided script to determine whether an update
|
||||
is available. Additional config parameters:
|
||||
|
||||
@@ -385,8 +389,8 @@ octoprint.plugin.softwareupdate.check_config
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
def get_update_information(*args, **kwargs):
|
||||
return dict(
|
||||
|
||||
+10
-8
@@ -1,4 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
#
|
||||
# OctoPrint documentation build configuration file, created by
|
||||
# sphinx-quickstart on Mon Dec 02 17:08:50 2013.
|
||||
@@ -49,8 +51,8 @@ source_suffix = '.rst'
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'OctoPrint'
|
||||
copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%d, Gina Häußge' % year_since
|
||||
project = 'OctoPrint'
|
||||
copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
@@ -207,8 +209,8 @@ htmlhelp_basename = 'OctoPrintdoc'
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
#latex_documents = [
|
||||
# ('index', 'OctoPrint.tex', u'OctoPrint Documentation',
|
||||
# u'Gina Häußge', 'manual'),
|
||||
# ('index', 'OctoPrint.tex', 'OctoPrint Documentation',
|
||||
# 'Gina Häußge', 'manual'),
|
||||
#]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
@@ -237,8 +239,8 @@ htmlhelp_basename = 'OctoPrintdoc'
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'octoprint', u'OctoPrint Documentation',
|
||||
[u'Gina Häußge'], 1)
|
||||
('index', 'octoprint', 'OctoPrint Documentation',
|
||||
['Gina Häußge'], 1)
|
||||
]
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
@@ -251,8 +253,8 @@ man_pages = [
|
||||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
('index', 'OctoPrint', u'OctoPrint Documentation',
|
||||
u'Gina Häußge', 'OctoPrint', 'One line description of project.',
|
||||
('index', 'OctoPrint', 'OctoPrint Documentation',
|
||||
'Gina Häußge', 'OctoPrint', 'One line description of project.',
|
||||
'Miscellaneous'),
|
||||
]
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ config.yaml
|
||||
|
||||
If not specified via the command line, the main configuration file ``config.yaml`` for OctoPrint is expected in its
|
||||
settings folder, which unless defined differently via the command line is located at ``~/.octoprint`` on Linux, at
|
||||
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on MacOS. If the file is not there,
|
||||
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on macOS. If the file is not there,
|
||||
you can just create it - it will only get created by OctoPrint once you save settings that deviate from the default
|
||||
settings.
|
||||
|
||||
@@ -29,7 +29,7 @@ Use the following settings to enable access control:
|
||||
# The user manager implementation to use for accessing user information. Currently only a filebased
|
||||
# user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml
|
||||
# in the default configuration folder, see below)
|
||||
userManager: octoprint.users.FilebasedUserManager
|
||||
userManager: octoprint.access.users.FilebasedUserManager
|
||||
|
||||
# The YAML user file to use. If left out defaults to users.yaml in the default configuration folder.
|
||||
userFile: /path/to/users.yaml
|
||||
@@ -290,6 +290,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# Whether to delete generated web assets on server startup (forcing a regeneration)
|
||||
clean_on_startup: true
|
||||
|
||||
# enable or disable the loading animation
|
||||
showLoadingAnimation: true
|
||||
|
||||
# Settings for the virtual printer
|
||||
virtualPrinter:
|
||||
|
||||
@@ -684,6 +687,11 @@ plugins are tracked:
|
||||
_disabled:
|
||||
- ...
|
||||
|
||||
# Identifiers of plugins for which python compatibility information will be ignored and
|
||||
# the plugin considered compatible in any case. Only for development, do NOT use in production.
|
||||
_forcedCompatible:
|
||||
- ...
|
||||
|
||||
# The rest are individual plugin settings, each tracked by their identifier, e.g.:
|
||||
some_plugin:
|
||||
some_setting: true
|
||||
@@ -1244,6 +1252,9 @@ Use the following settings to configure webcam support:
|
||||
# Should be left at 1 for RPi1.
|
||||
ffmpegThreads: 1
|
||||
|
||||
# Videocodec to be used for encoding. Defaults to mpeg2video.
|
||||
ffmpegVideoCodec: mpeg2video
|
||||
|
||||
# The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg.
|
||||
bitrate: 5000k
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ logging.yaml
|
||||
|
||||
The logging configuration file ``logging.yaml`` for OctoPrint is expected in its settings folder, which unless defined
|
||||
differently on the command line is located at ``~/.octoprint`` on Linux, at ``%APPDATA%/OctoPrint`` on Windows and at
|
||||
``~/Library/Application Support/OctoPrint`` on MacOS.
|
||||
``~/Library/Application Support/OctoPrint`` on macOS.
|
||||
|
||||
You can use it to change the log levels of the individual components within OctoPrint, which might be necessary to help
|
||||
in debugging issues you are experiencing, or to change the configuration of the logging handlers themselves, e.g. in
|
||||
|
||||
@@ -14,18 +14,34 @@ below.
|
||||
* Prerequisites:
|
||||
|
||||
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Python 3.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``
|
||||
* Checkout the OctoPrint sources from their Git repository:
|
||||
|
||||
* ``git clone -b devel 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``
|
||||
* Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for
|
||||
installing and running OctoPrint and its dependencies (this avoids potential versioning issues for the dependencies
|
||||
with system wide installed instances):
|
||||
|
||||
* PY2: ``virtualenv --python=python2 venv2``
|
||||
* PY3: ``virtualenv --python=python3 venv3``
|
||||
|
||||
* Activate one of the virtual environments:
|
||||
|
||||
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
* PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
|
||||
* 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]``
|
||||
including its regular *and* development and plugin development dependencies:
|
||||
|
||||
* ``pip install -e .[develop,plugins]``
|
||||
|
||||
When the virtual environment is activated you can then:
|
||||
|
||||
@@ -33,11 +49,19 @@ When the virtual environment is activated you can then:
|
||||
* 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``
|
||||
|
||||
To switch the activated virtual environment, simply activate the new environment as described above.
|
||||
|
||||
To deactivate the virtual environment and return to the system's default Python: ``deactivate``.
|
||||
|
||||
.. _sec-development-environment-source-linux:
|
||||
|
||||
Linux
|
||||
.....
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
@@ -70,7 +94,7 @@ Then:
|
||||
.. code-block:: none
|
||||
|
||||
cd ~/devel
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
git clone -b devel https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source ./venv/bin/activate
|
||||
@@ -85,12 +109,16 @@ environment.
|
||||
Windows
|
||||
.......
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
|
||||
|
||||
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/>`_
|
||||
* `Python 2.7.15 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2715/>`_
|
||||
|
||||
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
|
||||
|
||||
@@ -120,6 +148,10 @@ Mac OS X
|
||||
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.
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
@@ -158,6 +190,10 @@ You'll need a user account with administrator privileges.
|
||||
IDE Setup
|
||||
---------
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
|
||||
|
||||
.. todo::
|
||||
|
||||
Using another IDE than the ones below? Please send a
|
||||
@@ -170,8 +206,10 @@ 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
|
||||
- **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
|
||||
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
|
||||
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
|
||||
"Virtualenv Environment > "Existing Environment", select OctoPrint venv folder (e.g. ``~/devel/OctoPrint/venv``)
|
||||
- Right click "src" in project tree, mark as source folder
|
||||
- Add Run/Debug Configuration, select "Python":
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ be found in the full :ref:`config.yaml documentation <sec-configuration-config_y
|
||||
|
||||
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.
|
||||
* 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
|
||||
|
||||
+19
-2
@@ -104,7 +104,8 @@ ClientOpened
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that connected
|
||||
* ``remoteAddress``: the remote address (IP) of the client that connected. On the push socket only available with
|
||||
a valid login session.
|
||||
|
||||
**Note:** Name changed in version 1.1.0
|
||||
|
||||
@@ -115,6 +116,19 @@ ClientClosed
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
|
||||
UserLoggedIn
|
||||
A user logged in. On the push socket only available with a valid login session with admin rights.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``username``: the name of the user who logged in
|
||||
|
||||
UserLoggedOut
|
||||
A user logged out. On the push socket only available with a valid login session with admin rights.
|
||||
|
||||
Payload:
|
||||
* ``username``: the name of the user who logged out
|
||||
|
||||
ConnectivityChanged
|
||||
The server's internet connectivity changed
|
||||
|
||||
@@ -151,6 +165,9 @@ Error
|
||||
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
|
||||
on the connection.
|
||||
|
||||
Note that this event will not fire for error messages from the firmware that are handled (and as such recovered from)
|
||||
either by OctoPrint or a plugin.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``error``: the error string
|
||||
@@ -669,7 +686,7 @@ SettingsUpdated
|
||||
.. _sec-events-available_events-printer_profile:
|
||||
|
||||
Printer Profile
|
||||
--------
|
||||
---------------
|
||||
|
||||
PrinterProfileModified
|
||||
A printer profile was modified.
|
||||
|
||||
@@ -11,7 +11,7 @@ is clicked.
|
||||
|
||||
Unless :ref:`configured otherwise <sec-configuration-config_yaml-folder>`, OctoPrint expects scripts to be located in
|
||||
the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint``
|
||||
on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS).
|
||||
on Windows and ``~/Library/Application Support/OctoPrint`` on macOS).
|
||||
|
||||
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
|
||||
|
||||
@@ -75,12 +75,12 @@ When OctoPrint is running in safe mode the following changes to its normal opera
|
||||
* OctoPrint will not enable any of the installed third party plugins. OctoPrint considers all plugins third
|
||||
party plugins that do not ship with OctoPrint's sources, so any plugins installed either via `pip` or
|
||||
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint/plugins`` (Windows) and
|
||||
``~/Library/Application Support/OctoPrint/plugins`` (MacOS).
|
||||
``~/Library/Application Support/OctoPrint/plugins`` (macOS).
|
||||
* OctoPrint will not enable any of the installed third party language packs. OctoPrint considers all language packs
|
||||
third party language packs that do not ship with OctoPrint's sources, so any language plugins installed
|
||||
through the language pack manager within settings and/or stored in the language pack folder at
|
||||
``~/.octoprint/translations`` (Linux), ``%APPDATA%/OctoPrint/translations`` (Windows) or
|
||||
``~/Library/Application Support/OctoPrint/translations`` (MacOS).
|
||||
``~/Library/Application Support/OctoPrint/translations`` (macOS).
|
||||
* OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager.
|
||||
* OctoPrint will still allow to disable (bundled) plugins that are still enabled.
|
||||
* OctoPrint will not allow to enable third party plugins.
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
To register for all message types, provide ``*`` as the type to register for.
|
||||
|
||||
``handler`` is expected to be a function accepting one object parameter ``eventObj``, consisting
|
||||
of the received message as property ``key`` and the received payload (if any) as property ``data``.
|
||||
of the received message as property ``event`` and the received payload (if any) as property ``data``.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
.. _sec-modules-users:
|
||||
|
||||
octoprint.users
|
||||
---------------
|
||||
octoprint.access.users
|
||||
----------------------
|
||||
|
||||
.. automodule:: octoprint.users
|
||||
.. automodule:: octoprint.access.users
|
||||
:members:
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ plugin subsystem about themselves. These are simple package attributes defined i
|
||||
# ...
|
||||
|
||||
__plugin_name__ = "My Plugin"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
def __plugin_load__():
|
||||
# whatever you need to do to load your plugin, if anything at all
|
||||
pass
|
||||
@@ -52,6 +53,20 @@ The following properties are recognized:
|
||||
``__plugin_license__``
|
||||
License of your plugin, optional, overrides the license specified in ``setup.py`` if provided.
|
||||
|
||||
.. _sec-plugins-controlproperties-plugin_pythoncompat:
|
||||
|
||||
``__plugin_pythoncompat__``
|
||||
Python compatibility string of your plugin, optional, defaults to ``>=2.7,<3`` if not set and thus Python 2 but no
|
||||
Python 3 compatibility.
|
||||
|
||||
If your plugin is compatible to Python 3, you should set this to ``>=2.7,<4``, otherwise your plugin will not load
|
||||
on OctoPrint instances installed under Python 3.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
|
||||
|
||||
.. _sec-plugins-controlproperties-plugin_implementation:
|
||||
|
||||
``__plugin_implementation__``
|
||||
|
||||
@@ -54,8 +54,8 @@ We'll start at the most basic form a plugin can take - just a few simple lines o
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0.0"
|
||||
@@ -89,8 +89,8 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
:emphasize-lines: 4-8,13
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -289,8 +289,8 @@ and ``__plugin_description__`` from ``__init__.py``:
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -314,8 +314,8 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
|
||||
:emphasize-lines: 10
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -362,8 +362,8 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
|
||||
:emphasize-lines: 7
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -428,8 +428,8 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
|
||||
:emphasize-lines: 8, 10, 12-13
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -462,8 +462,8 @@ Adjust your plugin's ``__init__.py`` like this:
|
||||
:emphasize-lines: 15-16
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -569,8 +569,8 @@ again since we don't use that anymore:
|
||||
:emphasize-lines: 15-19
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -666,8 +666,8 @@ like so:
|
||||
:emphasize-lines: 9,22-25
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -846,8 +846,8 @@ a reference to our CSS file:
|
||||
:emphasize-lines: 26
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -931,8 +931,8 @@ Then adjust our returned assets to include our LESS file as well:
|
||||
:emphasize-lines: 27
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
|
||||
+106
-52
@@ -28,6 +28,7 @@ or as ``postfix`` (after the existing lines).
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from past import basestring
|
||||
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
|
||||
|
||||
# ...
|
||||
@@ -35,7 +36,7 @@ or as ``postfix`` (after the existing lines).
|
||||
for hook in self._gcodescript_hooks:
|
||||
try:
|
||||
retval = self._gcodescript_hooks[hook](self, "gcode", scriptName)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing gcodescript hook %s" % hook)
|
||||
else:
|
||||
if retval is None:
|
||||
@@ -44,10 +45,8 @@ or as ``postfix`` (after the existing lines).
|
||||
continue
|
||||
|
||||
def to_list(data):
|
||||
if isinstance(data, str):
|
||||
data = map(str.strip, data.split("\n"))
|
||||
elif isinstance(data, unicode):
|
||||
data = map(unicode.strip, data.split("\n"))
|
||||
if isinstance(data, basestring):
|
||||
data = map(x.strip() for x in data.split("\n"))
|
||||
|
||||
if isinstance(data, (list, tuple)):
|
||||
return list(data)
|
||||
@@ -201,34 +200,93 @@ Available plugin hooks
|
||||
.. contents::
|
||||
:local:
|
||||
|
||||
.. _sec-plugins-hook-accesscontrol-appkey:
|
||||
.. _sec-plugins-hook-permissions:
|
||||
|
||||
octoprint.accesscontrol.appkey
|
||||
octoprint.access.permissions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: additional_permissions_hook(*args, **kwargs)
|
||||
|
||||
Return a list of additional permissions to register in the system on behalf of the plugin. Use this
|
||||
to add granular permissions to your plugin which can be configured for users and user groups in the general
|
||||
access control settings of OctoPrint.
|
||||
|
||||
Additional permissions must be modelled as ``dict``s with at least a ``key`` and ``name`` field. Possible
|
||||
fields are as follows:
|
||||
|
||||
* ``key``: A key for the permission to be used for referring to it from source code. This will turned uppercase
|
||||
and prefixed with ``PLUGIN_<PLUGIN IDENTIFIER>_`` before being made available on ``octoprint.access.permissions.Permissions``,
|
||||
e.g. ``my_permission`` on the plugin with identifier ``example`` turns into ``PLUGIN_EXAMPLE_MY_PERMISSION`` and
|
||||
can be accessed as ``octoprint.access.permissions.Permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the server and
|
||||
``permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the ``AccessViewModel`` on the client. Must only contain a-z, A-Z, 0-9 and _.
|
||||
* ``name``: A human readable name for the permission.
|
||||
* ``description``: A human readable description of the permission.
|
||||
* ``permissions``: A list of permissions this permission includes, by key.
|
||||
* ``roles``: A list of roles this permission includes. Roles are simple strings you define. Usually one role will
|
||||
suffice.
|
||||
* ``dangerous``: Whether this permission should be considered dangerous (``True``) or not (``False``)
|
||||
* ``default_groups``: A list of standard groups this permission should be apply to by default. Standard groups
|
||||
are ``admins``, ``users``, ``readonly`` and ``guests``
|
||||
|
||||
The following example is based on some actual code included in the bundled Application Keys plugin and defines
|
||||
one additional permission called ``ADMIN`` with a role ``admin`` which is marked as dangerous (since it gives
|
||||
access to the management to other user's application keys) and by default will only be given to the standard admin
|
||||
group:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_additional_permissions(*args, **kwargs):
|
||||
return [
|
||||
dict(key="ADMIN",
|
||||
name="Admin access",
|
||||
description=gettext("Allows administrating all application keys"),
|
||||
roles=["admin"],
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.access.permissions": get_additional_permissions
|
||||
}
|
||||
|
||||
Once registered it can be referenced under the key ``PLUGIN_APPKEYS_ADMIN``.
|
||||
|
||||
:return: A list of additional permissions to register in the system.
|
||||
:rtype: A list of dicts.
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.access.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: acl_appkey_hook(*args, **kwargs)
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
|
||||
.. deprecated:: 1.3.11
|
||||
Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
|
||||
This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` instead.
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
By handling this hook plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
|
||||
within the system.
|
||||
* ``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`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
Overrides this to return your additional app information to be used for validating app session keys. You'll
|
||||
need to return a list of 3-tuples of the format (id, version, public key).
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
The ``id`` should be the (unique) identifier of the app. Using a domain prefix might make sense here, e.g.
|
||||
``org.octoprint.example.MyApp``.
|
||||
If none 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.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
``version`` should be a string specifying the version of the app for which the public key is valid. You can
|
||||
provide the string ``any`` here, in which case the provided public key will be valid for all versions of the
|
||||
app for which no specific public key is defined.
|
||||
: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
|
||||
|
||||
Finally, the public key is expected to be provided as a PKCS1 string without newlines.
|
||||
|
||||
:return: A list of 3-tuples as described above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-accesscontrol-keyvalidator:
|
||||
|
||||
@@ -241,7 +299,7 @@ octoprint.accesscontrol.keyvalidator
|
||||
|
||||
``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
|
||||
Hook handlers are expected to return a :class:`~octoprint.access.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.
|
||||
|
||||
@@ -259,7 +317,7 @@ octoprint.accesscontrol.keyvalidator
|
||||
|
||||
: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`
|
||||
:rtype: :class:`~octoprint.access.users.User`
|
||||
|
||||
.. _sec-plugins-hook-cli-commands:
|
||||
|
||||
@@ -1062,9 +1120,8 @@ octoprint.printer.factory
|
||||
* ``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`
|
||||
* ``user_manager``: The :class:`~octoprint.users.UserManager`
|
||||
* ``user_manager``: The :class:`~octoprint.access.users.UserManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance.
|
||||
@@ -1556,37 +1613,34 @@ octoprint.ui.web.templatetypes
|
||||
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
.. _sec-plugins-hook-timelapse-capture-pre:
|
||||
|
||||
octoprint.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
octoprint.timelapse.capture.pre
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
.. py:function:: capture_pre_hook(filename)
|
||||
|
||||
Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
Perform specific actions prior to capturing a timelapse frame.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
``filename`` will be the future path of the frame to be saved.
|
||||
|
||||
* ``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`
|
||||
:param str filename: The future path of the frame to be saved.
|
||||
:return: None
|
||||
:rtype: None
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
.. _sec-plugins-hook-timelapse-capture-post:
|
||||
|
||||
If none 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``.
|
||||
octoprint.timelapse.capture.post
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
: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
|
||||
.. py:function:: capture_post_hook(filename, success)
|
||||
|
||||
Perform specific actions after capturing a timelapse frame.
|
||||
|
||||
``filename`` will be the path of the frame that should have been saved.
|
||||
``sucesss`` indicates whether the capture was successful or not.
|
||||
|
||||
:param str filename: The path of the frame that should have been saved.
|
||||
:param boolean success: Indicates whether the capture was successful or not.
|
||||
:return: None
|
||||
:rtype: None
|
||||
@@ -41,10 +41,8 @@ An overview of these properties follows.
|
||||
OctoPrint's file manager, an instance of :class:`octoprint.filemanager.FileManager`.
|
||||
``self._printer``
|
||||
OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`.
|
||||
``self._app_session_manager``
|
||||
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`.
|
||||
OctoPrint's user manager, an instance of :class:`octoprint.access.users.UserManager`.
|
||||
``self._connectivity_checker``
|
||||
OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`.
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ Now, the execution order of the ``on_after_startup`` method will be determined b
|
||||
|
||||
This will result in the following messages to be generated:
|
||||
|
||||
.. code-block:: plain
|
||||
.. code-block:: none
|
||||
|
||||
Plugin B starting up
|
||||
Plugin C starting up
|
||||
|
||||
+43
-30
@@ -220,6 +220,11 @@ onUserLoggedIn(user)
|
||||
onUserLoggedOut()
|
||||
Called when a user gets logged out of the web app.
|
||||
|
||||
onUserPermissionsChanged(user)
|
||||
Called when a change in the permissions of the current user is detected. The user data of the just logged in user
|
||||
will be provided as only parameter. Note that this may also be triggered for not logged in guests if the guest
|
||||
group is modified. In this case ``user`` will be undefined.
|
||||
|
||||
onTabChange(next, current)
|
||||
Called before the main tab view switches to a new tab, so `before` the new tab becomes visible. Called with the
|
||||
next (changed to) and current (still visible) tab's hash (e.g. ``#control``). Note that ``current`` might be undefined
|
||||
@@ -313,13 +318,13 @@ Web interface startup
|
||||
|
||||
sequenceDiagram
|
||||
participant Main
|
||||
participant onServerConnect
|
||||
participant fetchSettings
|
||||
participant bindViewModels
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
participant SettingsViewModel
|
||||
participant UiStateViewModel
|
||||
|
||||
Note right of DataUpdater: connectCallback = undefined
|
||||
Note over DataUpdater: connectCallback = undefined
|
||||
Note over UiStateViewModel: loaded = false
|
||||
|
||||
activate Main
|
||||
|
||||
@@ -337,52 +342,60 @@ Web interface startup
|
||||
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
|
||||
Main->>+Main: onServerConnect
|
||||
Main->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>Main: ok
|
||||
Main-->>Main: ok
|
||||
deactivate Main
|
||||
deactivate Main
|
||||
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over Main,LoginStateViewModel: Session available!
|
||||
LoginStateViewModel-X+onServerConnect: done
|
||||
Note over Main,UiStateViewModel: Session available!
|
||||
LoginStateViewModel-X+Main: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
Main->>+DataUpdater: initialized
|
||||
Note right of DataUpdater: initialized = true
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>-onServerConnect: ok
|
||||
onServerConnect-X+Main: done
|
||||
deactivate onServerConnect
|
||||
DataUpdater-->>-Main: ok
|
||||
|
||||
Main->>+fetchSettings: call
|
||||
Note right of fetchSettings: trigger onStartup
|
||||
Main->>+Main: fetchSettings
|
||||
Note right of Main: trigger onStartup
|
||||
|
||||
fetchSettings-->>Main: ok
|
||||
Main->>+SettingsViewModel: requestData
|
||||
SettingsViewModel-->>Main: ok
|
||||
deactivate Main
|
||||
deactivate Main
|
||||
|
||||
fetchSettings->>+fetchSettings: asynchronous settings fetch
|
||||
fetchSettings->>+bindViewModels: call
|
||||
SettingsViewModel->>+SettingsViewModel: asynchronous settings fetch
|
||||
Note over Main,UiStateViewModel: Settings available!
|
||||
SettingsViewModel-X+Main: done
|
||||
deactivate SettingsViewModel
|
||||
deactivate SettingsViewModel
|
||||
|
||||
Main->>+Main: bindViewModels
|
||||
|
||||
loop for each view model
|
||||
bindViewModels->bindViewModels: trigger onBeforeBinding
|
||||
bindViewModels->bindViewModels: trigger onBoundTo
|
||||
bindViewModels->bindViewModels: trigger onAfterBinding
|
||||
Main->Main: trigger onBeforeBinding
|
||||
Main->Main: trigger onBoundTo
|
||||
Main->Main: trigger onAfterBinding
|
||||
end
|
||||
|
||||
bindViewModels->bindViewModels: trigger onAllBound
|
||||
Main->Main: trigger onAllBound
|
||||
opt User is logged in
|
||||
bindViewModels->>+LoginStateViewModel: onAllBound
|
||||
Main->>+LoginStateViewModel: onAllBound
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
LoginStateViewModel-->>-bindViewModels: ok
|
||||
LoginStateViewModel-->>-Main: ok
|
||||
end
|
||||
bindViewModels->bindViewModels: trigger onStartupComplete
|
||||
bindViewModels-->>-fetchSettings: ok
|
||||
|
||||
deactivate fetchSettings
|
||||
deactivate fetchSettings
|
||||
Main->>+UiStateViewModel: loaded
|
||||
Note right of UiStateViewModel: loaded = true
|
||||
UiStateViewModel-->>-Main: ok
|
||||
|
||||
Main->Main: trigger onStartupComplete
|
||||
deactivate Main
|
||||
deactivate Main
|
||||
|
||||
|
||||
.. _sec-plugins-viewmodels-reconnect:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
|
||||
@@ -84,7 +84,7 @@ class CodeBlockExt(CodeBlock):
|
||||
return node
|
||||
|
||||
# replace all created literal_blocks with literal_block_ext instances
|
||||
return map(find_and_wrap_literal_block, code_block)
|
||||
return list(map(find_and_wrap_literal_block, code_block))
|
||||
|
||||
def _wrap_literal_block(self, node):
|
||||
literal = literal_block_ext.from_literal_block(node)
|
||||
@@ -160,10 +160,10 @@ class PygmentsBridgeExt(object):
|
||||
# for py3, recognize interactive sessions, but do not try parsing...
|
||||
lexer = sphinx.highlighting.lexers['pycon3']
|
||||
elif lang == 'guess':
|
||||
try:
|
||||
# try:
|
||||
lexer = sphinx.highlighting.guess_lexer(source)
|
||||
except Exception:
|
||||
lexer = sphinx.highlighting.lexers['none']
|
||||
# except Exception:
|
||||
# lexer = sphinx.highlighting.lexers['none']
|
||||
else:
|
||||
if lang in sphinx.highlighting.lexers:
|
||||
lexer = sphinx.highlighting.lexers[lang]
|
||||
@@ -255,4 +255,4 @@ def setup(app):
|
||||
handler = (visit_literal_block_ext, depart_literal_block_ext)
|
||||
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
|
||||
|
||||
return dict(version="0.1")
|
||||
return dict(version="0.1")
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
|
||||
@@ -11,7 +11,7 @@ import requests
|
||||
from contextlib import closing
|
||||
|
||||
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
|
||||
nodes, set_source_info, parselinenos, logger, container_wrapper
|
||||
nodes, parselinenos, logger, container_wrapper
|
||||
|
||||
if False:
|
||||
# For type annotation
|
||||
@@ -39,11 +39,10 @@ class OnlineIncludeReader(LiteralIncludeReader):
|
||||
|
||||
return lines
|
||||
except (IOError, OSError):
|
||||
raise IOError(_('Include file %r not found or reading it failed') % filename)
|
||||
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))
|
||||
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):
|
||||
@@ -69,7 +68,7 @@ class OnlineIncludeDirective(LiteralInclude):
|
||||
text, lines = reader.read(location=location)
|
||||
|
||||
retnode = nodes.literal_block(text, text, source=url)
|
||||
set_source_info(self, retnode)
|
||||
self.set_source_info(retnode)
|
||||
if self.options.get('diff'): # if diff is set, set udiff
|
||||
retnode['language'] = 'udiff'
|
||||
elif 'language' in self.options:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
[pytest]
|
||||
testpaths = src tests
|
||||
addopts = --doctest-modules
|
||||
--doctest-repr=octoprint.util:pp
|
||||
--ignore=src/octoprint/vendor
|
||||
@@ -1,4 +1,6 @@
|
||||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import sys
|
||||
@@ -8,15 +10,17 @@ basedir = os.path.dirname(os.path.realpath(__file__))
|
||||
old = os.path.join(basedir, "octoprint")
|
||||
if os.path.exists(old):
|
||||
# rename left-overs from old file structure
|
||||
print """
|
||||
print("""
|
||||
Found left-overs from old file structure, renaming to
|
||||
"octoprint.backup". Please remove this manually (I don't
|
||||
dare to do so myself since you might have changes in there
|
||||
I don't know anything about).
|
||||
"""
|
||||
""")
|
||||
os.rename(old, os.path.join(basedir, "octoprint.backup"))
|
||||
|
||||
sys.path.insert(0, os.path.join(basedir, "src"))
|
||||
|
||||
import octoprint
|
||||
if len(sys.argv) == 1:
|
||||
sys.argv.append("serve")
|
||||
octoprint.main()
|
||||
+1
-1
@@ -13,5 +13,5 @@ octoprint.init => /etc/init.d/octoprint
|
||||
## systemd
|
||||
|
||||
```
|
||||
octoprint.service => /etc/systemd/service/octoprint.service
|
||||
octoprint.service => /etc/systemd/system/octoprint.service
|
||||
```
|
||||
@@ -1,6 +1,9 @@
|
||||
[metadata]
|
||||
license_file = LICENSE.txt
|
||||
|
||||
[bdist_wheel]
|
||||
universal = 1
|
||||
|
||||
[versioneer]
|
||||
VCS = git
|
||||
style = pep440-tag
|
||||
|
||||
@@ -9,34 +9,41 @@ import versioneer
|
||||
import sys
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
|
||||
import octoprint_setuptools
|
||||
import setuptools
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Supported python versions
|
||||
PYTHON_REQUIRES = ">=2.7.9,<3"
|
||||
# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported
|
||||
PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
|
||||
|
||||
# Requirements for setup.py
|
||||
SETUP_REQUIRES = [
|
||||
"markdown>=3.1,<3.2",
|
||||
]
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
|
||||
# changes that might affect plugins, or due to other observed problems
|
||||
|
||||
"flask>=0.10.1,<0.11", # newer versions require newer Jinja versions
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
|
||||
"Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
"flask>=0.12,<0.13", # newer versions require newer Jinja versions
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
|
||||
# anything below this should be checked on releases for new versions
|
||||
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Login>=0.4.1,<0.5",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"werkzeug>=0.15.1,<0.16",
|
||||
"blinker>=1.4,<1.5", # dependency of the now vendor bundled flask_principal
|
||||
"werkzeug>=0.16,<0.17",
|
||||
"cachelib>=0.1,<0.2",
|
||||
"PyYAML>=5.1,<6",
|
||||
"markdown>=3.0,<3.1",
|
||||
"markdown>=3.1,<3.2",
|
||||
"pyserial>=3.4,<3.5",
|
||||
"netaddr>=0.7.19,<0.8",
|
||||
"watchdog>=0.9.0,<0.10",
|
||||
@@ -45,44 +52,54 @@ INSTALL_REQUIRES = [
|
||||
"pylru>=1.2,<1.3",
|
||||
"rsa>=4.0,<5",
|
||||
"pkginfo>=1.5.0.1,<1.6",
|
||||
"requests>=2.21.0,<3",
|
||||
"semantic_version>=2.6,<2.7",
|
||||
"psutil>=5.6.1,<5.7",
|
||||
"requests>=2.22.0,<3",
|
||||
"semantic_version>=2.8,<2.9",
|
||||
"psutil>=5.6.5,<5.7",
|
||||
"Click>=7,<8",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
"chainmap>=1.0.3,<1.1",
|
||||
"future>=0.17.1,<0.18",
|
||||
"scandir>=1.10,<1.11",
|
||||
"future>=0.18.2,<0.19",
|
||||
"websocket-client>=0.56,<0.57",
|
||||
"wrapt>=1.11.1,<1.12",
|
||||
"futures>=3.2,<3.3",
|
||||
"emoji>=0.5.1,<0.6",
|
||||
"monotonic>=1.5,<1.6",
|
||||
"wrapt>=1.11.2,<1.12",
|
||||
"emoji>=0.5.4,<0.6",
|
||||
"frozendict>=1.2,<1.3",
|
||||
"sentry-sdk==0.7.7",
|
||||
"typing>=3.6.6,<4",
|
||||
"sentry-sdk==0.13.2",
|
||||
"filetype>=1.0.5,<2"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
INSTALL_REQUIRES.append("appdirs>=1.4.0")
|
||||
# Python 2 specific requirements
|
||||
INSTALL_REQUIRES_PYTHON2 = [
|
||||
"futures>=3.3,<3.4",
|
||||
"monotonic>=1.5,<1.6",
|
||||
"scandir>=1.10,<1.11",
|
||||
"chainmap>=1.0.3,<1.1",
|
||||
"typing>=3.7.4.1,<4"
|
||||
]
|
||||
|
||||
# OSX specific requirements
|
||||
INSTALL_REQUIRES_OSX = [
|
||||
"appdirs>=1.4.3",
|
||||
]
|
||||
|
||||
# Additional requirements for optional install options
|
||||
EXTRA_REQUIRES = dict(
|
||||
# Dependencies for developing OctoPrint
|
||||
develop=[
|
||||
# Testing dependencies
|
||||
"mock>=2.0.0,<3",
|
||||
"nose>=1.3.7,<1.4",
|
||||
# Testing dependencies - SEE ALSO tox.ini
|
||||
"mock>=3.0.5,<4",
|
||||
"pytest==4.6.6",
|
||||
"pytest-doctest-custom>=1.0.0,<1.1",
|
||||
"ddt",
|
||||
|
||||
# linter
|
||||
"flake8",
|
||||
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.6,<1.7",
|
||||
"sphinx>=1.8.5,<2",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid>=0.3",
|
||||
"sphinxcontrib-mermaid>=0.3.1",
|
||||
"sphinx_rtd_theme",
|
||||
"readthedocs-sphinx-ext==0.5.7"
|
||||
"readthedocs-sphinx-ext==0.5.17" # Later versions require Jinja >= 2.9
|
||||
],
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
@@ -94,6 +111,23 @@ EXTRA_REQUIRES = dict(
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
# adapted from https://hynek.me/articles/conditional-python-dependencies/
|
||||
if int(setuptools.__version__.split(".", 1)[0]) < 18:
|
||||
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
|
||||
# would get lost there
|
||||
assert "bdist_wheel" not in sys.argv
|
||||
|
||||
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
|
||||
if sys.version_info[0] < 3:
|
||||
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
|
||||
|
||||
if sys.platform == "darwin":
|
||||
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
|
||||
else:
|
||||
# environment markers supported
|
||||
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
|
||||
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
# Anything below here is just command setup and general setup configuration
|
||||
|
||||
@@ -104,14 +138,14 @@ def read_file_contents(path):
|
||||
with codecs.open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def data_copy_build_py_factory(files, baseclass):
|
||||
class data_copy_build_py(baseclass):
|
||||
def md_to_html_build_py_factory(files, baseclass):
|
||||
class md_to_html_build_py(baseclass):
|
||||
files = dict()
|
||||
|
||||
def run(self):
|
||||
import shutil
|
||||
print("RUNNING md_to_html_build_py")
|
||||
if not self.dry_run:
|
||||
for directory, files in self.__class__.files.items():
|
||||
for directory, files in self.files.items():
|
||||
target_dir = os.path.join(self.build_lib, directory)
|
||||
self.mkpath(target_dir)
|
||||
|
||||
@@ -119,16 +153,22 @@ def data_copy_build_py_factory(files, baseclass):
|
||||
if isinstance(entry, tuple):
|
||||
if len(entry) != 2:
|
||||
continue
|
||||
source, dest = entry
|
||||
source, dest = entry[0], os.path.join(target_dir, entry[1])
|
||||
else:
|
||||
source = dest = entry
|
||||
shutil.copy(source, os.path.join(target_dir, dest))
|
||||
source = entry
|
||||
dest = os.path.join(target_dir, source + ".html")
|
||||
|
||||
print("Rendering markdown from {} to {}".format(source, dest))
|
||||
|
||||
from markdown import markdownFromFile
|
||||
markdownFromFile(input=source,
|
||||
output=dest,
|
||||
encoding="utf-8")
|
||||
baseclass.run(self)
|
||||
|
||||
return type(data_copy_build_py)(data_copy_build_py.__name__,
|
||||
(data_copy_build_py,),
|
||||
dict(files=files))
|
||||
return type(md_to_html_build_py)(md_to_html_build_py.__name__,
|
||||
(md_to_html_build_py,),
|
||||
dict(files=files))
|
||||
|
||||
def get_cmdclass():
|
||||
cmdclass = versioneer.get_cmdclass()
|
||||
@@ -142,10 +182,9 @@ def get_cmdclass():
|
||||
bundled_dir = os.path.join("src", "octoprint", "translations")
|
||||
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
|
||||
|
||||
cmdclass["build_py"] = data_copy_build_py_factory({
|
||||
cmdclass["build_py"] = md_to_html_build_py_factory({
|
||||
"octoprint/templates/_data": [
|
||||
"AUTHORS.md",
|
||||
"CHANGELOG.md",
|
||||
"SUPPORTERS.md",
|
||||
"THIRDPARTYLICENSES.md",
|
||||
]
|
||||
@@ -164,6 +203,7 @@ def params():
|
||||
long_description_content_type = "text/markdown"
|
||||
|
||||
python_requires = PYTHON_REQUIRES
|
||||
setup_requires = SETUP_REQUIRES
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
@@ -185,6 +225,10 @@ def params():
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 2",
|
||||
"Programming Language :: Python :: 2.7",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.6",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
"Programming Language :: JavaScript",
|
||||
"Topic :: Printing",
|
||||
|
||||
+19
-13
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env python2
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
import io
|
||||
import sys
|
||||
import logging as log
|
||||
|
||||
@@ -297,7 +298,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
with open(logging_file, "r") as f:
|
||||
with io.open(logging_file, 'rt', encoding='utf-8') as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
|
||||
# we merge that with the default config
|
||||
@@ -370,13 +371,16 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
return True
|
||||
plugin_validators.append(validator)
|
||||
|
||||
compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"])
|
||||
|
||||
from octoprint.plugin import plugin_manager
|
||||
pm = plugin_manager(init=True,
|
||||
plugin_folders=plugin_folders,
|
||||
plugin_entry_points=plugin_entry_points,
|
||||
plugin_disabled_list=plugin_disabled_list,
|
||||
plugin_blacklist=plugin_blacklist,
|
||||
plugin_validators=plugin_validators)
|
||||
plugin_validators=plugin_validators,
|
||||
compatibility_ignored_list=compatibility_ignored_list)
|
||||
|
||||
settings_overlays = dict()
|
||||
disabled_from_overlays = dict()
|
||||
@@ -406,7 +410,9 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
if not startup:
|
||||
return
|
||||
|
||||
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, x[2], x[0]))
|
||||
from octoprint.util import sv
|
||||
|
||||
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, sv(x[2]), sv(x[0])))
|
||||
|
||||
disabled_list = pm.plugin_disabled_list
|
||||
already_processed = []
|
||||
@@ -489,7 +495,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
if os.stat(path).st_mtime + ttl < time.time():
|
||||
return None
|
||||
|
||||
with bom_aware_open(path, encoding="utf-8", mode="r") as f:
|
||||
with bom_aware_open(path, encoding="utf-8", mode='rt') as f:
|
||||
result = yaml.safe_load(f)
|
||||
|
||||
if isinstance(result, list):
|
||||
@@ -503,12 +509,12 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
|
||||
if cache is not None:
|
||||
try:
|
||||
with bom_aware_open(cache, encoding="utf-8", mode="w") as f:
|
||||
with bom_aware_open(cache, encoding="utf-8", mode='wt') 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))
|
||||
except Exception as e:
|
||||
logger.info("Fetched plugin blacklist but couldn't write it to its cache file: %s", e)
|
||||
except Exception as e:
|
||||
logger.info("Unable to fetch plugin blacklist from {}, proceeding without it: {}".format(url, e))
|
||||
return result
|
||||
|
||||
try:
|
||||
@@ -535,7 +541,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
logger.info("Blacklist processing done")
|
||||
|
||||
return blacklist
|
||||
except:
|
||||
except Exception:
|
||||
logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.")
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
#!/usr/bin/env python2
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
import sys
|
||||
if sys.version_info[0] >= 3:
|
||||
raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
if __name__ == "__main__":
|
||||
import octoprint
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
ADMIN_GROUP = "admins"
|
||||
USER_GROUP = "users"
|
||||
GUEST_GROUP = "guests"
|
||||
READONLY_GROUP = "readonly"
|
||||
@@ -0,0 +1,601 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from functools import partial
|
||||
|
||||
import yaml
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROUP
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
from octoprint.vendor.flask_principal import Need, Permission
|
||||
|
||||
DEFAULT_ADMIN_PERMISSIONS = [Permissions.ADMIN]
|
||||
"""Default admin permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
DEFAULT_USER_PERMISSIONS = [Permissions.STATUS,
|
||||
Permissions.CONNECTION,
|
||||
Permissions.WEBCAM,
|
||||
Permissions.FILES_UPLOAD,
|
||||
Permissions.FILES_DOWNLOAD,
|
||||
Permissions.FILES_DELETE,
|
||||
Permissions.FILES_SELECT,
|
||||
Permissions.PRINT,
|
||||
Permissions.MONITOR_TERMINAL,
|
||||
Permissions.CONTROL,
|
||||
Permissions.SLICE,
|
||||
Permissions.TIMELAPSE_LIST,
|
||||
Permissions.TIMELAPSE_ADMIN]
|
||||
"""Default user permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
DEFAULT_GUEST_PERMISSIONS = [Permissions.STATUS,
|
||||
Permissions.WEBCAM,
|
||||
Permissions.FILES_DOWNLOAD,
|
||||
Permissions.TIMELAPSE_LIST,
|
||||
Permissions.MONITOR_TERMINAL]
|
||||
"""Default guest permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
|
||||
GroupNeed = partial(Need, 'group')
|
||||
GroupNeed.__doc__ = """A need with the method preset to `"group"`."""
|
||||
|
||||
|
||||
class GroupPermission(Permission):
|
||||
def __init__(self, key):
|
||||
need = GroupNeed(key)
|
||||
super(GroupPermission, self).__init__(need)
|
||||
|
||||
|
||||
class GroupManager(object):
|
||||
@classmethod
|
||||
def default_permissions_for_group(cls, group):
|
||||
result = []
|
||||
for permission in Permissions.all():
|
||||
if group in permission.default_groups:
|
||||
result.append(permission)
|
||||
return result
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._group_change_listeners = []
|
||||
self._init_defaults()
|
||||
|
||||
@property
|
||||
def groups(self):
|
||||
return []
|
||||
|
||||
@property
|
||||
def admin_group(self):
|
||||
return self.find_group(ADMIN_GROUP)
|
||||
|
||||
@property
|
||||
def user_group(self):
|
||||
return self.find_group(USER_GROUP)
|
||||
|
||||
@property
|
||||
def guest_group(self):
|
||||
return self.find_group(GUEST_GROUP)
|
||||
|
||||
def _init_defaults(self):
|
||||
self.add_group(ADMIN_GROUP,
|
||||
"Admins",
|
||||
"Administrators",
|
||||
self.default_permissions_for_group(ADMIN_GROUP),
|
||||
[],
|
||||
changeable=False,
|
||||
removable=False,
|
||||
save=False)
|
||||
self.add_group(USER_GROUP,
|
||||
"Users",
|
||||
"All logged in users",
|
||||
self.default_permissions_for_group(USER_GROUP),
|
||||
[],
|
||||
default=True,
|
||||
removable=False,
|
||||
toggleable=False,
|
||||
save=False)
|
||||
self.add_group(GUEST_GROUP,
|
||||
"Guests",
|
||||
"Anyone who is not currently logged in",
|
||||
self.default_permissions_for_group(GUEST_GROUP),
|
||||
[],
|
||||
removable=False,
|
||||
toggleable=False,
|
||||
save=False),
|
||||
self.add_group(READONLY_GROUP,
|
||||
"Read-only Access",
|
||||
"Group to gain read-only access",
|
||||
self.default_permissions_for_group(READONLY_GROUP),
|
||||
[],
|
||||
changeable=False,
|
||||
removable=False,
|
||||
save=False)
|
||||
|
||||
def register_listener(self, listener):
|
||||
self._group_change_listeners.append(listener)
|
||||
|
||||
def unregister_listener(self, listener):
|
||||
self._group_change_listeners.remove(listener)
|
||||
|
||||
def add_group(self, key, name, description, permissions, subgroups,
|
||||
default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def remove_group(self, key, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def find_group(self, key):
|
||||
return None
|
||||
|
||||
def _to_permissions(self, *permissions):
|
||||
return list(filter(lambda x: x is not None,
|
||||
[Permissions.find(permission) for permission in permissions]))
|
||||
|
||||
def _from_permissions(self, *permissions):
|
||||
return [permission.key for permission in permissions]
|
||||
|
||||
def _from_groups(self, *groups):
|
||||
return [group.key for group in groups]
|
||||
|
||||
def _to_groups(self, *groups):
|
||||
return filter(lambda x: x is not None,
|
||||
[self._to_group(g) for g in groups])
|
||||
|
||||
def _to_group(self, group):
|
||||
# noinspection PyCompatibility
|
||||
if isinstance(group, Group):
|
||||
return group
|
||||
elif isinstance(group, basestring):
|
||||
return self.find_group(group)
|
||||
elif isinstance(group, dict):
|
||||
return self.find_group(group.get("key"))
|
||||
else:
|
||||
return None
|
||||
|
||||
def _notify_listeners(self, action, group, *args, **kwargs):
|
||||
method = "on_group_{}".format(action)
|
||||
for listener in self._group_change_listeners:
|
||||
try:
|
||||
getattr(listener, method)(group, *args, **kwargs)
|
||||
except Exception:
|
||||
self._logger.exception("Error notifying listener {!r} via {}".format(listener, method))
|
||||
|
||||
class GroupChangeListener(object):
|
||||
|
||||
def on_group_added(self, group):
|
||||
pass
|
||||
|
||||
def on_group_removed(self, group):
|
||||
pass
|
||||
|
||||
def on_group_permissions_changed(self, group, added=None, removed=None):
|
||||
pass
|
||||
|
||||
def on_group_subgroups_changed(self, group, added=None, removed=None):
|
||||
pass
|
||||
|
||||
|
||||
class FilebasedGroupManager(GroupManager):
|
||||
def __init__(self, path=None):
|
||||
if path is None:
|
||||
path = settings().get(["accessControl", "groupfile"])
|
||||
if path is None:
|
||||
path = os.path.join(settings().getBaseFolder("base"), "groups.yaml")
|
||||
|
||||
self._groupfile = path
|
||||
self._groups = dict()
|
||||
self._dirty = False
|
||||
|
||||
GroupManager.__init__(self)
|
||||
|
||||
self._load()
|
||||
|
||||
def _load(self):
|
||||
if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
|
||||
try:
|
||||
with io.open(self._groupfile, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
if not "groups" in data:
|
||||
groups = data
|
||||
data = dict(groups=groups)
|
||||
|
||||
groups = data.get("groups", dict())
|
||||
tracked_permissions = data.get("tracked", list())
|
||||
|
||||
for key, attributes in groups.items():
|
||||
if key in self._groups:
|
||||
# group is already there (from the defaults most likely)
|
||||
if not self._groups[key].is_changeable():
|
||||
# group may not be changed -> bail
|
||||
continue
|
||||
|
||||
removable = self._groups[key].is_removable()
|
||||
changeable = self._groups[key].is_changeable()
|
||||
toggleable = self._groups[key].is_toggleable()
|
||||
else:
|
||||
removable = True
|
||||
changeable = True
|
||||
toggleable = True
|
||||
|
||||
permissions = self._to_permissions(*attributes.get("permissions", []))
|
||||
default_permissions = self.default_permissions_for_group(key)
|
||||
for permission in default_permissions:
|
||||
if not permission.key in tracked_permissions and not permission in permissions:
|
||||
permissions.append(permission)
|
||||
|
||||
subgroups = attributes.get("subgroups", [])
|
||||
|
||||
group = Group(key, attributes.get("name", ""),
|
||||
description=attributes.get("description", ""),
|
||||
permissions=permissions,
|
||||
subgroups=subgroups,
|
||||
default=attributes.get("default", False),
|
||||
removable=removable,
|
||||
changeable=changeable,
|
||||
toggleable=toggleable)
|
||||
self._groups[key] = group
|
||||
|
||||
for group in self._groups.values():
|
||||
group._subgroups = self._to_groups(*group._subgroups)
|
||||
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading groups from file {}".format(self._groupfile))
|
||||
|
||||
def _save(self, force=False):
|
||||
if self._groupfile is None or not self._dirty and not force:
|
||||
return
|
||||
|
||||
groups = dict()
|
||||
for key in self._groups.keys():
|
||||
group = self._groups[key]
|
||||
groups[key] = dict(
|
||||
name=group._name,
|
||||
description=group._description,
|
||||
permissions=self._from_permissions(*group._permissions),
|
||||
subgroups=self._from_groups(*group._subgroups),
|
||||
default=group._default
|
||||
)
|
||||
|
||||
data = dict(groups=groups,
|
||||
tracked=[x.key for x in Permissions.all()])
|
||||
|
||||
with atomic_write(self._groupfile, mode='wt', permissions=0o600, max_permissions=0o666) as f:
|
||||
import yaml
|
||||
yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
@property
|
||||
def groups(self):
|
||||
return list(self._groups.values())
|
||||
|
||||
@property
|
||||
def default_groups(self):
|
||||
return [group for group in self._groups.values() if group.is_default()]
|
||||
|
||||
def find_group(self, key):
|
||||
if key is None:
|
||||
return None
|
||||
return self._groups.get(key)
|
||||
|
||||
def add_group(self, key, name, description, permissions, subgroups, default=False, removable=True,
|
||||
changeable=True, toggleable=True, overwrite=False, notify=True, save=True):
|
||||
if key in self._groups and not overwrite:
|
||||
raise GroupAlreadyExists(key)
|
||||
|
||||
if not permissions:
|
||||
permissions = []
|
||||
|
||||
permissions = self._to_permissions(*permissions)
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
subgroups = self._to_groups(*subgroups)
|
||||
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
|
||||
|
||||
group = Group(key, name,
|
||||
description=description,
|
||||
permissions=permissions,
|
||||
subgroups=subgroups,
|
||||
default=default,
|
||||
changeable=changeable,
|
||||
removable=removable,
|
||||
toggleable=toggleable)
|
||||
self._groups[key] = group
|
||||
|
||||
if save:
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
self._notify_listeners("added", group)
|
||||
|
||||
def remove_group(self, key, save=True, notify=True):
|
||||
"""Removes a Group by key"""
|
||||
group = self._to_group(key)
|
||||
if group is None:
|
||||
raise UnknownGroup(key)
|
||||
|
||||
if not group.is_removable():
|
||||
raise GroupUnremovable(key)
|
||||
|
||||
del self._groups[key]
|
||||
self._dirty = True
|
||||
|
||||
if save:
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
self._notify_listeners("removed", group)
|
||||
|
||||
def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True):
|
||||
group = self._to_group(key)
|
||||
if group is None:
|
||||
raise UnknownGroup(key)
|
||||
|
||||
if not group.is_changeable():
|
||||
raise GroupCantBeChanged(key)
|
||||
|
||||
if description is not None and description != group.get_description():
|
||||
group.change_description(description)
|
||||
self._dirty = True
|
||||
|
||||
notifications = []
|
||||
|
||||
if permissions is not None:
|
||||
permissions = self._to_permissions(*permissions)
|
||||
assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
removed_permissions = list(set(group._permissions) - set(permissions))
|
||||
added_permissions = list(set(permissions) - set(group._permissions))
|
||||
|
||||
if removed_permissions:
|
||||
self._dirty |= group.remove_permissions_from_group(removed_permissions)
|
||||
if added_permissions:
|
||||
self._dirty |= group.add_permissions_to_group(added_permissions)
|
||||
|
||||
notifications.append((("permissions_changed", group),
|
||||
dict(added=added_permissions, removed=removed_permissions)))
|
||||
|
||||
if subgroups is not None:
|
||||
subgroups = self._to_groups(*subgroups)
|
||||
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
|
||||
|
||||
removed_subgroups = list(set(group._subgroups) - set(subgroups))
|
||||
added_subgroups = list(set(subgroups) - set(group._subgroups))
|
||||
|
||||
if removed_subgroups:
|
||||
self._dirty = group.remove_subgroups_from_group(removed_subgroups)
|
||||
if added_subgroups:
|
||||
self._dirty = group.add_subgroups_to_group(added_subgroups)
|
||||
|
||||
notifications.append((("subgroups_changed", group),
|
||||
dict(added=added_subgroups, removed=removed_subgroups)))
|
||||
|
||||
if default is not None:
|
||||
group.change_default(default)
|
||||
self._dirty = True
|
||||
|
||||
if self._dirty:
|
||||
if save:
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
for args, kwargs in notifications:
|
||||
self._notify_listeners(*args, **kwargs)
|
||||
|
||||
|
||||
class GroupAlreadyExists(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group %s already exists" % key)
|
||||
|
||||
|
||||
class UnknownGroup(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Unknown group: %s" % key)
|
||||
|
||||
|
||||
class GroupUnremovable(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group can't be removed: %s" % key)
|
||||
|
||||
|
||||
class GroupCantBeChanged(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group can't be changed: %s" % key)
|
||||
|
||||
|
||||
class Group(object):
|
||||
def __init__(self, key, name, description="", permissions=None, subgroups=None, default=False, removable=True, changeable=True, toggleable=True):
|
||||
self._key = key
|
||||
self._name = name
|
||||
self._description = description
|
||||
self._permissions = permissions
|
||||
self._subgroups = subgroups
|
||||
self._default = default
|
||||
self._removable = removable
|
||||
self._changeable = changeable
|
||||
self._toggleable = toggleable
|
||||
|
||||
def as_dict(self):
|
||||
from octoprint.access.permissions import OctoPrintPermission
|
||||
return dict(
|
||||
key=self.key,
|
||||
name=self.get_name(),
|
||||
description=self._description,
|
||||
permissions=list(map(lambda p: p.key, self._permissions)),
|
||||
subgroups=list(map(lambda g: g.key, self._subgroups)),
|
||||
needs=OctoPrintPermission.convert_needs_to_dict(self.needs),
|
||||
default=self._default,
|
||||
removable=self._removable,
|
||||
changeable=self._changeable,
|
||||
toggleable=self._toggleable
|
||||
)
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
return self._key
|
||||
|
||||
def get_name(self):
|
||||
return self._name
|
||||
|
||||
def get_description(self):
|
||||
return self._description
|
||||
|
||||
def is_default(self):
|
||||
return self._default
|
||||
|
||||
def is_changeable(self):
|
||||
return self._changeable
|
||||
|
||||
def is_removable(self):
|
||||
return self._removable
|
||||
|
||||
def is_toggleable(self):
|
||||
return self._toggleable
|
||||
|
||||
def add_permissions_to_group(self, permissions):
|
||||
"""Adds a list of permissions to a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the permissions variable is of type list
|
||||
if not isinstance(permissions, list):
|
||||
permissions = [permissions]
|
||||
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
dirty = False
|
||||
for permission in permissions:
|
||||
if permissions not in self.permissions:
|
||||
self._permissions.append(permission)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def remove_permissions_from_group(self, permissions):
|
||||
"""Removes a list of permissions from a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the permissions variable is of type list
|
||||
if not isinstance(permissions, list):
|
||||
permissions = [permissions]
|
||||
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
dirty = False
|
||||
for permission in permissions:
|
||||
if permission in self._permissions:
|
||||
self._permissions.remove(permission)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def add_subgroups_to_group(self, subgroups):
|
||||
"""Adds a list of subgroups to a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the subgroups variable is of type list
|
||||
if not isinstance(subgroups, list):
|
||||
subgroups = [subgroups]
|
||||
|
||||
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
|
||||
|
||||
dirty = False
|
||||
for group in subgroups:
|
||||
if group.is_toggleable() and group not in self._subgroups:
|
||||
self._subgroups.append(group)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def remove_subgroups_from_group(self, subgroups):
|
||||
"""Removes a list of subgroups from a group"""
|
||||
"""Adds a list of subgroups to a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the subgroups variable is of type list
|
||||
if not isinstance(subgroups, list):
|
||||
subgroups = [subgroups]
|
||||
|
||||
assert (all(map(lambda g: isinstance(g, Group), subgroups)))
|
||||
|
||||
dirty = False
|
||||
for group in subgroups:
|
||||
if group.is_toggleable() and group in self._subgroups:
|
||||
self._subgroups.remove(group)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def change_default(self, default):
|
||||
"""Changes the default flag of a Group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
self._default = default
|
||||
|
||||
def change_description(self, description):
|
||||
"""Changes the description of a group"""
|
||||
self._description = description
|
||||
|
||||
@property
|
||||
def permissions(self):
|
||||
if Permissions.ADMIN in self._permissions:
|
||||
return Permissions.all()
|
||||
|
||||
return list(filter(lambda p: p is not None, self._permissions))
|
||||
|
||||
@property
|
||||
def subgroups(self):
|
||||
return filter(lambda g: g is not None, self._subgroups)
|
||||
|
||||
@property
|
||||
def needs(self):
|
||||
needs = set()
|
||||
needs.add(GroupNeed(self.key))
|
||||
for p in self.permissions:
|
||||
needs = needs.union(p.needs)
|
||||
for g in self.subgroups:
|
||||
needs = needs.union(g.needs)
|
||||
|
||||
return needs
|
||||
|
||||
def has_permission(self, permission):
|
||||
if Permissions.ADMIN.get_name() in self._permissions:
|
||||
return True
|
||||
|
||||
return permission.needs.issubset(self.needs)
|
||||
|
||||
def __repr__(self):
|
||||
return '{}("{}", "{}", description="{}", permissions={!r}, ' \
|
||||
'default={}, removable={}, changeable={})'.format(self.__class__.__name__,
|
||||
self._key,
|
||||
self._name,
|
||||
self._description,
|
||||
self._permissions,
|
||||
bool(self._default),
|
||||
bool(self._removable),
|
||||
bool(self._changeable))
|
||||
|
||||
def __hash__(self):
|
||||
return self.key.__hash__()
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, Group) and other.key == self.key
|
||||
@@ -0,0 +1,368 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from future.utils import with_metaclass
|
||||
from flask import g, abort
|
||||
from flask_babel import gettext
|
||||
from octoprint.vendor.flask_principal import Permission, PermissionDenied, RoleNeed, Need
|
||||
|
||||
from functools import wraps
|
||||
from collections import OrderedDict, defaultdict
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP
|
||||
|
||||
|
||||
class OctoPrintPermission(Permission):
|
||||
@classmethod
|
||||
def convert_needs_to_dict(cls, needs):
|
||||
ret_needs = defaultdict(list)
|
||||
for need in needs:
|
||||
if need.value not in ret_needs[need.method]:
|
||||
ret_needs[need.method].append(need.value)
|
||||
return ret_needs
|
||||
|
||||
@classmethod
|
||||
def convert_to_needs(cls, needs):
|
||||
result = []
|
||||
for need in needs:
|
||||
# noinspection PyCompatibility
|
||||
if isinstance(need, Need):
|
||||
result.append(need)
|
||||
elif isinstance(need, Permission):
|
||||
result += need.needs
|
||||
elif isinstance(need, basestring):
|
||||
result.append(RoleNeed(need))
|
||||
return result
|
||||
|
||||
def __init__(self, name, description, *needs, **kwargs):
|
||||
self._name = name
|
||||
self._description = description
|
||||
self._dangerous = kwargs.pop("dangerous", False)
|
||||
self._default_groups = kwargs.pop("default_groups", [])
|
||||
|
||||
self._key = None
|
||||
|
||||
Permission.__init__(self, *self.convert_to_needs(needs))
|
||||
|
||||
def as_dict(self):
|
||||
return dict(
|
||||
key=self.key,
|
||||
name=self.get_name(),
|
||||
dangerous=self._dangerous,
|
||||
default_groups=self._default_groups,
|
||||
description=self.get_description(),
|
||||
needs=self.convert_needs_to_dict(self.needs)
|
||||
)
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
return self._key
|
||||
|
||||
@key.setter
|
||||
def key(self, value):
|
||||
self._key = value
|
||||
|
||||
@property
|
||||
def default_groups(self):
|
||||
return self._default_groups
|
||||
|
||||
def get_name(self):
|
||||
return self._name
|
||||
|
||||
def get_description(self):
|
||||
return self._description
|
||||
|
||||
def union(self, other):
|
||||
"""Create a new OctoPrintPermission with the requirements of the union of this
|
||||
and other.
|
||||
|
||||
:param other: The other permission
|
||||
"""
|
||||
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
|
||||
p.excludes.update(self.excludes.union(other.excludes))
|
||||
return p
|
||||
|
||||
def difference(self, other):
|
||||
"""Create a new OctoPrintPermission consisting of requirements in this
|
||||
permission and not in the other.
|
||||
"""
|
||||
|
||||
p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
|
||||
p.excludes.update(self.excludes.difference(other.excludes))
|
||||
return p
|
||||
|
||||
def __repr__(self):
|
||||
return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
|
||||
self.get_name(),
|
||||
self.get_description(),
|
||||
', '.join(map(repr, self.needs)))
|
||||
|
||||
def __hash__(self):
|
||||
return self.get_name().__hash__()
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
|
||||
|
||||
|
||||
class PluginOctoPrintPermission(OctoPrintPermission):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.plugin = kwargs.pop("plugin", None)
|
||||
OctoPrintPermission.__init__(self, *args, **kwargs)
|
||||
|
||||
def as_dict(self):
|
||||
result = OctoPrintPermission.as_dict(self)
|
||||
result["plugin"] = self.plugin
|
||||
return result
|
||||
|
||||
|
||||
class PluginIdentityContext(object):
|
||||
"""Identity context for not initialized Permissions
|
||||
|
||||
Needed to support @Permissions.PLUGIN_X_Y.require()
|
||||
|
||||
Will search the permission when needed
|
||||
"""
|
||||
def __init__(self, key, http_exception=None):
|
||||
self.key = key
|
||||
self.http_exception = http_exception
|
||||
"""The permission of this principal
|
||||
"""
|
||||
|
||||
@property
|
||||
def identity(self):
|
||||
"""The identity of this principal
|
||||
"""
|
||||
return g.identity
|
||||
|
||||
def can(self):
|
||||
"""Whether the identity has access to the permission
|
||||
"""
|
||||
permission = getattr(Permissions, self.key)
|
||||
if permission is None or isinstance(permission, PluginPermissionDecorator):
|
||||
raise UnknownPermission(self.key)
|
||||
|
||||
return permission.can()
|
||||
|
||||
def __call__(self, f):
|
||||
@wraps(f)
|
||||
def _decorated(*args, **kw):
|
||||
with self:
|
||||
rv = f(*args, **kw)
|
||||
return rv
|
||||
|
||||
return _decorated
|
||||
|
||||
def __enter__(self):
|
||||
permission = getattr(Permissions, self.key)
|
||||
if permission is None or isinstance(permission, PluginPermissionDecorator):
|
||||
raise UnknownPermission(self.key)
|
||||
|
||||
# check the permission here
|
||||
if not permission.can():
|
||||
if self.http_exception:
|
||||
abort(self.http_exception, permission)
|
||||
raise PermissionDenied(permission)
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
|
||||
class PluginPermissionDecorator(Permission):
|
||||
"""Decorator Class for not initialized Permissions
|
||||
|
||||
Needed to support @Permissions.PLUGIN_X_Y.require()
|
||||
"""
|
||||
def __init__(self, key):
|
||||
self.key = key
|
||||
|
||||
def require(self, http_exception=None):
|
||||
return PluginIdentityContext(self.key, http_exception)
|
||||
|
||||
|
||||
class PermissionsMetaClass(type):
|
||||
permissions = OrderedDict()
|
||||
|
||||
def __new__(mcs, name, bases, args):
|
||||
cls = type.__new__(mcs, name, bases, args)
|
||||
|
||||
for key, value in args.items():
|
||||
if isinstance(value, OctoPrintPermission):
|
||||
value.key = key
|
||||
mcs.permissions[key] = value
|
||||
delattr(cls, key)
|
||||
|
||||
return cls
|
||||
|
||||
def __setattr__(cls, key, value):
|
||||
if isinstance(value, OctoPrintPermission):
|
||||
if key in cls.permissions:
|
||||
raise PermissionAlreadyExists(key)
|
||||
value.key = key
|
||||
cls.permissions[key] = value
|
||||
|
||||
def __getattr__(cls, key):
|
||||
permission = cls.permissions.get(key)
|
||||
|
||||
if key.startswith("PLUGIN_") and permission is None:
|
||||
return PluginPermissionDecorator(key)
|
||||
|
||||
return permission
|
||||
|
||||
def all(cls):
|
||||
return list(cls.permissions.values())
|
||||
|
||||
def filter(cls, cb):
|
||||
return list(filter(cb, cls.all()))
|
||||
|
||||
def find(cls, p, filter=None):
|
||||
key = None
|
||||
if isinstance(p, OctoPrintPermission):
|
||||
key = p.key
|
||||
elif isinstance(p, dict):
|
||||
key = p.get("key")
|
||||
elif isinstance(p, basestring):
|
||||
key = p
|
||||
|
||||
if key is None:
|
||||
return None
|
||||
|
||||
return cls.match(lambda p: p.key == key, filter=filter)
|
||||
|
||||
def match(cls, match, filter=None):
|
||||
if callable(filter):
|
||||
permissions = cls.filter(filter)
|
||||
else:
|
||||
permissions = cls.all()
|
||||
|
||||
for permission in permissions:
|
||||
if match(permission):
|
||||
return permission
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class Permissions(with_metaclass(PermissionsMetaClass)):
|
||||
|
||||
# Special permission
|
||||
ADMIN = OctoPrintPermission("Admin",
|
||||
gettext("Admin is allowed to do everything"),
|
||||
RoleNeed("admin"),
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
|
||||
STATUS = OctoPrintPermission("Status",
|
||||
gettext("Allows to gather status information, e.g. job progress, "
|
||||
"printer state, temperatures, ..."),
|
||||
RoleNeed("status"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
|
||||
CONNECTION = OctoPrintPermission("Connection",
|
||||
gettext("Allows to connect to and disconnect from a printer"),
|
||||
RoleNeed("connection"),
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
WEBCAM = OctoPrintPermission("Webcam",
|
||||
gettext("Allows to watch the webcam stream"),
|
||||
RoleNeed("webcam"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
|
||||
SYSTEM = OctoPrintPermission("System",
|
||||
gettext("Allows to run system commands, e.g. restart OctoPrint, "
|
||||
"shutdown or reboot the system"),
|
||||
RoleNeed("system"),
|
||||
dangerous=True)
|
||||
|
||||
FILES_LIST = OctoPrintPermission("File List",
|
||||
gettext("Allows to retrieve a list of all uploaded files, including"
|
||||
"their metadata (e.g. date, file size, analysis results, ...)"),
|
||||
RoleNeed("files_list"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
FILES_UPLOAD = OctoPrintPermission("File Upload",
|
||||
gettext("Allows users to upload new files"),
|
||||
RoleNeed("files_upload"),
|
||||
default_groups=[USER_GROUP])
|
||||
FILES_DOWNLOAD = OctoPrintPermission("File Download",
|
||||
gettext("Allows users to download files. The GCODE viewer is "
|
||||
"affected by this as well."),
|
||||
RoleNeed("files_download"), FILES_LIST,
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
FILES_DELETE = OctoPrintPermission("File Delete",
|
||||
gettext("Allows users to delete files"),
|
||||
RoleNeed("files_delete"), FILES_LIST,
|
||||
default_groups=[USER_GROUP])
|
||||
FILES_SELECT = OctoPrintPermission("File Select",
|
||||
gettext("Allows to select a file for printing"),
|
||||
RoleNeed("files_select"), FILES_LIST,
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
PRINT = OctoPrintPermission("Print",
|
||||
gettext("Allows to start, pause and cancel a print job. Includes the \"Select\" "
|
||||
"permission"),
|
||||
RoleNeed("print"), FILES_SELECT,
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
|
||||
gettext("Allows access to the GCODE viewer. Includes the \"File Download\""
|
||||
"permission."),
|
||||
RoleNeed("gcodeviewer"), FILES_DOWNLOAD,
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
|
||||
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
|
||||
gettext("Allows to watch the terminal tab but not to send commands "
|
||||
"to the printer from it"),
|
||||
RoleNeed("monitor_terminal"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
|
||||
CONTROL = OctoPrintPermission("Control",
|
||||
gettext("Allows to control of the printer by using the temperature controls,"
|
||||
"the control tab or sending commands through the terminal."),
|
||||
RoleNeed("control"),
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
SLICE = OctoPrintPermission("Slice",
|
||||
gettext("Allows to slice files"),
|
||||
RoleNeed("slice"),
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
|
||||
gettext("Allows to list timelapse videos"),
|
||||
RoleNeed("timelapse_list"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
|
||||
gettext("Allows to download timelapse videos"),
|
||||
RoleNeed("timelapse_download"),
|
||||
default_groups=[USER_GROUP, READONLY_GROUP])
|
||||
TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
|
||||
gettext("Allows to delete timelapse videos and unrendered timelapses"),
|
||||
RoleNeed("timelapse_delete"),
|
||||
default_groups=[USER_GROUP])
|
||||
TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
|
||||
gettext("Allows to change the timelapse settings and delete or "
|
||||
"render unrendered timelapses. Includes the \"Timelapse List\","
|
||||
"\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
|
||||
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
SETTINGS = OctoPrintPermission("Settings",
|
||||
gettext("Allows to manage settings"),
|
||||
RoleNeed("settings"),
|
||||
dangerous=True)
|
||||
|
||||
|
||||
|
||||
class PermissionAlreadyExists(Exception):
|
||||
def __init__(self, permission):
|
||||
Exception.__init__(self, "Permission %s already exists" % permission)
|
||||
|
||||
|
||||
class UnknownPermission(Exception):
|
||||
def __init__(self, permissionname):
|
||||
Exception.__init__(self, "Unknown permission: %s" % permissionname)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,12 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
import octoprint
|
||||
import sys
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
#~~ "octoprint util" commands
|
||||
|
||||
@@ -71,7 +72,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
|
||||
click.echo("DONE:{}s".format(monotonic_time() - start_time))
|
||||
click.echo("RESULTS:")
|
||||
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
|
||||
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=4, allow_unicode=True))
|
||||
|
||||
if __name__ == "__main__":
|
||||
gcode_command()
|
||||
@@ -1,10 +1,13 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
import io
|
||||
import json
|
||||
|
||||
import octoprint_client
|
||||
@@ -12,6 +15,7 @@ import octoprint_client
|
||||
from octoprint.cli import get_ctx_obj_option, bulk_options
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
|
||||
from past.builtins import unicode
|
||||
|
||||
class JsonStringParamType(click.ParamType):
|
||||
name = "json"
|
||||
@@ -19,7 +23,7 @@ class JsonStringParamType(click.ParamType):
|
||||
def convert(self, value, param, ctx):
|
||||
try:
|
||||
return json.loads(value)
|
||||
except:
|
||||
except Exception:
|
||||
self.fail("%s is not a valid json string" % value, param, ctx)
|
||||
|
||||
|
||||
@@ -143,16 +147,16 @@ 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:
|
||||
with io.open(file_path, 'rt') as fp:
|
||||
data = json.load(fp)
|
||||
else:
|
||||
import yaml
|
||||
with open(file_path, "rb") as fp:
|
||||
with io.open(file_path, 'rt') as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
else:
|
||||
with open(file_path, "rb") as fp:
|
||||
with io.open(file_path, 'rb') as fp:
|
||||
data = fp.read()
|
||||
|
||||
r = ctx.obj.client.post(path, data, timeout=timeout)
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
import logging
|
||||
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
@@ -17,7 +18,7 @@ import pprint
|
||||
|
||||
def _to_settings_path(path):
|
||||
if not isinstance(path, (list, tuple)):
|
||||
path = filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))
|
||||
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
|
||||
return path
|
||||
|
||||
def _set_helper(settings, path, value, data_type=None):
|
||||
@@ -207,7 +208,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
@@ -232,7 +233,7 @@ def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
@@ -116,7 +117,8 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
if key in options:
|
||||
val = options[key]
|
||||
else:
|
||||
raw = raw if isinstance(raw, basestring) else str(raw)
|
||||
if not isinstance(raw, basestring):
|
||||
raw = str(raw)
|
||||
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
|
||||
|
||||
if not no_input:
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
import logging
|
||||
|
||||
from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option
|
||||
@@ -88,10 +89,10 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
commands = hook(self, pass_octoprint_ctx)
|
||||
for command in commands:
|
||||
if not isinstance(command, click.Command):
|
||||
self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
|
||||
self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
|
||||
continue
|
||||
result[name + self.sep + command.name] = command
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
import logging
|
||||
import sys
|
||||
|
||||
|
||||
+54
-27
@@ -10,8 +10,9 @@ import logging
|
||||
|
||||
from octoprint import init_settings
|
||||
from octoprint.cli import get_ctx_obj_option
|
||||
from octoprint.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
|
||||
from octoprint.util import get_class
|
||||
from octoprint.access.groups import FilebasedGroupManager
|
||||
from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
|
||||
from octoprint.util import get_class, sv
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
@@ -36,17 +37,28 @@ def user(ctx):
|
||||
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
|
||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
|
||||
group_manager_name = settings.get(["accessControl", "groupManager"])
|
||||
try:
|
||||
clazz = get_class(group_manager_name)
|
||||
group_manager = clazz()
|
||||
except AttributeError:
|
||||
click.echo("Could not instantiate group manager {}, "
|
||||
"falling back to FilebasedGroupManager!".format(group_manager_name), err=True)
|
||||
group_manager = FilebasedGroupManager()
|
||||
|
||||
ctx.obj.group_manager = group_manager
|
||||
|
||||
name = settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = get_class(name)
|
||||
manager = clazz(settings=settings)
|
||||
user_manager = clazz(group_manager=group_manager, settings=settings)
|
||||
except Exception:
|
||||
click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
|
||||
manager = FilebasedUserManager(settings=settings)
|
||||
user_manager = FilebasedUserManager(group_manager, settings=settings)
|
||||
finally:
|
||||
manager.enabled = settings.getBoolean(["accessControl", "enabled"])
|
||||
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
|
||||
|
||||
ctx.obj.user_manager = manager
|
||||
ctx.obj.user_manager = user_manager
|
||||
|
||||
except Exception:
|
||||
click.echo("Could not instantiate user manager", err=True)
|
||||
@@ -57,28 +69,39 @@ def user(ctx):
|
||||
@click.pass_context
|
||||
def list_users_command(ctx):
|
||||
"""Lists user information"""
|
||||
users = ctx.obj.user_manager.getAllUsers()
|
||||
users = ctx.obj.user_manager.get_all_users()
|
||||
_print_list(users)
|
||||
|
||||
|
||||
@user.command(name="add")
|
||||
@click.argument("username", type=click.STRING, required=True)
|
||||
@click.password_option("--password", "password", help="Password for user")
|
||||
@click.password_option("--password", "password", help="Password for the user")
|
||||
@click.option("-g", "--group", "groups", multiple=True,
|
||||
help="Groups to set on the user")
|
||||
@click.option("-p", "--permission", "permissions", multiple=True,
|
||||
help="Individual permissions to set on the user")
|
||||
@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
|
||||
help="Sets admin role on user")
|
||||
help="Adds user to admin group")
|
||||
@click.pass_context
|
||||
def add_user_command(ctx, username, password, is_admin):
|
||||
def add_user_command(ctx, username, password, groups, permissions, is_admin):
|
||||
"""Add a new user."""
|
||||
try:
|
||||
ctx.obj.user_manager.addUser(username,
|
||||
password,
|
||||
roles=(("user", "admin") if is_admin else ("user",)),
|
||||
active=True)
|
||||
if not groups:
|
||||
groups = []
|
||||
|
||||
user = ctx.obj.user_manager.findUser(username)
|
||||
if is_admin:
|
||||
groups.append(ctx.obj.group_manager.admin_group)
|
||||
|
||||
try:
|
||||
ctx.obj.user_manager.add_user(username,
|
||||
password,
|
||||
groups=groups,
|
||||
permissions=permissions,
|
||||
active=True)
|
||||
|
||||
user = ctx.obj.user_manager.find_user(username)
|
||||
if user:
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||
click.echo("\t{}".format(_user_to_line(user.as_dict())))
|
||||
except UserAlreadyExists:
|
||||
click.echo("A user with the name {} does already exist!".format(username), err=True)
|
||||
|
||||
@@ -92,7 +115,7 @@ def remove_user_command(ctx, username):
|
||||
type=click.STRING)
|
||||
|
||||
if confirm.lower() == "yes":
|
||||
ctx.obj.user_manager.removeUser(username)
|
||||
ctx.obj.user_manager.remove_user(username)
|
||||
click.echo("User {} removed.".format(username))
|
||||
else:
|
||||
click.echo("User {} not removed.".format(username))
|
||||
@@ -105,7 +128,7 @@ def remove_user_command(ctx, username):
|
||||
def change_password_command(ctx, username, password):
|
||||
"""Change an existing user's password."""
|
||||
try:
|
||||
ctx.obj.user_manager.changeUserPassword(username, password)
|
||||
ctx.obj.user_manager.change_user_password(username, password)
|
||||
click.echo("Password changed for user {}.".format(username))
|
||||
except UnknownUser:
|
||||
click.echo("User {} does not exist!".format(username), err=True)
|
||||
@@ -117,10 +140,10 @@ def change_password_command(ctx, username, password):
|
||||
def activate_command(ctx, username):
|
||||
"""Activate a user account."""
|
||||
try:
|
||||
ctx.obj.user_manager.changeUserActivation(username, True)
|
||||
ctx.obj.user_manager.change_user_activation(username, True)
|
||||
click.echo("User {} activated.".format(username))
|
||||
|
||||
user = ctx.obj.user_manager.findUser(username)
|
||||
user = ctx.obj.user_manager.find_user(username)
|
||||
if user:
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||
@@ -134,10 +157,10 @@ def activate_command(ctx, username):
|
||||
def deactivate_command(ctx, username):
|
||||
"""Activate a user account."""
|
||||
try:
|
||||
ctx.obj.user_manager.changeUserActivation(username, False)
|
||||
ctx.obj.user_manager.change_user_activation(username, False)
|
||||
click.echo("User {} activated.".format(username))
|
||||
|
||||
user = ctx.obj.user_manager.findUser(username)
|
||||
user = ctx.obj.user_manager.find_user(username)
|
||||
if user:
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||
@@ -147,11 +170,15 @@ def deactivate_command(ctx, username):
|
||||
|
||||
def _print_list(users):
|
||||
click.echo("{} users registered in the system:".format(len(users)))
|
||||
for user in sorted(users, key=lambda x: x.get("name")):
|
||||
for user in sorted(map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))):
|
||||
click.echo("\t{}".format(_user_to_line(user)))
|
||||
|
||||
|
||||
def _user_to_line(user):
|
||||
return "{} (active: {}, admin: {})".format(user.get("name"),
|
||||
"yes" if user.get("active", False) else "no",
|
||||
"yes" if user.get("admin", False) else "no")
|
||||
return "{name}" \
|
||||
"\n\t\tactive: {active}" \
|
||||
"\n\t\tgroups: {groups}" \
|
||||
"\n\t\tpermissions: {permissions}".format(name=user.get("name"),
|
||||
active=user.get("active", "False"),
|
||||
groups=", ".join(user.get("groups", [])),
|
||||
permissions=", ".join(user.get("permissions", [])))
|
||||
+10
-9
@@ -1,12 +1,13 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
"""
|
||||
Generic linux daemon base class
|
||||
|
||||
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
import sys, os, time, signal
|
||||
import io, sys, os, time, signal
|
||||
|
||||
class Daemon:
|
||||
"""
|
||||
@@ -60,9 +61,9 @@ class Daemon:
|
||||
# redirect standard file descriptors
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
si = open(os.devnull, 'r')
|
||||
so = open(os.devnull, 'a+')
|
||||
se = open(os.devnull, 'a+')
|
||||
si = io.open(os.devnull, 'rt', encoding='utf-8')
|
||||
so = io.open(os.devnull, 'at+', encoding='utf-8')
|
||||
se = io.open(os.devnull, 'at+', encoding='utf-8')
|
||||
|
||||
os.dup2(si.fileno(), sys.stdin.fileno())
|
||||
os.dup2(so.fileno(), sys.stdout.fileno())
|
||||
@@ -133,7 +134,7 @@ class Daemon:
|
||||
except OSError:
|
||||
try:
|
||||
self.remove_pidfile()
|
||||
except:
|
||||
except Exception:
|
||||
self.error("Daemon found not running, but could not remove stale pidfile")
|
||||
return False
|
||||
else:
|
||||
@@ -142,7 +143,7 @@ class Daemon:
|
||||
def get_pid(self):
|
||||
"""Get the pid from the pidfile."""
|
||||
try:
|
||||
with open(self.pidfile,'r') as pf:
|
||||
with io.open(self.pidfile,'rt', encoding='utf-8') as pf:
|
||||
pid = int(pf.read().strip())
|
||||
except (IOError, ValueError):
|
||||
pid = None
|
||||
@@ -150,7 +151,7 @@ class Daemon:
|
||||
|
||||
def set_pid(self, pid):
|
||||
"""Write the pid to the pidfile."""
|
||||
with open(self.pidfile,'w+') as f:
|
||||
with io.open(self.pidfile,'wt+', encoding='utf-8') as f:
|
||||
f.write(str(pid) + '\n')
|
||||
|
||||
def remove_pidfile(self):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -59,7 +59,7 @@ class EnvironmentDetector(object):
|
||||
self.notify_plugins()
|
||||
|
||||
return environment
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Unexpected error while detecting environment")
|
||||
with self._cache_lock:
|
||||
self._cache = dict()
|
||||
@@ -76,21 +76,21 @@ class EnvironmentDetector(object):
|
||||
# determine python version
|
||||
try:
|
||||
result["version"] = get_python_version_string()
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error detecting python version")
|
||||
|
||||
# determine if we are running from a virtual environment
|
||||
try:
|
||||
if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
|
||||
result["virtualenv"] = sys.prefix
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error detecting whether we are running in a virtual environment")
|
||||
|
||||
# try to find pip version
|
||||
try:
|
||||
import pkg_resources
|
||||
result["pip"] = pkg_resources.get_distribution("pip").version
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error detecting pip version")
|
||||
|
||||
return result
|
||||
@@ -110,7 +110,7 @@ class EnvironmentDetector(object):
|
||||
result["freq"] = cpu_freq.max
|
||||
if ram and hasattr(ram, "total"):
|
||||
result["ram"] = ram.total
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while detecting hardware environment")
|
||||
|
||||
return result
|
||||
@@ -123,7 +123,7 @@ class EnvironmentDetector(object):
|
||||
additional = implementation.get_additional_environment()
|
||||
if additional is not None and isinstance(additional, dict) and len(additional):
|
||||
result[implementation._identifier] = additional
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while fetching additional "
|
||||
"environment data from plugin {}".format(implementation._identifier),
|
||||
extra=dict(plugin=implementation._identifier))
|
||||
@@ -140,7 +140,7 @@ class EnvironmentDetector(object):
|
||||
|
||||
try:
|
||||
_log(self._format())
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error logging detected environment")
|
||||
|
||||
def _format(self):
|
||||
@@ -151,10 +151,10 @@ class EnvironmentDetector(object):
|
||||
|
||||
dumped_environment = yaml.safe_dump(environment,
|
||||
default_flow_style=False,
|
||||
indent=" ",
|
||||
indent=4,
|
||||
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"],
|
||||
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
|
||||
environment["os"]["id"].title(),
|
||||
environment["os"]["platform"],
|
||||
environment_lines)
|
||||
@@ -168,6 +168,6 @@ class EnvironmentDetector(object):
|
||||
for implementation in self._environment_plugins:
|
||||
try:
|
||||
implementation.on_environment_detected(environment)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while sending environment "
|
||||
"detection result to plugin {}".format(implementation._identifier))
|
||||
+26
-30
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -47,6 +47,10 @@ class Events(object):
|
||||
CLIENT_OPENED = "ClientOpened"
|
||||
CLIENT_CLOSED = "ClientClosed"
|
||||
|
||||
# user login/logout
|
||||
USER_LOGGED_IN = "UserLoggedIn"
|
||||
USER_LOGGED_OUT = "UserLoggedOut"
|
||||
|
||||
# File management
|
||||
UPLOAD = "Upload"
|
||||
FILE_SELECTED = "FileSelected"
|
||||
@@ -181,14 +185,14 @@ class EventManager(object):
|
||||
self._logger.debug("Sending action to {!r}".format(listener))
|
||||
try:
|
||||
listener(event, payload)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=(event, payload))
|
||||
self._logger.info("Event loop shut down")
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
||||
|
||||
def fire(self, event, payload=None):
|
||||
@@ -227,14 +231,6 @@ class EventManager(object):
|
||||
|
||||
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"
|
||||
# TODO v1.4.0 Remove again
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
q.put((event, legacy_payload))
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||
@@ -252,12 +248,11 @@ class EventManager(object):
|
||||
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
|
||||
"""
|
||||
|
||||
if not callback in self._registeredListeners[event]:
|
||||
# callback not subscribed to event, just return
|
||||
return
|
||||
|
||||
self._registeredListeners[event].remove(callback)
|
||||
self._logger.debug("Unsubscribed listener {!r} for event {}".format(callback, event))
|
||||
try:
|
||||
self._registeredListeners[event].remove(callback)
|
||||
except ValueError:
|
||||
# not registered
|
||||
pass
|
||||
|
||||
def join(self, timeout=None):
|
||||
self._worker.join(timeout)
|
||||
@@ -300,7 +295,7 @@ class DebugEventListener(GenericEventListener):
|
||||
def __init__(self):
|
||||
GenericEventListener.__init__(self)
|
||||
|
||||
events = filter(lambda x: not x.startswith("__"), dir(Events))
|
||||
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
|
||||
self.subscribe(events)
|
||||
|
||||
def eventCallback(self, event, payload):
|
||||
@@ -334,12 +329,12 @@ class CommandTrigger(GenericEventListener):
|
||||
self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription))
|
||||
continue
|
||||
|
||||
if not "event" in subscription.keys() or not "command" in subscription.keys() \
|
||||
or not "type" in subscription.keys() or not subscription["type"] in ["system", "gcode"]:
|
||||
if not "event" in subscription or not "command" in subscription \
|
||||
or not "type" in subscription or not subscription["type"] in ["system", "gcode"]:
|
||||
self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription))
|
||||
continue
|
||||
|
||||
if "enabled" in subscription.keys() and not subscription["enabled"]:
|
||||
if "enabled" in subscription and not subscription["enabled"]:
|
||||
self._logger.info("Disabled command trigger: {!r}".format(subscription))
|
||||
continue
|
||||
|
||||
@@ -355,11 +350,11 @@ class CommandTrigger(GenericEventListener):
|
||||
events = [events]
|
||||
|
||||
for event in events:
|
||||
if not event in self._subscriptions.keys():
|
||||
if event not in self._subscriptions:
|
||||
self._subscriptions[event] = []
|
||||
self._subscriptions[event].append((command, commandType, debug))
|
||||
|
||||
if not event in eventsToSubscribe:
|
||||
if event not in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
|
||||
self.subscribe(eventsToSubscribe)
|
||||
@@ -384,8 +379,8 @@ class CommandTrigger(GenericEventListener):
|
||||
else:
|
||||
processedCommand = self._processCommand(command, event, payload)
|
||||
self.executeCommand(processedCommand, commandType, debug=debug)
|
||||
except KeyError as e:
|
||||
self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command)
|
||||
except KeyError:
|
||||
self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command)
|
||||
|
||||
def executeCommand(self, command, commandType, debug=False):
|
||||
if commandType == "system":
|
||||
@@ -413,10 +408,10 @@ class CommandTrigger(GenericEventListener):
|
||||
commandExecutioner(command)
|
||||
except subprocess.CalledProcessError as e:
|
||||
if debug:
|
||||
self._logger.warn("Command failed with return code {}: {}".format(e.returncode, str(e)))
|
||||
self._logger.warning("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.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
|
||||
except Exception:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
t = threading.Thread(target=process)
|
||||
@@ -455,7 +450,8 @@ class CommandTrigger(GenericEventListener):
|
||||
import json
|
||||
try:
|
||||
json_string = json.dumps(payload)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("JSON: Cannot dump %r", payload)
|
||||
json_string = ""
|
||||
|
||||
params = {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import io
|
||||
import os
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -78,7 +79,7 @@ def full_extension_tree():
|
||||
if plugin_result is None or not isinstance(plugin_result, dict):
|
||||
continue
|
||||
result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger)
|
||||
except:
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from SlicerPlugin {name}".format(name=plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
@@ -90,7 +91,7 @@ def full_extension_tree():
|
||||
if hook_result is None or not isinstance(hook_result, dict):
|
||||
continue
|
||||
result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger)
|
||||
except:
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from hook {name}".format(name=name),
|
||||
extra=dict(plugin=name))
|
||||
@@ -224,6 +225,7 @@ class FileManager(object):
|
||||
|
||||
import octoprint.settings
|
||||
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
|
||||
self._analyzeGcode = octoprint.settings.settings().get(["gcodeAnalysis", "runAt"])
|
||||
|
||||
def initialize(self, process_backlog=False):
|
||||
self.reload_plugins()
|
||||
@@ -231,6 +233,10 @@ class FileManager(object):
|
||||
self.process_backlog()
|
||||
|
||||
def process_backlog(self):
|
||||
# only check for a backlog if gcodeAnalysis is 'idle' or 'always'
|
||||
if self._analyzeGcode == "never":
|
||||
return
|
||||
|
||||
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():
|
||||
@@ -350,8 +356,8 @@ class FileManager(object):
|
||||
links = [("model", dict(name=source_path))]
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = StreamWrapper(os.path.basename(dest_path),
|
||||
io.BytesIO(u";Generated from {stl_name} (hash: {hash})\n".format(**locals()).encode("ascii", "replace")),
|
||||
io.FileIO(tmp_path, "rb"))
|
||||
io.BytesIO(";Generated from {stl_name} (hash: {hash})\n".format(**locals()).encode("ascii", "replace")),
|
||||
io.FileIO(tmp_path, 'rb'))
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
self.add_file(dest_location, dest_path, file_obj,
|
||||
@@ -429,16 +435,18 @@ class FileManager(object):
|
||||
if self._last_slicing_progress != progress_int:
|
||||
self._last_slicing_progress = progress_int
|
||||
for callback in self._slicing_progress_callbacks:
|
||||
try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except: self._logger.exception("Exception while pushing slicing progress",
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
try:
|
||||
callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while pushing slicing progress",
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
|
||||
if progress_int:
|
||||
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
for plugin in self._progress_plugins:
|
||||
try:
|
||||
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier,
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
@@ -462,8 +470,8 @@ class FileManager(object):
|
||||
|
||||
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
|
||||
if not destinations:
|
||||
destinations = self._storage_managers.keys()
|
||||
if isinstance(destinations, (str, unicode, basestring)):
|
||||
destinations = list(self._storage_managers.keys())
|
||||
if isinstance(destinations, basestring):
|
||||
destinations = [destinations]
|
||||
|
||||
result = dict()
|
||||
@@ -478,7 +486,7 @@ class FileManager(object):
|
||||
for name, hook in self._preprocessor_hooks.items():
|
||||
try:
|
||||
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra=dict(plugin=name))
|
||||
continue
|
||||
|
||||
@@ -638,9 +646,9 @@ class FileManager(object):
|
||||
pos=pos,
|
||||
date=time.time())
|
||||
try:
|
||||
with atomic_write(self._recovery_file, max_permissions=0o666) as f:
|
||||
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except:
|
||||
with atomic_write(self._recovery_file, mode='wt', max_permissions=0o666) as f:
|
||||
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=2, allow_unicode=True)
|
||||
except Exception:
|
||||
self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file))
|
||||
|
||||
def delete_recovery_data(self):
|
||||
@@ -649,7 +657,7 @@ class FileManager(object):
|
||||
|
||||
try:
|
||||
os.remove(self._recovery_file)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file))
|
||||
|
||||
def get_recovery_data(self):
|
||||
@@ -658,12 +666,12 @@ class FileManager(object):
|
||||
|
||||
import yaml
|
||||
try:
|
||||
with open(self._recovery_file) as f:
|
||||
with io.open(self._recovery_file, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
if not isinstance(data, dict) or not all(map(lambda x: x in data, ("origin", "path", "pos", "date"))):
|
||||
raise ValueError("Invalid recovery data structure")
|
||||
return data
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
|
||||
self.delete_recovery_data()
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -97,16 +97,16 @@ class AnalysisQueue(object):
|
||||
self._queues[entry.type].dequeue(entry.location, entry.path)
|
||||
|
||||
def dequeue_folder(self, destination, path):
|
||||
for queue in self._queues.values():
|
||||
queue.dequeue_folder(destination, path)
|
||||
for q in self._queues.values():
|
||||
q.dequeue_folder(destination, path)
|
||||
|
||||
def pause(self):
|
||||
for queue in self._queues.values():
|
||||
queue.pause()
|
||||
for q in self._queues.values():
|
||||
q.pause()
|
||||
|
||||
def resume(self):
|
||||
for queue in self._queues.values():
|
||||
queue.resume()
|
||||
for q in self._queues.values():
|
||||
q.resume()
|
||||
|
||||
def _analysis_finished(self, entry, result):
|
||||
for callback in self._callbacks:
|
||||
@@ -118,10 +118,7 @@ class AnalysisQueue(object):
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
"origin": entry.location,
|
||||
"result": result,
|
||||
|
||||
# TODO: deprecated, remove in a future release
|
||||
"file": entry.path})
|
||||
"result": result})
|
||||
|
||||
class AbstractAnalysisQueue(object):
|
||||
"""
|
||||
@@ -179,7 +176,10 @@ class AbstractAnalysisQueue(object):
|
||||
(False, default)
|
||||
"""
|
||||
|
||||
if high_priority:
|
||||
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
|
||||
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
|
||||
return
|
||||
elif high_priority:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
|
||||
prio = self.__class__.HIGH_PRIO
|
||||
else:
|
||||
@@ -260,10 +260,7 @@ class AbstractAnalysisQueue(object):
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
"origin": entry.location,
|
||||
"type": entry.type,
|
||||
|
||||
# TODO deprecated, remove in 1.4.0
|
||||
"file": entry.path})
|
||||
"type": entry.type})
|
||||
try:
|
||||
result = self._do_analysis(high_priority=high_priority)
|
||||
except TypeError:
|
||||
@@ -388,7 +385,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
|
||||
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)))
|
||||
raise RuntimeError("Error while trying to run command {}".format(" ".join(command)))
|
||||
|
||||
try:
|
||||
# let's wait for stuff to finish
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
class FileDestinations(object):
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
@@ -28,7 +28,7 @@ from slugify import Slugify
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path, to_unicode, timing
|
||||
from octoprint.util import is_hidden_path, to_unicode, to_bytes
|
||||
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
@@ -450,11 +450,11 @@ class LocalFileStorage(StorageInterface):
|
||||
This storage type implements :func:`path_on_disk`.
|
||||
"""
|
||||
|
||||
_UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]")
|
||||
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
|
||||
|
||||
@classmethod
|
||||
def _no_unicode_variations(cls, text):
|
||||
return cls._UNICODE_VARIATIONS.sub(u"", text)
|
||||
return cls._UNICODE_VARIATIONS.sub("", text)
|
||||
|
||||
_SLUGIFY = Slugify()
|
||||
_SLUGIFY.safe_chars = "-_.()[] "
|
||||
@@ -463,7 +463,7 @@ class LocalFileStorage(StorageInterface):
|
||||
def _slugify(cls, text):
|
||||
text = to_unicode(text)
|
||||
text = cls._no_unicode_variations(text)
|
||||
text = demojize(text, delimiters=(u"", u""))
|
||||
text = demojize(text, delimiters=("", ""))
|
||||
return cls._SLUGIFY(text)
|
||||
|
||||
def __init__(self, basefolder, create=False):
|
||||
@@ -502,10 +502,10 @@ class LocalFileStorage(StorageInterface):
|
||||
if os.path.exists(old_metadata_path):
|
||||
# load the old metadata file
|
||||
try:
|
||||
with open(old_metadata_path) as f:
|
||||
with io.open(old_metadata_path, 'rt', encoding='utf-8') as f:
|
||||
import yaml
|
||||
self._old_metadata = yaml.safe_load(f)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading old metadata file")
|
||||
|
||||
# make sure the metadata is initialized as far as possible
|
||||
@@ -516,7 +516,7 @@ class LocalFileStorage(StorageInterface):
|
||||
try:
|
||||
import shutil
|
||||
shutil.move(old_metadata_path, backup_path)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Could not rename old metadata.yaml file")
|
||||
|
||||
else:
|
||||
@@ -599,10 +599,10 @@ class LocalFileStorage(StorageInterface):
|
||||
path = self.sanitize_path(to_unicode(path))
|
||||
base = self.path_in_storage(path)
|
||||
if base:
|
||||
base += u"/"
|
||||
base += "/"
|
||||
else:
|
||||
path = self.basefolder
|
||||
base = u""
|
||||
base = ""
|
||||
return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive)
|
||||
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
@@ -917,14 +917,14 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def split_path(self, path):
|
||||
path = to_unicode(path)
|
||||
split = path.split(u"/")
|
||||
split = path.split("/")
|
||||
if len(split) == 1:
|
||||
return u"", split[0]
|
||||
return "", split[0]
|
||||
else:
|
||||
return self.join_path(*split[:-1]), split[-1]
|
||||
|
||||
def join_path(self, *path):
|
||||
return u"/".join(map(to_unicode, path))
|
||||
return "/".join(map(to_unicode, path))
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
@@ -953,23 +953,23 @@ class LocalFileStorage(StorageInterface):
|
||||
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"/")
|
||||
path = path.replace(os.path.sep, "/")
|
||||
path = path.split("/")
|
||||
if isinstance(path, (list, tuple)):
|
||||
if len(path) == 1:
|
||||
name = to_unicode(path[0])
|
||||
path = u""
|
||||
path = ""
|
||||
else:
|
||||
name = to_unicode(path[-1])
|
||||
path = self.join_path(*map(to_unicode, path[:-1]))
|
||||
if not path:
|
||||
path = u""
|
||||
path = ""
|
||||
|
||||
return path, name
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise
|
||||
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
|
||||
``(``, and ``)`` as is.
|
||||
"""
|
||||
@@ -978,11 +978,11 @@ class LocalFileStorage(StorageInterface):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if u"/" in name or u"\\" in name:
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
result = self._slugify(name).replace(u" ", u"_")
|
||||
if result and result != u"." and result != u".." and result[0] == u".":
|
||||
result = self._slugify(name).replace(" ", "_")
|
||||
if result and result != "." and result != ".." and result[0] == ".":
|
||||
# hidden files under *nix
|
||||
result = result[1:]
|
||||
return result
|
||||
@@ -996,12 +996,12 @@ class LocalFileStorage(StorageInterface):
|
||||
path = to_unicode(path)
|
||||
|
||||
if len(path):
|
||||
if path[0] == u"/":
|
||||
if path[0] == "/":
|
||||
path = path[1:]
|
||||
elif path[0] == u"." and path[1] == u"/":
|
||||
elif path[0] == "." and path[1] == "/":
|
||||
path = path[2:]
|
||||
|
||||
path_elements = path.split(u"/")
|
||||
path_elements = path.split("/")
|
||||
joined_path = self.basefolder
|
||||
for path_element in path_elements:
|
||||
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
|
||||
@@ -1021,16 +1021,16 @@ class LocalFileStorage(StorageInterface):
|
||||
counter = 1
|
||||
while os.path.exists(sanitized_path):
|
||||
counter += 1
|
||||
sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext))
|
||||
sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
|
||||
sanitized_path = os.path.join(path, sanitized)
|
||||
|
||||
try:
|
||||
shutil.move(entry_path, sanitized_path)
|
||||
|
||||
self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
|
||||
self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
|
||||
return sanitized, sanitized_path
|
||||
except:
|
||||
self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
|
||||
except Exception:
|
||||
self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
|
||||
raise
|
||||
|
||||
return entry, entry_path
|
||||
@@ -1038,12 +1038,12 @@ class LocalFileStorage(StorageInterface):
|
||||
def path_in_storage(self, path):
|
||||
if isinstance(path, (tuple, list)):
|
||||
path = self.join_path(*path)
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
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"/")
|
||||
if path.startswith(u"/"):
|
||||
path = path.replace(os.path.sep, "/")
|
||||
if path.startswith("/"):
|
||||
path = path[1:]
|
||||
|
||||
return path
|
||||
@@ -1120,8 +1120,8 @@ class LocalFileStorage(StorageInterface):
|
||||
print_time = history_entry["printTime"]
|
||||
try:
|
||||
print_time = float(print_time)
|
||||
except:
|
||||
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
|
||||
except Exception:
|
||||
self._logger.warning("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
|
||||
continue
|
||||
|
||||
if not printer_profile in former_print_times:
|
||||
@@ -1300,7 +1300,7 @@ class LocalFileStorage(StorageInterface):
|
||||
entry_is_file = entry.is_file()
|
||||
entry_is_dir = entry.is_dir()
|
||||
entry_stat = entry.stat()
|
||||
except:
|
||||
except Exception:
|
||||
# error while trying to fetch file metadata, that might be thanks to file already having
|
||||
# been moved or deleted - ignore it and continue
|
||||
continue
|
||||
@@ -1312,7 +1312,7 @@ class LocalFileStorage(StorageInterface):
|
||||
entry_name = new_entry_name
|
||||
entry_path = new_entry_path
|
||||
entry_stat = os.stat(entry_path)
|
||||
except:
|
||||
except Exception:
|
||||
# error while trying to rename the file, we'll continue here and ignore it
|
||||
continue
|
||||
|
||||
@@ -1417,7 +1417,7 @@ class LocalFileStorage(StorageInterface):
|
||||
extended_entry_data["size"] = get_size()
|
||||
|
||||
result[entry_name] = extended_entry_data
|
||||
except:
|
||||
except Exception:
|
||||
# So something went wrong somewhere while processing this file entry - log that and continue
|
||||
self._logger.exception("Error while processing entry {}".format(entry_path))
|
||||
continue
|
||||
@@ -1473,7 +1473,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
blocksize = 65536
|
||||
hash = hashlib.sha1()
|
||||
with open(path, "rb") as f:
|
||||
with io.open(path, 'rb') as f:
|
||||
buffer = f.read(blocksize)
|
||||
while len(buffer) > 0:
|
||||
hash.update(buffer)
|
||||
@@ -1541,10 +1541,10 @@ class LocalFileStorage(StorageInterface):
|
||||
metadata = None
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
if os.path.exists(metadata_path):
|
||||
with open(metadata_path) as f:
|
||||
with io.open(metadata_path, 'rt', encoding='utf-8') as f:
|
||||
try:
|
||||
metadata = json.load(f)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
|
||||
|
||||
def valid_json(value):
|
||||
@@ -1579,9 +1579,9 @@ class LocalFileStorage(StorageInterface):
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
try:
|
||||
with atomic_write(metadata_path) as f:
|
||||
json.dump(metadata, f, indent=4, separators=(",", ": "))
|
||||
except:
|
||||
with atomic_write(metadata_path, mode='wb') as f:
|
||||
f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": "))))
|
||||
except Exception:
|
||||
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
|
||||
|
||||
def _delete_metadata(self, path):
|
||||
@@ -1596,7 +1596,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if os.path.exists(metadata_path):
|
||||
try:
|
||||
os.remove(metadata_path)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
|
||||
|
||||
@staticmethod
|
||||
@@ -1622,14 +1622,14 @@ class LocalFileStorage(StorageInterface):
|
||||
# already migrated
|
||||
try:
|
||||
os.remove(metadata_path_yaml)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
|
||||
return
|
||||
|
||||
with open(metadata_path_yaml) as f:
|
||||
with io.open(metadata_path_yaml, 'rt', encoding='utf-8') as f:
|
||||
try:
|
||||
metadata = yaml.safe_load(f)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
|
||||
return
|
||||
|
||||
@@ -1637,12 +1637,12 @@ class LocalFileStorage(StorageInterface):
|
||||
# looks invalid, ignore it
|
||||
return
|
||||
|
||||
with atomic_write(metadata_path_json) as f:
|
||||
json.dump(metadata, f, indent=4, separators=(",", ": "))
|
||||
with atomic_write(metadata_path_json, mode='wb') as f:
|
||||
f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": "))))
|
||||
|
||||
try:
|
||||
os.remove(metadata_path_yaml)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
|
||||
|
||||
@contextmanager
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -64,7 +64,7 @@ class DiskFileWrapper(AbstractFileWrapper):
|
||||
shutil.copy2(self.path, path)
|
||||
|
||||
def stream(self):
|
||||
return io.open(self.path, "rb")
|
||||
return io.open(self.path, 'rb')
|
||||
|
||||
class StreamWrapper(AbstractFileWrapper):
|
||||
"""
|
||||
@@ -87,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper):
|
||||
"""
|
||||
import shutil
|
||||
|
||||
with atomic_write(path, "wb") as dest:
|
||||
with atomic_write(path, mode='wb') as dest:
|
||||
with self.stream() as source:
|
||||
shutil.copyfileobj(source, dest)
|
||||
|
||||
@@ -142,7 +142,7 @@ class MultiStream(io.RawIOBase):
|
||||
for stream in self.streams:
|
||||
try:
|
||||
stream.close()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def readable(self, *args, **kwargs):
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
from past.builtins import basestring, unicode
|
||||
|
||||
from octoprint.logging import handlers
|
||||
|
||||
@@ -79,17 +81,17 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
|
||||
Examples:
|
||||
|
||||
>>> get_divider_line("-")
|
||||
>>> get_divider_line("-") # doctest: +ALLOW_UNICODE
|
||||
'------------------------------------------------------------------------------'
|
||||
>>> get_divider_line("=", length=10)
|
||||
>>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE
|
||||
'=========='
|
||||
>>> get_divider_line("-", message="Hi", length=10)
|
||||
>>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE
|
||||
'--- Hi ---'
|
||||
>>> get_divider_line("-", message="A slightly longer text")
|
||||
>>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE
|
||||
'--- A slightly longer text ---------------------------------------------------'
|
||||
>>> get_divider_line("-", message="A slightly longer text", indent=5)
|
||||
>>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE
|
||||
'----- A slightly longer text -------------------------------------------------'
|
||||
>>> get_divider_line("-", message="Hello World!", length=10)
|
||||
>>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE
|
||||
'--- Hello World!'
|
||||
>>> get_divider_line(None)
|
||||
Traceback (most recent call last):
|
||||
@@ -122,7 +124,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
formatted divider line
|
||||
"""
|
||||
|
||||
assert isinstance(c, (str, unicode, bytes)), "c is not text"
|
||||
assert isinstance(c, basestring), "c is not text"
|
||||
assert len(c) == 1, "c is not a single character"
|
||||
assert isinstance(length, int), "length is not an int"
|
||||
assert isinstance(indent, int), "indent is not an int"
|
||||
@@ -130,7 +132,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
if message is None:
|
||||
return c * length
|
||||
|
||||
assert isinstance(message, (str, unicode, bytes)), "message is not text"
|
||||
assert isinstance(message, basestring), "message is not text"
|
||||
|
||||
space = length - 2 * (indent + 1)
|
||||
if space >= len(message):
|
||||
@@ -152,4 +154,3 @@ def prefix_multilines(text, prefix=u": "):
|
||||
|
||||
return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line),
|
||||
lines[1:]))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
import logging.handlers
|
||||
import os
|
||||
@@ -18,7 +18,7 @@ class AsyncLogHandlerMixin(logging.Handler):
|
||||
def emit(self, record):
|
||||
try:
|
||||
self._executor.submit(self._emit, record)
|
||||
except:
|
||||
except Exception:
|
||||
self.handleError(record)
|
||||
|
||||
def _emit(self, record):
|
||||
@@ -29,6 +29,8 @@ class AsyncLogHandlerMixin(logging.Handler):
|
||||
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
|
||||
|
||||
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
|
||||
|
||||
# clean up old files on handler start
|
||||
@@ -40,6 +42,10 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler
|
||||
class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler):
|
||||
rollover_callbacks = []
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
|
||||
super(OctoPrintLogHandler, self).__init__(*args, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def registerRolloverCallback(cls, callback, *args, **kwargs):
|
||||
cls.rollover_callbacks.append((callback, args, kwargs))
|
||||
@@ -67,6 +73,7 @@ class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandle
|
||||
cls.do_rollover = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
|
||||
super(SerialLogHandler, self).__init__(*args, **kwargs)
|
||||
self.cleanupFiles()
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
"""
|
||||
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
|
||||
registered plugin types.
|
||||
@@ -13,8 +15,6 @@ registered plugin types.
|
||||
:members:
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -25,9 +25,10 @@ import threading
|
||||
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
from octoprint.plugin.types import *
|
||||
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
|
||||
from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules
|
||||
|
||||
from octoprint.util import deprecated
|
||||
from octoprint.util import deprecated, to_native_str
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
@@ -37,7 +38,7 @@ def _validate_plugin(phase, plugin_info):
|
||||
|
||||
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):
|
||||
plugin_validators=None, compatibility_ignored_list=None):
|
||||
"""
|
||||
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
|
||||
singleton.
|
||||
@@ -63,6 +64,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
|
||||
plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will
|
||||
not be enabled since they might depend on functionality that is no longer available.
|
||||
plugin_validators (list): A list of additional plugin validators through which to process each plugin.
|
||||
compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as
|
||||
incompatible. This is for development purposes only and should not be used in production.
|
||||
|
||||
Returns:
|
||||
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
|
||||
@@ -86,6 +89,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
"octoprint.printer.factory",
|
||||
"octoprint.access.permissions",
|
||||
"octoprint.timelapse.extensions"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
@@ -104,7 +108,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
|
||||
plugin_blacklist=plugin_blacklist,
|
||||
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
|
||||
plugin_obsolete_hooks=plugin_obsolete_hooks,
|
||||
plugin_validators=plugin_validators)
|
||||
plugin_validators=plugin_validators,
|
||||
compatibility_ignored_list=compatibility_ignored_list)
|
||||
else:
|
||||
raise ValueError("Plugin Manager not initialized yet")
|
||||
return _instance
|
||||
@@ -152,7 +157,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
||||
|
||||
try:
|
||||
get_preprocessors, set_preprocessors = instance.get_settings_preprocessors()
|
||||
except:
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key))
|
||||
return None
|
||||
|
||||
@@ -501,7 +506,7 @@ class PluginSettings(object):
|
||||
self.settings.remove(self._prefix_path())
|
||||
|
||||
def __getattr__(self, item):
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
all_access_methods = list(self.access_methods.keys()) + list(self.deprecated_access_methods.keys())
|
||||
if item in all_access_methods:
|
||||
decorator = None
|
||||
if item in self.deprecated_access_methods:
|
||||
@@ -517,44 +522,9 @@ class PluginSettings(object):
|
||||
|
||||
def _func(*args, **kwargs):
|
||||
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
|
||||
_func.__name__ = item
|
||||
_func.__name__ = to_native_str(item)
|
||||
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
|
||||
|
||||
return _func
|
||||
|
||||
return getattr(self.settings, item)
|
||||
|
||||
##~~ deprecated methods follow
|
||||
|
||||
# TODO: Remove with release of 1.3.0
|
||||
|
||||
globalGet = deprecated("globalGet has been renamed to global_get",
|
||||
includedoc="Replaced by :func:`global_get`",
|
||||
since="1.2.0-dev-546")(global_get)
|
||||
globalGetInt = deprecated("globalGetInt has been renamed to global_get_int",
|
||||
includedoc="Replaced by :func:`global_get_int`",
|
||||
since="1.2.0-dev-546")(global_get_int)
|
||||
globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float",
|
||||
includedoc="Replaced by :func:`global_get_float`",
|
||||
since="1.2.0-dev-546")(global_get_float)
|
||||
globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean",
|
||||
includedoc="Replaced by :func:`global_get_boolean`",
|
||||
since="1.2.0-dev-546")(global_get_boolean)
|
||||
globalSet = deprecated("globalSet has been renamed to global_set",
|
||||
includedoc="Replaced by :func:`global_set`",
|
||||
since="1.2.0-dev-546")(global_set)
|
||||
globalSetInt = deprecated("globalSetInt has been renamed to global_set_int",
|
||||
includedoc="Replaced by :func:`global_set_int`",
|
||||
since="1.2.0-dev-546")(global_set_int)
|
||||
globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float",
|
||||
includedoc="Replaced by :func:`global_set_float`",
|
||||
since="1.2.0-dev-546")(global_set_float)
|
||||
globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean",
|
||||
includedoc="Replaced by :func:`global_set_boolean`",
|
||||
since="1.2.0-dev-546")(global_set_boolean)
|
||||
globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder",
|
||||
includedoc="Replaced by :func:`global_get_basefolder`",
|
||||
since="1.2.0-dev-546")(global_get_basefolder)
|
||||
getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path",
|
||||
includedoc="Replaced by :func:`get_plugin_logfile_path`",
|
||||
since="1.2.0-dev-546")(get_plugin_logfile_path)
|
||||
+211
-116
@@ -1,4 +1,6 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
"""
|
||||
In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic
|
||||
way and could be extracted into a separate Python module in the future.
|
||||
@@ -20,32 +22,55 @@ way and could be extracted into a separate Python module in the future.
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
import imp
|
||||
import io
|
||||
from collections import defaultdict, namedtuple, OrderedDict
|
||||
import logging
|
||||
import fnmatch
|
||||
import inspect
|
||||
import sys
|
||||
|
||||
import pkg_resources
|
||||
import pkginfo
|
||||
|
||||
from past.builtins import unicode
|
||||
|
||||
from octoprint.util import to_unicode
|
||||
from octoprint.util import to_unicode, sv
|
||||
from octoprint.util.version import is_python_compatible, get_python_version_string
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
|
||||
if sys.version_info[0] == 2:
|
||||
# noinspection PyDeprecation
|
||||
import imp
|
||||
else:
|
||||
# deprecated in Python 3.4+ and hence vendored for now
|
||||
import octoprint.vendor.imp as imp
|
||||
|
||||
|
||||
# noinspection PyDeprecation
|
||||
def _find_module(name, path=None):
|
||||
if path is not None:
|
||||
spec = imp.find_module(name, [path])
|
||||
else:
|
||||
spec = imp.find_module(name)
|
||||
return spec[1], spec
|
||||
|
||||
|
||||
# noinspection PyDeprecation
|
||||
def _load_module(name, spec):
|
||||
f, filename, details = spec
|
||||
return imp.load_module(name, f, filename, details)
|
||||
|
||||
|
||||
EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version")
|
||||
FolderOrigin = namedtuple("FolderOrigin", "type, folder")
|
||||
ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder")
|
||||
@@ -93,6 +118,18 @@ class PluginInfo(object):
|
||||
attr_license = '__plugin_license__'
|
||||
""" Module attribute from which to retrieve the plugin's license. """
|
||||
|
||||
attr_pythoncompat = '__plugin_pythoncompat__'
|
||||
"""
|
||||
Module attribute from which to retrieve the plugin's python compatibility string.
|
||||
|
||||
If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
|
||||
Python 2 but not Python 3.
|
||||
|
||||
To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
|
||||
|
||||
Bundled plugins will automatically be assumed to be compatible.
|
||||
"""
|
||||
|
||||
attr_hooks = '__plugin_hooks__'
|
||||
""" Module attribute from which to retrieve the plugin's provided hooks. """
|
||||
|
||||
@@ -148,10 +185,12 @@ class PluginInfo(object):
|
||||
self.enabled = True
|
||||
self.blacklisted = False
|
||||
self.forced_disabled = False
|
||||
self.incompatible = False
|
||||
self.bundled = False
|
||||
self.loaded = False
|
||||
self.managable = True
|
||||
self.needs_restart = False
|
||||
self.invalid_syntax = False
|
||||
|
||||
self._name = name
|
||||
self._version = version
|
||||
@@ -163,12 +202,14 @@ class PluginInfo(object):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._cached_parsed_metadata = parsed_metadata
|
||||
if self._cached_parsed_metadata is None:
|
||||
self._cached_parsed_metadata = self._parse_metadata()
|
||||
|
||||
def validate(self, phase, additional_validators=None):
|
||||
result = True
|
||||
|
||||
if phase == "before_import":
|
||||
result = not self.forced_disabled and not self.blacklisted and result
|
||||
result = not self.forced_disabled and not self.blacklisted and not self.incompatible and not self.invalid_syntax and result
|
||||
|
||||
elif phase == "before_load":
|
||||
# if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__
|
||||
@@ -210,13 +251,13 @@ class PluginInfo(object):
|
||||
|
||||
def __str__(self):
|
||||
if self.version:
|
||||
return u"{name} ({version})".format(name=self.name, version=self.version)
|
||||
return "{name} ({version})".format(name=self.name, version=self.version)
|
||||
else:
|
||||
return to_unicode(self.name)
|
||||
|
||||
def long_str(self, show_bundled=False, bundled_strs=(u" [B]", u""),
|
||||
show_location=False, location_str=u" - {location}",
|
||||
show_enabled=False, enabled_strs=(u"* ", u" ", u"X ")):
|
||||
def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""),
|
||||
show_location=False, location_str=" - {location}",
|
||||
show_enabled=False, enabled_strs=("* ", " ", "X ", "C ")):
|
||||
"""
|
||||
Long string representation of the plugin's information. Will return a string of the format ``<enabled><str(self)><bundled><location>``.
|
||||
|
||||
@@ -224,8 +265,9 @@ class PluginInfo(object):
|
||||
The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows:
|
||||
|
||||
``enabled_str``
|
||||
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.
|
||||
a 4-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
|
||||
and the fourth when it is incompatible.
|
||||
``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.
|
||||
@@ -245,11 +287,16 @@ class PluginInfo(object):
|
||||
str: The long string representation of the plugin as described above
|
||||
"""
|
||||
if show_enabled:
|
||||
ret = to_unicode(enabled_strs[2]) if self.blacklisted \
|
||||
else (to_unicode(enabled_strs[0]) if self.enabled
|
||||
else to_unicode(enabled_strs[1]))
|
||||
if self.incompatible:
|
||||
ret = to_unicode(enabled_strs[3])
|
||||
elif self.blacklisted:
|
||||
ret = to_unicode(enabled_strs[2])
|
||||
elif not self.enabled:
|
||||
ret = to_unicode(enabled_strs[1])
|
||||
else:
|
||||
ret = to_unicode(enabled_strs[0])
|
||||
else:
|
||||
ret = u""
|
||||
ret = ""
|
||||
|
||||
ret += unicode(self)
|
||||
|
||||
@@ -384,10 +431,23 @@ class PluginInfo(object):
|
||||
default=self._license,
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def pythoncompat(self):
|
||||
"""
|
||||
Python compatibility string of the plugin module as defined in :attr:`attr_pythoncompat` if available, otherwise
|
||||
defaults to ``>=2.7,<3``.
|
||||
|
||||
Returns:
|
||||
str: Python compatibility string of the plugin
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_pythoncompat,
|
||||
default=">=2.7,<3",
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def hooks(self):
|
||||
"""
|
||||
Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defiend in
|
||||
Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in
|
||||
:attr:`attr_hooks` if available, otherwise an empty dictionary is returned.
|
||||
|
||||
Returns:
|
||||
@@ -491,8 +551,6 @@ class PluginInfo(object):
|
||||
|
||||
@property
|
||||
def parsed_metadata(self):
|
||||
if self._cached_parsed_metadata is None:
|
||||
self._cached_parsed_metadata = self._parse_metadata()
|
||||
return self._cached_parsed_metadata
|
||||
|
||||
def _parse_metadata(self):
|
||||
@@ -517,18 +575,19 @@ class PluginInfo(object):
|
||||
try:
|
||||
import ast
|
||||
|
||||
with open(path, "rb") as f:
|
||||
root = ast.parse(f.read())
|
||||
with io.open(path, 'rb') as f:
|
||||
root = ast.parse(f.read(), filename=path)
|
||||
|
||||
assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets,
|
||||
root.body)
|
||||
assignments = list(filter(lambda x: isinstance(x, ast.Assign) and x.targets,
|
||||
root.body))
|
||||
|
||||
def extract_target_ids(node):
|
||||
return map(lambda x: x.id,
|
||||
filter(lambda x: isinstance(x, ast.Name), node.targets))
|
||||
return list(map(lambda x: x.id,
|
||||
filter(lambda x: isinstance(x, ast.Name), node.targets)))
|
||||
|
||||
for key in (self.__class__.attr_name, self.__class__.attr_version, self.__class__.attr_author,
|
||||
self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license):
|
||||
self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license,
|
||||
self.__class__.attr_pythoncompat):
|
||||
for a in reversed(assignments):
|
||||
targets = extract_target_ids(a)
|
||||
if key in targets:
|
||||
@@ -541,8 +600,11 @@ class PluginInfo(object):
|
||||
result[key] = a.value.args[0].s
|
||||
|
||||
break
|
||||
except:
|
||||
pass
|
||||
except SyntaxError:
|
||||
self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key))
|
||||
self.invalid_syntax = True
|
||||
except Exception:
|
||||
self._logger.exception("Error while parsing AST from {} for plugin {}".format(path, self.key))
|
||||
|
||||
return result
|
||||
|
||||
@@ -557,7 +619,7 @@ class PluginManager(object):
|
||||
|
||||
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):
|
||||
plugin_obsolete_hooks=None, plugin_validators=None, compatibility_ignored_list=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if logging_prefix is None:
|
||||
@@ -572,6 +634,8 @@ class PluginManager(object):
|
||||
plugin_disabled_list = []
|
||||
if plugin_blacklist is None:
|
||||
plugin_blacklist = []
|
||||
if compatibility_ignored_list is None:
|
||||
compatibility_ignored_list = []
|
||||
|
||||
self.plugin_folders = plugin_folders
|
||||
self.plugin_bases = plugin_bases
|
||||
@@ -582,6 +646,7 @@ class PluginManager(object):
|
||||
self.plugin_obsolete_hooks = plugin_obsolete_hooks
|
||||
self.plugin_validators = plugin_validators
|
||||
self.logging_prefix = logging_prefix
|
||||
self.compatibility_ignored_list = compatibility_ignored_list
|
||||
|
||||
self.enabled_plugins = dict()
|
||||
self.disabled_plugins = dict()
|
||||
@@ -633,7 +698,7 @@ class PluginManager(object):
|
||||
|
||||
@property
|
||||
def plugin_hooks(self):
|
||||
return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()}
|
||||
return {key: list(map(lambda v: (v[1], v[2]), value)) for key, value in self._plugin_hooks.items()}
|
||||
|
||||
def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False):
|
||||
added, found = self._find_plugins(existing=existing, ignore_uninstalled=ignore_uninstalled)
|
||||
@@ -656,8 +721,8 @@ class PluginManager(object):
|
||||
ignored_uninstalled=ignore_uninstalled)
|
||||
result_added.update(added)
|
||||
result_found += found
|
||||
except:
|
||||
self.logger.exception(u"Error fetching plugins from folders")
|
||||
except Exception:
|
||||
self.logger.exception("Error fetching plugins from folders")
|
||||
|
||||
if self.plugin_entry_points:
|
||||
existing.update(result_added)
|
||||
@@ -667,8 +732,8 @@ class PluginManager(object):
|
||||
ignore_uninstalled=ignore_uninstalled)
|
||||
result_added.update(added)
|
||||
result_found += found
|
||||
except:
|
||||
self.logger.exception(u"Error fetching plugins from entry points")
|
||||
except Exception:
|
||||
self.logger.exception("Error fetching plugins from entry points")
|
||||
|
||||
return result_added, result_found
|
||||
|
||||
@@ -690,7 +755,7 @@ class PluginManager(object):
|
||||
actual_readonly = not os.access(folder, os.W_OK)
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn(u"Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
self.logger.warning("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
for entry in scandir(folder):
|
||||
@@ -735,10 +800,10 @@ class PluginManager(object):
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.enabled = False
|
||||
added[key] = plugin
|
||||
except:
|
||||
self.logger.exception(u"Error processing folder entry {!r} from folder {}".format(entry, folder))
|
||||
except:
|
||||
self.logger.exception(u"Error processing folder {}".format(folder))
|
||||
except Exception:
|
||||
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
|
||||
except Exception:
|
||||
self.logger.exception("Error processing folder {}".format(folder))
|
||||
|
||||
return added, found
|
||||
|
||||
@@ -767,9 +832,9 @@ class PluginManager(object):
|
||||
for entry in gen:
|
||||
try:
|
||||
yield entry
|
||||
except:
|
||||
self.logger.exception(u"Something went wrong while processing the entry points of a package in the "
|
||||
u"Python environment - broken entry_points.txt in some package?")
|
||||
except Exception:
|
||||
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?")
|
||||
|
||||
for group in groups:
|
||||
for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)):
|
||||
@@ -787,8 +852,8 @@ class PluginManager(object):
|
||||
package_name = entry_point.dist.project_name
|
||||
try:
|
||||
entry_point_metadata = EntryPointMetadata(entry_point)
|
||||
except:
|
||||
self.logger.exception(u"Something went wrong while retrieving metadata for module {}".format(module_name))
|
||||
except Exception:
|
||||
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
|
||||
else:
|
||||
kwargs.update(dict(
|
||||
name=entry_point_metadata.name,
|
||||
@@ -817,8 +882,8 @@ class PluginManager(object):
|
||||
plugin.location))
|
||||
|
||||
added[key] = plugin
|
||||
except:
|
||||
self.logger.exception(u"Error processing entry point {!r} for group {}".format(entry_point, group))
|
||||
except Exception:
|
||||
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
|
||||
|
||||
return added, found
|
||||
|
||||
@@ -827,43 +892,53 @@ class PluginManager(object):
|
||||
# TODO error handling
|
||||
try:
|
||||
if folder:
|
||||
module = imp.find_module(key, [folder])
|
||||
location, spec = _find_module(key, path=folder)
|
||||
elif module_name:
|
||||
module = imp.find_module(module_name)
|
||||
location, spec = _find_module(module_name)
|
||||
else:
|
||||
return None
|
||||
except:
|
||||
self.logger.warn(u"Could not locate plugin {key}".format(key=key))
|
||||
except Exception:
|
||||
self.logger.exception("Could not locate plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
# Create a simple dummy entry first ...
|
||||
plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author,
|
||||
plugin = PluginInfo(key, location, None, name=name, version=version, description=summary, author=author,
|
||||
url=url, license=license)
|
||||
plugin.bundled = bundled
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
self.logger.info(u"Plugin {} is disabled.".format(plugin))
|
||||
self.logger.info("Plugin {} is disabled.".format(plugin))
|
||||
plugin.forced_disabled = True
|
||||
|
||||
if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)):
|
||||
self.logger.warn(u"Plugin {} is blacklisted.".format(plugin))
|
||||
self.logger.warning("Plugin {} is blacklisted.".format(plugin))
|
||||
plugin.blacklisted = True
|
||||
|
||||
python_version = get_python_version_string()
|
||||
if self._is_plugin_incompatible(key, plugin):
|
||||
if plugin.invalid_syntax:
|
||||
self.logger.warning("Plugin {} can't be compiled under Python {} due to invalid syntax".format(plugin, python_version))
|
||||
else:
|
||||
self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat))
|
||||
plugin.incompatible = True
|
||||
|
||||
if not plugin.validate("before_import", additional_validators=self.plugin_validators):
|
||||
return plugin
|
||||
|
||||
# ... then create and return the real one
|
||||
return self._import_plugin(key, *module,
|
||||
module_name=module_name, name=name, version=version, summary=summary, author=author, url=url,
|
||||
license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata)
|
||||
return self._import_plugin(key, spec,
|
||||
module_name=module_name, name=name, location=plugin.location, version=version,
|
||||
summary=summary, author=author, url=url, license=license, bundled=bundled,
|
||||
parsed_metadata=plugin.parsed_metadata)
|
||||
|
||||
def _import_plugin(self, key, f, filename, description, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
|
||||
def _import_plugin(self, key, spec, module_name=None, name=None, location=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
|
||||
try:
|
||||
if module_name:
|
||||
instance = imp.load_module(module_name, f, filename, description)
|
||||
module = _load_module(module_name, spec)
|
||||
else:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
plugin = PluginInfo(key, filename, instance,
|
||||
module = _load_module(key, spec)
|
||||
|
||||
plugin = PluginInfo(key, location, module,
|
||||
name=name,
|
||||
version=version,
|
||||
description=summary,
|
||||
@@ -871,15 +946,16 @@ class PluginManager(object):
|
||||
url=url,
|
||||
license=license,
|
||||
parsed_metadata=parsed_metadata)
|
||||
|
||||
plugin.bundled = bundled
|
||||
except:
|
||||
self.logger.exception(u"Error loading plugin {key}".format(key=key))
|
||||
except Exception:
|
||||
self.logger.exception("Error loading plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
if plugin.check():
|
||||
return plugin
|
||||
else:
|
||||
self.logger.info(u"Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
|
||||
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
def _is_plugin_disabled(self, key):
|
||||
@@ -888,6 +964,11 @@ class PluginManager(object):
|
||||
def _is_plugin_blacklisted(self, key):
|
||||
return key in self.plugin_blacklist
|
||||
|
||||
def _is_plugin_incompatible(self, key, plugin):
|
||||
return not plugin.bundled \
|
||||
and not is_python_compatible(plugin.pythoncompat) \
|
||||
and key not in self.compatibility_ignored_list
|
||||
|
||||
def _is_plugin_version_blacklisted(self, key, version):
|
||||
def matches_plugin(entry):
|
||||
if isinstance(entry, (tuple, list)) and len(entry) == 2:
|
||||
@@ -899,7 +980,7 @@ class PluginManager(object):
|
||||
self.plugin_blacklist))
|
||||
|
||||
def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None):
|
||||
self.logger.info(u"Loading plugins from {folders} and installed plugin packages...".format(
|
||||
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))
|
||||
))
|
||||
|
||||
@@ -910,7 +991,7 @@ class PluginManager(object):
|
||||
incl_all_found=True)
|
||||
|
||||
# let's clean everything we DIDN'T find first
|
||||
removed = [key for key in self.enabled_plugins.keys() + self.disabled_plugins.keys() if key not in found]
|
||||
removed = [key for key in list(self.enabled_plugins.keys()) + list(self.disabled_plugins.keys()) if key not in found]
|
||||
for key in removed:
|
||||
try:
|
||||
del self.enabled_plugins[key]
|
||||
@@ -943,7 +1024,7 @@ class PluginManager(object):
|
||||
try:
|
||||
if plugin.loaded and not plugin.forced_disabled:
|
||||
if plugin.blacklisted:
|
||||
self.logger.warn(u"Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
continue
|
||||
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
|
||||
except PluginNeedsRestart:
|
||||
@@ -956,9 +1037,9 @@ class PluginManager(object):
|
||||
force_reload=force_reload)
|
||||
|
||||
if len(self.enabled_plugins) <= 0:
|
||||
self.logger.info(u"No plugins found")
|
||||
self.logger.info("No plugins found")
|
||||
else:
|
||||
self.logger.info(u"Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
|
||||
self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
|
||||
count=len(self.enabled_plugins) + len(self.disabled_plugins),
|
||||
implementations=len(self.plugin_implementations),
|
||||
hooks=sum(map(lambda x: len(x), self.plugin_hooks.values()))
|
||||
@@ -966,7 +1047,7 @@ class PluginManager(object):
|
||||
|
||||
def mark_plugin(self, name, **kwargs):
|
||||
if not name in self.plugins:
|
||||
self.logger.debug(u"Trying to mark an unknown plugin {name}".format(**locals()))
|
||||
self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals()))
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if value is None:
|
||||
@@ -985,7 +1066,7 @@ class PluginManager(object):
|
||||
|
||||
def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True):
|
||||
if not name in self.plugins:
|
||||
self.logger.warn(u"Trying to load an unknown plugin {name}".format(**locals()))
|
||||
self.logger.warning("Trying to load an unknown plugin {name}".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -1000,15 +1081,15 @@ class PluginManager(object):
|
||||
self.on_plugin_loaded(name, plugin)
|
||||
plugin.loaded = True
|
||||
|
||||
self.logger.debug(u"Loaded plugin {name}: {plugin}".format(**locals()))
|
||||
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
except:
|
||||
self.logger.exception(u"There was an error loading plugin %s" % name)
|
||||
except Exception:
|
||||
self.logger.exception("There was an error loading plugin %s" % name)
|
||||
|
||||
def unload_plugin(self, name):
|
||||
if not name in self.plugins:
|
||||
self.logger.warn(u"Trying to unload unknown plugin {name}".format(**locals()))
|
||||
self.logger.warning("Trying to unload unknown plugin {name}".format(**locals()))
|
||||
return
|
||||
|
||||
plugin = self.plugins[name]
|
||||
@@ -1028,11 +1109,11 @@ class PluginManager(object):
|
||||
|
||||
plugin.loaded = False
|
||||
|
||||
self.logger.debug(u"Unloaded plugin {name}: {plugin}".format(**locals()))
|
||||
self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals()))
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
except:
|
||||
self.logger.exception(u"There was an error unloading plugin {name}".format(**locals()))
|
||||
except Exception:
|
||||
self.logger.exception("There was an error unloading plugin {name}".format(**locals()))
|
||||
|
||||
# make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins
|
||||
if name in self.enabled_plugins:
|
||||
@@ -1042,7 +1123,7 @@ class PluginManager(object):
|
||||
|
||||
def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False):
|
||||
if not name in self.disabled_plugins:
|
||||
self.logger.warn(u"Tried to enable plugin {name}, however it is not disabled".format(**locals()))
|
||||
self.logger.warning("Tried to enable plugin {name}, however it is not disabled".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -1062,7 +1143,7 @@ class PluginManager(object):
|
||||
self._activate_plugin(name, plugin)
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
except:
|
||||
except Exception:
|
||||
self.logger.exception("There was an error while enabling plugin {name}".format(**locals()))
|
||||
return False
|
||||
else:
|
||||
@@ -1078,13 +1159,13 @@ class PluginManager(object):
|
||||
plugin.implementation.on_plugin_enabled()
|
||||
self.on_plugin_enabled(name, plugin)
|
||||
|
||||
self.logger.debug(u"Enabled plugin {name}: {plugin}".format(**locals()))
|
||||
self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals()))
|
||||
|
||||
return True
|
||||
|
||||
def disable_plugin(self, name, plugin=None):
|
||||
if not name in self.enabled_plugins:
|
||||
self.logger.warn(u"Tried to disable plugin {name}, however it is not enabled".format(**locals()))
|
||||
self.logger.warning("Tried to disable plugin {name}, however it is not enabled".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -1098,8 +1179,8 @@ class PluginManager(object):
|
||||
self._deactivate_plugin(name, plugin)
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
except:
|
||||
self.logger.exception(u"There was an error while disabling plugin {name}".format(**locals()))
|
||||
except Exception:
|
||||
self.logger.exception("There was an error while disabling plugin {name}".format(**locals()))
|
||||
return False
|
||||
else:
|
||||
if name in self.enabled_plugins:
|
||||
@@ -1111,7 +1192,7 @@ class PluginManager(object):
|
||||
plugin.implementation.on_plugin_disabled()
|
||||
self.on_plugin_disabled(name, plugin)
|
||||
|
||||
self.logger.debug(u"Disabled plugin {name}: {plugin}".format(**locals()))
|
||||
self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals()))
|
||||
|
||||
return True
|
||||
|
||||
@@ -1123,7 +1204,7 @@ class PluginManager(object):
|
||||
try:
|
||||
callback, order = self._get_callback_and_order(definition)
|
||||
except ValueError as e:
|
||||
self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
continue
|
||||
|
||||
self._plugin_hooks[hook].append((order, name, callback))
|
||||
@@ -1142,7 +1223,7 @@ class PluginManager(object):
|
||||
try:
|
||||
callback, order = self._get_callback_and_order(definition)
|
||||
except ValueError as e:
|
||||
self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
continue
|
||||
|
||||
try:
|
||||
@@ -1201,7 +1282,7 @@ class PluginManager(object):
|
||||
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
|
||||
hooks = hooks[0]
|
||||
|
||||
hooks = filter(lambda hook: hook is not None, hooks)
|
||||
hooks = list(filter(lambda hook: hook is not None, hooks))
|
||||
if not hooks:
|
||||
return False
|
||||
if not plugin or not plugin.hooks:
|
||||
@@ -1235,7 +1316,7 @@ class PluginManager(object):
|
||||
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
|
||||
hooks = hooks[0]
|
||||
|
||||
hooks = filter(lambda hook: hook is not None, hooks)
|
||||
hooks = list(filter(lambda hook: hook is not None, hooks))
|
||||
if not hooks:
|
||||
return False
|
||||
if not hook:
|
||||
@@ -1273,7 +1354,7 @@ class PluginManager(object):
|
||||
if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)):
|
||||
mixins = mixins[0]
|
||||
|
||||
mixins = filter(lambda mixin: mixin is not None, mixins)
|
||||
mixins = list(filter(lambda mixin: mixin is not None, mixins))
|
||||
if not mixins:
|
||||
return False
|
||||
if not plugin or not plugin.implementation:
|
||||
@@ -1289,7 +1370,7 @@ class PluginManager(object):
|
||||
additional_pre_inits=additional_pre_inits,
|
||||
additional_post_inits=additional_post_inits)
|
||||
|
||||
self.logger.info(u"Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||
|
||||
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
if plugin.implementation is None:
|
||||
@@ -1343,8 +1424,8 @@ class PluginManager(object):
|
||||
for factory in inject_factories:
|
||||
try:
|
||||
return_value = factory(name, implementation)
|
||||
except:
|
||||
self.logger.exception(u"Exception while executing injection factory %r" % factory)
|
||||
except Exception:
|
||||
self.logger.exception("Exception while executing injection factory %r" % factory)
|
||||
else:
|
||||
if return_value is not None:
|
||||
if isinstance(return_value, dict):
|
||||
@@ -1368,19 +1449,19 @@ class PluginManager(object):
|
||||
if isinstance(e, PluginLifecycleException):
|
||||
raise e
|
||||
else:
|
||||
self.logger.exception(u"Exception while initializing plugin {name}, disabling it".format(**locals()))
|
||||
self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals()))
|
||||
return False
|
||||
else:
|
||||
self.on_plugin_implementations_initialized(name, plugin)
|
||||
|
||||
self.logger.debug(u"Initialized plugin mixin implementation for plugin {name}".format(**locals()))
|
||||
self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals()))
|
||||
return True
|
||||
|
||||
|
||||
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()
|
||||
all_plugins = list(self.enabled_plugins.values()) + list(self.disabled_plugins.values())
|
||||
|
||||
def _log(message, level=logging.INFO):
|
||||
if only_to_handler is not None:
|
||||
@@ -1390,7 +1471,7 @@ class PluginManager(object):
|
||||
self.logger.log(level, message)
|
||||
|
||||
if len(all_plugins) <= 0:
|
||||
_log(u"No plugins available")
|
||||
_log("No plugins available")
|
||||
else:
|
||||
formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
|
||||
bundled_strs=bundled_str,
|
||||
@@ -1399,8 +1480,10 @@ class PluginManager(object):
|
||||
show_enabled=show_enabled,
|
||||
enabled_strs=enabled_str),
|
||||
sorted(self.plugins.values(), key=lambda x: unicode(x).lower())))
|
||||
_log(u"{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
|
||||
plugins=formatted_plugins))
|
||||
legend = "Prefix legend: {1} = disabled, {2} = blacklisted, {3} = incompatible".format(*enabled_str)
|
||||
_log("{count} plugin(s) registered with the system:\n{plugins}\n{legend}".format(count=len(all_plugins),
|
||||
plugins=formatted_plugins,
|
||||
legend=legend))
|
||||
|
||||
def get_plugin(self, identifier, require_enabled=True):
|
||||
"""
|
||||
@@ -1491,18 +1574,18 @@ class PluginManager(object):
|
||||
if sorting_context is not None and isinstance(impl[1], SortablePlugin):
|
||||
try:
|
||||
sorting_value = impl[1].get_sorting_key(sorting_context)
|
||||
except:
|
||||
self.logger.exception(u"Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
|
||||
except Exception:
|
||||
self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
|
||||
|
||||
if sorting_value is not None:
|
||||
try:
|
||||
sorting_value = int(sorting_value)
|
||||
except ValueError:
|
||||
self.logger.warn(u"The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
|
||||
self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
|
||||
sorting_value = None
|
||||
|
||||
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
|
||||
return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0]
|
||||
return sorting_value is None, sv(sorting_value), not plugin_info.bundled if plugin_info else True, sv(impl[0])
|
||||
|
||||
return [impl[1] for impl in sorted(result, key=sort_func)]
|
||||
|
||||
@@ -1520,7 +1603,7 @@ class PluginManager(object):
|
||||
|
||||
assert callable(f)
|
||||
implementations = self.get_implementations(*types, sorting_context=kwargs.get("sorting_context", None))
|
||||
return filter(f, implementations)
|
||||
return list(filter(f, implementations))
|
||||
|
||||
def get_helpers(self, name, *helpers):
|
||||
"""
|
||||
@@ -1551,7 +1634,8 @@ class PluginManager(object):
|
||||
def register_message_receiver(self, client):
|
||||
"""
|
||||
Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two
|
||||
input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself).
|
||||
input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself), and one
|
||||
optional keyword argument, ``permissions`` (an optional list of permissions to test against).
|
||||
"""
|
||||
|
||||
if client is None:
|
||||
@@ -1563,25 +1647,32 @@ class PluginManager(object):
|
||||
Unregisters a ``client`` for receiving plugin messages.
|
||||
"""
|
||||
|
||||
self.registered_clients.remove(client)
|
||||
try:
|
||||
self.registered_clients.remove(client)
|
||||
except ValueError:
|
||||
# not registered
|
||||
pass
|
||||
|
||||
def send_plugin_message(self, plugin, data):
|
||||
def send_plugin_message(self, plugin, data, permissions=None):
|
||||
"""
|
||||
Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them
|
||||
with the two arguments.
|
||||
with the three arguments.
|
||||
|
||||
Arguments:
|
||||
plugin (str): The sending plugin's identifier.
|
||||
data (object): The message.
|
||||
permissions (list): A list of permissions to test against in the client.
|
||||
"""
|
||||
|
||||
for client in self.registered_clients:
|
||||
try: client(plugin, data)
|
||||
except: self.logger.exception(u"Exception while sending plugin data to client")
|
||||
try:
|
||||
client(plugin, data, permissions=permissions)
|
||||
except Exception:
|
||||
self.logger.exception("Exception while sending plugin data to client")
|
||||
|
||||
def _sort_hooks(self, hook):
|
||||
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
|
||||
key=lambda x: (x[0] is None, x[0], x[1], x[2]))
|
||||
key=lambda x: (x[0] is None, sv(x[0]), sv(x[1]), sv(x[2])))
|
||||
|
||||
def _get_callback_and_order(self, hook):
|
||||
if callable(hook):
|
||||
@@ -1632,13 +1723,14 @@ def is_editable_install(install_dir, package, module, location):
|
||||
if os.path.isfile(package_link):
|
||||
expected_target = os.path.normcase(os.path.realpath(location))
|
||||
try:
|
||||
with open(package_link) as f:
|
||||
with io.open(package_link, 'rt', encoding='utf-8') as f:
|
||||
contents = f.readlines()
|
||||
for line in contents:
|
||||
target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module)))
|
||||
if target == expected_target:
|
||||
return True
|
||||
except:
|
||||
except Exception:
|
||||
raise # TODO really ignore this?
|
||||
pass
|
||||
return False
|
||||
|
||||
@@ -1658,10 +1750,13 @@ class EntryPointMetadata(pkginfo.Distribution):
|
||||
for metadata_file in metadata_files:
|
||||
try:
|
||||
return self.entry_point.dist.get_metadata(metadata_file)
|
||||
except:
|
||||
except (IOError, OSError):
|
||||
# file not found, metadata file might be missing, ignore
|
||||
# IOError: file not found in Py2
|
||||
# OSError (specifically FileNotFoundError): file not found in Py3
|
||||
pass
|
||||
|
||||
warnings.warn('No package metadata found for package: {}'.format(self.entry_point.module_name))
|
||||
warnings.warn('No package metadata found for package {}'.format(self.entry_point.module_name))
|
||||
|
||||
|
||||
class Plugin(object):
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
"""
|
||||
This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent
|
||||
class, :class:`OctoPrintPlugin`.
|
||||
@@ -16,8 +18,6 @@ Please note that the plugin implementation types are documented in the section
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -66,7 +66,7 @@ class OctoPrintPlugin(Plugin):
|
||||
|
||||
.. attribute:: _app_session_manager
|
||||
|
||||
The :class:`~octoprint.users.SessionManager` instance. Injected by the plugin core system upon initialization of
|
||||
The :class:`~octoprint.access.users.SessionManager` instance. Injected by the plugin core system upon initialization of
|
||||
the implementation.
|
||||
|
||||
.. attribute:: _plugin_lifecycle_manager
|
||||
@@ -76,7 +76,7 @@ class OctoPrintPlugin(Plugin):
|
||||
|
||||
.. attribute:: _user_manager
|
||||
|
||||
The :class:`~octoprint.users.UserManager` instance. Injected by the plugin core system upon initialization
|
||||
The :class:`~octoprint.access.users.UserManager` instance. Injected by the plugin core system upon initialization
|
||||
of the implementation.
|
||||
|
||||
.. attribute:: _connectivity_checker
|
||||
@@ -1497,6 +1497,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
from flask_login import current_user
|
||||
import copy
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
data = copy.deepcopy(self._settings.get_all_data(merged=True))
|
||||
if self.config_version_key in data:
|
||||
del data[self.config_version_key]
|
||||
@@ -1540,8 +1542,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
else:
|
||||
node[key] = None
|
||||
|
||||
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous(),
|
||||
admin=lambda: current_user is not None and not current_user.is_anonymous() and current_user.is_admin(),
|
||||
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous,
|
||||
admin=lambda: current_user is not None and current_user.has_permission(Permissions.SETTINGS),
|
||||
never=lambda: False)
|
||||
|
||||
for level, condition in conditions.items():
|
||||
@@ -1617,8 +1619,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
Retrieves the list of paths in the plugin's settings which be restricted on the REST API.
|
||||
|
||||
Override this in your plugin's implementation to restrict whether a path should only be returned to logged in
|
||||
users & admins, only to admins, or never on the REST API.
|
||||
Override this in your plugin's implementation to restrict whether a path should only be returned to users with
|
||||
the SETTINGS permission, any logged in users, or never on the REST API.
|
||||
|
||||
Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of
|
||||
the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin``
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -7,6 +7,8 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server import user_permission
|
||||
from octoprint.access import USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.events import Events
|
||||
|
||||
import flask
|
||||
@@ -53,10 +55,21 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._cap_prompt_support = False
|
||||
|
||||
def initialize(self):
|
||||
self._enable = self._settings.get([b"enable"])
|
||||
self._command = self._settings.get([b"command"])
|
||||
self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"])
|
||||
self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"])
|
||||
self._enable = self._settings.get(["enable"])
|
||||
self._command = self._settings.get(["command"])
|
||||
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
|
||||
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="INTERACT",
|
||||
name="Interact with printer prompts",
|
||||
description=gettext("Allows to see and interact with printer prompts"),
|
||||
default_groups=[USER_GROUP],
|
||||
roles=["interact"])
|
||||
]
|
||||
|
||||
#~ AssetPlugin
|
||||
|
||||
@@ -82,10 +95,10 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def on_settings_save(self, data):
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
self._enable = self._settings.get([b"enable"])
|
||||
self._command = self._settings.get([b"command"])
|
||||
self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"])
|
||||
self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"])
|
||||
self._enable = self._settings.get(["enable"])
|
||||
self._command = self._settings.get(["command"])
|
||||
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
|
||||
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
|
||||
|
||||
#~ SimpleApiPlugin
|
||||
|
||||
@@ -94,7 +107,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if command == "select":
|
||||
if not user_permission.can():
|
||||
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
|
||||
return flask.abort(403, "Insufficient permissions")
|
||||
|
||||
if self._prompt is None:
|
||||
@@ -107,7 +120,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._answer_prompt(choice)
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not user_permission.can():
|
||||
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
|
||||
return flask.abort(403, "Insufficient permissions")
|
||||
if self._prompt is None:
|
||||
return flask.jsonify()
|
||||
@@ -122,39 +135,39 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~ action command handler
|
||||
|
||||
def action_command_handler(self, comm, line, action, *args, **kwargs):
|
||||
if not action.startswith(b"prompt_"):
|
||||
if not action.startswith("prompt_"):
|
||||
return
|
||||
|
||||
parts = action.split(None, 1)
|
||||
if len(parts) == 1:
|
||||
action = parts[0]
|
||||
parameter = b""
|
||||
parameter = ""
|
||||
else:
|
||||
action, parameter = parts
|
||||
|
||||
if action == b"prompt_begin":
|
||||
if action == "prompt_begin":
|
||||
if self._prompt is not None and self._prompt.active:
|
||||
self._logger.warn("Prompt is already defined")
|
||||
self._logger.warning("Prompt is already defined")
|
||||
return
|
||||
self._prompt = Prompt(parameter.strip())
|
||||
|
||||
elif action == b"prompt_choice" or action == b"prompt_button":
|
||||
elif action == "prompt_choice" or action == "prompt_button":
|
||||
if self._prompt is None:
|
||||
return
|
||||
if self._prompt.active:
|
||||
self._logger.warn("Prompt is already active")
|
||||
self._logger.warning("Prompt is already active")
|
||||
return
|
||||
self._prompt.add_choice(parameter.strip())
|
||||
|
||||
elif action == b"prompt_show":
|
||||
elif action == "prompt_show":
|
||||
if self._prompt is None:
|
||||
return
|
||||
if self._prompt.active:
|
||||
self._logger.warn("Prompt is already active")
|
||||
self._logger.warning("Prompt is already active")
|
||||
return
|
||||
self._show_prompt()
|
||||
|
||||
elif action == b"prompt_end":
|
||||
elif action == "prompt_end":
|
||||
if self._prompt is None:
|
||||
return
|
||||
self._close_prompt()
|
||||
@@ -174,7 +187,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
return
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode)
|
||||
return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode)
|
||||
|
||||
#~ capability reporting
|
||||
|
||||
@@ -207,8 +220,11 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
return
|
||||
|
||||
self._close_prompt()
|
||||
self._printer.commands(["{command} S{choice}".format(command=self._command,
|
||||
choice=choice)])
|
||||
if "{choice}" in self._command:
|
||||
self._printer.commands([self._command.format(choice=choice)])
|
||||
else:
|
||||
self._printer.commands(["{command} S{choice}".format(command=self._command,
|
||||
choice=choice)])
|
||||
|
||||
|
||||
__plugin_name__ = "Action Command Prompt Support"
|
||||
@@ -219,7 +235,8 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin your printer wil
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = ActionCommandPromptPlugin()
|
||||
__plugin_hooks__ = {
|
||||
b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
|
||||
b"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
|
||||
b"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler
|
||||
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
|
||||
"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
|
||||
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -3,6 +3,7 @@ $(function() {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
|
||||
self.modal = ko.observable(undefined);
|
||||
|
||||
@@ -17,7 +18,7 @@ $(function() {
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.isUser()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
|
||||
|
||||
OctoPrint.plugins.action_command_prompt.get()
|
||||
.done(self.fromResponse);
|
||||
@@ -72,7 +73,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (!self.loginState.isUser()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
|
||||
if (plugin !== "action_command_prompt") {
|
||||
return;
|
||||
}
|
||||
@@ -97,7 +98,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ActionCommandPromptViewModel,
|
||||
dependencies: ["loginStateViewModel"],
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"],
|
||||
elements: ["#navbar_plugin_action_command_prompt"]
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -9,23 +9,27 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms
|
||||
import octoprint.plugin
|
||||
|
||||
import calendar
|
||||
import codecs
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import threading
|
||||
import sys
|
||||
PY2 = sys.version_info[0] < 3
|
||||
|
||||
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, monotonic_time
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify, count, monotonic_time
|
||||
from flask_babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
|
||||
|
||||
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
@@ -42,6 +46,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._slugify = Slugify()
|
||||
self._slugify.safe_chars = "-_."
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="READ",
|
||||
name="Read announcements",
|
||||
description=gettext("Allows to read announcements"),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["read"]),
|
||||
dict(key="MANAGE",
|
||||
name="Manage announcement subscriptions",
|
||||
description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" "
|
||||
"permission"),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["manage"],
|
||||
permissions=["PLUGIN_ANNOUNCEMENTS_READ"])
|
||||
]
|
||||
|
||||
# StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
@@ -87,7 +109,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
ttl=6*60,
|
||||
display_limit=3,
|
||||
summary_limit=300)
|
||||
settings["enabled_channels"] = settings["channels"].keys()
|
||||
settings["enabled_channels"] = list(settings["channels"].keys())
|
||||
return settings
|
||||
|
||||
def get_settings_version(self):
|
||||
@@ -127,14 +149,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True),
|
||||
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.isAdmin")
|
||||
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)")
|
||||
]
|
||||
|
||||
# Blueprint Plugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
|
||||
def get_channel_data(self):
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
|
||||
@@ -153,7 +175,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
for key, data in channel_configs.items():
|
||||
read_until = channel_configs[key].get("read_until", None)
|
||||
entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True)
|
||||
unread = len(filter(lambda e: not e["read"], entries))
|
||||
unread = count(filter(lambda e: not e["read"], entries))
|
||||
|
||||
if read_until is None and entries:
|
||||
last = entries[0]["published"]
|
||||
@@ -174,14 +196,16 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
def etag():
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
hash.update(repr(sorted(enabled)))
|
||||
hash.update(repr(sorted(forced)))
|
||||
hash.update(OCTOPRINT_VERSION)
|
||||
def hash_update(value):
|
||||
hash.update(value.encode("utf-8"))
|
||||
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]))
|
||||
hash_update(repr(channel_configs[channel]))
|
||||
channel_data = self._get_channel_data_from_cache(channel, channel_configs[channel])
|
||||
hash.update(repr(channel_data))
|
||||
hash_update(repr(channel_data))
|
||||
|
||||
return hash.hexdigest()
|
||||
|
||||
@@ -194,8 +218,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
unless=lambda: force)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
|
||||
def channel_command(self, channel):
|
||||
from octoprint.server.util.flask import get_json_command_from_request
|
||||
from octoprint.server import NO_CONTENT
|
||||
@@ -212,6 +236,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._mark_read_until(channel, until)
|
||||
|
||||
elif command == "toggle":
|
||||
if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can():
|
||||
return flask.make_response("Insufficient rights", 403)
|
||||
self._toggle(channel)
|
||||
|
||||
return NO_CONTENT
|
||||
@@ -339,7 +365,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
now = time.time()
|
||||
if os.stat(channel_path).st_mtime + ttl > now:
|
||||
d = feedparser.parse(channel_path)
|
||||
self._logger.debug(u"Loaded channel {} from cache at {}".format(key, channel_path))
|
||||
self._logger.debug("Loaded channel {} from cache at {}".format(key, channel_path))
|
||||
return d
|
||||
|
||||
return None
|
||||
@@ -354,15 +380,15 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
start = monotonic_time()
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start))
|
||||
except Exception as e:
|
||||
self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start))
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e)))
|
||||
"Could not fetch channel {} from {}".format(key, config["url"]))
|
||||
return None
|
||||
|
||||
response = r.text
|
||||
channel_path = self._get_channel_cache_path(key)
|
||||
with codecs.open(channel_path, mode="w", encoding="utf-8") as f:
|
||||
with io.open(channel_path, mode="wt", encoding="utf-8") as f:
|
||||
f.write(response)
|
||||
return feedparser.parse(response)
|
||||
|
||||
@@ -376,16 +402,16 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while converting entry from feed, skipping it")
|
||||
return result
|
||||
|
||||
def _to_internal_entry(self, entry, read_until=None):
|
||||
"""Convert feed entries to internal data structure."""
|
||||
|
||||
timestamp = entry.get("published_parsed",
|
||||
entry.get("updated_parsed",
|
||||
None))
|
||||
timestamp = entry.get("published_parsed", None)
|
||||
if timestamp is None:
|
||||
timestamp = entry.get("updated_parsed", None)
|
||||
if timestamp is None:
|
||||
return None
|
||||
|
||||
@@ -413,22 +439,22 @@ 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'
|
||||
>>> _strip_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>") # doctest: +ALLOW_UNICODE
|
||||
"<a href='test.html'>I'm a link</a> and this is an image: "
|
||||
>>> _strip_images("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\\">") # doctest: +ALLOW_UNICODE
|
||||
'One and two and three and four '
|
||||
>>> _strip_images("No images here") # doctest: +ALLOW_UNICODE
|
||||
'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'
|
||||
>>> _replace_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback) # doctest: +ALLOW_UNICODE
|
||||
"<a href='test.html'>I'm a link</a> and this is an image: foobar"
|
||||
>>> _replace_images("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) # doctest: +ALLOW_UNICODE
|
||||
'One foobar and two foobar and three foobar and four foobar'
|
||||
"""
|
||||
result = text
|
||||
for match in _image_tag_re.finditer(text):
|
||||
@@ -440,14 +466,14 @@ def _replace_images(text, callback):
|
||||
_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'
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>") # doctest: +ALLOW_UNICODE
|
||||
'<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("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png") # doctest: +ALLOW_UNICODE
|
||||
'<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("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") # doctest: +ALLOW_UNICODE
|
||||
'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("No images here") # doctest: +ALLOW_UNICODE
|
||||
'No images here'
|
||||
"""
|
||||
if placeholder is None:
|
||||
# 1px transparent gif
|
||||
@@ -466,18 +492,22 @@ def _lazy_images(text, placeholder=None):
|
||||
|
||||
def _strip_tags(text):
|
||||
"""
|
||||
>>> _strip_tags(u"<a href='test.html'>Hello world</a><img src='foo.jpg'>")
|
||||
u"Hello world<img src='foo.jpg'>"
|
||||
>>> _strip_tags(u"> > Foo")
|
||||
u'> > Foo'
|
||||
>>> _strip_tags("<a href='test.html'>Hello world</a><img src='foo.jpg'>") # doctest: +ALLOW_UNICODE
|
||||
"Hello world<img src='foo.jpg'>"
|
||||
>>> _strip_tags("> > Foo") # doctest: +ALLOW_UNICODE
|
||||
'> > Foo'
|
||||
"""
|
||||
|
||||
from HTMLParser import HTMLParser
|
||||
try:
|
||||
# noinspection PyCompatibility
|
||||
from html.parser import HTMLParser
|
||||
except ImportError:
|
||||
# noinspection PyCompatibility
|
||||
from HTMLParser import HTMLParser
|
||||
|
||||
class TagStripper(HTMLParser):
|
||||
|
||||
def __init__(self):
|
||||
HTMLParser.__init__(self)
|
||||
def __init__(self, **kw):
|
||||
HTMLParser.__init__(self, **kw)
|
||||
self._fed = []
|
||||
|
||||
def handle_data(self, data):
|
||||
@@ -492,7 +522,7 @@ def _strip_tags(text):
|
||||
def get_data(self):
|
||||
return "".join(self._fed)
|
||||
|
||||
tag_stripper = TagStripper()
|
||||
tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False)
|
||||
tag_stripper.feed(text)
|
||||
return tag_stripper.get_data()
|
||||
|
||||
@@ -504,3 +534,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin you might miss i
|
||||
"regarding security or other critical issues concerning OctoPrint.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = AnnouncementPlugin()
|
||||
|
||||
__plugin_hooks__ = {
|
||||
'octoprint.access.permissions': __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -4,6 +4,7 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self.channels = new ItemListHelper(
|
||||
"plugin.announcements.channels",
|
||||
@@ -67,7 +68,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.markRead = function(channel, until, reload) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
reload = !!reload;
|
||||
|
||||
@@ -93,7 +94,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleChannel = function(channel) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return;
|
||||
|
||||
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
|
||||
|
||||
@@ -118,7 +119,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.retrieveData = function(force) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
var url = PLUGIN_BASEURL + "announcements/channels";
|
||||
if (force) {
|
||||
@@ -136,7 +137,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
|
||||
|
||||
@@ -157,7 +158,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.showAnnouncementDialog = function(channel) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
// lazy load images that still need lazy-loading
|
||||
$("#plugin_announcements_dialog_content article img").lazyload();
|
||||
@@ -194,7 +195,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.displayAnnouncements = function(channels) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
|
||||
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
|
||||
@@ -321,12 +322,12 @@ $(function() {
|
||||
self.settings.show("settings_plugin_announcements");
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.retrieveData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.hideAnnouncements();
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) {
|
||||
self.hideAnnouncements();
|
||||
} else {
|
||||
self.retrieveData();
|
||||
}
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
@@ -344,7 +345,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: AnnouncementsViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import flask
|
||||
import threading
|
||||
import os
|
||||
import yaml
|
||||
import codecs
|
||||
import io
|
||||
import time
|
||||
from binascii import hexlify
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from flask_babel import gettext
|
||||
|
||||
@@ -15,9 +15,10 @@ import octoprint.plugin
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
||||
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
||||
from octoprint.users import DummyUser
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer, generate_api_key
|
||||
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
@@ -112,6 +113,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
|
||||
self._load_keys()
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="ADMIN",
|
||||
name="Admin access",
|
||||
description=gettext("Allows administrating all application keys"),
|
||||
roles=["admin"],
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
]
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
@@ -212,12 +225,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
|
||||
if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can():
|
||||
keys = self._all_api_keys()
|
||||
else:
|
||||
keys = self._api_keys_for_user(user_id)
|
||||
|
||||
return flask.jsonify(keys=map(lambda x: x.external(), keys),
|
||||
return flask.jsonify(keys=list(map(lambda x: x.external(), keys)),
|
||||
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
@@ -286,7 +299,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
def _expire_pending(self, user_token):
|
||||
with self._pending_lock:
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
self._pending_decisions = list(filter(lambda x: x.user_token != user_token,
|
||||
self._pending_decisions))
|
||||
len_after = len(self._pending_decisions)
|
||||
|
||||
if len_after < len_before:
|
||||
@@ -299,8 +313,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
with self._pending_lock:
|
||||
cutoff = monotonic_time() - CUTOFF_TIME
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.created >= cutoff,
|
||||
self._pending_decisions)
|
||||
self._pending_decisions = list(filter(lambda x: x.created >= cutoff,
|
||||
self._pending_decisions))
|
||||
len_after = len(self._pending_decisions)
|
||||
if len_after < len_before:
|
||||
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
|
||||
@@ -320,7 +334,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
|
||||
|
||||
with self._pending_lock:
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
self._pending_decisions = list(filter(lambda x: x.user_token != user_token,
|
||||
self._pending_decisions))
|
||||
|
||||
return True
|
||||
|
||||
@@ -338,7 +353,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
api_key = self._add_api_key(decision.user_id, decision.app_id)
|
||||
|
||||
with self._ready_lock:
|
||||
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
|
||||
self._ready_decisions = list(filter(lambda x: x.app_token != app_token,
|
||||
self._ready_decisions))
|
||||
|
||||
return api_key
|
||||
|
||||
@@ -356,17 +372,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
def _delete_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
self._keys[user_id] = filter(lambda x: x.api_key != api_key, data)
|
||||
self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data))
|
||||
self._save_keys()
|
||||
|
||||
def _user_for_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
if filter(lambda x: x.api_key == api_key, data):
|
||||
if any(filter(lambda x: x.api_key == api_key, data)):
|
||||
if self._user_manager.enabled:
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
elif user_id == "dummy":
|
||||
return DummyUser()
|
||||
return self._user_manager.find_user(userid=user_id)
|
||||
elif user_id == "_admin" or user_id == "dummy":
|
||||
# dummy = backwards compatible
|
||||
return self._user_manager.anonymous_user_factory()
|
||||
return None
|
||||
|
||||
def _api_keys_for_user(self, user_id):
|
||||
@@ -381,7 +398,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
return result
|
||||
|
||||
def _generate_key(self):
|
||||
return hexlify(os.urandom(16))
|
||||
return generate_api_key()
|
||||
|
||||
def _load_keys(self):
|
||||
with self._keys_lock:
|
||||
@@ -389,9 +406,9 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
return
|
||||
|
||||
try:
|
||||
with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
|
||||
with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f:
|
||||
persisted = yaml.safe_load(f)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Could not load application keys from {}".format(self._key_path))
|
||||
return
|
||||
|
||||
@@ -410,17 +427,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
to_persist[user_id] = [x.internal() for x in keys]
|
||||
|
||||
try:
|
||||
with atomic_write(self._key_path) as f:
|
||||
yaml.safe_dump(to_persist, f)
|
||||
except:
|
||||
with atomic_write(self._key_path, mode='wt') as f:
|
||||
yaml.safe_dump(to_persist, f, allow_unicode=True)
|
||||
except Exception:
|
||||
self._logger.exception("Could not write application keys to {}".format(self._key_path))
|
||||
|
||||
__plugin_name__ = u"Application Keys Plugin"
|
||||
__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys"
|
||||
__plugin_author__ = u"Gina Häußge, Aldo Hoeben"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to "
|
||||
u"obtain an API key without you manually copy-pasting it.")
|
||||
__plugin_name__ = "Application Keys Plugin"
|
||||
__plugin_description__ = "Implements a workflow for third party clients to obtain API keys"
|
||||
__plugin_author__ = "Gina Häußge, Aldo Hoeben"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to "
|
||||
"obtain an API key without you manually copy-pasting it.")
|
||||
__plugin_implementation__ = AppKeysPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
|
||||
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -52,7 +52,7 @@ $(function() {
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -68,7 +68,7 @@ $(function() {
|
||||
|
||||
self.promptForAccess = function(app, token) {
|
||||
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
|
||||
message = _.sprintf(message, {app: app});
|
||||
message = _.sprintf(message, {app: _.escape(app)});
|
||||
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
|
||||
return new PNotify({
|
||||
title: gettext("Access Request"),
|
||||
@@ -210,7 +210,7 @@ $(function() {
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -258,11 +258,11 @@ $(function() {
|
||||
handler = function(key) {
|
||||
return OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: _.escape(key)}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(jqXHR.responseText)});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -9,11 +9,13 @@ import octoprint.plugin
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.plugin.core import FolderOrigin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.server.util.flask import no_firstrun_access
|
||||
from octoprint.util import is_hidden_path, to_bytes
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import is_os_compatible
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
@@ -28,7 +30,7 @@ except ImportError:
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import codecs
|
||||
import io
|
||||
import flask
|
||||
import logging
|
||||
import os
|
||||
@@ -68,6 +70,18 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
self._in_progress = []
|
||||
self._in_progress_lock = threading.RLock()
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="ACCESS",
|
||||
name="Backup access",
|
||||
description=gettext("Allows access to backups and restores"),
|
||||
roles=["access"],
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
]
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
@@ -85,13 +99,13 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="settings", name=gettext(u"Backup & Restore"))]
|
||||
return [dict(type="settings", name=gettext("Backup & Restore"))]
|
||||
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_state(self):
|
||||
backups = self._get_backups()
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
@@ -101,34 +115,34 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
restore_supported=is_os_compatible(["!windows"]))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_unknown_plugins(self):
|
||||
# TODO add caching
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(unknown_plugins=unknown_plugins)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def delete_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_backups(self):
|
||||
backups = self._get_backups()
|
||||
return flask.jsonify(backups=backups)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def create_backup(self):
|
||||
backup_file = build_backup_filename()
|
||||
|
||||
@@ -136,8 +150,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
exclude = data.get("exclude", [])
|
||||
|
||||
def on_backup_start(name, temporary_path, exclude):
|
||||
self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path,
|
||||
u",".join(exclude) if len(exclude) else "-"))
|
||||
self._logger.info("Creating backup zip at {} (excluded: {})...".format(temporary_path,
|
||||
",".join(exclude) if len(exclude) else "-"))
|
||||
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.append(name)
|
||||
@@ -148,7 +162,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
self._in_progress.remove(name)
|
||||
self._send_client_message("backup_done", payload=dict(name=name))
|
||||
|
||||
self._logger.info(u"... done creating backup zip.")
|
||||
self._logger.info("... done creating backup zip.")
|
||||
|
||||
def on_backup_error(name, exc_info):
|
||||
with self._in_progress_lock:
|
||||
@@ -159,8 +173,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
pass
|
||||
|
||||
self._send_client_message("backup_error", payload=dict(name=name,
|
||||
error=u"{}".format(exc_info[1])))
|
||||
self._logger.error(u"Error while creating backup zip", exc_info=exc_info)
|
||||
error="{}".format(exc_info[1])))
|
||||
self._logger.error("Error while creating backup zip", exc_info=exc_info)
|
||||
|
||||
thread = threading.Thread(target=self._create_backup,
|
||||
args=(backup_file,),
|
||||
@@ -180,8 +194,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def delete_backup(self, filename):
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
full_path = os.path.realpath(os.path.join(backup_folder, filename))
|
||||
@@ -190,17 +204,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
and not is_hidden_path(full_path):
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except:
|
||||
self._logger.exception(u"Could not delete {}".format(filename))
|
||||
except Exception:
|
||||
self._logger.exception("Could not delete {}".format(filename))
|
||||
raise
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def perform_restore(self):
|
||||
if not is_os_compatible(["!windows"]):
|
||||
return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400)
|
||||
return flask.make_response("Invalid request, the restores are not supported on the underlying operating system", 400)
|
||||
|
||||
input_name = "file"
|
||||
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
||||
@@ -219,7 +233,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
return flask.abort(404)
|
||||
|
||||
else:
|
||||
return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400)
|
||||
return flask.make_response("Invalid request, neither a file nor a path of a file to restore provided", 400)
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
@@ -235,20 +249,20 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
self._logger.warn("Cannot install plugin {}, it is incompatible to this version "
|
||||
"of OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint".format(plugin["id"]))
|
||||
self._logger.warn("Cannot install plugin {}, it is incompatible to this version "
|
||||
"of OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
self._logger.warn("Cannot install plugin {}, it is incompatible to the underlying "
|
||||
"operating system".format(plugin["id"]))
|
||||
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
|
||||
octoprint_compatible=octoprint_compatible,
|
||||
os_compatible=os_compatible))
|
||||
continue
|
||||
|
||||
self._logger.info(u"Installing plugin {}".format(plugin["id"]))
|
||||
self._logger.info("Installing plugin {}".format(plugin["id"]))
|
||||
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
@@ -387,7 +401,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
path = os.path.join(datafolder, path)
|
||||
|
||||
if not os.path.exists(path):
|
||||
click.echo(u"Backup {} does not exist".format(path), err=True)
|
||||
click.echo("Backup {} does not exist".format(path), err=True)
|
||||
sys.exit(-1)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
@@ -403,7 +417,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def log(line):
|
||||
click.echo(u"\t{}".format(line))
|
||||
click.echo("\t{}".format(line))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||
@@ -411,17 +425,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
click.echo("Cannot install plugin {}, it is incompatible to this version of "
|
||||
"OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint".format(plugin["id"]))
|
||||
click.echo("Cannot install plugin {}, it is incompatible to this version of "
|
||||
"OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
click.echo("Cannot install plugin {}, it is incompatible to the underlying "
|
||||
"operating system".format(plugin["id"]))
|
||||
continue
|
||||
|
||||
click.echo(u"Installing plugin {}".format(plugin["id"]))
|
||||
click.echo("Installing plugin {}".format(plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
@@ -431,9 +445,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.")
|
||||
click.echo("The following plugins were not found in the plugin repository. You'll need to install them manually.")
|
||||
for plugin in plugins:
|
||||
click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
|
||||
click.echo("\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
|
||||
|
||||
def on_log_progress(line):
|
||||
click.echo(line)
|
||||
@@ -456,9 +470,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_invalid_backup=on_log_error):
|
||||
click.echo(u"Restored from {}".format(path))
|
||||
click.echo("Restored from {}".format(path))
|
||||
else:
|
||||
click.echo(u"Restoring from {} failed".format(path), err=True)
|
||||
click.echo("Restoring from {} failed".format(path), err=True)
|
||||
|
||||
return [backup_command, restore_command]
|
||||
|
||||
@@ -484,28 +498,28 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
if os.path.exists(data_file):
|
||||
try:
|
||||
with codecs.open(data_file, mode="r", encoding="utf-8") as f:
|
||||
with io.open(data_file, mode='rb', encoding="utf-8") as f:
|
||||
unknown_plugins = json.load(f)
|
||||
|
||||
assert isinstance(unknown_plugins, list)
|
||||
assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins))
|
||||
|
||||
installed_plugins = self._plugin_manager.plugins
|
||||
unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
|
||||
unknown_plugins = list(filter(lambda x: x["key"] not in installed_plugins, unknown_plugins))
|
||||
if not unknown_plugins:
|
||||
# no plugins left uninstalled, delete data file
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
except Exception:
|
||||
self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return unknown_plugins
|
||||
except:
|
||||
self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file))
|
||||
except Exception:
|
||||
self._logger.exception("Error while reading list of unknown plugins from {}".format(data_file))
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
except Exception:
|
||||
self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return []
|
||||
|
||||
@@ -517,10 +531,10 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
if os.path.exists(basedir_backup):
|
||||
def remove_bck():
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Found config folder backup from prior restore, deleting it...")
|
||||
on_log_progress("Found config folder backup from prior restore, deleting it...")
|
||||
shutil.rmtree(basedir_backup)
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"... deleted.")
|
||||
on_log_progress("... deleted.")
|
||||
|
||||
thread = threading.Thread(target=remove_bck)
|
||||
thread.daemon = True
|
||||
@@ -555,8 +569,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
try:
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
except:
|
||||
logger.exception(u"Error while fetching the plugin repository data from {}".format(url))
|
||||
except Exception:
|
||||
logger.exception("Error while fetching the plugin repository data from {}".format(url))
|
||||
return dict()
|
||||
|
||||
from octoprint.plugins.pluginmanager import map_repository_entry
|
||||
@@ -573,16 +587,16 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
# prepare pip caller
|
||||
def log(prefix, *lines):
|
||||
for line in lines:
|
||||
on_log(u"{} {}".format(prefix, line.rstrip()))
|
||||
on_log("{} {}".format(prefix, line.rstrip()))
|
||||
|
||||
def log_call(*lines):
|
||||
log(u">", *lines)
|
||||
log(">", *lines)
|
||||
|
||||
def log_stdout(*lines):
|
||||
log(u"<", *lines)
|
||||
log("<", *lines)
|
||||
|
||||
def log_stderr(*lines):
|
||||
log(u"!", *lines)
|
||||
log("!", *lines)
|
||||
|
||||
if cls._pip_caller is None:
|
||||
cls._pip_caller = LocalPipCaller(force_user=force_user)
|
||||
@@ -706,7 +720,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
if callable(on_backup_done):
|
||||
on_backup_done(name, final_path, exclude)
|
||||
except:
|
||||
except Exception as exc: ## noqa: F841
|
||||
# TODO py3: use the exception, not sys.exc_info()
|
||||
if callable(on_backup_error):
|
||||
exc_info = sys.exc_info()
|
||||
try:
|
||||
@@ -730,7 +745,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
on_restore_failed=None):
|
||||
if not is_os_compatible(["!windows"]):
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Restore is not supported on this operating system")
|
||||
on_log_error("Restore is not supported on this operating system")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
@@ -757,7 +772,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
metadata_zipinfo = zip.getinfo("metadata.json")
|
||||
except KeyError:
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
|
||||
on_invalid_backup("Not an OctoPrint backup, lacks metadata.json")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
@@ -768,7 +783,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
backup_version = get_comparable_version(metadata["version"], base=True)
|
||||
if backup_version > get_octoprint_version(base=True):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
|
||||
on_invalid_backup("Backup is from a newer version of OctoPrint and cannot be applied")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
@@ -777,7 +792,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
temp = tempfile.mkdtemp()
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacking backup to {}...".format(temp))
|
||||
on_log_progress("Unpacking backup to {}...".format(temp))
|
||||
abstemp = os.path.abspath(temp)
|
||||
for member in zip.infolist():
|
||||
abspath = os.path.abspath(os.path.join(temp, member.filename))
|
||||
@@ -788,33 +803,33 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
configfile = os.path.join(temp, "basedir", "config.yaml")
|
||||
if not os.path.exists(configfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks config.yaml")
|
||||
on_invalid_backup("Backup lacks config.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
import yaml
|
||||
|
||||
with codecs.open(configfile) as f:
|
||||
with io.open(configfile, "rt", encoding="utf-8") as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
|
||||
if configdata.get("accessControl", dict()).get("enabled", True):
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks users.yaml")
|
||||
on_invalid_backup("Backup lacks users.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacked")
|
||||
on_log_progress("Unpacked")
|
||||
|
||||
# install available plugins
|
||||
plugins = []
|
||||
plugin_list_file = os.path.join(temp, "plugin_list.json")
|
||||
if os.path.exists(plugin_list_file):
|
||||
with codecs.open(plugin_list_file, "r") as f:
|
||||
with io.open(os.path.join(temp, "plugin_list.json"), 'rb') as f:
|
||||
plugins = json.load(f)
|
||||
|
||||
known_plugins = []
|
||||
@@ -839,9 +854,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
if callable(on_log_progress):
|
||||
if known_plugins:
|
||||
on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins))))
|
||||
on_log_progress("Known and installable plugins: {}".format(", ".join(map(lambda x: x["id"], known_plugins))))
|
||||
if unknown_plugins:
|
||||
on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins))))
|
||||
on_log_progress("Unknown plugins: {}".format(", ".join(map(lambda x: x["key"], unknown_plugins))))
|
||||
|
||||
if callable(on_install_plugins):
|
||||
on_install_plugins(known_plugins)
|
||||
@@ -854,17 +869,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
basedir_extracted = os.path.join(temp, "basedir")
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
|
||||
on_log_progress("Renaming {} to {}...".format(basedir, basedir_backup))
|
||||
shutil.move(basedir, basedir_backup)
|
||||
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
|
||||
on_log_progress("Moving {} to {}...".format(basedir_extracted, basedir))
|
||||
shutil.move(basedir_extracted, basedir)
|
||||
except:
|
||||
except Exception:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
|
||||
on_log_error(u"Rolling back old config data")
|
||||
on_log_error("Error while restoring config data", exc_info=sys.exc_info())
|
||||
on_log_error("Rolling back old config data")
|
||||
|
||||
shutil.move(basedir_backup, basedir)
|
||||
|
||||
@@ -874,30 +889,30 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
if unknown_plugins:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Writing info file about unknown plugins")
|
||||
on_log_progress("Writing info file about unknown plugins")
|
||||
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f:
|
||||
json.dump(unknown_plugins, f)
|
||||
except:
|
||||
with io.open(unknown_plugins_path, mode='wb') as f:
|
||||
f.write(to_bytes(json.dumps(unknown_plugins)))
|
||||
except Exception:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
|
||||
on_log_error("Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
|
||||
exc_info = sys.exc_info())
|
||||
|
||||
finally:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary unpacked folder")
|
||||
on_log_progress("Removing temporary unpacked folder")
|
||||
shutil.rmtree(temp)
|
||||
|
||||
except:
|
||||
except Exception:
|
||||
exc_info = sys.exc_info()
|
||||
try:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while running restore", exc_info=exc_info)
|
||||
on_log_error("Error while running restore", exc_info=exc_info)
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
finally:
|
||||
@@ -907,7 +922,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
finally:
|
||||
# remove zip
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary zip")
|
||||
on_log_progress("Removing temporary zip")
|
||||
os.remove(path)
|
||||
|
||||
# restart server
|
||||
@@ -915,17 +930,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
import sarge
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Restarting...")
|
||||
on_log_progress("Restarting...")
|
||||
if callable(on_restore_done):
|
||||
on_restore_done(path)
|
||||
|
||||
try:
|
||||
sarge.run(restart_command, async_=True)
|
||||
except:
|
||||
except Exception:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restarting via command {}".format(restart_command),
|
||||
on_log_error("Error while restarting via command {}".format(restart_command),
|
||||
exc_info=sys.exc_info())
|
||||
on_log_error(u"Please restart OctoPrint manually")
|
||||
on_log_error("Please restart OctoPrint manually")
|
||||
return False
|
||||
|
||||
else:
|
||||
@@ -946,15 +961,16 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
class InsufficientSpace(Exception):
|
||||
pass
|
||||
|
||||
__plugin_name__ = u"Backup & Restore"
|
||||
__plugin_author__ = u"Gina Häußge"
|
||||
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
|
||||
u"& restore your OctoPrint settings and data.")
|
||||
__plugin_license__ = u"AGPLv3"
|
||||
__plugin_name__ = "Backup & Restore"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Backup & restore your OctoPrint settings and data"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to backup "
|
||||
"& restore your OctoPrint settings and data.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = BackupPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
|
||||
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
|
||||
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook
|
||||
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -85,7 +85,7 @@ $(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: _.escape(backup)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -101,7 +101,7 @@ $(function() {
|
||||
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(backup)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -117,7 +117,7 @@ $(function() {
|
||||
|
||||
self.backupUploadData.submit();
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(self.backupUploadName())}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -182,7 +182,7 @@ $(function() {
|
||||
self.backupInProgress(false);
|
||||
new PNotify({
|
||||
title: gettext("Creating the backup failed"),
|
||||
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
|
||||
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error: _.escape(data.error)}),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
@@ -200,13 +200,13 @@ $(function() {
|
||||
} else if (data.type === "installing_plugin") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: data.plugin}),
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: _.escape(data.plugin)}),
|
||||
stream: "message"
|
||||
});
|
||||
} else if (data.type === "plugin_incompatible") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}),
|
||||
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: _.escape(data.plugin.key)}),
|
||||
stream: "stderr"
|
||||
});
|
||||
} else if (data.type === "unknown_plugins") {
|
||||
@@ -245,11 +245,11 @@ $(function() {
|
||||
handler = function(filename) {
|
||||
return OctoPrint.plugins.backup.deleteBackup(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(filename)}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -9,7 +9,8 @@ import octoprint.plugin
|
||||
import sys
|
||||
import inspect
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP
|
||||
from octoprint.util import to_native_str
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
class ServerCommandsSubwizard(object):
|
||||
@@ -55,7 +56,7 @@ class AclSubwizard(object):
|
||||
return True
|
||||
|
||||
def _is_acl_wizard_required(self):
|
||||
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
|
||||
return self._user_manager.enabled and not self._user_manager.has_been_customized()
|
||||
|
||||
def _get_acl_wizard_details(self):
|
||||
return dict(required=self._is_acl_wizard_required())
|
||||
@@ -71,27 +72,24 @@ class AclSubwizard(object):
|
||||
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():
|
||||
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized():
|
||||
abort(404)
|
||||
|
||||
data = request.values
|
||||
if hasattr(request, "json") and request.json:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
data = request.values
|
||||
|
||||
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"]:
|
||||
"user" in data and "pass1" in data and \
|
||||
"pass2" in data 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:
|
||||
|
||||
self._user_manager.add_user(data["user"], data["pass1"], True, [], [USER_GROUP, ADMIN_GROUP], overwrite=True)
|
||||
elif "ac" in data 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
|
||||
@@ -148,7 +146,7 @@ class PrinterProfileSubwizard(object):
|
||||
return gettext("Default Printer Profile")
|
||||
|
||||
|
||||
Subwizards = type("Subwizwards",
|
||||
Subwizards = type(to_native_str("Subwizards"),
|
||||
tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
|
||||
if clsname.endswith("Subwizard")),
|
||||
dict())
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -20,8 +20,9 @@ import octoprint.plugin
|
||||
import octoprint.util
|
||||
|
||||
try:
|
||||
# TODO: looks like pybonjour is py2 only - find alternatives or port?
|
||||
import pybonjour
|
||||
except:
|
||||
except ImportError:
|
||||
pybonjour = False
|
||||
|
||||
|
||||
@@ -199,19 +200,19 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
while True:
|
||||
try:
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self._logger.info(u"Registered '{name}' for {regtype}".format(**params))
|
||||
self._logger.info("Registered '{name}' for {regtype}".format(**params))
|
||||
return True
|
||||
except pybonjour.BonjourError as be:
|
||||
if be.errorCode == pybonjour.kDNSServiceErr_NameConflict:
|
||||
# Name already registered by different service, let's try a counter postfix. See #2852
|
||||
counter += 1
|
||||
params["name"] = u"{} ({})".format(name, counter)
|
||||
params["name"] = "{} ({})".format(name, counter)
|
||||
else:
|
||||
raise
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
Unregisteres a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
|
||||
Unregisters a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
|
||||
|
||||
:param reg_type: the type of the service to be unregistered
|
||||
:param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given
|
||||
@@ -232,7 +233,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
try:
|
||||
sd_ref.close()
|
||||
self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
|
||||
def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5):
|
||||
@@ -378,7 +379,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
def browse_callback(results):
|
||||
for result in results:
|
||||
print "Location: {}".format(result)
|
||||
print("Location: {}".format(result))
|
||||
|
||||
:param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices
|
||||
:param block: whether to block, defaults to True
|
||||
@@ -390,10 +391,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
"""
|
||||
|
||||
import threading
|
||||
|
||||
import httplib
|
||||
import io
|
||||
class Response(httplib.HTTPResponse):
|
||||
|
||||
try:
|
||||
# noinspection PyCompatibility
|
||||
from http.client import HTTPResponse # py3
|
||||
except ImportError:
|
||||
# noinspection PyCompatibility
|
||||
from httplib import HTTPResponse # py2
|
||||
|
||||
class Response(HTTPResponse):
|
||||
def __init__(self, response_text):
|
||||
self.fp = io.BytesIO(response_text)
|
||||
self.debuglevel = 0
|
||||
@@ -431,7 +438,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
mcast_addr=self.__class__.ssdp_multicast_addr,
|
||||
mcast_port=self.__class__.ssdp_multicast_port)
|
||||
for _ in range(2):
|
||||
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
|
||||
sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
|
||||
|
||||
try:
|
||||
data = sock.recv(1024)
|
||||
@@ -441,7 +448,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
response = Response(data)
|
||||
|
||||
result.append(response.getheader("Location"))
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if callback:
|
||||
@@ -598,8 +605,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
mcast_port=self.__class__.ssdp_multicast_port)
|
||||
for _ in range(2):
|
||||
# send twice, stuff might get lost, it's only UDP
|
||||
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
|
||||
except:
|
||||
sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._ssdp_last_notify = octoprint.util.monotonic_time()
|
||||
@@ -652,22 +659,23 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0'))
|
||||
|
||||
self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name()))
|
||||
self._logger.info("Registered {} for SSDP".format(self.get_instance_name()))
|
||||
|
||||
self._ssdp_notify(alive=True)
|
||||
|
||||
try:
|
||||
while (self._ssdp_monitor_active):
|
||||
while self._ssdp_monitor_active:
|
||||
try:
|
||||
data, address = sock.recvfrom(4096)
|
||||
request = Request(data)
|
||||
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
|
||||
interface_address = octoprint.util.address_for_client(*address)
|
||||
if not interface_address:
|
||||
self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
self._logger.warning("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
continue
|
||||
message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
sock.sendto(message, address)
|
||||
message = location_message.format(uuid=self.get_uuid(),
|
||||
location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
sock.sendto(message.encode("utf-8"), address)
|
||||
self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
|
||||
except socket.timeout:
|
||||
pass
|
||||
@@ -676,7 +684,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
##~~ helpers
|
||||
@@ -693,10 +701,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
def get_instance_name(self):
|
||||
name = self._settings.global_get(["appearance", "name"])
|
||||
if name:
|
||||
return u"OctoPrint instance \"{}\"".format(name)
|
||||
return "OctoPrint instance \"{}\"".format(name)
|
||||
else:
|
||||
import socket
|
||||
return u"OctoPrint instance on {}".format(socket.gethostname())
|
||||
return "OctoPrint instance on {}".format(socket.gethostname())
|
||||
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
|
||||
@@ -13,8 +13,8 @@ from octoprint.util.version import get_octoprint_version_string, is_released_oct
|
||||
from flask import jsonify
|
||||
from flask_babel import gettext
|
||||
|
||||
SENTRY_URL_SERVER = "https://562288d61d724563b6d43e2a6670616e@sentry.io/1373987"
|
||||
SENTRY_URL_COREUI = "https://5c2e838ac5554162bfc30142788362db@sentry.io/1374096"
|
||||
SENTRY_URL_SERVER = "https://e8dadc4407e74f159e77919e551bd1a7@sentry.io/1373987"
|
||||
SENTRY_URL_COREUI = "https://1da95af9c999483ba5705577f24d1e28@sentry.io/1374096"
|
||||
|
||||
SETTINGS_DEFAULTS = dict(enabled=False,
|
||||
enabled_unreleased=False,
|
||||
|
||||
@@ -1,202 +0,0 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import flask
|
||||
import flask_login
|
||||
from flask_babel import gettext
|
||||
|
||||
from collections import defaultdict
|
||||
import threading
|
||||
|
||||
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
MAX_BACKLOG_LEN = 100
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._message_backlog = defaultdict(list)
|
||||
self._message_backlog_mutex = threading.RLock()
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
# we are only active if ACL is enabled AND configured
|
||||
return self._user_manager.enabled and self._user_manager.hasBeenCustomized()
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/viewmodel.js"]
|
||||
)
|
||||
|
||||
def will_handle_ui(self, request):
|
||||
if not self.active:
|
||||
# not active, not responsible
|
||||
return False
|
||||
|
||||
from octoprint.server.util import loginUserFromApiKey, loginUserFromAuthorizationHeader, InvalidApiKeyException
|
||||
from octoprint.server.util.flask import passive_login
|
||||
|
||||
# first try to login via api key & authorization header, just in case that's set
|
||||
try:
|
||||
if loginUserFromApiKey():
|
||||
# successful? No need for handling the UI
|
||||
return False
|
||||
except InvalidApiKeyException:
|
||||
pass # ignored
|
||||
|
||||
if loginUserFromAuthorizationHeader():
|
||||
# successful? No need for handling the UI
|
||||
return False
|
||||
|
||||
# then try a passive login
|
||||
result = passive_login()
|
||||
if hasattr(result, "status_code") and result.status_code == 200:
|
||||
# successful? No need for handling the UI
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def on_ui_render(self, now, request, render_kwargs):
|
||||
from flask import render_template, make_response
|
||||
|
||||
"""
|
||||
Support theming of the login dialog, just in case the core UI is themed as well.
|
||||
|
||||
Example usage by a plugin:
|
||||
|
||||
def forcelogin_theming():
|
||||
from flask import url_for
|
||||
return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.forcelogin.theming": forcelogin_theming
|
||||
}
|
||||
|
||||
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
|
||||
url_for like in the example above to be prepared for any configured prefix URLs.
|
||||
"""
|
||||
additional_assets = []
|
||||
for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
|
||||
try:
|
||||
assets = hook()
|
||||
if isinstance(assets, (tuple, list)):
|
||||
additional_assets += assets
|
||||
except:
|
||||
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
render_kwargs.update(dict(forcelogin_theming=additional_assets))
|
||||
return make_response(render_template("forcelogin_index.jinja2", **render_kwargs))
|
||||
|
||||
def get_ui_custom_tracked_files(self):
|
||||
from os.path import join as opj
|
||||
|
||||
paths = [opj("static", "css", "forcelogin.css"),
|
||||
opj("static", "js", "main.js"),
|
||||
opj("static", "js", "viewmodel.js"),
|
||||
opj("static", "less", "forcelogin.less"),
|
||||
opj("templates", "parts", "forcelogin_css.jinja2"),
|
||||
opj("templates", "parts", "forcelogin_javascripts.jinja2"),
|
||||
opj("templates", "forcelogin_index.jinja2")]
|
||||
|
||||
return [opj(self._basefolder, path) for path in paths]
|
||||
|
||||
def get_ui_preemptive_caching_enabled(self):
|
||||
return False
|
||||
|
||||
def get_sorting_key(self, context=None):
|
||||
if context == "UiPlugin.on_ui_render":
|
||||
# If a plugin *really* wants to come before this plugin, it'll have to turn to negative numbers.
|
||||
#
|
||||
# This is obviously discouraged for security reasons, but very specific setups might make it necessary,
|
||||
# so we make it possible. If this should get abused long term we can always turn this into -inf.
|
||||
return 0
|
||||
|
||||
def get_before_request_handlers(self, plugin=None, *args, **kwargs):
|
||||
def check_login_required():
|
||||
if not self.active:
|
||||
# not active, no handling
|
||||
return
|
||||
|
||||
if flask.request.endpoint in ("api.login",) or flask.request.endpoint.endswith(".static"):
|
||||
return
|
||||
|
||||
if plugin is not None and not plugin.is_blueprint_protected():
|
||||
return
|
||||
|
||||
user = flask_login.current_user
|
||||
if user is None or user.is_anonymous() or not user.is_active():
|
||||
return flask.make_response("Forbidden", 403)
|
||||
|
||||
return [check_login_required]
|
||||
|
||||
def access_validator(self, request):
|
||||
if not self.active:
|
||||
# not active, no handling
|
||||
return
|
||||
|
||||
import tornado.web
|
||||
from octoprint.server.util.flask import get_flask_user_from_request
|
||||
|
||||
user = get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated():
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
def socket_register_validator(self, socket, user):
|
||||
if not self.active:
|
||||
# not active, no limitation
|
||||
return True
|
||||
|
||||
return user is not None and not user.is_anonymous() and user.is_active()
|
||||
|
||||
def socket_authed(self, socket, user):
|
||||
with self._message_backlog_mutex:
|
||||
backlog = self._message_backlog.pop(socket, [])
|
||||
|
||||
if len(backlog):
|
||||
for message, payload in backlog:
|
||||
socket._do_emit(message, payload)
|
||||
self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog)))
|
||||
|
||||
def socket_emit_validator(self, socket, user, message, payload):
|
||||
if not self.active:
|
||||
# not active, no limitation
|
||||
return True
|
||||
|
||||
if message in ("connected", "reauthRequired"):
|
||||
return True
|
||||
|
||||
if user is not None and not user.is_anonymous() and user.is_active():
|
||||
return True
|
||||
|
||||
with self._message_backlog_mutex:
|
||||
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
|
||||
self._message_backlog[socket].append((message, payload))
|
||||
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
|
||||
else:
|
||||
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
|
||||
|
||||
return False
|
||||
|
||||
|
||||
__plugin_name__ = "Force Login"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Forces users to login, disables read-only mode."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your "
|
||||
"OctoPrint instance. Only disable this if you are comfortable with this, your "
|
||||
"OctoPrint instance is not publicly reachable on the internet and you fully "
|
||||
"trust everyone who has access to your local network!")
|
||||
|
||||
__plugin_implementation__ = ForceLoginPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
|
||||
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
|
||||
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
|
||||
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
|
||||
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
|
||||
@@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Will get included into the login dialog, NOT into the regular OctoPrint
|
||||
* web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
var overlayElement = $("#login-overlay");
|
||||
var errorElement = $("#login-error");
|
||||
var offlineElement = $("#login-offline");
|
||||
var buttonElement = $("#login-button");
|
||||
var reconnectElement = $("#login-reconnect");
|
||||
|
||||
buttonElement.click(function() {
|
||||
var usernameElement = $("#login-user");
|
||||
var passwordElement = $("#login-password");
|
||||
var rememberElement = $("#login-remember");
|
||||
|
||||
var username = usernameElement.val();
|
||||
var password = passwordElement.val();
|
||||
var remember = rememberElement.prop("checked");
|
||||
|
||||
overlayElement.addClass("in");
|
||||
errorElement.removeClass("in");
|
||||
|
||||
OctoPrint.browser.login(username, password, remember)
|
||||
.done(function() {
|
||||
location.reload();
|
||||
})
|
||||
.fail(function() {
|
||||
usernameElement.val("");
|
||||
passwordElement.val("");
|
||||
|
||||
overlayElement.removeClass("in");
|
||||
errorElement.addClass("in");
|
||||
});
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
var OctoPrint = window.OctoPrint;
|
||||
|
||||
OctoPrint.options.baseurl = BASE_URL;
|
||||
|
||||
OctoPrint.socket.onConnected = function() {
|
||||
buttonElement.prop("disabled", false);
|
||||
offlineElement.removeClass("in");
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function() {
|
||||
buttonElement.prop("disabled", true);
|
||||
offlineElement.addClass("in");
|
||||
};
|
||||
|
||||
reconnectElement.click(function() {
|
||||
OctoPrint.socket.reconnect();
|
||||
});
|
||||
|
||||
OctoPrint.socket.connect();
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
/*
|
||||
* View model that takes care to redirect to / on logout in the regular
|
||||
* OctoPrint web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
function ForceLoginViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([ForceLoginViewModel, [], []]);
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
body {
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.form-signin {
|
||||
max-width: 300px;
|
||||
padding: 19px 29px 29px;
|
||||
margin: 0 auto 20px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #e5e5e5;
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
|
||||
.form-signin-heading, .checkbox {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
input[type="text"], input[type="password"] {
|
||||
font-size: 16px;
|
||||
height: auto;
|
||||
margin-bottom: 15px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
}
|
||||
|
||||
#login-error,
|
||||
#login-offline {
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
#login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.background {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #000000;
|
||||
filter:alpha(opacity=50);
|
||||
-moz-opacity:0.5;
|
||||
-khtml-opacity: 0.5;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
|
||||
.outer {
|
||||
display: table;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.inner {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
|
||||
.content {
|
||||
text-align: center;
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>OctoPrint Login</title>
|
||||
|
||||
<link rel="shortcut icon" href="{{ url_for('static', filename='img/tentacle-32x32.png') }}">
|
||||
<link rel="mask-icon" href="{{ url_for('static', filename='img/mask.svg') }}" color="#56BE37">
|
||||
<link rel="mask-icon-theme" href="{{ url_for('static', filename='img/mask-theme.svg') }}" color="#56BE37">
|
||||
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
|
||||
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
|
||||
|
||||
{% include "parts/forcelogin_css.jinja2" %}
|
||||
|
||||
{% include "parts/forcelogin_javascripts.jinja2" %}
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin">
|
||||
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
|
||||
|
||||
<div id="login-error" class="alert alert-error">{{ _('Incorrect username or password.') }}</div>
|
||||
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
|
||||
|
||||
<input type="text" id="login-user" class="input-block-level" placeholder="{{ _('Username')|edq }}" autofocus>
|
||||
<input type="password" id="login-password" class="input-block-level" placeholder="{{ _('Password')|edq }}">
|
||||
<span class="pull-right"><small><a href="https://faq.octoprint.org/forgotten-password" id="login-forgotpassword" target="_blank" tabindex="-1">{{ _('Forgot password?') }}</a></small></span>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="login-remember"> {{ _('Remember me') }}
|
||||
</label>
|
||||
<button class="btn btn-block btn-large btn-primary" id="login-button" type="submit">{{ _('Log in') }}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="login-overlay">
|
||||
<div class="background"></div>
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<i class="fa fa-spinner fa-spin fa-4x"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,10 +0,0 @@
|
||||
<!-- le CSS -->
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("plugin.forcelogin.static", filename="css/forcelogin.css") }}">
|
||||
|
||||
{% for url in forcelogin_theming %}
|
||||
<link rel="stylesheet" href="{{ url }}">
|
||||
{% endfor %}
|
||||
@@ -1,15 +0,0 @@
|
||||
<!-- le javascript -->
|
||||
|
||||
<script>
|
||||
var BASE_URL = "{{ url_for('index') }}";
|
||||
</script>
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
{% assets "js_client" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
<script src="{{ url_for("plugin.forcelogin.static", filename="js/main.js") }}"></script>
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -7,15 +7,19 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from flask_babel import gettext
|
||||
|
||||
from werkzeug.utils import secure_filename
|
||||
from werkzeug.exceptions import BadRequest
|
||||
import yaml
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
try:
|
||||
@@ -27,9 +31,21 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="MANAGE",
|
||||
name="Logging management",
|
||||
description=gettext("Allows to download and delete log files and list and set log levels."),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["manage"])
|
||||
]
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_all(self):
|
||||
files = self._getLogFiles()
|
||||
free, total = self._get_usage()
|
||||
@@ -39,22 +55,22 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
setup=dict(loggers=loggers, levels=levels))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_log_files(self):
|
||||
files = self._getLogFiles()
|
||||
free, total = self._get_usage()
|
||||
return jsonify(files=files, free=free, total=total)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def download_log(self, filename):
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def delete_log(self, filename):
|
||||
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
|
||||
if not os.path.exists(secure):
|
||||
@@ -65,22 +81,22 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_logging_setup(self):
|
||||
loggers = self._get_available_loggers()
|
||||
levels = self._get_logging_levels()
|
||||
return jsonify(loggers=loggers, levels=levels)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_logging_levels_api(self):
|
||||
return jsonify(self._get_logging_levels())
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def set_logging_levels_api(self):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
@@ -120,7 +136,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return files
|
||||
|
||||
def _get_available_loggers(self):
|
||||
return filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys())
|
||||
return list(filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys()))
|
||||
|
||||
def _get_logging_file(self):
|
||||
# TODO this might not be the logging config we are actually using here (command line parameter...)
|
||||
@@ -132,7 +148,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
with open(logging_file, "r") as f:
|
||||
with io.open(logging_file, 'rt', encoding='utf-8') as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
return config_from_file
|
||||
|
||||
@@ -151,23 +167,25 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
config = self._get_logging_config()
|
||||
|
||||
# clear all configured logging levels
|
||||
if config.has_key("loggers"):
|
||||
if "loggers" in config:
|
||||
purge = []
|
||||
for component in config["loggers"]:
|
||||
for component, data in config["loggers"].items():
|
||||
if not self._is_managed_logger(component): continue
|
||||
try:
|
||||
del config["loggers"][component]["level"]
|
||||
del data["level"]
|
||||
self._logger.manager.loggerDict[component].setLevel(logging.INFO)
|
||||
except:
|
||||
except KeyError:
|
||||
pass
|
||||
if len(config["loggers"][component]) == 0:
|
||||
if len(data) == 0:
|
||||
purge.append(component)
|
||||
for component in purge:
|
||||
del config["loggers"][component]
|
||||
else:
|
||||
config["loggers"] = dict()
|
||||
|
||||
# update all logging levels
|
||||
for logger, level in new_levels.items():
|
||||
if not config["loggers"].has_key(logger):
|
||||
if logger not in config["loggers"]:
|
||||
config["loggers"][logger] = dict()
|
||||
config["loggers"][logger]["level"] = level
|
||||
|
||||
@@ -175,8 +193,8 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)}
|
||||
|
||||
# save
|
||||
with octoprint.util.atomic_write(self._get_logging_file(), "wb", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(config, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
with octoprint.util.atomic_write(self._get_logging_file(), mode='wt', max_permissions=0o666) as f:
|
||||
yaml.safe_dump(config, f, default_flow_style=False, indent=2, allow_unicode=True)
|
||||
|
||||
# set runtime logging levels now
|
||||
for logger, level in new_levels.items():
|
||||
@@ -205,4 +223,11 @@ __plugin_description__ = "Provides access to OctoPrint's logs and logging config
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to retrieve "
|
||||
"OctoPrint's logs or modify the current logging levels through "
|
||||
"the web interface.")
|
||||
__plugin_implementation__ = LoggingPlugin()
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = LoggingPlugin()
|
||||
|
||||
global __plugin_hooks__
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -121,7 +121,7 @@ $(function() {
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: filename}),
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: _.escape(filename)}),
|
||||
perform);
|
||||
};
|
||||
|
||||
@@ -172,11 +172,11 @@ $(function() {
|
||||
var handler = function(filename) {
|
||||
return OctoPrint.plugins.logging.deleteLog(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(filename)}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import flask
|
||||
import io
|
||||
import os
|
||||
import sarge
|
||||
|
||||
@@ -18,14 +19,23 @@ _PROC_DT_MODEL_PATH = "/proc/device-tree/model"
|
||||
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
|
||||
_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled"
|
||||
|
||||
### uncomment for local debugging
|
||||
#import sys
|
||||
#base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
|
||||
#_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
|
||||
#_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
|
||||
#_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
|
||||
#import itertools
|
||||
#_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70000"))
|
||||
_CHECK_INTERVAL_OK = 300
|
||||
_CHECK_INTERVAL_THROTTLED = 30
|
||||
|
||||
__LOCAL_DEBUG = False
|
||||
|
||||
if __LOCAL_DEBUG:
|
||||
### mocks & settings for local debugging
|
||||
import sys
|
||||
base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
|
||||
_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
|
||||
_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
|
||||
_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
|
||||
import itertools
|
||||
_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005"))
|
||||
|
||||
_CHECK_INTERVAL_OK = 10
|
||||
_CHECK_INTERVAL_THROTTLED = 5
|
||||
|
||||
|
||||
# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790
|
||||
@@ -127,15 +137,18 @@ def get_proc_dt_model():
|
||||
global _proc_dt_model
|
||||
|
||||
if _proc_dt_model is None:
|
||||
with open(_PROC_DT_MODEL_PATH, "r") as f:
|
||||
with io.open(_PROC_DT_MODEL_PATH, 'rt', encoding='utf-8') as f:
|
||||
_proc_dt_model = f.readline().strip(" \t\r\n\0")
|
||||
|
||||
return _proc_dt_model
|
||||
|
||||
|
||||
def get_vcgencmd_throttled_state(command):
|
||||
output = sarge.get_stdout(command)
|
||||
#output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging
|
||||
if __LOCAL_DEBUG:
|
||||
output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging
|
||||
else:
|
||||
output = sarge.get_stdout(command)
|
||||
|
||||
if not "throttled=0x" in output:
|
||||
raise ValueError("cannot parse \"{}\" output: {}".format(command, output))
|
||||
|
||||
@@ -153,7 +166,7 @@ def get_octopi_version():
|
||||
global _octopi_version
|
||||
|
||||
if _octopi_version is None:
|
||||
with open(_OCTOPI_VERSION_PATH, "r") as f:
|
||||
with io.open(_OCTOPI_VERSION_PATH, 'rt', encoding='utf-8') as f:
|
||||
_octopi_version = f.readline().strip(" \t\r\n\0")
|
||||
|
||||
return _octopi_version
|
||||
@@ -236,11 +249,9 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
|
||||
def _check_throttled_state_interval(self):
|
||||
if self._throttle_state.current_issue:
|
||||
# check state every 30s if something's currently amiss
|
||||
return 30
|
||||
return _CHECK_INTERVAL_THROTTLED
|
||||
else:
|
||||
# check state every 5min if nothing's currently amiss
|
||||
return 300
|
||||
return _CHECK_INTERVAL_OK
|
||||
|
||||
def _check_throttled_state_condition(self):
|
||||
return self._throttle_functional
|
||||
@@ -261,8 +272,8 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
self._logger.debug("Retrieving throttle state via \"{}\"".format(command))
|
||||
try:
|
||||
state = get_vcgencmd_throttled_state(command)
|
||||
except:
|
||||
self._logger.exception("Got an error while trying to fetch the current throttle state via \"{}\"".format(command))
|
||||
except ValueError:
|
||||
self._logger.warning("Fetching the current throttle state via \"{}\" doesn't work".format(command))
|
||||
self._throttle_functional = False
|
||||
return
|
||||
|
||||
@@ -287,7 +298,7 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \
|
||||
"CPU and GPU."
|
||||
|
||||
self._logger.warn(message)
|
||||
self._logger.warning(message)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
|
||||
state=self._throttle_state.as_dict()))
|
||||
@@ -313,7 +324,7 @@ def __plugin_check__():
|
||||
proc_dt_model = get_proc_dt_model()
|
||||
if proc_dt_model is None:
|
||||
return False
|
||||
except:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
return "raspberry pi" in proc_dt_model.lower()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -11,16 +11,19 @@ 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
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util import to_bytes
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible, is_python_compatible
|
||||
from octoprint.util.platform import get_os, is_os_compatible
|
||||
from octoprint.events import Events
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask_babel import gettext
|
||||
|
||||
import io
|
||||
import logging
|
||||
import sarge
|
||||
import sys
|
||||
@@ -33,7 +36,12 @@ import threading
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
try:
|
||||
from os import scandir
|
||||
except:
|
||||
from scandir import scandir
|
||||
|
||||
_DATA_FORMAT_VERSION = "v3"
|
||||
|
||||
|
||||
def map_repository_entry(entry):
|
||||
@@ -47,7 +55,8 @@ def map_repository_entry(entry):
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True
|
||||
os=True,
|
||||
python=True
|
||||
)
|
||||
|
||||
if "compatibility" in entry:
|
||||
@@ -59,6 +68,12 @@ def map_repository_entry(entry):
|
||||
entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"])
|
||||
|
||||
if "python" in entry["compatibility"] and entry["compatibility"]["python"] is not None and isinstance(entry["compatibility"]["python"], basestring):
|
||||
result["is_compatible"]["python"] = is_python_compatible(entry["compatibility"]["python"])
|
||||
else:
|
||||
# we default to only assume py2 compatiblity for now
|
||||
result["is_compatible"]["python"] = is_python_compatible(">=2.7,<3")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -114,6 +129,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._notices_cache_ttl = 0
|
||||
self._notices_mtime = None
|
||||
|
||||
self._orphans = None
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
self._get_throttled = lambda: False
|
||||
@@ -124,7 +141,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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._confirm_uninstall = self._settings.global_get_boolean(["confirm_uninstall"])
|
||||
self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"])
|
||||
|
||||
self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"]))
|
||||
@@ -138,6 +154,24 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
# set a maximum body size of 50 MB for plugin archive uploads
|
||||
return [("POST", r"/upload_archive", 50 * 1024 * 1024)]
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="MANAGE",
|
||||
name="Manage plugins",
|
||||
description=gettext("Allows to enable, disable and uninstall installed plugins."),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["manage"]),
|
||||
dict(key="INSTALL",
|
||||
name="Install new plugins",
|
||||
description=gettext("Allows to install new plugins. Includes the \"Manage plugins\" permission."),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["install"],
|
||||
permissions=["PLUGIN_PLUGINMANAGER_MANAGE"],
|
||||
dangerous=True)
|
||||
]
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
@@ -153,6 +187,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
|
||||
if helpers and "get_throttled" in helpers:
|
||||
self._get_throttled = helpers["get_throttled"]
|
||||
if self._settings.get_boolean(["ignore_throttled"]):
|
||||
self._logger.warn("!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.")
|
||||
|
||||
# decouple repository fetching from server startup
|
||||
self._fetch_all_data(do_async=True)
|
||||
@@ -167,10 +203,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
notices_ttl=6*60,
|
||||
pip_args=None,
|
||||
pip_force_user=False,
|
||||
confirm_uninstall=True,
|
||||
confirm_disable=False,
|
||||
dependency_links=False,
|
||||
hidden=[]
|
||||
hidden=[],
|
||||
ignore_throttled=False
|
||||
)
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -179,7 +215,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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"])
|
||||
self._confirm_uninstall = self._settings.global_get_boolean(["confirm_uninstall"])
|
||||
self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"])
|
||||
|
||||
##~~ AssetPlugin
|
||||
@@ -204,7 +239,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower())
|
||||
return dict(
|
||||
all=plugins,
|
||||
thirdparty=filter(lambda p: not p["bundled"], plugins),
|
||||
thirdparty=list(filter(lambda p: not p["bundled"], plugins)),
|
||||
archive_extensions=self.__class__.ARCHIVE_EXTENSIONS
|
||||
)
|
||||
|
||||
@@ -216,8 +251,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403)
|
||||
def upload_archive(self):
|
||||
import flask
|
||||
|
||||
@@ -230,7 +265,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
upload_path = flask.request.values[input_upload_path]
|
||||
upload_name = flask.request.values[input_upload_name]
|
||||
|
||||
exts = filter(lambda x: upload_name.lower().endswith(x), self.__class__.ARCHIVE_EXTENSIONS)
|
||||
exts = list(filter(lambda x: upload_name.lower().endswith(x), self.__class__.ARCHIVE_EXTENSIONS))
|
||||
if not len(exts):
|
||||
return flask.make_response("File doesn't have a valid extension for a plugin archive", 400)
|
||||
|
||||
@@ -249,7 +284,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
try:
|
||||
os.remove(archive.name)
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
|
||||
self._logger.warning("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
@@ -267,11 +302,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
"uninstall": ["plugin"],
|
||||
"enable": ["plugin"],
|
||||
"disable": ["plugin"],
|
||||
"cleanup": ["plugin"],
|
||||
"cleanup_all": [],
|
||||
"refresh_repository": []
|
||||
}
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not admin_permission.can():
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
|
||||
from octoprint.server import safe_mode
|
||||
@@ -284,12 +321,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if refresh_notices or not self._is_notices_cache_valid():
|
||||
self._notices_available = self._refresh_notices()
|
||||
|
||||
refresh_orphan = request.values.get("refresh_orphans", "false") in valid_boolean_trues
|
||||
|
||||
def view():
|
||||
return jsonify(plugins=self._get_plugins(),
|
||||
repository=dict(
|
||||
available=self._repository_available,
|
||||
plugins=self._repository_plugins
|
||||
),
|
||||
orphan_data=self._get_orphans(refresh=refresh_orphan),
|
||||
os=get_os(),
|
||||
octoprint=get_octoprint_version_string(),
|
||||
pip=dict(
|
||||
@@ -307,14 +347,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def etag():
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
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))
|
||||
def hash_update(value):
|
||||
value = value.encode('utf-8')
|
||||
hash.update(value)
|
||||
|
||||
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(self._get_orphans()))
|
||||
hash_update(repr(safe_mode))
|
||||
hash_update(repr(self._connectivity_checker.online))
|
||||
hash_update(repr(_DATA_FORMAT_VERSION))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -322,10 +367,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
unless=lambda: refresh_repository or refresh_notices)(view)()
|
||||
unless=lambda: refresh_repository or refresh_notices or refresh_orphan)(view)()
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not admin_permission.can():
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
@@ -333,6 +378,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return make_response("Printer is currently printing or paused", 409)
|
||||
|
||||
if command == "install":
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
url = data["url"]
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
return self.command_install(url=url,
|
||||
@@ -347,7 +394,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return make_response("Unknown plugin: %s" % plugin_name, 404)
|
||||
|
||||
plugin = self._plugin_manager.plugins[plugin_name]
|
||||
return self.command_uninstall(plugin)
|
||||
return self.command_uninstall(plugin, cleanup=data.get("cleanup", False))
|
||||
|
||||
elif command == "cleanup":
|
||||
plugin = data["plugin"]
|
||||
try:
|
||||
plugin = self._plugin_manager.plugins[plugin]
|
||||
except KeyError:
|
||||
# not installed, we are cleaning up left overs, that's ok
|
||||
pass
|
||||
|
||||
return self.command_cleanup(plugin, include_disabled=True)
|
||||
|
||||
elif command == "cleanup_all":
|
||||
return self.command_cleanup_all()
|
||||
|
||||
elif command == "enable" or command == "disable":
|
||||
plugin_name = data["plugin"]
|
||||
@@ -359,7 +419,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
|
||||
throttled = self._get_throttled()
|
||||
if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False):
|
||||
if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]):
|
||||
# currently throttled, we refuse to run
|
||||
return make_response("System is currently throttled, refusing to install "
|
||||
"anything due to possible stability issues", 409)
|
||||
@@ -416,7 +476,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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:
|
||||
except Exception:
|
||||
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:
|
||||
@@ -426,14 +486,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
except:
|
||||
except Exception:
|
||||
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 = list(filter(lambda x: x.startswith(success_string) or x.startswith(failure_string),
|
||||
stdout))[-1]
|
||||
except IndexError:
|
||||
self._logger.error("Installing the plugin from {} failed, could not parse output from pip. "
|
||||
"See plugin_pluginmanager_console.log for generated output".format(source))
|
||||
@@ -476,12 +536,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
installed = map(lambda x: x.strip(), result_line[len(success_string):].split(" "))
|
||||
installed = list(map(lambda x: x.strip(), result_line[len(success_string):].split(" ")))
|
||||
all_plugins_after = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
|
||||
|
||||
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 "
|
||||
self._logger.warning("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,
|
||||
@@ -528,7 +588,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
def command_uninstall(self, plugin):
|
||||
def command_uninstall(self, plugin, cleanup=False):
|
||||
if plugin.key == "pluginmanager":
|
||||
return make_response("Can't uninstall Plugin Manager", 403)
|
||||
|
||||
@@ -539,7 +599,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return make_response("Bundled plugins cannot be uninstalled", 403)
|
||||
|
||||
if plugin.origin is None:
|
||||
self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals()))
|
||||
self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown".format(**locals()))
|
||||
return make_response("Could not uninstall plugin, its origin is unknown")
|
||||
|
||||
if plugin.origin.type == "entry_point":
|
||||
@@ -551,8 +611,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin]
|
||||
try:
|
||||
self._call_pip(pip_args)
|
||||
except:
|
||||
self._logger.exception(u"Could not uninstall plugin via pip")
|
||||
except Exception:
|
||||
self._logger.exception("Could not uninstall plugin via pip")
|
||||
return make_response("Could not uninstall plugin via pip, see the log for more details", 500)
|
||||
|
||||
elif plugin.origin.type == "folder":
|
||||
@@ -562,10 +622,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
if os.path.isdir(full_path):
|
||||
# plugin is installed via a plugin folder, need to use rmtree to get rid of it
|
||||
self._log_stdout(u"Deleting plugin from {folder}".format(folder=plugin.location))
|
||||
self._log_stdout("Deleting plugin from {folder}".format(folder=plugin.location))
|
||||
shutil.rmtree(full_path)
|
||||
elif os.path.isfile(full_path):
|
||||
self._log_stdout(u"Deleting plugin from {file}".format(file=plugin.location))
|
||||
self._log_stdout("Deleting plugin from {file}".format(file=plugin.location))
|
||||
os.remove(full_path)
|
||||
|
||||
if full_path.endswith(".py"):
|
||||
@@ -574,10 +634,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
os.remove(pyc_file)
|
||||
|
||||
else:
|
||||
self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals()))
|
||||
self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals()))
|
||||
return make_response("Could not uninstall plugin, its origin is unknown")
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup
|
||||
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()
|
||||
|
||||
@@ -591,7 +651,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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))
|
||||
self._logger.exception("Problem disabling plugin {name}".format(name=plugin.key))
|
||||
result = dict(result=False, uninstalled=True, disabled=False, unloaded=False, reason=e.reason)
|
||||
self._send_result_notification("uninstall", result)
|
||||
return jsonify(result)
|
||||
@@ -600,7 +660,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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))
|
||||
self._logger.exception("Problem unloading plugin {name}".format(name=plugin.key))
|
||||
result = dict(result=False, uninstalled=True, disabled=True, unloaded=False, reason=e.reason)
|
||||
self._send_result_notification("uninstall", result)
|
||||
return jsonify(result)
|
||||
@@ -617,8 +677,108 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
needs_reconnect=needs_reconnect,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
self._send_result_notification("uninstall", result)
|
||||
self._logger.info("Plugin {} uninstalled".format(plugin.key))
|
||||
|
||||
self._cleanup_disabled(plugin.key)
|
||||
if cleanup:
|
||||
self.command_cleanup(plugin.key, result_notifications=False)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
def command_cleanup(self, plugin, include_disabled=False, result_notifications=True, settings_save=True):
|
||||
if isinstance(plugin, basestring):
|
||||
key = result_value = plugin
|
||||
else:
|
||||
key = plugin.key
|
||||
result_value = self._to_external_plugin(plugin)
|
||||
|
||||
message = "Cleaning up plugin {}...".format(key)
|
||||
self._logger.info(message)
|
||||
self._log_stdout(message)
|
||||
|
||||
# delete plugin settings
|
||||
self._cleanup_settings(key)
|
||||
|
||||
# delete plugin disabled entry
|
||||
if include_disabled:
|
||||
self._cleanup_disabled(key)
|
||||
|
||||
# delete plugin data folder
|
||||
result_data = True
|
||||
if not self._cleanup_data(key):
|
||||
message = "Could not delete data folder of plugin {}".format(key)
|
||||
self._logger.exception(message)
|
||||
self._log_stderr(message)
|
||||
result_data = False
|
||||
|
||||
if settings_save:
|
||||
self._settings.save()
|
||||
|
||||
result = dict(result=result_data,
|
||||
needs_restart=True,
|
||||
plugin=result_value)
|
||||
if result_notifications:
|
||||
self._send_result_notification("cleanup", result)
|
||||
|
||||
# cleaning orphan cache
|
||||
self._orphans = None
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
def command_cleanup_all(self):
|
||||
orphans = self._get_orphans()
|
||||
cleaned_up = set()
|
||||
|
||||
for orphan in sorted(orphans.keys()):
|
||||
self.command_cleanup(orphan,
|
||||
include_disabled=True,
|
||||
result_notifications=False,
|
||||
settings_save=False)
|
||||
cleaned_up.add(orphan)
|
||||
|
||||
self._settings.save()
|
||||
|
||||
result = dict(result=True,
|
||||
needs_restart=len(cleaned_up) > 0,
|
||||
cleaned_up=sorted(list(cleaned_up)))
|
||||
self._send_result_notification("cleanup_all", result)
|
||||
self._logger.info("Cleaned up all data, {} left overs removed".format(len(cleaned_up)))
|
||||
|
||||
# cleaning orphan cache
|
||||
self._orphans = None
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
def _cleanup_disabled(self, plugin):
|
||||
# delete from disabled list
|
||||
disabled = self._settings.global_get(["plugins", "_disabled"])
|
||||
try:
|
||||
disabled.remove(plugin)
|
||||
except ValueError:
|
||||
# not in list, ok
|
||||
pass
|
||||
self._settings.global_set(["plugins", "_disabled"], disabled)
|
||||
|
||||
def _cleanup_settings(self, plugin):
|
||||
# delete plugin settings
|
||||
self._settings.global_set(["plugins", plugin], None)
|
||||
return True
|
||||
|
||||
def _cleanup_data(self, plugin):
|
||||
import os
|
||||
import shutil
|
||||
|
||||
data_folder = os.path.join(self._settings.getBaseFolder("data"), plugin)
|
||||
if os.path.exists(data_folder):
|
||||
try:
|
||||
shutil.rmtree(data_folder)
|
||||
return True
|
||||
except Exception:
|
||||
self._logger.exception("Could not delete plugin data folder at {}".format(data_folder))
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def command_toggle(self, plugin, command):
|
||||
if plugin.key == "pluginmanager":
|
||||
return make_response("Can't enable/disable Plugin Manager", 400)
|
||||
@@ -640,7 +800,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
elif command == "enable":
|
||||
self._mark_plugin_enabled(plugin, needs_restart=needs_restart)
|
||||
except octoprint.plugin.core.PluginLifecycleException as e:
|
||||
self._logger.exception(u"Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason))
|
||||
self._logger.exception("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,
|
||||
@@ -695,10 +855,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
def _call_pip(self, args):
|
||||
if self._pip_caller is None or not self._pip_caller.available:
|
||||
raise RuntimeError(u"No pip available, can't operate".format(**locals()))
|
||||
raise RuntimeError("No pip available, can't operate".format(**locals()))
|
||||
|
||||
if "--process-dependency-links" in args:
|
||||
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
|
||||
self._log_message("Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
|
||||
|
||||
additional_args = self._settings.get(["pip_args"])
|
||||
|
||||
@@ -706,7 +866,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
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)
|
||||
additional_args = re.sub(r"(^|\s)" + re.escape(inapplicable_argument) + r"\\b", "", additional_args)
|
||||
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
@@ -716,25 +876,25 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return self._pip_caller.execute(*args, **kwargs)
|
||||
|
||||
def _log_message(self, *lines):
|
||||
self._log(lines, prefix=u"*", stream="message")
|
||||
self._log(lines, prefix="*", stream="message")
|
||||
|
||||
def _log_call(self, *lines):
|
||||
self._log(lines, prefix=u" ", stream="call")
|
||||
self._log(lines, prefix=" ", stream="call")
|
||||
|
||||
def _log_stdout(self, *lines):
|
||||
self._log(lines, prefix=u">", stream="stdout")
|
||||
self._log(lines, prefix=">", stream="stdout")
|
||||
|
||||
def _log_stderr(self, *lines):
|
||||
self._log(lines, prefix=u"!", stream="stderr")
|
||||
self._log(lines, prefix="!", stream="stderr")
|
||||
|
||||
def _log(self, lines, prefix=None, stream=None, strip=True):
|
||||
if strip:
|
||||
lines = map(lambda x: x.strip(), lines)
|
||||
lines = list(map(lambda x: x.strip(), lines))
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines",
|
||||
loglines=[dict(line=line, stream=stream) for line in lines]))
|
||||
for line in lines:
|
||||
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
|
||||
self._console_logger.debug("{prefix} {line}".format(**locals()))
|
||||
|
||||
def _mark_plugin_enabled(self, plugin, needs_restart=False):
|
||||
disabled_list = list(self._settings.global_get(["plugins", "_disabled"],
|
||||
@@ -794,6 +954,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
import time
|
||||
if mtime is None:
|
||||
mtime = self._repository_mtime
|
||||
if mtime is None:
|
||||
return False
|
||||
return mtime + self._repository_cache_ttl >= time.time() > mtime
|
||||
|
||||
def _fetch_repository_from_disk(self):
|
||||
@@ -804,11 +966,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if self._is_repository_cache_valid(mtime=mtime):
|
||||
try:
|
||||
import json
|
||||
with open(self._repository_cache_path) as f:
|
||||
with io.open(self._repository_cache_path, 'rt', encoding='utf-8') as f:
|
||||
repo_data = json.load(f)
|
||||
self._repository_mtime = mtime
|
||||
self._logger.info("Loaded plugin repository data from disk, was still valid")
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path))
|
||||
|
||||
return self._refresh_repository(repo_data=repo_data)
|
||||
@@ -824,13 +986,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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)))
|
||||
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=e))
|
||||
return None
|
||||
|
||||
try:
|
||||
repo_data = r.json()
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while reading repository data")
|
||||
self._logger.exception("Error while reading repository data: {}".format(e))
|
||||
return None
|
||||
|
||||
# validation
|
||||
@@ -840,11 +1002,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
try:
|
||||
import json
|
||||
with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f:
|
||||
json.dump(repo_data, f)
|
||||
with octoprint.util.atomic_write(self._repository_cache_path, mode='wb') as f:
|
||||
f.write(to_bytes(json.dumps(repo_data)))
|
||||
self._repository_mtime = os.path.getmtime(self._repository_cache_path)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
|
||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, e))
|
||||
|
||||
return repo_data
|
||||
|
||||
@@ -854,14 +1016,16 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if repo_data is None:
|
||||
return False
|
||||
|
||||
self._repository_plugins = filter(lambda x: x is not None,
|
||||
map(map_repository_entry, repo_data))
|
||||
self._repository_plugins = list(filter(lambda x: x is not None,
|
||||
map(map_repository_entry, repo_data)))
|
||||
return True
|
||||
|
||||
def _is_notices_cache_valid(self, mtime=None):
|
||||
import time
|
||||
if mtime is None:
|
||||
mtime = self._notices_mtime
|
||||
if mtime is None:
|
||||
return False
|
||||
return mtime + self._notices_cache_ttl >= time.time() > mtime
|
||||
|
||||
def _fetch_notices_from_disk(self):
|
||||
@@ -872,11 +1036,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if self._is_notices_cache_valid(mtime=mtime):
|
||||
try:
|
||||
import json
|
||||
with open(self._notices_cache_path) as f:
|
||||
with io.open(self._notices_cache_path, 'rt', encoding='utf-8') as f:
|
||||
notice_data = json.load(f)
|
||||
self._notices_mtime = mtime
|
||||
self._logger.info("Loaded notice data from disk, was still valid")
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
|
||||
|
||||
return self._refresh_notices(notice_data=notice_data)
|
||||
@@ -899,8 +1063,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
try:
|
||||
import json
|
||||
with octoprint.util.atomic_write(self._notices_cache_path, "wb") as f:
|
||||
json.dump(notice_data, f)
|
||||
with octoprint.util.atomic_write(self._notices_cache_path, mode="wb") as f:
|
||||
f.write(to_bytes(json.dumps(notice_data)))
|
||||
self._notices_mtime = os.path.getmtime(self._notices_cache_path)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e)))
|
||||
@@ -928,7 +1092,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
parsed_date = datetime.strptime(notice["date"], "%Y-%m-%d %H:%M:%S +0000")
|
||||
notice["timestamp"] = parsed_date.timetuple()
|
||||
except Exception as e:
|
||||
self._logger.warn("Error while parsing date {!r} for plugin notice "
|
||||
self._logger.warning("Error while parsing date {!r} for plugin notice "
|
||||
"of plugin {}, ignoring notice: {}".format(notice["date"], key, str(e)))
|
||||
continue
|
||||
|
||||
@@ -939,6 +1103,41 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._notices = notices
|
||||
return True
|
||||
|
||||
def _get_orphans(self, refresh=False):
|
||||
from collections import defaultdict
|
||||
|
||||
if self._orphans is not None and not refresh:
|
||||
return self._orphans
|
||||
|
||||
installed_keys = self._plugin_manager.plugins.keys()
|
||||
orphans = defaultdict(lambda: dict(settings=False, data=False, disabled=False))
|
||||
|
||||
# settings
|
||||
for key in list(self._settings.global_get(["plugins"]).keys()):
|
||||
if key.startswith("_"):
|
||||
# internal key, like _disabled
|
||||
continue
|
||||
|
||||
if key not in installed_keys:
|
||||
orphans[key]["settings"] = True
|
||||
|
||||
# data
|
||||
for entry in scandir(self._settings.getBaseFolder("data")):
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
|
||||
if entry.name not in installed_keys:
|
||||
orphans[entry.name]["data"] = True
|
||||
|
||||
# disabled
|
||||
disabled = self._settings.global_get(["plugins", "_disabled"])
|
||||
for key in disabled:
|
||||
if key not in installed_keys:
|
||||
orphans[key]["disabled"] = True
|
||||
|
||||
self._orphans = dict(**orphans)
|
||||
return self._orphans
|
||||
|
||||
@property
|
||||
def _reconnect_hooks(self):
|
||||
reconnect_hooks = self.__class__.RECONNECT_HOOKS
|
||||
@@ -949,7 +1148,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
result = hook()
|
||||
if isinstance(result, (list, tuple)):
|
||||
reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result))
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving additional hooks for which a "
|
||||
"reconnect is required from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
@@ -1012,10 +1211,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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)))
|
||||
return list(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,
|
||||
@@ -1044,5 +1243,6 @@ def __plugin_load__():
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
|
||||
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
|
||||
"octoprint.events.register_custom_events": _register_custom_events
|
||||
"octoprint.events.register_custom_events": _register_custom_events,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -10,18 +10,21 @@
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
|
||||
var refresh_repo, refresh_notices;
|
||||
var refresh_repo, refresh_notices, refresh_orphans;
|
||||
if (_.isPlainObject(refresh)) {
|
||||
refresh_repo = refresh.repo || false;
|
||||
refresh_notices = refresh.notices || false;
|
||||
refresh_orphans = refresh.orphans || false;
|
||||
} else {
|
||||
refresh_repo = refresh;
|
||||
refresh_notices = false;
|
||||
refresh_orphans = false;
|
||||
}
|
||||
|
||||
var query = [];
|
||||
if (refresh_repo) query.push("refresh_repository=true");
|
||||
if (refresh_notices) query.push("refresh_notices=true");
|
||||
if (refresh_orphans) query.push("refresh_orphans=true");
|
||||
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
|
||||
};
|
||||
@@ -52,11 +55,30 @@
|
||||
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, cleanup, opts) {
|
||||
// backwards compatibility to former argument list (plugin, opts)
|
||||
if (arguments.length === 2 && typeof cleanup === "object") {
|
||||
opts = cleanup;
|
||||
cleanup = false;
|
||||
}
|
||||
|
||||
var data = {
|
||||
plugin: plugin,
|
||||
cleanup: !!cleanup
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.cleanup = function(plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
|
||||
return this.base.simpleApiCommand("pluginmanager", "cleanup", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.cleanupAll = function(plugin, opts) {
|
||||
var data = {};
|
||||
return this.base.simpleApiCommand("pluginmanager", "cleanup_all", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
|
||||
|
||||
@@ -1 +1 @@
|
||||
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#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_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
@@ -6,9 +6,10 @@ $(function() {
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.printerState = parameters[2];
|
||||
self.systemViewModel = parameters[3];
|
||||
self.access = parameters[4];
|
||||
|
||||
// optional
|
||||
self.piSupport = parameters[4];
|
||||
self.piSupport = parameters[5];
|
||||
|
||||
self.config_repositoryUrl = ko.observable();
|
||||
self.config_repositoryTtl = ko.observable();
|
||||
@@ -32,10 +33,22 @@ $(function() {
|
||||
}
|
||||
},
|
||||
{
|
||||
"bundled": function(item) {
|
||||
return item.bundled;
|
||||
},
|
||||
"3rdparty": function(item) {
|
||||
return !item.bundled;
|
||||
},
|
||||
"enabled": function(item) {
|
||||
return item.enabled;
|
||||
},
|
||||
"disabled": function(item) {
|
||||
return !item.enabled;
|
||||
}
|
||||
},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
[["bundled", "3rdparty"], ["enabled", "disabled"]],
|
||||
0
|
||||
);
|
||||
|
||||
@@ -60,7 +73,7 @@ $(function() {
|
||||
return !self.installed(plugin);
|
||||
},
|
||||
"filter_incompatible": function(plugin) {
|
||||
return plugin.is_compatible.octoprint && plugin.is_compatible.os;
|
||||
return plugin.is_compatible.octoprint && plugin.is_compatible.os && plugin.is_compatible.python;
|
||||
}
|
||||
},
|
||||
"title",
|
||||
@@ -69,6 +82,23 @@ $(function() {
|
||||
0
|
||||
);
|
||||
|
||||
self.orphans = new ItemListHelper(
|
||||
"plugin.pluginmanager.orphans",
|
||||
{
|
||||
"identifier": function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["identifier"].toLocaleLowerCase() < b["identifier"].toLocaleLowerCase()) return -1;
|
||||
if (a["identifier"].toLocaleLowerCase() > b["identifier"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"identifier",
|
||||
[],
|
||||
[],
|
||||
0
|
||||
);
|
||||
|
||||
self.uploadElement = $("#settings_plugin_pluginmanager_repositorydialog_upload");
|
||||
self.uploadButton = $("#settings_plugin_pluginmanager_repositorydialog_upload_start");
|
||||
|
||||
@@ -79,6 +109,11 @@ $(function() {
|
||||
self.performRepositorySearch();
|
||||
});
|
||||
|
||||
self.listingSearchQuery = ko.observable();
|
||||
self.listingSearchQuery.subscribe(function() {
|
||||
self.performListingSearch();
|
||||
});
|
||||
|
||||
self.installUrl = ko.observable();
|
||||
self.uploadFilename = ko.observable();
|
||||
|
||||
@@ -149,7 +184,7 @@ $(function() {
|
||||
});
|
||||
|
||||
self.enableManagement = ko.pureComputed(function() {
|
||||
return !self.printerState.isPrinting();
|
||||
return !self.printerState.isBusy();
|
||||
});
|
||||
|
||||
self.enableToggle = function(data) {
|
||||
@@ -168,12 +203,18 @@ $(function() {
|
||||
&& !data.pending_uninstall;
|
||||
};
|
||||
|
||||
self.enableCleanup = function(data) {
|
||||
return self.enableManagement()
|
||||
&& data.key !== 'pluginmanager'
|
||||
&& !data.pending_uninstall;
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && !self.throttled() && self.online() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.throttled = ko.pureComputed(function() {
|
||||
return self.piSupport && self.piSupport.currentIssue();
|
||||
return self.piSupport && self.piSupport.currentIssue() && !self.settingsViewModel.settings.plugins.pluginmanager.ignore_throttled();
|
||||
});
|
||||
|
||||
self.invalidUrl = ko.pureComputed(function() {
|
||||
@@ -277,9 +318,21 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.performListingSearch = function() {
|
||||
var query = self.listingSearchQuery();
|
||||
if (query !== undefined && query.trim() !== "") {
|
||||
query = query.toLocaleLowerCase();
|
||||
self.plugins.changeSearchFunction(function (entry) {
|
||||
return entry && (entry["name"].toLocaleLowerCase().indexOf(query) > -1 || (entry.description && entry.description.toLocaleLowerCase().indexOf(query) > -1));
|
||||
});
|
||||
} else {
|
||||
self.plugins.resetSearch();
|
||||
}
|
||||
};
|
||||
|
||||
self.performRepositorySearch = function() {
|
||||
var query = self.repositorySearchQuery();
|
||||
if (query !== undefined && query.trim() != "") {
|
||||
if (query !== undefined && query.trim() !== "") {
|
||||
query = query.toLocaleLowerCase();
|
||||
self.repositoryplugins.changeSearchFunction(function(entry) {
|
||||
return entry && (entry["title"].toLocaleLowerCase().indexOf(query) > -1 || entry["description"].toLocaleLowerCase().indexOf(query) > -1);
|
||||
@@ -292,6 +345,7 @@ $(function() {
|
||||
|
||||
self.fromResponse = function(data, options) {
|
||||
self._fromPluginsResponse(data.plugins, options);
|
||||
self._fromOrphanResponse(data.orphan_data, options);
|
||||
self._fromRepositoryResponse(data.repository, options);
|
||||
self._fromPipResponse(data.pip, options);
|
||||
|
||||
@@ -325,6 +379,14 @@ $(function() {
|
||||
self.plugins.updateItems(data);
|
||||
};
|
||||
|
||||
self._fromOrphanResponse = function(data) {
|
||||
var orphans = [];
|
||||
_.each(data, function(value, key) {
|
||||
orphans.push({identifier: key, settings: value.settings, data: value.data});
|
||||
});
|
||||
self.orphans.updateItems(orphans);
|
||||
};
|
||||
|
||||
self._fromRepositoryResponse = function(data) {
|
||||
self.repositoryAvailable(data.available);
|
||||
if (data.available) {
|
||||
@@ -353,31 +415,32 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestData = function(options) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_.isPlainObject(options)) {
|
||||
options = {
|
||||
refresh_repo: options,
|
||||
refresh_orphans: false,
|
||||
refresh_notices: false,
|
||||
eval_notices: false
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
options.refresh_repo = options.refresh_repo || false;
|
||||
options.refresh_orphans = options.refresh_orphans || 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})
|
||||
OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices, orphans: options.refresh_orphans})
|
||||
.done(function(data) {
|
||||
self.fromResponse(data, options);
|
||||
});
|
||||
};
|
||||
|
||||
self.togglePlugin = function(data) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -413,7 +476,7 @@ $(function() {
|
||||
|
||||
// always warn if plugin is marked "disabling discouraged"
|
||||
if (data.disabling_discouraged) {
|
||||
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: data.name})
|
||||
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: _.escape(data.name)})
|
||||
+ "</p><p>" + data.disabling_discouraged;
|
||||
showConfirmationDialog({
|
||||
title: gettext("This is not recommended"),
|
||||
@@ -427,7 +490,7 @@ $(function() {
|
||||
// warn if global "warn disabling" setting is set"
|
||||
else if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()) {
|
||||
showConfirmationDialog({
|
||||
message: _.sprintf(gettext("You are about to disable \"%(name)s\""), {name: data.name}),
|
||||
message: _.sprintf(gettext("You are about to disable \"%(name)s\""), {name: _.escape(data.name)}),
|
||||
cancel: gettext("Keep enabled"),
|
||||
proceed: gettext("Disable plugin"),
|
||||
onproceed: performDisabling,
|
||||
@@ -449,7 +512,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.installFromRepository = function(data) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -461,7 +524,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -486,13 +549,13 @@ $(function() {
|
||||
if (!reinstall) {
|
||||
workTitle = gettext("Installing plugin...");
|
||||
if (name) {
|
||||
workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: url, name: name});
|
||||
workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)});
|
||||
} else {
|
||||
workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: url});
|
||||
workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: _.escape(url)});
|
||||
}
|
||||
} else {
|
||||
workTitle = gettext("Reinstalling plugin...");
|
||||
workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: url, name: name});
|
||||
workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)});
|
||||
}
|
||||
self._markWorking(workTitle, workText);
|
||||
|
||||
@@ -527,7 +590,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.uninstallPlugin = function(data) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -536,14 +599,14 @@ $(function() {
|
||||
}
|
||||
|
||||
if (data.bundled) return;
|
||||
if (data.key == "pluginmanager") return;
|
||||
if (data.key === "pluginmanager") return;
|
||||
|
||||
// defining actual uninstall logic as functor in order to handle
|
||||
// the confirm/no-confirm logic without duplication of logic
|
||||
var performUninstall = function() {
|
||||
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
|
||||
var performUninstall = function(cleanup) {
|
||||
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: _.escape(data.name)}));
|
||||
|
||||
OctoPrint.plugins.pluginmanager.uninstall(data.key)
|
||||
OctoPrint.plugins.pluginmanager.uninstall(data.key, cleanup)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
@@ -560,23 +623,99 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_uninstall()) {
|
||||
// confirmation needed. Show confirmation dialog and call performUninstall if user clicks Yes
|
||||
showConfirmationDialog({
|
||||
message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: data.name}),
|
||||
cancel: gettext("Keep installed"),
|
||||
proceed: gettext("Uninstall"),
|
||||
onproceed: performUninstall,
|
||||
nofade: true
|
||||
});
|
||||
showConfirmationDialog({
|
||||
message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: _.escape(data.name)}),
|
||||
cancel: gettext("Keep installed"),
|
||||
proceed: [
|
||||
gettext("Uninstall"),
|
||||
gettext("Uninstall & clean up data")
|
||||
],
|
||||
onproceed: function(button) {
|
||||
// buttons: 0=uninstall, 1=uninstall&cleanup
|
||||
performUninstall(button === 1)
|
||||
},
|
||||
nofade: true
|
||||
});
|
||||
};
|
||||
|
||||
self.cleanupPlugin = function(data) {
|
||||
var key, name;
|
||||
if (_.isObject(data)) {
|
||||
key = data.key;
|
||||
name = data.name;
|
||||
} else {
|
||||
// no confirmation needed, just go ahead and uninstall
|
||||
performUninstall();
|
||||
key = name = data;
|
||||
}
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === "pluginmanager") return;
|
||||
|
||||
var performCleanup = function() {
|
||||
self._markWorking(gettext("Cleaning up plugin data..."), _.sprintf(gettext("Cleaning up data of plugin \"%(name)s\""), {name: _.escape(name)}));
|
||||
|
||||
OctoPrint.plugins.pluginmanager.cleanup(key)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Please consult octoprint.log for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
})
|
||||
.always(function() {
|
||||
self._markDone();
|
||||
})
|
||||
};
|
||||
|
||||
showConfirmationDialog({
|
||||
message: _.sprintf(gettext("You are about to cleanup the plugin data of \"%(name)s\". This operation cannot be reversed."), {name: _.escape(name)}),
|
||||
cancel: gettext("Keep data"),
|
||||
proceed: gettext("Cleanup data"),
|
||||
onproceed: performCleanup,
|
||||
nofade: true
|
||||
});
|
||||
};
|
||||
|
||||
self.cleanupAll = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var performCleanup = function() {
|
||||
var title = gettext("Cleaning up all left over plugin data...");
|
||||
self._markWorking(title, title);
|
||||
|
||||
OctoPrint.plugins.pluginmanager.cleanupAll()
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Please consult octoprint.log for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
})
|
||||
.always(function() {
|
||||
self._markDone();
|
||||
})
|
||||
};
|
||||
|
||||
showConfirmationDialog({
|
||||
message: gettext("You are about to cleanup left over plugin settings and data of plugins no longer installed. This operation cannot be reversed."),
|
||||
cancel: gettext("Keep data"),
|
||||
proceed: gettext("Cleanup all data"),
|
||||
onproceed: performCleanup,
|
||||
nofade: true
|
||||
});
|
||||
};
|
||||
|
||||
self.refreshRepository = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
|
||||
return;
|
||||
}
|
||||
self.requestData({refresh_repo: true});
|
||||
@@ -642,7 +781,6 @@ $(function() {
|
||||
notices_ttl: noticesTtl,
|
||||
pip_args: pipArgs,
|
||||
pip_force_user: self.config_pipForceUser(),
|
||||
confirm_uninstall: self.config_confirmUninstall(),
|
||||
confirm_disable: self.config_confirmDisable(),
|
||||
}
|
||||
}
|
||||
@@ -661,7 +799,6 @@ $(function() {
|
||||
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());
|
||||
self.config_confirmUninstall(self.settingsViewModel.settings.plugins.pluginmanager.confirm_uninstall());
|
||||
self.config_confirmDisable(self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable());
|
||||
};
|
||||
|
||||
@@ -670,7 +807,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.isCompatible = function(data) {
|
||||
return data.is_compatible.octoprint && data.is_compatible.os;
|
||||
return data.is_compatible.octoprint && data.is_compatible.os && data.is_compatible.python;
|
||||
};
|
||||
|
||||
self.installButtonText = function(data) {
|
||||
@@ -719,13 +856,21 @@ $(function() {
|
||||
line = gettext("Disable <em>%(plugin)s</em>: %(result)s");
|
||||
break;
|
||||
}
|
||||
case "cleanup": {
|
||||
line = gettext("Cleanup <em>%(plugin)s</em>: %(result)s");
|
||||
break;
|
||||
}
|
||||
case "cleanup_all": {
|
||||
line = gettext("Cleanup all: %(result)s");
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
text += "<li>"
|
||||
+ _.sprintf(line, {plugin: step.plugin, result: step.result ? "<i class=\"fa fa-check\"></i>" : "<i class=\"fa fa-remove\"></i>"})
|
||||
+ _.sprintf(line, {plugin: _.escape(step.plugin), result: step.result ? "<i class=\"fa fa-check\"></i>" : "<i class=\"fa fa-remove\"></i>"})
|
||||
+ "</li>";
|
||||
});
|
||||
text += "</ul></p>";
|
||||
@@ -903,16 +1048,16 @@ $(function() {
|
||||
|
||||
var title;
|
||||
if (important) {
|
||||
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: name});
|
||||
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: _.escape(name)});
|
||||
} else {
|
||||
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: name});
|
||||
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: _.escape(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>";
|
||||
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: _.escape(versions)}) + "</small>";
|
||||
} else {
|
||||
text += "<small>" + gettext("Affected versions: all") + "</small>";
|
||||
}
|
||||
@@ -1040,18 +1185,14 @@ $(function() {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function(user) {
|
||||
if (user.admin) {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
if (self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
self.requestData({eval_notices: true});
|
||||
} else {
|
||||
self.onUserLoggedOut();
|
||||
self._resetNotifications();
|
||||
}
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self._resetNotifications();
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
self.requestData({eval_notices: true});
|
||||
};
|
||||
@@ -1092,7 +1233,7 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1112,7 +1253,11 @@ $(function() {
|
||||
var name = "Unknown";
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
if (data.plugin !== "unknown") {
|
||||
name = data.plugin.name;
|
||||
if (_.isPlainObject(data.plugin)) {
|
||||
name = data.plugin.name;
|
||||
} else {
|
||||
name = data.plugin;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1132,7 +1277,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PluginManagerViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "piSupportViewModel"],
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel", "piSupportViewModel"],
|
||||
optional: ["piSupportViewModel"],
|
||||
elements: ["#settings_plugin_pluginmanager"]
|
||||
});
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
#settings_plugin_pluginmanager {
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_pluginlist {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 400px;
|
||||
max-height: 400px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
@@ -33,6 +36,41 @@
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_orphanlist {
|
||||
display: block;
|
||||
width: auto;
|
||||
max-height: 400px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
margin-bottom: 1em;
|
||||
|
||||
table {
|
||||
|
||||
th, td {
|
||||
&.settings_plugin_plugin_manager_orphans_id {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.settings_plugin_plugin_manager_orphans_actions {
|
||||
text-align: center;
|
||||
width: 80px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_repositorydialog {
|
||||
h4 {
|
||||
position: relative;
|
||||
@@ -64,7 +102,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_repositorydialog_unavailable {
|
||||
#settings_plugin_pluginmanager_repositorydialog_unavailable,
|
||||
#settings_plugin_pluginmanager_repositorydialog_empty {
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
height: 300px;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% macro pluginmanager_printing() %}
|
||||
<div class="alert" data-bind="visible: !enableManagement()">
|
||||
{{ _('Take note that all plugin management functionality is disabled while your printer is printing.') }}
|
||||
{{ _('Take note that all plugin management functionality is disabled while your printer is printing or paused.') }}
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
@@ -34,78 +34,144 @@
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
{{ pluginmanager_throttled() }}
|
||||
<ul class="nav nav-pills">
|
||||
<li class="active">
|
||||
<a href="#settings_plugin_pluginmanager_plugins" data-toggle="tab">{{ _('Plugins') }}</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#settings_plugin_pluginmanager_cleanup" data-toggle="tab">{{ _('Cleanup') }}</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="settings_plugin_pluginmanager_plugins">
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
{{ pluginmanager_throttled() }}
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_pluginlist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint')|edq }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint')|edq }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect')|edq }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install')|edq }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall')|edq }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode')|edq }}" 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')|edq }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted')|edq }}" 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="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>
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
|
||||
<div style="margin-bottom: 1em" class="clearfix">
|
||||
<input type="text" class="input-block search-query pull-left" data-bind="value: listingSearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
|
||||
|
||||
<div class="pull-right">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.removeFilter('bundled'); plugins.removeFilter('3rdparty'); }, css: {active: !_.contains(plugins.currentFilters(), 'bundled') && !_.contains(plugins.currentFilters(), '3rdparty')}" title="{{ _('Show both bundled and third-party plugins')|edq }}">All</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('bundled') }, css: {active: _.contains(plugins.currentFilters(), 'bundled')}" title="{{ _('Show only bundled plugins')|edq }}">{{ _('Bundled') }}</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('3rdparty') }, css: {active: _.contains(plugins.currentFilters(), '3rdparty')}" title="{{ _('Show only third-party plugins')|edq }}">{{ _('3rd party') }}</button>
|
||||
</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="fa fa-trash-o" title="{{ _('Uninstall Plugin')|edq }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.removeFilter('enabled'); plugins.removeFilter('disabled'); }, css: {active: !_.contains(plugins.currentFilters(), 'enabled') && !_.contains(plugins.currentFilters(), 'disabled')}" title="{{ _('Show both enabled and disabled plugins')|edq }}">All</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('enabled') }, css: {active: _.contains(plugins.currentFilters(), 'enabled')}" title="{{ _('Show only enabled plugins')|edq }}">{{ _('Enabled') }}</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('disabled') }, css: {active: _.contains(plugins.currentFilters(), 'disabled')}" title="{{ _('Show only disabled plugins')|edq }}">{{ _('Disabled') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||
<div id="settings_plugin_pluginmanager_pluginlist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint')|edq }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint')|edq }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect')|edq }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install')|edq }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall')|edq }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode')|edq }}" 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')|edq }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted')|edq }}" 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="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="fa fa-eraser" title="{{ _('Cleanup Plugin Data')|edq }}" data-bind="css: {disabled: !$root.enableCleanup($data)}, enable: $root.enableCleanup($data), click: function() { $root.cleanupPlugin($data) }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin')|edq }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="muted" data-bind="visible: pipAvailable()">
|
||||
<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="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>
|
||||
<div class="hide">
|
||||
<small>
|
||||
Installation directory: <span data-bind="text: pipInstallDir"></span> ("--user" flag: <span data-bind="text: pipUseUserString"></span>)<br />
|
||||
Virtual environment: <span data-bind="text: pipVirtualEnvString"></span><br />
|
||||
<span data-bind="visible: pipAdditionalArgs">Additional Arguments: <span data-bind="text: pipAdditionalArgs"></span></span>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||
|
||||
<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 class="muted" data-bind="visible: pipAvailable()">
|
||||
<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="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>
|
||||
<div class="hide">
|
||||
<small>
|
||||
Installation directory: <span data-bind="text: pipInstallDir"></span> ("--user" flag: <span data-bind="text: pipUseUserString"></span>)<br />
|
||||
Virtual environment: <span data-bind="text: pipVirtualEnvString"></span><br />
|
||||
<span data-bind="visible: pipAdditionalArgs">Additional Arguments: <span data-bind="text: pipAdditionalArgs"></span></span>
|
||||
</small>
|
||||
</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>
|
||||
<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 class="tab-pane" id="settings_plugin_pluginmanager_cleanup">
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.requestData({refresh_orphans: true}) }" title="{{ _('Refresh')|edq }}"><i class="fa fa-refresh"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Cleanup') }}</h3>
|
||||
|
||||
<div data-bind="visible: orphans.paginatedItems().length > 0">
|
||||
<div id="settings_plugin_pluginmanager_orphanlist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_orphans_id">{{ _('Identifier') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_orphans_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: orphans.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_orphans_id">
|
||||
<span data-bind="text: identifier"></span>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_orphans_actions">
|
||||
<a href="javascript:void(0)" class="fa fa-eraser" title="{{ _('Cleanup Plugin Data')|edq }}" data-bind="click: function() { $root.cleanupPlugin($data.identifier) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-danger btn-block" data-bind="click: $root.cleanupAll">{{ _('Cleanup all') }}</button>
|
||||
</div>
|
||||
<div data-bind="visible: orphans.paginatedItems().length == 0">
|
||||
{{ _('Nothing to cleanup! There are no settings or data left over from plugins which are no longer installed.') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -154,7 +220,7 @@
|
||||
<input type="text" class="input-block search-query" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
|
||||
</form>
|
||||
|
||||
<div data-bind="visible: repositoryAvailable()">
|
||||
<div data-bind="visible: repositoryAvailable() && repositoryplugins.paginatedItems().length > 0">
|
||||
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="foreach: repositoryplugins.paginatedItems">
|
||||
<div class="entry">
|
||||
<div class="row-fluid">
|
||||
@@ -187,6 +253,13 @@
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div id="settings_plugin_pluginmanager_repositorydialog_empty" data-bind="visible: repositoryAvailable() && repositoryplugins.paginatedItems().length === 0">
|
||||
<div>
|
||||
<p>
|
||||
<strong>{{ _('It looks like there are no compatible plugins available') }}</strong>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h4>{{ _('... from URL') }}</h4>
|
||||
|
||||
@@ -246,13 +319,6 @@
|
||||
<fieldset>
|
||||
<legend>{{ _('Confirmations') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('Confirm before uninstalling a plugin')|edq }}">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: config_confirmUninstall"> {{ _('Confirm before uninstalling a plugin') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Confirm before disabling a plugin')|edq }}">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
|
||||
@@ -7,7 +7,8 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.events import Events
|
||||
from octoprint.server import user_permission
|
||||
from octoprint.access import USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
from .checks.firmware_unsafe import FirmwareUnsafeChecks
|
||||
@@ -70,7 +71,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
|
||||
##~~ SimpleApiPlugin API
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not user_permission.can():
|
||||
if not Permissions.PLUGIN_PRINTER_SAFETY_CHECK_DISPLAY.can():
|
||||
return flask.make_response("Insufficient rights", 403)
|
||||
return flask.jsonify(self._warnings)
|
||||
|
||||
@@ -97,6 +98,17 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
|
||||
to_unicode(cap, errors="replace"),
|
||||
enabled)
|
||||
|
||||
##~~ Additional permissions hook handler
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="DISPLAY",
|
||||
name="Display printer safety warnings",
|
||||
description=gettext("Allows to see printer safety warnings"),
|
||||
roles=["display"],
|
||||
default_groups=[USER_GROUP])
|
||||
]
|
||||
|
||||
##~~ Helpers
|
||||
|
||||
def _run_checks(self, check_type, *args, **kwargs):
|
||||
@@ -121,7 +133,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
|
||||
# execute method
|
||||
try:
|
||||
method(*args, **kwargs)
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("There was an error running method {} on check {!r}".format(check_type, check))
|
||||
continue
|
||||
|
||||
@@ -185,6 +197,7 @@ __plugin_hooks__ = {
|
||||
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received,
|
||||
"octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received,
|
||||
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received,
|
||||
"octoprint.events.register_custom_events": register_custom_events
|
||||
"octoprint.events.register_custom_events": register_custom_events,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
|
||||
@@ -4,11 +4,12 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.printerState = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self.warnings = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.isUser()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PRINTER_SAFETY_CHECK_DISPLAY)) {
|
||||
self.warnings([]);
|
||||
return;
|
||||
}
|
||||
@@ -32,11 +33,7 @@ $(function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
@@ -52,7 +49,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PrinterSafetyCheckViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel"],
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel", "accessViewModel"],
|
||||
elements: ["#sidebar_plugin_printer_safety_check_wrapper"]
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import io
|
||||
import copy
|
||||
import flask
|
||||
import os
|
||||
@@ -24,8 +25,10 @@ from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import VERSION, REVISION, BRANCH
|
||||
from octoprint.access import USER_GROUP, ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util import dict_merge, to_unicode
|
||||
from octoprint.util.version import get_comparable_version, get_python_version_string
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
@@ -40,7 +43,6 @@ MINIMUM_PIP = "9.0.3"
|
||||
|
||||
##~~ Plugin
|
||||
|
||||
|
||||
class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
@@ -92,8 +94,27 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks)
|
||||
self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks)
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="CHECK",
|
||||
name="Check",
|
||||
description=gettext("Allows to check for software updates"),
|
||||
roles=["check"],
|
||||
default_groups=[USER_GROUP]),
|
||||
dict(key="UPDATE",
|
||||
name="Update",
|
||||
description=gettext("Allows to perform software updates"),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["update"],
|
||||
dangerous=True)
|
||||
]
|
||||
|
||||
def on_startup(self, host, port):
|
||||
console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024)
|
||||
console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"),
|
||||
maxBytes=2*1024*1024,
|
||||
encoding="utf-8")
|
||||
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
console_logging_handler.setLevel(logging.DEBUG)
|
||||
|
||||
@@ -104,6 +125,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
|
||||
if helpers and "get_throttled" in helpers:
|
||||
self._get_throttled = helpers["get_throttled"]
|
||||
if self._settings.get_boolean(["ignore_throttled"]):
|
||||
self._logger.warn("!!! THROTTLE STATE IGNORED !!! You have configured the Software Update plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.")
|
||||
|
||||
def on_after_startup(self):
|
||||
self._check_environment()
|
||||
@@ -116,16 +139,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._configured_checks = self._settings.get(["checks"], merged=True)
|
||||
|
||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||
check_providers = self._settings.get(["check_providers"], merged=True)
|
||||
if not isinstance(check_providers, dict):
|
||||
check_providers = dict()
|
||||
check_providers = dict()
|
||||
|
||||
effective_configs = dict()
|
||||
|
||||
for name, hook in update_check_hooks.items():
|
||||
try:
|
||||
hook_checks = hook()
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving update information "
|
||||
"from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
@@ -133,9 +154,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
for key, default_config in hook_checks.items():
|
||||
if key in effective_configs or key == "octoprint":
|
||||
if key == name:
|
||||
self._logger.warn("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook")))
|
||||
self._logger.warning("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook")))
|
||||
else:
|
||||
self._logger.warn("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key))
|
||||
self._logger.warning("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key))
|
||||
continue
|
||||
|
||||
check_providers[key] = name
|
||||
@@ -160,22 +181,19 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if effective_config:
|
||||
effective_configs[key] = effective_config
|
||||
else:
|
||||
self._logger.warn("Update for {} is empty or None, ignoring it".format(key))
|
||||
self._logger.warning("Update for {} is empty or None, ignoring it".format(key))
|
||||
|
||||
# finally set all our internal representations to our processed results
|
||||
for key, config in effective_configs.items():
|
||||
self._configured_checks[key] = config
|
||||
|
||||
self._settings.set(["check_providers"], check_providers)
|
||||
self._settings.save()
|
||||
|
||||
# we only want to process checks that came from plugins for
|
||||
# which the plugins are still installed and enabled
|
||||
config_checks = self._settings.get(["checks"])
|
||||
plugin_and_not_enabled = lambda k: k in check_providers and \
|
||||
not check_providers[k] in self._plugin_manager.enabled_plugins
|
||||
obsolete_plugin_checks = filter(plugin_and_not_enabled,
|
||||
config_checks.keys())
|
||||
obsolete_plugin_checks = list(filter(plugin_and_not_enabled,
|
||||
config_checks.keys()))
|
||||
for key in obsolete_plugin_checks:
|
||||
self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key]))
|
||||
del self._configured_checks[key]
|
||||
@@ -205,10 +223,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
import yaml
|
||||
try:
|
||||
with open(self._version_cache_path) as f:
|
||||
with io.open(self._version_cache_path, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
timestamp = os.stat(self._version_cache_path).st_mtime
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading version cache from disk")
|
||||
else:
|
||||
try:
|
||||
@@ -232,7 +250,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = timestamp
|
||||
self._logger.info("Loaded version cache from disk")
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error parsing in version cache data")
|
||||
|
||||
def _save_version_cache(self):
|
||||
@@ -243,8 +261,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint_version = get_versions()["version"]
|
||||
self._version_cache["__version"] = octoprint_version
|
||||
|
||||
with atomic_write(self._version_cache_path, max_permissions=0o666) as file_obj:
|
||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
with atomic_write(self._version_cache_path, mode='wt', max_permissions=0o666) as file_obj:
|
||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=2, allow_unicode=True)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = time.time()
|
||||
@@ -277,11 +295,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
},
|
||||
},
|
||||
"pip_command": None,
|
||||
"check_providers": {},
|
||||
|
||||
"cache_ttl": 24 * 60,
|
||||
|
||||
"notify_users": True
|
||||
"notify_users": True,
|
||||
|
||||
"ignore_throttled": False
|
||||
}
|
||||
|
||||
def on_settings_load(self):
|
||||
@@ -289,12 +308,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if "checks" in data:
|
||||
del data["checks"]
|
||||
|
||||
if "check_providers" in data:
|
||||
del data["check_providers"]
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
data["octoprint_checkout_folder"] = self._get_octoprint_checkout_folder(checks=checks)
|
||||
data["octoprint_tracked_branch"] = self._get_octoprint_tracked_branch(checks=checks)
|
||||
data["octoprint_pip_target"] = self._get_octoprint_pip_target(checks=checks)
|
||||
data["octoprint_type"] = checks["octoprint"].get("type", None)
|
||||
|
||||
try:
|
||||
@@ -325,6 +343,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
data["octoprint_type"] = None
|
||||
data["octoprint_branch_mappings"] = []
|
||||
|
||||
data["pip_enable_check"] = "pip" in checks
|
||||
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -350,6 +370,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
)
|
||||
|
||||
updated_octoprint_check_config = False
|
||||
update_pip_check_config = False
|
||||
|
||||
if "octoprint_checkout_folder" in data:
|
||||
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
|
||||
@@ -365,11 +386,24 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
elif octoprint_type == "github_commit":
|
||||
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_tracked_branch" in data:
|
||||
self._settings.set(["checks", "octoprint", "branch"], data["octoprint_tracked_branch"], defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "octoprint_pip_target" in data:
|
||||
self._settings.set(["checks", "octoprint", "pip"], data["octoprint_pip_target"], 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]:
|
||||
@@ -381,6 +415,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "pip_enable_check" in data:
|
||||
checks = self._settings.get(["checks"], merged=True)
|
||||
if data["pip_enable_check"] in octoprint.settings.valid_boolean_trues:
|
||||
checks["pip"] = dict(type="pypi_release",
|
||||
package="pip",
|
||||
pip="pip=={target_version}")
|
||||
elif "pip" in checks:
|
||||
del checks["pip"]
|
||||
self._settings.set(["checks"], checks, force=True)
|
||||
self._settings.save()
|
||||
update_pip_check_config = True
|
||||
|
||||
if updated_octoprint_check_config:
|
||||
self._refresh_configured_checks = True
|
||||
try:
|
||||
@@ -389,8 +435,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
pass
|
||||
self._version_cache_dirty = True
|
||||
|
||||
if update_pip_check_config:
|
||||
self._refresh_configured_checks = True
|
||||
try:
|
||||
del self._version_cache["pip"]
|
||||
except KeyError:
|
||||
pass
|
||||
self._version_cache_dirty = True
|
||||
|
||||
def get_settings_version(self):
|
||||
return 6
|
||||
return 7
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
@@ -475,6 +529,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
||||
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
||||
|
||||
if current is None or current < 7:
|
||||
# remove check_providers again
|
||||
self._settings.set(["check_providers"], None, defaults=dict(check_providers=dict()))
|
||||
|
||||
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
|
||||
if not data:
|
||||
# nothing to do
|
||||
@@ -507,10 +565,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
#~~ BluePrint API
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
|
||||
@restricted_access
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403)
|
||||
def check_for_update(self):
|
||||
if "check" in flask.request.values:
|
||||
check_targets = map(lambda x: x.strip(), flask.request.values["check"].split(","))
|
||||
check_targets = list(map(lambda x: x.strip(), flask.request.values["check"].split(",")))
|
||||
else:
|
||||
check_targets = None
|
||||
|
||||
@@ -538,28 +597,30 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if targets is None:
|
||||
targets = checks.keys()
|
||||
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
def hash_update(value):
|
||||
value = value.encode('utf-8')
|
||||
hash.update(value)
|
||||
|
||||
targets = sorted(targets)
|
||||
for target in targets:
|
||||
current_hash = self._get_check_hash(checks.get(target, dict()))
|
||||
if target in self._version_cache and not force:
|
||||
data = self._version_cache[target]
|
||||
hash.update(current_hash)
|
||||
hash.update(str(data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]))
|
||||
hash.update(repr(data["information"]))
|
||||
hash.update(str(data["available"]))
|
||||
hash.update(str(data["possible"]))
|
||||
hash.update(str(data.get("online", None)))
|
||||
hash_update(current_hash)
|
||||
hash_update(str(data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]))
|
||||
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(",".join(targets))
|
||||
|
||||
hash.update(str(self._environment_supported))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
hash.update(str(self._connectivity_checker.online))
|
||||
hash.update(str(self._update_in_progress))
|
||||
hash.update(self.DATA_FORMAT_VERSION)
|
||||
hash_update(str(self._environment_supported))
|
||||
hash_update(str(self._version_cache_timestamp))
|
||||
hash_update(str(self._connectivity_checker.online))
|
||||
hash_update(str(self._update_in_progress))
|
||||
hash_update(self.DATA_FORMAT_VERSION)
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -571,11 +632,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
|
||||
def perform_update(self):
|
||||
throttled = self._get_throttled()
|
||||
if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False):
|
||||
if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]):
|
||||
# currently throttled, we refuse to run
|
||||
return flask.make_response("System is currently throttled, refusing to update "
|
||||
"anything due to possible stability issues", 409)
|
||||
@@ -590,10 +651,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if not "application/json" in flask.request.headers["Content-Type"]:
|
||||
return flask.make_response("Expected content-type JSON", 400)
|
||||
|
||||
json_data = flask.request.json
|
||||
json_data = flask.request.get_json(silent=True)
|
||||
if json_data is None:
|
||||
return flask.make_response("Invalid JSON", 400)
|
||||
|
||||
if "targets" in json_data:
|
||||
targets = map(lambda x: x.strip(), json_data["targets"])
|
||||
targets = list(map(lambda x: x.strip(), json_data["targets"]))
|
||||
else:
|
||||
targets = None
|
||||
|
||||
@@ -654,7 +717,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if check_targets is None:
|
||||
check_targets = checks.keys()
|
||||
check_targets = list(checks.keys())
|
||||
|
||||
update_available = False
|
||||
update_possible = False
|
||||
@@ -681,11 +744,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
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,
|
||||
self._logger.warning("Unknown update check type for target {}: {}".format(target,
|
||||
check.get("type",
|
||||
"<n/a>")))
|
||||
continue
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Could not check {} for updates".format(target))
|
||||
continue
|
||||
|
||||
@@ -765,7 +828,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
return "{" + ", ".join(lines) + "}"
|
||||
|
||||
hash = hashlib.md5()
|
||||
hash.update(dict_to_sorted_repr(check))
|
||||
def hash_update(value):
|
||||
value = value.encode('utf-8')
|
||||
hash.update(value)
|
||||
hash_update(dict_to_sorted_repr(check))
|
||||
return hash.hexdigest()
|
||||
|
||||
def _get_current_version(self, target, check, force=False, online=None):
|
||||
@@ -797,14 +863,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
update_possible = False
|
||||
information["needs_online"] = True
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown check type %s for %s" % (check["type"], target))
|
||||
self._logger.warning("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)
|
||||
self._logger.warning("Could not check %s for updates due to a network error" % target)
|
||||
update_possible = False
|
||||
error = "network"
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Could not check %s for updates" % target)
|
||||
update_possible = False
|
||||
error = "unknown"
|
||||
@@ -812,7 +878,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
try:
|
||||
updater = self._get_updater(target, check)
|
||||
update_possible = updater.can_perform_update(target, check, online=online)
|
||||
except:
|
||||
except Exception:
|
||||
update_possible = False
|
||||
|
||||
self._version_cache[target] = dict(timestamp=time.time(),
|
||||
@@ -845,7 +911,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
populated_checks[target] = self._populated_check(target, check)
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.debug("Ignoring unknown check type for target {}".format(target))
|
||||
except:
|
||||
except Exception:
|
||||
self._logger.exception("Error while populating check prior to update for target {}".format(target))
|
||||
|
||||
if targets is None:
|
||||
@@ -855,6 +921,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
to_be_updated.remove("octoprint")
|
||||
tmp = ["octoprint"] + to_be_updated
|
||||
to_be_updated = tmp
|
||||
if "pip" in to_be_updated:
|
||||
to_be_updated.remove("pip")
|
||||
tmp = ["pip"] + to_be_updated
|
||||
to_be_updated = tmp
|
||||
|
||||
updater_thread = threading.Thread(target=self._update_worker, args=(populated_checks, to_be_updated, force))
|
||||
updater_thread.daemon = False
|
||||
@@ -949,7 +1019,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
return False, None
|
||||
|
||||
if not update_possible:
|
||||
self._logger.warn("Cannot perform update for %s, update type is not fully configured" % target)
|
||||
self._logger.warning("Cannot perform update for %s, update type is not fully configured" % target)
|
||||
return False, None
|
||||
|
||||
# determine the target version to update to
|
||||
@@ -990,12 +1060,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
trigger_event(True)
|
||||
|
||||
except exceptions.UnknownUpdateType:
|
||||
self._logger.warn("Update of %s can not be performed, unknown update type" % target)
|
||||
self._logger.warning("Update of %s can not be performed, unknown update type" % target)
|
||||
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._logger.warning("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:
|
||||
@@ -1042,30 +1112,33 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
util.execute(restart_command, evaluate_returncode=False, do_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))
|
||||
self._logger.warn("Restart stderr:\n{}".format(e.stderr))
|
||||
self._logger.warning("Restart stdout:\n{}".format(e.stdout))
|
||||
self._logger.warning("Restart stderr:\n{}".format(e.stderr))
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
from flask_babel import gettext
|
||||
|
||||
if not "type" in check:
|
||||
raise exceptions.UnknownCheckType()
|
||||
|
||||
result = dict(check)
|
||||
|
||||
if target == "octoprint":
|
||||
from flask_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 = check.get("displayName")
|
||||
if displayName is None:
|
||||
# displayName missing or set to None
|
||||
result["displayName"] = to_unicode(gettext("OctoPrint"), errors="replace")
|
||||
displayName = gettext("OctoPrint")
|
||||
result["displayName"] = to_unicode(displayName, errors="replace")
|
||||
|
||||
result["displayVersion"] = to_unicode(check.get("displayVersion"), errors="replace")
|
||||
if result["displayVersion"] is None:
|
||||
displayVersion = check.get("displayVersion")
|
||||
if displayVersion is None:
|
||||
# displayVersion missing or set to None
|
||||
result["displayVersion"] = u"{octoprint_version}"
|
||||
displayVersion = "{octoprint_version}"
|
||||
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
|
||||
|
||||
stable_branch = "master"
|
||||
release_branches = []
|
||||
@@ -1106,11 +1179,27 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# we force an exact version & python unequality check, to be able to downgrade
|
||||
result["force_exact_version"] = True
|
||||
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"
|
||||
|
||||
elif target == "pip":
|
||||
import pkg_resources
|
||||
|
||||
displayName = check.get("displayName")
|
||||
if displayName is None:
|
||||
# displayName missing or set to None
|
||||
displayName = gettext("pip")
|
||||
result["displayName"] = to_unicode(displayName, errors="replace")
|
||||
|
||||
displayVersion = check.get("displayVersion")
|
||||
if displayVersion is None:
|
||||
# displayVersion missing or set to None
|
||||
distribution = pkg_resources.get_distribution("pip")
|
||||
if distribution:
|
||||
displayVersion = distribution.version
|
||||
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
|
||||
|
||||
else:
|
||||
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
|
||||
if result["displayName"] is None:
|
||||
@@ -1120,7 +1209,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
result["displayVersion"] = to_unicode(check.get("displayVersion", check.get("current")), errors="replace")
|
||||
if result["displayVersion"] is None:
|
||||
# displayVersion AND current missing or None
|
||||
result["displayVersion"] = u"unknown"
|
||||
result["displayVersion"] = "unknown"
|
||||
|
||||
if check["type"] in self.COMMIT_TRACKING_TYPES:
|
||||
result["current"] = check.get("current", None)
|
||||
@@ -1135,11 +1224,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
def _log(self, lines, prefix=None, stream=None, strip=True):
|
||||
if strip:
|
||||
lines = map(lambda x: x.strip(), lines)
|
||||
lines = list(map(lambda x: x.strip(), lines))
|
||||
|
||||
self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines]))
|
||||
for line in lines:
|
||||
self._console_logger.debug(u"{} {}".format(prefix, line))
|
||||
self._console_logger.debug("{} {}".format(prefix, line))
|
||||
|
||||
def _send_client_message(self, message_type, data=None):
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data))
|
||||
@@ -1198,7 +1287,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
python_updater=updaters.python_updater,
|
||||
sleep_a_bit=updaters.sleep_a_bit)
|
||||
|
||||
method = self._get_update_method(target, check, valid_methods=mapping.keys())
|
||||
method = self._get_update_method(target, check, valid_methods=list(mapping.keys()))
|
||||
return mapping[method]
|
||||
|
||||
def _get_octoprint_checkout_folder(self, checks=None):
|
||||
@@ -1215,6 +1304,24 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
return None
|
||||
|
||||
def _get_octoprint_tracked_branch(self, checks=None):
|
||||
if checks is None:
|
||||
checks = self._get_configured_checks()
|
||||
|
||||
if not "octoprint" in checks:
|
||||
return None
|
||||
|
||||
return checks["octoprint"].get("branch")
|
||||
|
||||
def _get_octoprint_pip_target(self, checks=None):
|
||||
if checks is None:
|
||||
checks = self._get_configured_checks()
|
||||
|
||||
if not "octoprint" in checks:
|
||||
return None
|
||||
|
||||
return checks["octoprint"].get("pip")
|
||||
|
||||
|
||||
def _register_custom_events(*args, **kwargs):
|
||||
return ["update_succeeded", "update_failed"]
|
||||
@@ -1243,7 +1350,6 @@ def __plugin_load__():
|
||||
global __plugin_hooks__
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.cli.commands": cli.commands,
|
||||
"octoprint.events.register_custom_events": _register_custom_events
|
||||
"octoprint.events.register_custom_events": _register_custom_events,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
import click
|
||||
click.disable_unicode_literals_warning = True
|
||||
import sys
|
||||
import requests.exceptions
|
||||
from octoprint.cli.client import create_client, client_options
|
||||
|
||||
Loaded 100 of 341 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user