Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8409fdaa48 | ||
|
|
f29e736427 | ||
|
|
a70a45f062 | ||
|
|
61b0845f19 | ||
|
|
b9665a8af4 | ||
|
|
15522a98b0 | ||
|
|
c4258c5bb0 | ||
|
|
58799888b7 | ||
|
|
fb6d57963b | ||
|
|
03f228c0ef | ||
|
|
93ae368f58 | ||
|
|
378752e155 | ||
|
|
bec307900d | ||
|
|
0eac10d5a6 | ||
|
|
2a42f02aec | ||
|
|
7c48cfd0f7 | ||
|
|
bba796d551 | ||
|
|
a855f3e62c | ||
|
|
5079e7e891 | ||
|
|
ddc948fa94 | ||
|
|
f88f2b25ea | ||
|
|
ea59dab7ab | ||
|
|
f0914c2214 | ||
|
|
b3e76c3ecc | ||
|
|
a4d5acb0b8 | ||
|
|
79b66f17b6 | ||
|
|
bcb6c7a1d4 | ||
|
|
36198c684f | ||
|
|
a3a60c5967 | ||
|
|
6df3cb5c12 | ||
|
|
0611329a6d | ||
|
|
2f90fca5ce | ||
|
|
e4e97190da | ||
|
|
9c748a85b4 | ||
|
|
78c2199d89 | ||
|
|
0e67906d1e | ||
|
|
4c602cba2e | ||
|
|
89255e2ec9 | ||
|
|
372b3662e9 | ||
|
|
e007dbaf4c | ||
|
|
f67f9b9399 | ||
|
|
c6c5328418 | ||
|
|
accbfc2b45 | ||
|
|
9976f2b7a3 | ||
|
|
f249563b2c | ||
|
|
09e023917c | ||
|
|
799b86b287 | ||
|
|
ea1bcf8e5d | ||
|
|
ee93e25ffd | ||
|
|
d25f664be3 | ||
|
|
3bffe4f7cb | ||
|
|
f140dd9d44 | ||
|
|
d44747b39a | ||
|
|
f2da9d8d7d | ||
|
|
5483ef7cd4 | ||
|
|
85d212ba97 | ||
|
|
44af09580a | ||
|
|
530fca95e4 | ||
|
|
59ae7e39f2 | ||
|
|
72167d14d2 | ||
|
|
2c6568acd1 | ||
|
|
e27c216a05 | ||
|
|
7b4c148dd7 | ||
|
|
a924520dd6 | ||
|
|
e88eb6dd85 | ||
|
|
59dfa994bd | ||
|
|
6959ce4d38 | ||
|
|
08bc0082cf | ||
|
|
6069d74a54 | ||
|
|
68ee7030f1 | ||
|
|
81342acccc | ||
|
|
e029f33901 | ||
|
|
7bd8cff137 | ||
|
|
055dcfa0e1 | ||
|
|
8acf417383 | ||
|
|
b50e1aee8a | ||
|
|
c714bce17e | ||
|
|
a9a8e48489 | ||
|
|
9dec840818 | ||
|
|
9af125ca6d | ||
|
|
1f4fabe6ef | ||
|
|
121f36704d | ||
|
|
85ff545c07 | ||
|
|
3662c84de5 | ||
|
|
79558fdfbf | ||
|
|
11040f272a | ||
|
|
fa2716c65c | ||
|
|
768b06e35a | ||
|
|
0820c23aea | ||
|
|
361fbaa366 | ||
|
|
a91359f2af | ||
|
|
4bfabf82ae | ||
|
|
c90f556fe9 | ||
|
|
352b190a72 | ||
|
|
e9b0bd9e65 | ||
|
|
c8ea808d93 | ||
|
|
d40c3e6241 | ||
|
|
e94f789b72 | ||
|
|
9ff44c49a6 | ||
|
|
c7b933ba00 | ||
|
|
6765b25803 | ||
|
|
59b60f5dad | ||
|
|
2822992843 | ||
|
|
1b82aa859f | ||
|
|
12be637f85 | ||
|
|
3bd9d11fc3 | ||
|
|
e864d6b03e | ||
|
|
547db7c1f5 | ||
|
|
d6516e4a4c | ||
|
|
2387b4a771 | ||
|
|
b03d43156d | ||
|
|
07423712a6 | ||
|
|
2edd2ba887 | ||
|
|
fcef3a1bbd | ||
|
|
d1d24dba9a | ||
|
|
81735d07c9 | ||
|
|
2c640ff8b8 | ||
|
|
0331a25ae3 | ||
|
|
326422013a | ||
|
|
9b4da62e69 | ||
|
|
b46a66caa8 | ||
|
|
6711813fef | ||
|
|
7726e5c04e | ||
|
|
495d99fbe9 | ||
|
|
a35b7cddf2 | ||
|
|
f2af5e8b86 | ||
|
|
289c3a4d0f | ||
|
|
4cb67fe72c | ||
|
|
b79fc94a4e | ||
|
|
fca626a3d6 | ||
|
|
f5a04973c4 | ||
|
|
1c9ff91bae | ||
|
|
e1e521300b | ||
|
|
c1e8bc717a | ||
|
|
22d7392769 | ||
|
|
904e7d2ecd | ||
|
|
b3173386ae | ||
|
|
1e3b8dfb2c | ||
|
|
94d172ab67 | ||
|
|
7dac6ca433 | ||
|
|
9aeeb5fecc | ||
|
|
52f65b469d | ||
|
|
0843c0fbc7 | ||
|
|
11607fbc73 | ||
|
|
1521b76090 | ||
|
|
a33a7b4d67 | ||
|
|
c00fdbf73b | ||
|
|
af32858549 | ||
|
|
d1104ddbae | ||
|
|
e2519abbbe | ||
|
|
967b3bbff8 | ||
|
|
9721aec32a | ||
|
|
68952c20bd | ||
|
|
03e328fd13 | ||
|
|
9775d99feb | ||
|
|
bfcff9a1cd | ||
|
|
5ca286f4e3 | ||
|
|
7dae700215 | ||
|
|
58806a3d00 | ||
|
|
72cc1afb45 | ||
|
|
323131cbc5 | ||
|
|
f389773036 | ||
|
|
0a04043922 | ||
|
|
84fa3b6073 | ||
|
|
d6576306b0 | ||
|
|
8970fb42b1 | ||
|
|
55e8cc1118 | ||
|
|
43e2f79575 | ||
|
|
132e2cb244 | ||
|
|
de6d1afdd6 | ||
|
|
0a1cc68a6b | ||
|
|
f1309dad1d | ||
|
|
b353c4eee2 | ||
|
|
34c30ed73f | ||
|
|
c28faa8032 | ||
|
|
8da5bb2d42 | ||
|
|
54c885f1ad | ||
|
|
65fe048ade | ||
|
|
7efcf00baf | ||
|
|
a3254466f7 | ||
|
|
f8dc504773 | ||
|
|
3574c2ddf9 | ||
|
|
1dc0f1fb31 | ||
|
|
30ddbfd324 | ||
|
|
5c522d86ca | ||
|
|
f785c8180b | ||
|
|
18e7d2b72a | ||
|
|
410c3ee5f6 | ||
|
|
48825fd4c2 | ||
|
|
ff9c83ea25 | ||
|
|
2c18a40dcb | ||
|
|
0b6dd7e76e | ||
|
|
d68c7bfc67 | ||
|
|
c879ad27f4 | ||
|
|
d1914824c6 | ||
|
|
79196eeaf7 | ||
|
|
6491db730d | ||
|
|
bd07cda205 | ||
|
|
9c7ca0ab7a | ||
|
|
c4da5d6764 | ||
|
|
47187c233d | ||
|
|
982ed793d9 | ||
|
|
718306073e | ||
|
|
df6e94f7a3 | ||
|
|
1a2739c640 | ||
|
|
9d318a4031 | ||
|
|
292d608b97 | ||
|
|
2d7cb40633 | ||
|
|
ce9315850f | ||
|
|
b8dbc627cb | ||
|
|
73df8c2407 | ||
|
|
55ec8b1809 | ||
|
|
33eba705bf | ||
|
|
9ec3a6ae7a | ||
|
|
ec2ba63425 | ||
|
|
6097222b7b | ||
|
|
40396847e3 | ||
|
|
a296574c70 | ||
|
|
547962f4bc | ||
|
|
1d2ceefb72 | ||
|
|
3d4422021e | ||
|
|
3b5c11a2bb | ||
|
|
4908d94c97 | ||
|
|
17a7e508c3 | ||
|
|
0069c94d35 | ||
|
|
99e7824913 | ||
|
|
ceade46dd7 | ||
|
|
bc66d29d02 | ||
|
|
9ea1074b03 | ||
|
|
6e069211cc | ||
|
|
8d3befb01f | ||
|
|
42a6cab92e | ||
|
|
083e424529 | ||
|
|
d5eefcd1a5 | ||
|
|
c1670d03c8 | ||
|
|
b2637eb06a | ||
|
|
47179f2956 | ||
|
|
d64b8512ab | ||
|
|
602ec5c495 | ||
|
|
a63ee9355e | ||
|
|
e44ae7a024 | ||
|
|
76ad332287 | ||
|
|
93ab7bb089 | ||
|
|
b4e7e73e29 | ||
|
|
92ad53a9ec | ||
|
|
21c9c51858 | ||
|
|
38a321e175 | ||
|
|
32050c31ae | ||
|
|
f020fc1bc6 | ||
|
|
a1e8694073 | ||
|
|
e748b52098 | ||
|
|
8668c6200a | ||
|
|
e01f391b30 | ||
|
|
92618362e1 | ||
|
|
d071684d41 | ||
|
|
7d0bd6a339 | ||
|
|
1b5a654a2d | ||
|
|
f0ee7f343e | ||
|
|
3e16f0901a | ||
|
|
8866ed716d | ||
|
|
0f157d3747 | ||
|
|
fdb4e75241 | ||
|
|
4dbb24ecd7 | ||
|
|
a15e2de251 | ||
|
|
c652bed871 | ||
|
|
253a38c32d | ||
|
|
e08becbb4c | ||
|
|
09a043b393 | ||
|
|
0c4f4383e3 | ||
|
|
45aa26f13e | ||
|
|
4a64bc6023 | ||
|
|
8e6773d19f | ||
|
|
dfcddea581 | ||
|
|
ff59e275bf | ||
|
|
0f8f1ec8e0 | ||
|
|
0e302d440f | ||
|
|
980616519d | ||
|
|
434751634f | ||
|
|
c35708a422 | ||
|
|
64464a38ce | ||
|
|
0e482151fd | ||
|
|
c5bf58e1cc | ||
|
|
38b7be0142 | ||
|
|
28a515ba6a | ||
|
|
38868303da | ||
|
|
fe65f18f78 | ||
|
|
e1e302f93d | ||
|
|
1cea388481 | ||
|
|
14a3d903d7 | ||
|
|
34d6a6f8ce | ||
|
|
6a03532ea7 | ||
|
|
649bfdbe37 | ||
|
|
8ce2290d63 | ||
|
|
b1413abfff | ||
|
|
772914f38c | ||
|
|
c6b4eee437 | ||
|
|
e67f72ce3d | ||
|
|
de6da3f360 | ||
|
|
b744c341eb | ||
|
|
697af69e97 | ||
|
|
601451a3f1 | ||
|
|
81d523b73d | ||
|
|
deacd9c188 | ||
|
|
6e0024149e | ||
|
|
dd3b318327 | ||
|
|
069e83c63c | ||
|
|
0cf345f29b | ||
|
|
0fda153d60 | ||
|
|
61ac8430d6 | ||
|
|
6b4dfcb960 | ||
|
|
61431c0df3 | ||
|
|
cc0b63cbb9 | ||
|
|
020403dc54 | ||
|
|
21a82bbdb6 | ||
|
|
727fd12939 | ||
|
|
100fe5f290 | ||
|
|
1acf69cb6d | ||
|
|
3815c340a8 | ||
|
|
c36a378b60 | ||
|
|
9a7ebde76b | ||
|
|
c23bafd788 | ||
|
|
1aea92a5f1 | ||
|
|
fb38c396e8 | ||
|
|
904b3c6cf5 | ||
|
|
7f2b79bcd5 | ||
|
|
dd692d6f30 | ||
|
|
5d021d76a0 | ||
|
|
2db230549e | ||
|
|
01484b630a | ||
|
|
d8088887e1 | ||
|
|
379411cea7 | ||
|
|
5e953c12a1 | ||
|
|
bd58138acf | ||
|
|
44b4c6cc40 | ||
|
|
f3f1061f9d | ||
|
|
68410cb3d7 | ||
|
|
db009e3ba2 | ||
|
|
09d3c44161 | ||
|
|
c2814651f9 | ||
|
|
eb46815789 | ||
|
|
449fa0c7ec | ||
|
|
0489dfeaee | ||
|
|
a9b395dac8 | ||
|
|
44a40b8297 | ||
|
|
49728f18c6 | ||
|
|
f6ec0bca6e | ||
|
|
6a069de240 | ||
|
|
2287c65784 | ||
|
|
3b26a2f7d2 | ||
|
|
18ffdcff6b | ||
|
|
faab946aeb | ||
|
|
a48e069aa6 | ||
|
|
d4d5bed514 | ||
|
|
97f84f120c | ||
|
|
cdc69ea93c | ||
|
|
467dd344cf | ||
|
|
6b9c9f47da | ||
|
|
b7f17531d2 | ||
|
|
987379d6e7 | ||
|
|
62b1d91901 | ||
|
|
7cb5013b08 | ||
|
|
06a3baa588 | ||
|
|
07934d26eb | ||
|
|
3ae97a3e13 | ||
|
|
5f22e68985 | ||
|
|
df1dc17c51 | ||
|
|
71aa405b26 | ||
|
|
2d2986922d | ||
|
|
7b5dbef166 | ||
|
|
da61a49bd8 | ||
|
|
002802bb20 | ||
|
|
45b59494ca | ||
|
|
83530ec7b9 | ||
|
|
918b70185e | ||
|
|
6aa89b77dc | ||
|
|
1679b45cd6 | ||
|
|
4728a1a5a9 | ||
|
|
c35a387520 | ||
|
|
d7aae66886 | ||
|
|
67ab9d577a | ||
|
|
10d045d743 | ||
|
|
44818993ff | ||
|
|
970b9c3384 | ||
|
|
89f94be96a | ||
|
|
52cfd93301 | ||
|
|
2a8d103dc6 | ||
|
|
d452051c0a | ||
|
|
99b32fc6c3 | ||
|
|
4e9437114b | ||
|
|
52c7321c78 | ||
|
|
ef94646083 | ||
|
|
37f3396be3 | ||
|
|
f8f461b804 | ||
|
|
5396daa7f6 | ||
|
|
bb51dc23fc | ||
|
|
2733838574 | ||
|
|
a23d92158b | ||
|
|
99225244f1 | ||
|
|
e30f1b9f82 | ||
|
|
054bbead72 | ||
|
|
30294e9009 | ||
|
|
bf5bc14c87 | ||
|
|
f6dd13af7a | ||
|
|
5760b4b264 | ||
|
|
49b995b234 | ||
|
|
8cf5ca9589 | ||
|
|
ae36a3905a | ||
|
|
bfd847f0a6 | ||
|
|
ef81702219 | ||
|
|
7cbe6244ae | ||
|
|
112a8b9c8b | ||
|
|
98b692d845 | ||
|
|
f4f7c87640 | ||
|
|
5af5cbbb37 | ||
|
|
a657ebd528 | ||
|
|
e628aedbc1 | ||
|
|
38fce1665b | ||
|
|
f51a98768c | ||
|
|
4d04c323f6 | ||
|
|
94116bfd53 | ||
|
|
a05761e63f | ||
|
|
89469d38ae | ||
|
|
bd2616e888 | ||
|
|
02e996436d | ||
|
|
a3f2e0b56c | ||
|
|
c4295d6a81 | ||
|
|
d60cab1962 | ||
|
|
b01e327f9d | ||
|
|
09af2813d0 | ||
|
|
2f69a84352 | ||
|
|
13260fa219 | ||
|
|
9a90093dda | ||
|
|
8292408c79 | ||
|
|
9165f83084 | ||
|
|
c2ef371089 | ||
|
|
fa9472d4aa | ||
|
|
037e92c447 | ||
|
|
170804d4df | ||
|
|
ac129a2576 | ||
|
|
db8d420860 | ||
|
|
7d7cbb1760 | ||
|
|
89979f1bee | ||
|
|
bd241e8e6c | ||
|
|
7939b0ae4d | ||
|
|
6b57ba2d7d | ||
|
|
2c5465f9a6 | ||
|
|
1565129cfb | ||
|
|
b8d4a58207 | ||
|
|
900f03dc8a | ||
|
|
0c4c4a9d18 | ||
|
|
ff4ed38329 | ||
|
|
5f78ab7b73 | ||
|
|
6556d555bd | ||
|
|
d318ff82b8 | ||
|
|
ff53a826f9 | ||
|
|
abb14dc17a | ||
|
|
a45c86eed1 | ||
|
|
c30380d423 | ||
|
|
d79e777911 | ||
|
|
335e635ec7 | ||
|
|
a5754a8552 | ||
|
|
a8c91ff6ba | ||
|
|
6285fd8010 | ||
|
|
92629468c0 | ||
|
|
56a1d4f966 | ||
|
|
799aedcaed | ||
|
|
de42ce73f7 | ||
|
|
962e09906e | ||
|
|
f607f55683 | ||
|
|
8e464f59ac | ||
|
|
91b524813c | ||
|
|
1b45047826 | ||
|
|
edd4d90b12 | ||
|
|
0a3ad8a880 | ||
|
|
82615791a2 | ||
|
|
4548be34f0 | ||
|
|
2b5af2c36a | ||
|
|
a939130748 | ||
|
|
b7e373c40f | ||
|
|
dae0264a58 | ||
|
|
b2e50e13d4 | ||
|
|
cb4404a833 | ||
|
|
38bb81cfe7 | ||
|
|
1667f9bd52 | ||
|
|
1ec61a9fe6 | ||
|
|
98c84b6bb9 | ||
|
|
76f48b3b13 | ||
|
|
8596ae5c4a | ||
|
|
c1482eaacd | ||
|
|
e23fe4a925 | ||
|
|
8939537fb5 | ||
|
|
2f08b90200 | ||
|
|
68ca2c5e51 | ||
|
|
343195477b | ||
|
|
4caf4ef09b | ||
|
|
0ba987e126 | ||
|
|
0325628693 | ||
|
|
e14c00f135 | ||
|
|
b0a4a49f99 | ||
|
|
5b4839369e | ||
|
|
1ff02b9f1c | ||
|
|
e2c1fa3d43 | ||
|
|
39a466e316 | ||
|
|
9e940eacc3 | ||
|
|
2e38f237de | ||
|
|
7f36ffdafd | ||
|
|
39b2da3230 | ||
|
|
c489829efb | ||
|
|
e30e129e2a | ||
|
|
32d5b25013 | ||
|
|
6227a0dfb9 | ||
|
|
e234c6146e | ||
|
|
c146731e5a | ||
|
|
5ee242be4a | ||
|
|
556878a774 | ||
|
|
00aa4876e9 | ||
|
|
e5e8581f9a | ||
|
|
95a9f84b39 | ||
|
|
371f1a818f | ||
|
|
4ed5f7ed28 | ||
|
|
4eb81aae9d | ||
|
|
dafa4c97ad | ||
|
|
0268cafa90 | ||
|
|
a5caac8d38 | ||
|
|
7ca9d56327 | ||
|
|
d9323b7172 | ||
|
|
8f6d67195d | ||
|
|
342d526a51 | ||
|
|
d7c5f57c98 | ||
|
|
d89ca38ee8 | ||
|
|
cb969be403 | ||
|
|
7cb649c303 | ||
|
|
6d7d365b27 | ||
|
|
8ad720e554 | ||
|
|
37190da2d6 | ||
|
|
2746139fa6 | ||
|
|
c9f10ae723 | ||
|
|
202006149c | ||
|
|
671973062e | ||
|
|
1d15c2a176 | ||
|
|
5e490ec7fd | ||
|
|
1889a40241 | ||
|
|
6d2be1743a | ||
|
|
e9e4adf09b | ||
|
|
535ad6eae6 | ||
|
|
c4167a82c5 | ||
|
|
087a9ece2c | ||
|
|
b77380a8ac | ||
|
|
169275b052 | ||
|
|
757dfcf5c7 | ||
|
|
8e39eac207 | ||
|
|
9e48b8ab65 | ||
|
|
36b07b2337 | ||
|
|
e57c46fb67 | ||
|
|
df8226b8c5 | ||
|
|
2f89082df2 | ||
|
|
e0943527d6 | ||
|
|
108db045ce | ||
|
|
025986794f | ||
|
|
ac2354907a | ||
|
|
7b5d2e3e0c | ||
|
|
efa556a812 | ||
|
|
7f9764c386 | ||
|
|
e95e546c08 | ||
|
|
b0e7df47a6 | ||
|
|
257fc0d1cd | ||
|
|
3fe2b611bc | ||
|
|
d6c63a5cb9 | ||
|
|
ad8205c386 | ||
|
|
6efd4dfd08 | ||
|
|
469bf844ee | ||
|
|
4f58c64881 | ||
|
|
b428faacc8 | ||
|
|
4e3adcc3f3 | ||
|
|
f88147003c | ||
|
|
bbbe85f737 | ||
|
|
fc97d0b424 | ||
|
|
b054ec47ad | ||
|
|
87e7a19fdd | ||
|
|
fed257b5d8 | ||
|
|
e53ae8cd56 | ||
|
|
a9f76dd1a3 | ||
|
|
6bc5b8a7a9 | ||
|
|
cb9bedb6a0 | ||
|
|
5ff790048d | ||
|
|
f32ea65b2c | ||
|
|
1f957e1ee2 | ||
|
|
32be5ca87c | ||
|
|
8876ab0ce5 | ||
|
|
ad8910354c | ||
|
|
e8d6a9b221 | ||
|
|
f3cfe2ba48 | ||
|
|
d2ecb0a28f | ||
|
|
134ee77e4a | ||
|
|
10f3f72b9c | ||
|
|
78b6d3a5e2 | ||
|
|
a920c4fe21 | ||
|
|
52468e7e1c | ||
|
|
9112a800c8 | ||
|
|
177d235b29 | ||
|
|
2de2dc7c31 | ||
|
|
8074a06d33 | ||
|
|
75c801d63f | ||
|
|
ed07764f09 | ||
|
|
a929100889 | ||
|
|
286376321c | ||
|
|
4a36a3eed2 | ||
|
|
8bf9b8650d | ||
|
|
d6da819cd6 | ||
|
|
2fbc81604a | ||
|
|
2ca63febee | ||
|
|
224674f27e | ||
|
|
2f1d71a98c | ||
|
|
7366110f07 | ||
|
|
e5eb72cbfb | ||
|
|
b0028cd3fb | ||
|
|
2343caea30 | ||
|
|
61d037f188 | ||
|
|
2a79d9183a | ||
|
|
5dbc88b6f2 | ||
|
|
83876806db | ||
|
|
5a5785be4a | ||
|
|
25cd4f8201 | ||
|
|
2d72a52338 | ||
|
|
b5a161594d | ||
|
|
a24363c4b0 | ||
|
|
524562527e | ||
|
|
26856d052f | ||
|
|
17f8817b78 | ||
|
|
4eb1d2bf80 | ||
|
|
62120affae | ||
|
|
66b501cfaa | ||
|
|
140bf9aa5a | ||
|
|
711ca457f2 | ||
|
|
07ae4ffe14 | ||
|
|
3800b21e69 | ||
|
|
196b152ec4 | ||
|
|
970810dc92 | ||
|
|
4fec14197b | ||
|
|
b354334a2e | ||
|
|
a934750504 | ||
|
|
9dc29689f4 | ||
|
|
8518b40b5f | ||
|
|
aabd624f88 | ||
|
|
6ae88ab8c6 | ||
|
|
6251031d6e | ||
|
|
249b3f442b | ||
|
|
ff6012bb00 | ||
|
|
a137946e3a | ||
|
|
909dd551d6 | ||
|
|
687b449207 | ||
|
|
efe552264c | ||
|
|
b7e788ec1b | ||
|
|
e964d2410c | ||
|
|
09284cd9b9 | ||
|
|
4963a4b849 | ||
|
|
46e425de88 | ||
|
|
376d38e0cf | ||
|
|
2e8f543aa3 | ||
|
|
d2dfd22a2c | ||
|
|
b51cb31b46 | ||
|
|
eea1050a18 | ||
|
|
a37165d7d9 | ||
|
|
b06f804e9e | ||
|
|
d64ca79f05 | ||
|
|
490ade5e17 | ||
|
|
573503e84d | ||
|
|
9e0e4bf7b6 | ||
|
|
452645d950 | ||
|
|
d2bb731bd7 | ||
|
|
40b5c272c4 | ||
|
|
31e4df44f9 | ||
|
|
cd3c8ebbe6 | ||
|
|
59a435a787 | ||
|
|
71cc312ccc | ||
|
|
8d1ae438e5 | ||
|
|
7ebcb47955 | ||
|
|
71e60183c5 | ||
|
|
9c055137eb | ||
|
|
eaa8933782 | ||
|
|
0d330e3c5a | ||
|
|
18ed113122 | ||
|
|
48e454856c | ||
|
|
917b86655f | ||
|
|
7a2225b332 | ||
|
|
20237a73ac | ||
|
|
4a3f894064 | ||
|
|
0c9098f7bf | ||
|
|
53a2e04501 | ||
|
|
c6f5f1a0f7 | ||
|
|
1cff2581db | ||
|
|
5cf02ac9ee | ||
|
|
9559f09ec7 | ||
|
|
542edbc3e6 | ||
|
|
f82d50b0f6 | ||
|
|
e224b0ac71 | ||
|
|
68f4ecefb0 | ||
|
|
d73d930e5f | ||
|
|
8c1262dd3f | ||
|
|
792fe328ef | ||
|
|
111a37e97e | ||
|
|
c2bb234c20 | ||
|
|
2dda3a0e32 | ||
|
|
e2394446b0 | ||
|
|
1befd0ecc1 | ||
|
|
7587f34c94 | ||
|
|
6b54a15ed9 | ||
|
|
d391f0c12b | ||
|
|
8460a4173d | ||
|
|
fe7149c715 | ||
|
|
443647e78e | ||
|
|
50bb0bcfd4 | ||
|
|
14661339ef | ||
|
|
8ca188e509 | ||
|
|
3da4877d50 | ||
|
|
382f10557e | ||
|
|
d9c6cca370 | ||
|
|
abf4f90f0e | ||
|
|
13ab34a5c8 | ||
|
|
2a67772f46 | ||
|
|
f69718b060 | ||
|
|
08c384ac68 | ||
|
|
00354f4a1e | ||
|
|
1a9b6c01a6 | ||
|
|
c4dc7d0f55 | ||
|
|
5a60af9d13 | ||
|
|
cb8ce62ec4 |
No files matched your search
@@ -11,6 +11,7 @@ trim_trailing_whitespace = true
|
||||
|
||||
[**.py]
|
||||
indent_style = tab
|
||||
indent_size = 4
|
||||
|
||||
[src/octoprint/static/js/app/**.js]
|
||||
indent_style = space
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [foosel]
|
||||
patreon: foosel
|
||||
custom: https://octoprint.org/support-octoprint/
|
||||
@@ -1,3 +1,9 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help improve OctoPrint
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
READ THE FOLLOWING FIRST:
|
||||
|
||||
@@ -12,7 +18,7 @@ plugins and not unofficial OctoPrint versions).
|
||||
|
||||
Do not seek support here ("I need help with ...", "I have a
|
||||
question ..."), that belongs on the community forum at
|
||||
discourse.octoprint.org, NOT here.
|
||||
community.octoprint.org, NOT here.
|
||||
|
||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||
reports fully fill out the bug reporting template (if you don't know
|
||||
@@ -39,9 +45,10 @@ don't know what you did to get it to happen in the first place.
|
||||
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||
-->
|
||||
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
<!--
|
||||
If you encountered a problem with specific files of any sorts, make sure
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
Please make sure to add [Request] to your issue's title. Thank you!
|
||||
-->
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -16,8 +16,9 @@ checklist:
|
||||
made sure your changes don't interfere with current development by
|
||||
talking it through with the maintainers, e.g. through a
|
||||
Brainstorming ticket
|
||||
* [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's
|
||||
a bug fix for an issue present in the current stable version (no PRs
|
||||
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
|
||||
new feature, or maintenance if it's a bug fix or improvement of
|
||||
existing functionality for the current stable version (no PRs
|
||||
against master or anything else please)
|
||||
* [ ] Your PR was opened from a custom branch on your repository
|
||||
(no PRs from your version of master, maintenance or devel please),
|
||||
|
||||
@@ -18,16 +18,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.9
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.12
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
maintenance 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
fix/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
improve/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.9rc4
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.12rc2
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
|
||||
regressionfix/.* 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
|
||||
staging/maintenance 1.3.12rc2 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
|
||||
regressionfix/.* 1.3.12rc2 2a42f02aecaedf2c55579984e0bc94e44402cc15 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
|
||||
@@ -91,6 +91,23 @@ date of first contribution):
|
||||
* [Ganey](https://github.com/ganey)
|
||||
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
||||
* [Andy Castille](https://github.com/klikini)
|
||||
* [Gaston Dombiak](https://github.com/gdombiak)
|
||||
* [Brad Fisher](https://github.com/bradcfisher)
|
||||
* [Aldo Hoeben](https://github.com/fieldofview)
|
||||
* [Henning Groß](https://github.com/hgross)
|
||||
* [Jubaleth](https://github.com/jubaleth)
|
||||
* [Daniel Joyce](https://github.com/DanielJoyce)
|
||||
* [Andy Qua](https://github.com/AndyQ)
|
||||
* [Fabio Santos](https://github.com/Fabi0San)
|
||||
* [Jack Wilsdon](https://github.com/jackwilsdon)
|
||||
* [Ryan Finnie](https://github.com/rfinnie)
|
||||
* [Timur Duehr](https://github.com/tduehr)
|
||||
* [Nicolai Nielsen](https://github.com/dovecode)
|
||||
* [Janne Mäntyharju](https://github.com/JanneMantyharju)
|
||||
* [Steven Spungin](https://github.com/flamenco)
|
||||
* [Piotr Usewicz](https://github.com/pusewicz)
|
||||
* [Aliaksei Pilko](https://github.com/aliaksei135)
|
||||
* [Ben Yarmis](https://github.com/byarmis)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
@@ -27,7 +27,7 @@ to **address problems in a timely manner** but also keep it possible for them
|
||||
to **fix bugs, add new and improve on existing functionality** instead of doing
|
||||
nothing but ticket management.
|
||||
|
||||

|
||||

|
||||
|
||||
- **[Read the FAQ](https://faq.octoprint.org)**
|
||||
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
|
||||
@@ -36,14 +36,14 @@ nothing but ticket management.
|
||||
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
|
||||
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
|
||||
something is **not** what qualifies as a request here, use the
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
|
||||
[community forum at community.octoprint.org](https://community.octoprint.org) for
|
||||
such support issues.
|
||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
||||
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
|
||||
`[Brainstorming] New plugin hook for doing some cool stuff`).
|
||||
changes to the plugin system, please get in touch on the
|
||||
[community forum at community.octoprint.org](https://community.octoprint.org/c/development).
|
||||
- If you need **support**, have a **question** or some **other reason** that
|
||||
doesn't fit any of the above categories, the issue tracker is not the right place.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
|
||||
Consult the [community forum at community.octoprint.org](https://community.octoprint.org/c/support) instead.
|
||||
|
||||
No matter what kind of ticket you create, never mix two or more "ticket reasons"
|
||||
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
@@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
> A bot is in place that monitors new tickets, automatically
|
||||
> categorizes them and checks new bug reports for usage of the provided template.
|
||||
> That bot will only bother you if you open a ticket that appears to be a bug (no
|
||||
> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
|
||||
> `[Request]` in the title) without the complete template, and it
|
||||
> will do that only to ensure that all information needed to solve the issue is
|
||||
> available for the maintainers to directly start tackling that problem.
|
||||
|
||||
@@ -75,7 +75,7 @@ following section *completely* and also follow the instructions in the
|
||||
**OctoPrint doesn't manage your network connection or your webcam nor
|
||||
can it fix your printer not getting detected as a serial interface** -
|
||||
if you have any kinds of problems with that, get in touch on the
|
||||
[community forum](https://discourse.octoprint.org).
|
||||
[community forum](https://community.octoprint.org).
|
||||
|
||||
**This is not the bug tracker of OctoPi**, which is the preconfigured
|
||||
Raspberry Pi image including OctoPrint among other things - that one can be found
|
||||
@@ -126,7 +126,7 @@ following section *completely* and also follow the instructions in the
|
||||
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
|
||||
very diligent here!
|
||||
|
||||
If in doubt about any of the above - get in touch on the [community forum](https://discourse.octoprint.org)
|
||||
If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org)
|
||||
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
|
||||
there.
|
||||
|
||||
@@ -153,7 +153,7 @@ plugins and not unofficial OctoPrint versions).
|
||||
|
||||
Do not seek support here ("I need help with ...", "I have a
|
||||
question ..."), that belongs on the community forum at
|
||||
discourse.octoprint.org, NOT here.
|
||||
community.octoprint.org, NOT here.
|
||||
|
||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||
reports fully fill out the bug reporting template (if you don't know
|
||||
@@ -275,11 +275,11 @@ all requested information or your ticket will be closed.
|
||||
|
||||
### Where can I find which version and branch I'm on?
|
||||
|
||||
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
|
||||
Please refer to [this FAQ entry](https://community.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
|
||||
|
||||
### Where can I find those log files you keep talking about?
|
||||
|
||||
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
|
||||
Please refer to [this FAQ entry](https://community.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
|
||||
|
||||
### Where can I find my browser's error console?
|
||||
|
||||
@@ -301,7 +301,8 @@ the documentation.
|
||||
the discussion going on how best to solve *this* in OctoPrint's plugin
|
||||
system - maybe that's the actual PR you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large or otherwise disruptive changes to the
|
||||
code or appearance, please open a "Brainstorming" ticket first** so
|
||||
code or appearance, please get in touch on the
|
||||
[forums](https://community.octoprint.org/c/development)** first so
|
||||
that we can determine if it's a good time for your specific pull
|
||||
request. It might be that we're currently in the process of making
|
||||
heavy changes to the code locations you'd target as well, or your
|
||||
@@ -311,7 +312,8 @@ the documentation.
|
||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
||||
`dev/myNewFeature`)[1].
|
||||
4. Create your pull request **only against the `maintenance` or `devel` branch**:
|
||||
* if it's a bug fix for a bug in the current stable version: `maintenance` branch
|
||||
* if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
|
||||
*small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
|
||||
* otherwise: `devel` branch
|
||||
5. Create **one pull request per feature/bug fix**.
|
||||
6. Make sure there are **only relevant changes** included in your PR. No
|
||||
@@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 2017-11-22: Added note on how to run the unit tests
|
||||
* 2018-03-15: Link to new community forum and some clarifications re bug
|
||||
reporting
|
||||
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
|
||||
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
|
||||
* 2018-10-18: Allow PRs against `maintenance` branch for improvements and small
|
||||
new features, suggest getting in touch on the forum for larger changes
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||

|
||||
[](https://travis-ci.org/foosel/OctoPrint)
|
||||
[](https://discourse.octoprint.org)
|
||||
[](https://community.octoprint.org)
|
||||
[](https://chat.octoprint.org)
|
||||
[](https://twitter.com/OctoPrint3d)
|
||||
|
||||
@@ -13,7 +13,7 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org
|
||||
|
||||
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint).
|
||||
|
||||
@@ -31,16 +31,16 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!**
|
||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
|
||||
might be of more interest for you. You might also want to subscribe to join
|
||||
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) where there are other active users who might be
|
||||
might be of more interest for you. You might also want to subscribe to join
|
||||
[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
|
||||
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help
|
||||
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
|
||||
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org)
|
||||
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
|
||||
[the community forum at community.octoprint.org](https://community.octoprint.org)
|
||||
and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
|
||||
|
||||
If you think something is bad about OctoPrint or its documentation the way it is, please help
|
||||
@@ -65,14 +65,15 @@ you already have Python 2.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`
|
||||
3. Create a user-owned virtual environment therein: `virtualenv venv`
|
||||
3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is
|
||||
python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`.
|
||||
4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .`
|
||||
|
||||
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
|
||||
for details.
|
||||
|
||||
After installation, please make sure you follow the first-run wizard and set up
|
||||
access control as necessary.
|
||||
access control as necessary.
|
||||
|
||||
## Dependencies
|
||||
|
||||
@@ -142,5 +143,8 @@ be edited from OctoPrint's settings dialog.
|
||||
|
||||
## Special Thanks
|
||||
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
||||
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](https://www.browserstack.com/).
|
||||
|
||||
Profiling is done with the help of [PyVmMonitor](https://www.pyvmmonitor.com).
|
||||
|
||||
Error tracking is powered and sponsored by [Sentry](https://sentry.io).
|
||||
@@ -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.
|
||||
@@ -6,58 +6,54 @@ thanks to everyone who contributed!
|
||||
|
||||
## Patreon Patrons
|
||||
|
||||
* Andre Bubel
|
||||
* Andrew Moorby
|
||||
* ANTONIO AUGUSTO DE LIMA PONTES
|
||||
* Arnljot Arntsen
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brian E. Tyler
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* COLLE+McVOY
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Dorian Gray
|
||||
* E3D BigBox
|
||||
* Eric Betts
|
||||
* Ernesto Martinez
|
||||
* F. Kunsmann
|
||||
* Frank Sander
|
||||
* Franziska Kunsmann
|
||||
* George Robles
|
||||
* günter weber
|
||||
* Hydra Research LLC
|
||||
* James Seigel
|
||||
* Jeff Moe
|
||||
* jean-claude migneault
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
* Joseph Payne
|
||||
* Josh Daniels
|
||||
* Joshua Wills
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kodama Inc.
|
||||
* Lewis Newby
|
||||
* LA 3D Printer Repair
|
||||
* Lee Dohm
|
||||
* LulzBot®
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Martin Beattie
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* mitchell hirsch
|
||||
* Noe Ruiz
|
||||
* Mosaic Manufacturing
|
||||
* OMER MEHMET SUTAS
|
||||
* Patrick Glyré
|
||||
* Patrick McGinnis
|
||||
* Prof Yuh Wen Chen
|
||||
* Randy C. Will
|
||||
* Ranjib Dey
|
||||
* Robert Gusek
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Rudolff Vang
|
||||
* Samer Najia
|
||||
* Shawn Lewis
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Sven Mueller
|
||||
* Symbiotic Devices
|
||||
* Thomas Hatley
|
||||
* Timothy D Hoogland
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
* Vladislav Kuzemchik
|
||||
|
||||
and 1351 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1615 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
@@ -36,7 +36,6 @@
|
||||
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
|
||||
* [chainmap](https://bitbucket.org/jeunice/chainmap): Python
|
||||
* [Click](http://click.pocoo.org/): BSD
|
||||
* [dateutil](https://dateutil.readthedocs.io/): BSD
|
||||
* [emoji](https://github.com/carpedm20/emoji/): BSD
|
||||
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
|
||||
* [Flask](http://flask.pocoo.org/): BSD
|
||||
|
||||
@@ -11,6 +11,10 @@ Apps
|
||||
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.
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ Issue a connection command
|
||||
Issue a connection command. Currently available command are:
|
||||
|
||||
connect
|
||||
Instructs OctoPrint to connect to the printer. Additional parameters are:
|
||||
Instructs OctoPrint to connect or, if already connected, reconnect to the printer. Additional parameters are:
|
||||
|
||||
* ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if
|
||||
no preference is available auto detection will be attempted.
|
||||
|
||||
@@ -218,6 +218,17 @@ Progress information
|
||||
- 1
|
||||
- Integer
|
||||
- Estimate of time left to print, in seconds
|
||||
* - ``printTimeLeftOrigin``
|
||||
- 1
|
||||
- String
|
||||
- Origin of the current time left estimate. Can currently be either of:
|
||||
|
||||
* ``linear``: based on an linear approximation of the progress in file in bytes vs time
|
||||
* ``analysis``: based on an analysis of the file
|
||||
* ``estimate``: calculated estimate after stabilization of linear estimation
|
||||
* ``average``: based on the average total from past prints of the same model against the same printer profile
|
||||
* ``mixed-analysis``: mixture of ``estimate`` and ``analysis``
|
||||
* ``mixed-average``: mixture of ``estimate`` and ``average``
|
||||
|
||||
.. _sec-api-datamodel-files:
|
||||
|
||||
|
||||
@@ -11,9 +11,12 @@ General information
|
||||
Authorization
|
||||
=============
|
||||
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one, a user specific one if "Access Control" is enabled or an :ref:`App Session Key <sec-api-apps-sessionkey>`.
|
||||
Users are able to generate and revoke their custom API key via the "Change password" dialog.
|
||||
If :ref:`Access Control <sec-features-access_control>` is enabled OctoPrint's API expects an API key to be supplied with each request. This API
|
||||
key can be either the globally configured one, a user specific one or an app and user specific one as generated by the
|
||||
authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
|
||||
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
|
||||
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
|
||||
|
||||
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
|
||||
@@ -23,8 +26,6 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`.
|
||||
|
||||
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -34,6 +35,24 @@ For testing purposes it is also possible to supply the API key via a query param
|
||||
|
||||
Please be advised that clients should use the header field variant if at all possible.
|
||||
|
||||
If the key is missing or invalid, OctoPrint will treat the request as it would any unauthenticated anonymous request to the endpoint.
|
||||
Consequently, if the bundled :ref:`ForceLogin plugin <sec-bundledplugins-forcelogin>` is active (which is the default), that means
|
||||
that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login <sec-api-general-login>`
|
||||
will be denied with a :http:statuscode:`403`.
|
||||
|
||||
.. warning::
|
||||
|
||||
If :ref:`Access Control <sec-features-access_control>` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests
|
||||
with an invalid or outright missing API key as requests with full admin rights!
|
||||
|
||||
.. note::
|
||||
|
||||
The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to
|
||||
be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the
|
||||
HTML page and also available on the :ref:`Push API <sec-api-push>`. The presence and ready availability of this unauthenticated
|
||||
anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a
|
||||
meaningful way, so it was finally abandoned in 1.3.11.
|
||||
|
||||
.. _fig-api-general-globalapikey:
|
||||
.. figure:: ../images/settings-global-api-key.png
|
||||
:align: center
|
||||
@@ -55,11 +74,6 @@ Please be advised that clients should use the header field variant if at all pos
|
||||
|
||||
The API key options in the "Change password" dialog. Users can generate and revoke their custom API key here.
|
||||
|
||||
.. note::
|
||||
OctoPrint's web interface uses a custom API key that is freshly generated on every server start. This key is not
|
||||
intended to be used by any other client and would not be very useful in any case, since it basically represents
|
||||
a completely anonymous client.
|
||||
|
||||
.. _sec-api-general-contenttype:
|
||||
|
||||
Content Type
|
||||
@@ -120,3 +134,94 @@ If CORS is not enabled you will get errors like the following::
|
||||
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
|
||||
header is present on the requested resource.
|
||||
|
||||
.. _sec-api-general-login:
|
||||
|
||||
Login
|
||||
=====
|
||||
|
||||
.. http:post:: /api/login
|
||||
|
||||
Creates a login session or retrieves information about the currently existing session ("passive login").
|
||||
|
||||
Can be used in one of two ways: to login a user via username and password and create a persistent session (usually
|
||||
from a UI in the browser), or to retrieve information about the active user (from an existing session or an API key)
|
||||
via the ``passive`` flag.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
|
||||
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
|
||||
|
||||
:json passive: If present, performs a passive login only, returning information about the current user that's
|
||||
active either through an existing session or the used API key
|
||||
:json user: (active login only) Username
|
||||
:json pass: (active login only) Password
|
||||
:json remember: (active login only) Whether to set a "remember me" cookie on the session
|
||||
:status 200: Successful login
|
||||
:status 401: Username/password mismatch or unknown user
|
||||
:status 403: Deactivated account
|
||||
|
||||
.. _sec-api-general-logout:
|
||||
|
||||
Logout
|
||||
======
|
||||
|
||||
.. http:post:: /api/logout
|
||||
|
||||
Ends the current login session of the current user.
|
||||
|
||||
Only makes sense in the context of browser based workflows.
|
||||
|
||||
Will return a :http:statuscode:`204`.
|
||||
|
||||
:status 204: No error
|
||||
|
||||
.. _sec-api-general-datamodel:
|
||||
|
||||
Data model
|
||||
==========
|
||||
|
||||
.. _sec-api-general-datamodel-login:
|
||||
|
||||
Login response
|
||||
--------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- the user's name/id
|
||||
* - ``active``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user's account is active or not
|
||||
* - ``admin``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has admin rights or not
|
||||
* - ``user``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has user rights or not (always ``true``)
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- string or None
|
||||
- The user's API key, if set
|
||||
* - ``settings``
|
||||
- 1
|
||||
- dict
|
||||
- The user's settings, if any
|
||||
* - ``session``
|
||||
- 1
|
||||
- string
|
||||
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
|
||||
* - ``_is_external_client``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the client that made the request got detected as external from the local network or not.
|
||||
@@ -212,7 +212,8 @@ Retrieve information about the current job
|
||||
"filepos": 337942,
|
||||
"printTime": 276,
|
||||
"printTimeLeft": 912
|
||||
}
|
||||
},
|
||||
"state": "Printing"
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
@@ -243,4 +244,8 @@ Job information response
|
||||
- 1
|
||||
- :ref:`sec-api-datamodel-jobs-progress`
|
||||
- Information regarding the progress of the current print job
|
||||
|
||||
* - ``state``
|
||||
- 1
|
||||
- String
|
||||
- A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused",
|
||||
"Cancelling", "Error" or "Offline".
|
||||
@@ -22,6 +22,11 @@ Bed
|
||||
corresponding resource returns temperature information including an optional history. Note that Bed commands
|
||||
are only available if the currently selected printer profile has a heated bed.
|
||||
See :ref:`sec-api-printer-bedcommand`.
|
||||
Chamber
|
||||
Chamber commands allow setting the temperature and temperature offset for the printer's heated chamber. Querying
|
||||
the corresponding resource returns temperature information including an option history. Note that Chamber commands
|
||||
are only available if the currently selected printer profile has a heated chamber.
|
||||
See :ref:`sec-api-printer-chambercommand`.
|
||||
SD card
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
|
||||
corresponding resource returns the current SD card state.
|
||||
@@ -219,7 +224,7 @@ Issue a print head command
|
||||
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
|
||||
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
|
||||
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
|
||||
interpreted as an integer signifying the speed in mm/s, to append to the command.
|
||||
interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
home
|
||||
Homes the print head in all of the given axes. Additional parameters are:
|
||||
@@ -345,7 +350,7 @@ Issue a tool command
|
||||
Sets the given target temperature on the printer's tools. Additional parameters:
|
||||
|
||||
* ``targets``: Target temperature(s) to set, properties must match the format ``tool{n}`` with ``n`` being the
|
||||
tool's index starting with 0.
|
||||
tool's index starting with 0. A value of `0` will turn the heater off.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's tools. Additional parameters:
|
||||
@@ -362,6 +367,8 @@ Issue a tool command
|
||||
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
|
||||
|
||||
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
|
||||
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
|
||||
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
flowrate
|
||||
Changes the flow rate factor to apply to extrusion of the tool.
|
||||
@@ -621,12 +628,12 @@ Issue a bed command
|
||||
are:
|
||||
|
||||
target
|
||||
Sets the given target temperature on the printer's tools. Additional parameters:
|
||||
Sets the given target temperature on the printer's bed. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set.
|
||||
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's tools. Additional parameters:
|
||||
Sets the given temperature offset on the printer's bed. Additional parameters:
|
||||
|
||||
* ``offset``: Offset to set.
|
||||
|
||||
@@ -708,7 +715,7 @@ Retrieve the current bed state
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
.. note::
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
If you want tool, bed and chamber temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
|
||||
**Example**
|
||||
@@ -758,6 +765,154 @@ Retrieve the current bed state
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated bed.
|
||||
|
||||
.. _sec-api-printer-chambercommand:
|
||||
|
||||
Issue a chamber command
|
||||
=======================
|
||||
|
||||
.. http:post:: /api/printer/chamber
|
||||
|
||||
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
|
||||
are:
|
||||
|
||||
target
|
||||
Sets the given target temperature on the printer's chamber. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's chamber. Additional parameters:
|
||||
|
||||
* ``offset``: Offset to set.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational. Otherwise a :http:statuscode:`409`
|
||||
is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
If no heated chamber is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires user rights.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
Set the target temperature for the printer's heated chamber to 50°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/chamber HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "target",
|
||||
"target": 50
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Offset Temperature Request**
|
||||
|
||||
Set the temperature offset for the heated chamber to -5°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/chamber HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "offset",
|
||||
"offset": -5
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``target`` or ``offset``.
|
||||
:json object target: ``target`` command: The target temperature to set.
|
||||
:json object offset: ``offset`` command: The offset temperature to set.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
|
||||
request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated chamber.
|
||||
|
||||
.. _sec-api-printer-chamberstate:
|
||||
|
||||
Retrieve the current chamber state
|
||||
==================================
|
||||
|
||||
.. http:get:: /api/printer/chamber
|
||||
|
||||
Retrieves the current temperature data (actual, target and offset) plus optionally a (limited) history (actual, target,
|
||||
timestamp) for the printer's heated chamber.
|
||||
|
||||
It's also possible to retrieve the temperature history by supplying the ``history`` query parameter set to ``true``. The
|
||||
amount of returned history data points can be limited using the ``limit`` query parameter.
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
If no heated chamber is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
.. note::
|
||||
If you want tool, bed and chamber temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
|
||||
**Example**
|
||||
|
||||
Query the chamber temperature data and also include the temperature history but limit it to two entries.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer/chamber?history=true&limit=2 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"chamber": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0,
|
||||
"offset": 5
|
||||
},
|
||||
"history": [
|
||||
{
|
||||
"time": 1395651928,
|
||||
"chamber": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"time": 1395651926,
|
||||
"chamber": {
|
||||
"actual": 49.1123,
|
||||
"target": 70.0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
:query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response
|
||||
too. If no ``limit`` parameter is given, all available temperature history data will be returned.
|
||||
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
|
||||
will be returned. Will be ignored if ``history`` is not enabled.
|
||||
:statuscode 200: No error
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated chamber.
|
||||
|
||||
.. _sec-api-printer-sdcommand:
|
||||
|
||||
Issue an SD command
|
||||
|
||||
@@ -52,6 +52,7 @@ Retrieve all printer profiles
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -93,6 +94,7 @@ Retrieve all printer profiles
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": true,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -184,6 +186,7 @@ Add a new printer profile
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -267,6 +270,7 @@ Add a new printer profile
|
||||
"height": 300
|
||||
},
|
||||
"heatedBed": false,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -352,6 +356,7 @@ Update an existing printer profile
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -578,6 +583,10 @@ Profile
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the printer has a heated bed (``true``) or not (``false``)
|
||||
* - ``heatedChamber``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the printer has a heated chamber (``true``) or not (``false``)
|
||||
* - ``axes``
|
||||
- 0..1
|
||||
- Object
|
||||
|
||||
@@ -47,23 +47,41 @@ Clients must ignore any unknown messages.
|
||||
|
||||
The data model of the attached payloads is described further below.
|
||||
|
||||
OctoPrint's SockJS socket also accepts one command from the client to the server,
|
||||
the ``throttle`` command. Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
OctoPrint's SockJS socket also accepts two commands from the client to the server.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
|
||||
existing user session with the socket. That is of special importance to receive
|
||||
any kind of messages if the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` is enabled
|
||||
(as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated
|
||||
clients.
|
||||
|
||||
.. sourcecode:: javascript
|
||||
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
|
||||
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
Example for a ``auth`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"auth": "someuser:LGZ0trf8By"
|
||||
}
|
||||
|
||||
* ``throttle``: Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
|
||||
.. _sec-api-push-datamodel:
|
||||
|
||||
|
||||
@@ -274,10 +274,10 @@ Fetch template data
|
||||
"plugin_name": "Action Command Prompt Support"
|
||||
},
|
||||
{
|
||||
"id": "plugin_cura",
|
||||
"name": "CuraEngine (<= 15.04)",
|
||||
"plugin_id": "cura",
|
||||
"plugin_name": "CuraEngine (<= 15.04)"
|
||||
"id": "plugin_curalegacy",
|
||||
"name": "Cura Legacy",
|
||||
"plugin_id": "curalegacy",
|
||||
"plugin_name": "Cura Legacy"
|
||||
}
|
||||
],
|
||||
"sidebar": [
|
||||
@@ -396,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
-
|
||||
* - ``feature.sdSupport``
|
||||
-
|
||||
* - ``feature.sdReleativePath``
|
||||
* - ``feature.sdRelativePath``
|
||||
-
|
||||
* - ``feature.sdAlwaysAvailable``
|
||||
-
|
||||
|
||||
@@ -42,22 +42,22 @@ List All Slicers and Slicing Profiles
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"cura": {
|
||||
"key": "cura",
|
||||
"displayName": "CuraEngine",
|
||||
"curalegacy": {
|
||||
"key": "curalegacy",
|
||||
"displayName": "Cura Legacy",
|
||||
"default": true,
|
||||
"profiles": {
|
||||
"high_quality": {
|
||||
"key": "high_quality",
|
||||
"displayName": "High Quality",
|
||||
"default": false,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality"
|
||||
},
|
||||
"medium_quality": {
|
||||
"key": "medium_quality",
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ List Slicing Profiles of a Specific Slicer
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/cura/profiles HTTP/1.1
|
||||
GET /api/slicing/curalegacy/profiles HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
@@ -95,13 +95,13 @@ List Slicing Profiles of a Specific Slicer
|
||||
"key": "high_quality",
|
||||
"displayName": "High Quality",
|
||||
"default": false,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality"
|
||||
},
|
||||
"medium_quality": {
|
||||
"key": "medium_quality",
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +125,7 @@ Retrieve Specific Profile
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/cura/profiles/quick_test HTTP/1.1
|
||||
GET /api/slicing/curalegacy/profiles/quick_test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
@@ -137,7 +137,7 @@ Retrieve Specific Profile
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test",
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/quick_test",
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test",
|
||||
"data": {
|
||||
"bottom_layer_speed": 20.0,
|
||||
"bottom_thickness": 0.3,
|
||||
@@ -174,14 +174,14 @@ Add Slicing Profile
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
PUT /api/slicing/cura/profiles/quick_test HTTP/1.1
|
||||
PUT /api/slicing/curalegacy/profiles/quick_test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
|
||||
"description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count",
|
||||
"data": {
|
||||
"layer_height": 0.2,
|
||||
"skirt_line_count": 3
|
||||
@@ -197,8 +197,8 @@ Add Slicing Profile
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/quick_test"
|
||||
"description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count",
|
||||
"resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test"
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to add the profile
|
||||
|
||||
@@ -7,7 +7,8 @@ Version information
|
||||
.. http:get:: /api/version
|
||||
|
||||
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
|
||||
the API version, ``server`` containing the server version.
|
||||
the API version, ``server`` containing the server version, ``text`` containing the server version including
|
||||
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
|
||||
|
||||
**Example Request**
|
||||
|
||||
@@ -26,7 +27,8 @@ Version information
|
||||
|
||||
{
|
||||
"api": "0.1",
|
||||
"server": "1.1.0"
|
||||
"server": "1.3.10",
|
||||
"text": "OctoPrint 1.3.10"
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
@@ -0,0 +1,67 @@
|
||||
.. _sec-bundledplugins-announcements:
|
||||
|
||||
Announcement Plugin
|
||||
===================
|
||||
|
||||
The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11).
|
||||
|
||||
It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new
|
||||
plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels
|
||||
via RSS or Atom feed URLs.
|
||||
|
||||
.. _fig-bundledplugins-announcements-example1:
|
||||
.. figure:: ../images/bundledplugins-announcements-example1.png
|
||||
:align: center
|
||||
:alt: Example notification
|
||||
|
||||
An example notification from the Announcement Plugin.
|
||||
|
||||
.. _fig-bundledplugins-announcements-example2:
|
||||
.. figure:: ../images/bundledplugins-announcements-example2.png
|
||||
:align: center
|
||||
:alt: Announcement reader
|
||||
|
||||
The Announcement Plugin's reader dialog.
|
||||
|
||||
.. _fig-bundledplugins-announcements-settings:
|
||||
.. figure:: ../images/bundledplugins-announcements-settings.png
|
||||
:align: center
|
||||
:alt: Announcement settings
|
||||
|
||||
The Announcement Plugin's settings dialog.
|
||||
|
||||
.. _sec-bundledplugins-announcements-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog.
|
||||
|
||||
On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the
|
||||
configuration of the existing channels through ``config.yaml``.
|
||||
|
||||
The available configuration keys are:
|
||||
|
||||
* ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure
|
||||
that follows this format:
|
||||
|
||||
* ``name``: Name of the channel, used e.g. in the title of the displayed notifications.
|
||||
* ``description``: Description of the channel.
|
||||
* ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification).
|
||||
* ``type``: Currently unused.
|
||||
* ``url``: URL for the feed acting as notification source, must be RSS or Atom format.
|
||||
|
||||
* ``enabled_channels``: List of identifiers of enabled channels.
|
||||
* ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly).
|
||||
* ``channel_order``: List of channel identifiers in the order they should appear in the UI.
|
||||
* ``ttl``: Time to live of the channel cache in minutes (default: 6 hours).
|
||||
* ``display_limit``: Limit of items to display per channel (default: 3).
|
||||
* ``summary_limit``: Limit of characters to display from each channel entry (default: 300).
|
||||
|
||||
.. _sec-bundledplugins-announcements-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Announcement plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/announcements``.
|
||||
@@ -0,0 +1,543 @@
|
||||
.. _sec-bundledplugins-appkeys:
|
||||
|
||||
Application Keys Plugin
|
||||
=======================
|
||||
|
||||
The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10).
|
||||
|
||||
It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it
|
||||
on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed
|
||||
on a per-user base as well as globally by administrators.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-confirmation:
|
||||
.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png
|
||||
:align: center
|
||||
:alt: Confirmation
|
||||
|
||||
The plugin's confirmation generated for a new application key request.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-user_settings:
|
||||
.. figure:: ../images/bundledplugins-appkeys-user_settings.png
|
||||
:align: center
|
||||
:alt: Key management via user settings
|
||||
|
||||
Users can manage the application specific API keys registered to their account via their user settings.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-settings:
|
||||
.. figure:: ../images/bundledplugins-appkeys-settings.png
|
||||
:align: center
|
||||
:alt: Global key management via settings
|
||||
|
||||
Administrators can manage all application specific API keys registered to any user.
|
||||
|
||||
.. _sec-bundledplugins-appkeys-workflow:
|
||||
|
||||
Workflow
|
||||
--------
|
||||
|
||||
The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist
|
||||
of the following steps:
|
||||
|
||||
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
|
||||
enters their username which is also their user ID into the App.
|
||||
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
|
||||
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
|
||||
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
|
||||
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
|
||||
authorization process.
|
||||
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
|
||||
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
|
||||
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
|
||||
signals that no decision has been made yet.
|
||||
6. The User either accepts or denies the access request which makes the Webinterface send a
|
||||
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
|
||||
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
|
||||
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
|
||||
an HTTP :http:statuscode:`404`.
|
||||
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant App
|
||||
participant Webinterface
|
||||
participant Server
|
||||
|
||||
note over User, Server: Step 1, 2 & 3
|
||||
|
||||
User->>App: enters URL of instance to connect to and optional user_id
|
||||
|
||||
App->>Server: GET /plugin/appkeys/probe
|
||||
|
||||
alt Workflow unsupported
|
||||
|
||||
Server->>App: 404
|
||||
App->>User: alternative workflow, copy-paste key manually
|
||||
|
||||
else Workflow supported
|
||||
|
||||
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
|
||||
|
||||
note over User, Server: Step 4
|
||||
|
||||
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
|
||||
Webinterface-->>User: Display confirmation dialog
|
||||
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
|
||||
|
||||
note over User, Server: Step 5
|
||||
|
||||
loop Poll for decision
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 202
|
||||
end
|
||||
|
||||
note over User, Server: Step 6 & 7
|
||||
|
||||
alt User accepts
|
||||
|
||||
User-->>Webinterface: Allow access
|
||||
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (True)
|
||||
Server->>Webinterface: 204
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 200, api_key
|
||||
|
||||
else User denies
|
||||
|
||||
User-->>Webinterface: Deny access
|
||||
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (False)
|
||||
Server->>Webinterface: 204
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 404
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api:
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-probe:
|
||||
|
||||
Probe for workflow support
|
||||
..........................
|
||||
|
||||
.. http:get:: /plugin/appkeys/probe
|
||||
|
||||
Probes for support of the workflow.
|
||||
|
||||
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
|
||||
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
|
||||
|
||||
:status 204: the workflow is supported
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-startauthprocess:
|
||||
|
||||
Start authorization process
|
||||
...........................
|
||||
|
||||
.. http:post:: /plugin/appkeys/request
|
||||
|
||||
Starts the authorization process.
|
||||
|
||||
Expects a :ref:`Key request <sec-bundledplugins-appkey-datamodel-keyrequest>` as request body.
|
||||
|
||||
The ``app`` parameter should be a human readable identifier to use
|
||||
for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively,
|
||||
so ``My App`` and ``my APP`` are considered the same application identifiers.
|
||||
|
||||
The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter
|
||||
is left unset, any user will be able to complete the authorization process and grant access to the app with their
|
||||
account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use
|
||||
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
|
||||
is logged in on.
|
||||
|
||||
:json app: application identifier to use for the request, case insensitive
|
||||
:json user: optional user id to restrict the decision to the specified user
|
||||
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-polldecision:
|
||||
|
||||
Poll for decision on existing request
|
||||
.....................................
|
||||
|
||||
.. http:get:: /plugin/appkeys/request/<str:app_token>
|
||||
|
||||
Endpoint generated per authorization request to poll for the result.
|
||||
|
||||
Returns an HTTP :http:statuscode:`202` while no decision has been made yet, an HTTP :http:statuscode:`200` and
|
||||
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
|
||||
HTTP :http:statuscode:`404` if the request has been denied or timed out.
|
||||
|
||||
.. note::
|
||||
|
||||
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
|
||||
for more than 5s.
|
||||
|
||||
:status 200: access granted, API key in response body
|
||||
:status 202: no decision has been made yet, continue polling
|
||||
:status 404: access denied or request timed out
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-decide:
|
||||
|
||||
Decide on existing request
|
||||
..........................
|
||||
|
||||
.. http:post:: /plugin/appkeys/decision/<str:user_token>
|
||||
|
||||
Endpoint to decide on the authorization request.
|
||||
|
||||
Expects a :ref:`Decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` as request body.
|
||||
|
||||
Returns an HTTP :http:statuscode:`204` on success.
|
||||
|
||||
:json decision: boolean value to indicate whether to confirm (``True``) or deny (``False``) access
|
||||
:status 204: success
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-fetchlist:
|
||||
|
||||
Fetch list of existing application keys
|
||||
.......................................
|
||||
|
||||
.. http:get:: /api/plugin/appkeys
|
||||
|
||||
Fetches a list of existing application keys and pending requests registered in the system for the current user.
|
||||
|
||||
If the additional optional parameter ``all`` is provided and the user has administrator rights, fetches a list
|
||||
of *all** application keys and pending requests registered in the system for any user.
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`List response <sec-bundledplugins-appkey-datamodel-listreponse>` in the
|
||||
body upon success.
|
||||
|
||||
:query all: Fetch all application keys and pending requests from all users. Requires administrator rights.
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-issuecommand:
|
||||
|
||||
Issue an application key command
|
||||
................................
|
||||
|
||||
.. http:post:: /api/plugin/appkeys
|
||||
|
||||
Application key commands allow revoking existing application keys and manually generating new ones. The available
|
||||
commands are:
|
||||
|
||||
revoke
|
||||
Revokes an existing application key. Must belong to the user issuing the command, unless the user has admin rights
|
||||
in which case they make revoke any application key in the system. Expects the key in question as parameter ``key``.
|
||||
|
||||
generate
|
||||
Generates a new application key for the user, using the application identifier provided as parameter ``app``.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires user rights.
|
||||
|
||||
**Example revoke request**
|
||||
|
||||
Revokes the (fictional) key ``aabbccddeeff112233445566``.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/plugin/appkeys HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "revoke",
|
||||
"key": "aabbccddeeff112233445566"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example generate request**
|
||||
|
||||
Generates a new key for application identifier "My awesome application 1.0".
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/plugin/appkeys HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "generate",
|
||||
"key": "My awesome application 1.0"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``revoke`` or ``generate``
|
||||
:json string key: ``revoke`` command: The key to revoke
|
||||
:json string app: ``generate`` command: Application identifier for which to generate a key
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: Invalid or missing parameter
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel:
|
||||
|
||||
Data model
|
||||
----------
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keyrequest:
|
||||
|
||||
Key request
|
||||
...........
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``app``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier to use for the request
|
||||
* - ``user``
|
||||
- 0..1
|
||||
- str
|
||||
- User identifier/name to restrict the request to
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keyresponse:
|
||||
|
||||
Key response
|
||||
............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- str
|
||||
- the API key generated for the application
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-decisionrequest:
|
||||
|
||||
Decision request
|
||||
................
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``decision``
|
||||
- 1
|
||||
- boolean
|
||||
- ``True`` if the access request it to be granted, ``False`` otherwise
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-listreponse:
|
||||
|
||||
List response
|
||||
.............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``keys``
|
||||
- 1
|
||||
- list of :ref:`key list entries <sec-bundledplugins-appkey-datamodel-keylistentry>`
|
||||
- Keys registered in the system
|
||||
* - ``pending``
|
||||
- 1
|
||||
- list of :ref:`pending list entries <sec-bundledplugins-appkey-datamodel-pendinglistentry>`
|
||||
- Currently pending authorization requests
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keylistentry:
|
||||
|
||||
Key list entry
|
||||
..............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``api_key``
|
||||
- 1
|
||||
- str
|
||||
- API key
|
||||
* - ``app_id``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier
|
||||
* - ``user_id``
|
||||
- 1
|
||||
- str
|
||||
- User ID of the key's owner
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-pendinglistentry:
|
||||
|
||||
Pending list entry
|
||||
..................
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``app_id``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier
|
||||
* - ``user_id``
|
||||
- 0..1
|
||||
- str
|
||||
- optional: User ID of user who can grant or deny request
|
||||
* - ``user_token``
|
||||
- 1
|
||||
- str
|
||||
- Token to grant or deny request
|
||||
|
||||
.. _sec-bundledplugins-appkeys-jsclientlib:
|
||||
|
||||
JavaScript Client Library
|
||||
-------------------------
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.getKeys(opts)
|
||||
|
||||
Retrieves registered keys and pending requests for the current user.
|
||||
|
||||
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.getAllKeys(opts)
|
||||
|
||||
Retrieves registered keys and pending requests for all users.
|
||||
|
||||
Needs administrator rights.
|
||||
|
||||
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.generateKey(app, opts)
|
||||
|
||||
Generates a key for the given ``app`` and the current user.
|
||||
|
||||
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
|
||||
|
||||
:param string app: Application identifier
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.revokeKey(key, opts)
|
||||
|
||||
Revokes the given ``key``. The key must belong to the current user, or the current user must have administrator
|
||||
rights.
|
||||
|
||||
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
|
||||
|
||||
:param string key: Key to revoke
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.decide(token, decision, opts)
|
||||
|
||||
Decides on an existing authorization request.
|
||||
|
||||
See :ref:`Decide on existing request <sec-bundledplugins-appkeys-api-decide>` for more details.
|
||||
|
||||
:param string token: User token for which to make the decision, as pushed to the client via the socket.
|
||||
:param boolean decision: Whether to grant access (``true``) or not (``false``).
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
|
||||
|
||||
Probes for workflow support.
|
||||
|
||||
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` identifier.
|
||||
|
||||
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.requestForUser(app, user, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` and ``user`` identifiers.
|
||||
|
||||
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.checkDecision(token, opts)
|
||||
|
||||
Polls for a decision on an existing authorization request identified by ``token``.
|
||||
|
||||
See :ref:`Poll for decision on existing request <sec-bundledplugins-appkeys-api-polldecision>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
|
||||
|
||||
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
|
||||
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
|
||||
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
|
||||
for the workflow, the promise is rejected.
|
||||
|
||||
**Example usage**
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
OctoPrint.plugins.appkeys.authenticate("My App", "some_user")
|
||||
.done(function(api_key) {
|
||||
console.log("Got our API key:", api_key);
|
||||
})
|
||||
.fail(function() {
|
||||
console.log("No API key for us");
|
||||
})
|
||||
|
||||
:param string app: Application identifier
|
||||
:param string user: Optional user identifier
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. _sec-bundledplugins-appkeys-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Application Keys plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/appkeys``.
|
||||
@@ -0,0 +1,70 @@
|
||||
.. _sec-bundledplugins-backup:
|
||||
|
||||
Backup Plugin
|
||||
=============
|
||||
|
||||
The OctoPrint Backup Plugin comes bundled with OctoPrint (starting with 1.3.10).
|
||||
|
||||
It allows the creation and restoration of backups of OctoPrint's settings, data and installed plugins [#]_.
|
||||
|
||||
This allows easy migration
|
||||
to newly setup instances as well as making regular backups to prevent data loss.
|
||||
|
||||
.. _fig-bundledplugins-backup-settings:
|
||||
.. figure:: ../images/bundledplugins-backup-settings.png
|
||||
:align: center
|
||||
:alt: OctoPrint Backup Plugin
|
||||
|
||||
The plugin's settings panel with existing backups, the backup creation and restore sections.
|
||||
|
||||
As long as plugins adhere to the standard of storing their data and settings in OctoPrint's plugin data folders, their
|
||||
data will be part of the backup. Note that the backups made by the Backup Plugin will *not* be part of any backups -
|
||||
you'll need to persist the resulting zip files yourself!
|
||||
|
||||
.. _sec-bundledplugins-backup-cli:
|
||||
|
||||
Command line usage
|
||||
------------------
|
||||
|
||||
The Backup Plugin implements a command line interface that allows creation and restoration of backups.
|
||||
It adds two new commands, ``backup:backup`` and ``backup_restore``.
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
$ octoprint plugins backup:backup --help
|
||||
Initializing settings & plugin subsystem...
|
||||
Usage: octoprint plugins backup:backup [OPTIONS]
|
||||
|
||||
Creates a new backup.
|
||||
|
||||
Options:
|
||||
--exclude TEXT Identifiers of data folders to exclude, e.g. 'uploads' to
|
||||
exclude uploads or 'timelapse' to exclude timelapses.
|
||||
--help Show this message and exit.
|
||||
|
||||
$ octoprint plugins backup:restore --help
|
||||
Initializing settings & plugin subsystem...
|
||||
Usage: octoprint plugins backup:restore [OPTIONS] PATH
|
||||
|
||||
Restores an existing backup from the backup zip provided as argument.
|
||||
|
||||
OctoPrint does not need to run for this to proceed.
|
||||
|
||||
Options:
|
||||
--help Show this message and exit.
|
||||
|
||||
.. note::
|
||||
|
||||
The ``backup:backup`` command can be useful in combination with a cronjob to create backups in regular intervals.
|
||||
|
||||
.. _sec-bundledplugins-backup-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Backup plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/backup``.
|
||||
|
||||
.. [#] Note that only those plugins that are available on `OctoPrint's official plugin repository <https://plugins.octoprint.org>`_
|
||||
can be automatically restored. If you have plugins installed that are not available on there you'll get their
|
||||
names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them.
|
||||
@@ -1,130 +0,0 @@
|
||||
.. _sec-bundledplugins-cura:
|
||||
|
||||
Cura
|
||||
====
|
||||
|
||||
The Cura Plugin allows slicing of STL files uploaded to OctoPrint directly via
|
||||
the `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_ **up to and
|
||||
including version 15.04.x** and supersedes the slicing support integrated into
|
||||
OctoPrint so far. It comes bundled with OctoPrint starting with version 1.2.0.
|
||||
|
||||
.. note::
|
||||
|
||||
Versions of CuraEngine later than 15.04.x have changed their calling
|
||||
parameters in such a way that the current implementation of OctoPrint's Cura plugin
|
||||
is not compatible to it. For this reason, please use only CuraEngine versions up to
|
||||
and including 15.04 for now, as available in the ``legacy`` branch of the CuraEngine
|
||||
repository on Github.
|
||||
|
||||
The plugin offers a settings module that allows configuring the path to the
|
||||
CuraEngine executable to use, as well as importing and managing slicing
|
||||
profiles to be used. Please note that the Cura Plugin will use the printer
|
||||
parameters you configured within OctoPrint (meaning bed size and extruder
|
||||
count and offsets) for slicing.
|
||||
|
||||
.. _sec-bundledplugins-cura-firststeps:
|
||||
|
||||
First Steps
|
||||
-----------
|
||||
|
||||
Before you can slice from within OctoPrint, you'll need to
|
||||
|
||||
#. :ref:`Install CuraEngine <sec-bundledplugins-cura-installing>`
|
||||
#. :ref:`Configure the path to CuraEngine within OctoPrint <sec-bundledplugins-cura-configuring>`
|
||||
#. :ref:`Export a slicing profile from Cura and import it within OctoPrint <sec-bundledplugins-cura-profiles>`
|
||||
|
||||
.. note::
|
||||
|
||||
OctoPi 0.12.0 and later ships with steps 1 and 2 already done, you only need to
|
||||
supply one or more slicing profiles to get going :)
|
||||
|
||||
.. _sec-bundledplugins-cura-installing:
|
||||
|
||||
Installing CuraEngine
|
||||
---------------------
|
||||
|
||||
You'll need a build of ``legacy`` branch of `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_
|
||||
in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch
|
||||
`here <https://github.com/ultimaker/curaengine/tree/legacy>`__.
|
||||
|
||||
If you previously used the `old variant of the Cura integration <https://github.com/foosel/OctoPrint/wiki/Cura-Integration>`_,
|
||||
you probably still have a fully functional binary lying around in the
|
||||
installation folder of the full install of Cura you used then -- just put the
|
||||
path to that in the plugin settings.
|
||||
|
||||
.. _sec-bundledplugins-cura-installing-raspbian:
|
||||
|
||||
Compiling for Raspbian
|
||||
++++++++++++++++++++++
|
||||
|
||||
Raspbian Jessie and later
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Building on Raspbian Jessie and later is as easy as::
|
||||
|
||||
sudo apt-get -y install gcc-4.7 g++-4.7
|
||||
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
|
||||
cd CuraEngine
|
||||
make
|
||||
|
||||
After this has completed, you'll find your shiny new build of CuraEngine in
|
||||
the `build` folder (full path for above example:
|
||||
``~/CuraEngine/build/CuraEngine``).
|
||||
|
||||
Raspbian Wheezy
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
You'll need to install a new version of gcc and g++ and patch CuraEngine's
|
||||
Makefile (see `this post <http://umforum.ultimaker.com/index.php?/topic/5943-recent-build-of-curaengine-wont-compile-on-raspberry-pi/#entry58539>`_)
|
||||
in order for the compilation to work on current Raspbian builds (e.g. OctoPi)::
|
||||
|
||||
sudo apt-get -y install gcc-4.7 g++-4.7
|
||||
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
|
||||
cd CuraEngine
|
||||
wget http://bit.ly/curaengine_makefile_patch -O CuraEngine.patch
|
||||
patch < CuraEngine.patch
|
||||
make CXX=g++-4.7
|
||||
|
||||
After this has completed, you'll find your shiny new build of CuraEngine in
|
||||
the `build` folder (full path for above example:
|
||||
``~/CuraEngine/build/CuraEngine``).
|
||||
|
||||
.. _sec-bundledplugins-cura-configuring:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The Cura plugin needs to be configured with the full path to your copy of the
|
||||
CuraEngine executable that it's supposed to use. You can do this either via
|
||||
the Cura plugin settings dialog or by manually configuring the path to the
|
||||
executable via ``config.yaml``, example:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
plugins:
|
||||
cura:
|
||||
cura_engine: /path/to/CuraEngine
|
||||
|
||||
.. _sec-bundledplugins-cura-profiles:
|
||||
|
||||
Using Cura Profiles
|
||||
-------------------
|
||||
|
||||
The Cura Plugin supports importing your existing profiles for Cura **up to and
|
||||
including Cura 15.04.x**. Newer Cura releases (e.g. 15.06 or 2.x) use a different
|
||||
internal format that will *not* work with the current version of the Cura Plugin.
|
||||
|
||||
You can find downloads of Cura 15.04.x for Windows, Mac and Linux `on Ultimaker's download page <https://ultimaker.com/en/products/cura-software/list>`_.
|
||||
|
||||
In order to export a slicing profile from the Cura desktop UI, open it,
|
||||
set up your profile, then click on "File" and there on "Save Profile". You can
|
||||
import the .ini-file this creates via the "Import Profile" button in the
|
||||
Cura Settings within OctoPrint.
|
||||
|
||||
.. _sec-bundledplugins-cura-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Cura plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/cura``.
|
||||
@@ -0,0 +1,40 @@
|
||||
.. _sec-bundledplugins-errortracking:
|
||||
|
||||
Error Tracking Plugin
|
||||
=====================
|
||||
|
||||
The Error Tracking plugin will cause any logged exceptions in the server and the browser interface to be sent to
|
||||
OctoPrint's `Sentry instance <https://sentry.io/>`_.
|
||||
|
||||
By enabling it you help to gather detailed information on the cause of bugs or other issues. This is especially
|
||||
valuable on release candidates, which is why this plugin will also prompt you to enable error tracking if it detects
|
||||
that you are subscribed to an RC release channel.
|
||||
|
||||
By default, even when enabled it will only be active if you are running a released OctoPrint version, so either a stable
|
||||
release or a release candidate.
|
||||
|
||||
The Error Tracking plugin is using a Sentry instance kindly provided by `sentry.io <https://sentry.io/>`_. For information on their service
|
||||
please refer to their `Security & Compliance documentation <https://sentry.io/security/>`_
|
||||
and their `Privacy Policy <https://sentry.io/privacy/>`_.
|
||||
|
||||
The Error Tracking plugin has been bundled with OctoPrint since version 1.3.11.
|
||||
|
||||
.. _sec-bundledplugins-errortracking-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin supports the following configuration keys:
|
||||
|
||||
* ``enabled``: Whether to enable error tracking. Defaults to ``false``.
|
||||
* ``enabled_unreleased``: Whether to also enable tracking on unreleased OctoPrint versions (anything not stable releases
|
||||
or release candidates). Defaults to ``false``.
|
||||
* ``unique_id``: Unique instance identifier, auto generated on first activation
|
||||
|
||||
.. _sec-bundledplugins-errortracking-sourcecode:
|
||||
|
||||
Source Code
|
||||
-----------
|
||||
|
||||
The source of the Error Tracking plugin is bundled with OctoPrint and can be
|
||||
found in its source repository under ``src/octoprint/plugins/errortracking``.
|
||||
@@ -0,0 +1,35 @@
|
||||
.. _sec-bundledplugins-forcelogin:
|
||||
|
||||
ForceLogin Plugin
|
||||
=================
|
||||
|
||||
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
|
||||
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
|
||||
instead forces users to log in if they want to get any kind of information from OctoPrint.
|
||||
|
||||
.. _fig-bundledplugins-forcelogin:
|
||||
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
|
||||
:align: center
|
||||
:alt: Forced login dialog
|
||||
|
||||
OctoPrint's new forced login dialog.
|
||||
|
||||
.. warning::
|
||||
|
||||
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
|
||||
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
|
||||
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
|
||||
is not OctoPrint itself.
|
||||
|
||||
.. note::
|
||||
|
||||
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
|
||||
the ForceLogin Plugin in OctoPrint's plugin manager.
|
||||
|
||||
.. _sec-bundledplugins-forcelogin-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/forcelogin``.
|
||||
@@ -8,8 +8,13 @@ Bundled Plugins
|
||||
:maxdepth: 2
|
||||
|
||||
action_command_prompt.rst
|
||||
cura.rst
|
||||
announcements.rst
|
||||
tracking.rst
|
||||
appkeys.rst
|
||||
backup.rst
|
||||
discovery.rst
|
||||
errortracking.rst
|
||||
forcelogin.rst
|
||||
logging.rst
|
||||
pluginmanager.rst
|
||||
printer_safety_check.rst
|
||||
|
||||
@@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
|
||||
- hidden
|
||||
- plugins
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-events:
|
||||
|
||||
Events
|
||||
------
|
||||
|
||||
plugin_pluginmanager_install_plugin
|
||||
A plugin was installed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``id``: the identifier of the installed plugin
|
||||
* ``version``: the version of the installed plugin
|
||||
* ``source``: source from which the plugin was installed, can be an URL or a path in the local file system
|
||||
* ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path``
|
||||
|
||||
plugin_pluginmanager_uninstall_plugin
|
||||
A plugin was uninstalled.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``id``: the identifier of the uninstalled plugin
|
||||
* ``version``: the version of the uninstalled plugin
|
||||
|
||||
plugin_pluginmanager_enable_plugin
|
||||
A plugin was enabled.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``id``: the identifier of the enabled plugin
|
||||
* ``version``: the version of the enabled plugin
|
||||
|
||||
plugin_pluginmanager_disabled_plugin
|
||||
A plugin was disabled.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``id``: the identifier of the disabled plugin
|
||||
* ``version``: the version of the disabled plugin
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-hooks:
|
||||
|
||||
Hooks
|
||||
|
||||
@@ -16,17 +16,12 @@ such identification.
|
||||
|
||||
An example of a warning generated by the Printer Safety Check
|
||||
|
||||
Currently the following firmwares produce this warning:
|
||||
|
||||
* Anet A8 stock firmware
|
||||
Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
for a list of currently identified printers.
|
||||
|
||||
If you know of further printers/printer firmwares that need to be added here, please
|
||||
`get in touch on the forum and provide their response to an M115 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
|
||||
.. note::
|
||||
|
||||
Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
|
||||
@@ -34,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl
|
||||
unexpectedly and with `catastrophic <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
|
||||
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
|
||||
|
||||
.. _sec-bundledplugins-printer_safety_check-events:
|
||||
|
||||
Events
|
||||
------
|
||||
|
||||
warning
|
||||
A printer safety warning was triggered.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``)
|
||||
* ``check_name``: name of check that was triggered (e.g. ``aneta8``)
|
||||
* ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``)
|
||||
|
||||
.. _sec-bundledplugins-printer_safety_check-source:
|
||||
|
||||
Source Code
|
||||
|
||||
@@ -325,6 +325,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing
|
||||
branch: devel
|
||||
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-events:
|
||||
|
||||
Events
|
||||
------
|
||||
|
||||
plugin_softwareupdate_update_succeeded
|
||||
An update succeeded.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``target``: update target
|
||||
* ``from_version``: version from which was updated
|
||||
* ``to_version``: version to which was updated
|
||||
|
||||
plugin_softwareupdate_update_failed
|
||||
An update failed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``target``: update target
|
||||
* ``from_version``: version from which was updated
|
||||
* ``to_version``: version to which was updated
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-hooks:
|
||||
|
||||
Hooks
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
.. _sec-bundledplugins-tracking:
|
||||
|
||||
Anonymous Usage Tracking Plugin
|
||||
===============================
|
||||
|
||||
The Anonymous Usage Tracking plugin provides valuable insights into how many instances running what versions of
|
||||
OctoPrint are out there, whether they are successfully completing print jobs and various other metrics.
|
||||
|
||||
By enabling it you help to identify problems with new releases and release candidates early on, and to better tailor
|
||||
OctoPrint's future development to actual use.
|
||||
|
||||
For details on what gets tracked, please refer to `tracking.octoprint.org <https://tracking.octoprint.org>`_
|
||||
and also the `Privacy Policy at tracking.octoprint.org <https://tracking.octoprint.org/privacy>`_.
|
||||
|
||||
The Anonymous Usage Tracking plugin has been bundled with OctoPrint since version 1.3.10.
|
||||
|
||||
.. _sec-bundledplugins-tracking-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin supports the following configuration keys:
|
||||
|
||||
* ``enabled``: Whether to enable usage tracking. Defaults to ``false``.
|
||||
* ``unique_id``: Unique instance identifier, auto generated on first activation
|
||||
* ``server``: The tracking server to track against. Defaults to a tracking endpoint on ``https://tracking.octoprint.org``.
|
||||
* ``ping``: How often to send a ``ping`` tracking event, in seconds. Defaults to a 15min interval.
|
||||
* ``events``: Granular configuration of enabled tracking events. All default to ``true``.
|
||||
|
||||
* ``startup``: Whether to track startup/shutdown events
|
||||
* ``printjob``: Whether to track print job related events (start, completion, cancel, ...)
|
||||
* ``commerror``: Whether to track communication errors with the printer
|
||||
* ``plugin``: Whether to track plugin related events (install, uninstall, ...)
|
||||
* ``update``: Whether to track update related events (update successful or not, ...)
|
||||
* ``printer``: Whether to track printer related events (connected, firmware, ...)
|
||||
* ``printer_safety_check``: Whether to track warnings of the :ref:`Printer Safety Check <sec-bundledplugins-printer_safety_check>`
|
||||
* ``throttled``: Whether to track throttle events detected on the underlying system
|
||||
|
||||
.. _sec-bundledplugins-tracking-sourcecode:
|
||||
|
||||
Source Code
|
||||
-----------
|
||||
|
||||
The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be
|
||||
found in its source repository under ``src/octoprint/plugins/tracking``.
|
||||
@@ -62,6 +62,18 @@ Use the following settings to enable access control:
|
||||
# header and login the user without further checks. Use with caution.
|
||||
checkBasicAuthenticationPassword: true
|
||||
|
||||
# Whether to trust remote user headers. If you have setup authentication in front of
|
||||
# OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will
|
||||
# be logged into OctoPrint as the user provided in the header. Your should ONLY ENABLE THIS if your
|
||||
# OctoPrint instance is only accessible through a connection locked down through an authenticating reverse proxy!
|
||||
trustRemoteUser: false
|
||||
|
||||
# Header used by the reverse proxy to convey the authenticated user.
|
||||
remoteUserHeader: REMOTE_USER
|
||||
|
||||
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
|
||||
addRemoteUsers: false
|
||||
|
||||
.. _sec-configuration-config_yaml-api:
|
||||
|
||||
API
|
||||
@@ -81,7 +93,8 @@ Settings for the REST API:
|
||||
# Whether to allow cross origin access to the API or not
|
||||
allowCrossOrigin: false
|
||||
|
||||
# Additional app api keys, see REST API > Apps in the docs
|
||||
# Additional app api keys, see REST API > Apps in the docs.
|
||||
# Deprecated since 1.3.11, to be removed in 1.4.0!
|
||||
apps:
|
||||
"some.app.identifier:some_version":
|
||||
pubkey: <RSA pubkey>
|
||||
@@ -322,6 +335,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# Whether the simulated printer should also simulate a heated bed or not
|
||||
hasBed: true
|
||||
|
||||
# Whether the simulated printer should also simulate a heated chamber or not
|
||||
hasChamber: false
|
||||
|
||||
# If enabled, reports the set target temperatures as separate messages from the firmware
|
||||
#
|
||||
# True: > M109 S220.0
|
||||
@@ -409,8 +425,7 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# Lines to send on simulated reset
|
||||
resetLines:
|
||||
- start
|
||||
- Marlin: Virtual Marlin!
|
||||
- "\x80"
|
||||
- "Marlin: Virtual Marlin!"
|
||||
- "SD card ok"
|
||||
|
||||
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
|
||||
@@ -562,6 +577,9 @@ Use the following settings to enable or disable OctoPrint features:
|
||||
- M117
|
||||
- M118
|
||||
|
||||
# whether G90/G91 also influence absolute/relative mode of extruders
|
||||
g90InfluencesExtruder: false
|
||||
|
||||
.. _sec-configuration-config_yaml-folder:
|
||||
|
||||
Folder
|
||||
@@ -806,6 +824,19 @@ Use the following settings to configure the serial connection to the printer:
|
||||
additionalBaudrates:
|
||||
- 123456
|
||||
|
||||
# Commands which should not be sent to the printer, e.g. because they are known to block serial
|
||||
# communication until physical interaction with the printer as is the case on most firmwares with
|
||||
# the default M0 and M1.
|
||||
blockedCommands:
|
||||
- M0
|
||||
- M1
|
||||
|
||||
# Commands which should cause OctoPrint to pause any ongoing prints.
|
||||
pausingCommands:
|
||||
- M0
|
||||
- M1
|
||||
- M25
|
||||
|
||||
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
|
||||
# homing, dwelling, auto leveling etc. Defaults to the below commands.
|
||||
longRunningCommands:
|
||||
@@ -932,6 +963,13 @@ Use the following settings to configure the server:
|
||||
# reset the setting to false
|
||||
startOnceInSafeMode: false
|
||||
|
||||
# Signals to OctoPrint that the last startup was incomplete. OctoPrint will then startup
|
||||
# in safe mode
|
||||
incompleteStartup: false
|
||||
|
||||
# Set this to true to make OctoPrint ignore incomplete startups. Helpful for development.
|
||||
ignoreIncompleteStartup: false
|
||||
|
||||
# Secret key for encrypting cookies and such, randomly generated on first run
|
||||
secretKey: someSecretKey
|
||||
|
||||
@@ -1058,6 +1096,15 @@ Use the following settings to configure the server:
|
||||
# How many days to leave unused entries in the preemptive cache config
|
||||
until: 7
|
||||
|
||||
# Configuration of the client IP check to warn about connections from external networks
|
||||
ipCheck:
|
||||
|
||||
# whether to enable the check, defaults to true
|
||||
enabled: true
|
||||
|
||||
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
|
||||
trustedSubnets: []
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -1087,14 +1134,14 @@ Settings for the built-in slicing support:
|
||||
slicing:
|
||||
|
||||
# Whether to enable slicing support or not
|
||||
enabled:
|
||||
enabled: true
|
||||
|
||||
# Default slicer to use
|
||||
defaultSlicer: cura
|
||||
defaultSlicer: null
|
||||
|
||||
# Default slicing profiles per slicer
|
||||
defaultProfiles:
|
||||
cura: ...
|
||||
curalegacy: ...
|
||||
|
||||
.. _sec-configuration-config_yaml-system:
|
||||
|
||||
@@ -1165,7 +1212,7 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
|
||||
# A list of filters to display in the terminal tab. Defaults to the filters shown below
|
||||
terminalFilters:
|
||||
- name: Suppress temperature messages
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv: ok T:)'
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)'
|
||||
- name: Suppress SD status messages
|
||||
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
|
||||
- name: Suppress wait responses
|
||||
|
||||
@@ -39,8 +39,8 @@ A list of important components for which an increase in logging might be interes
|
||||
* ``octoprint.filemanager``: the file management layer
|
||||
* ``octoprint.plugin``: the plugin sub system
|
||||
* ``octoprint.plugins.<plugin>``: the plugin ``<plugin>``, e.g. ``octoprint.plugins.discovery`` to change the log level of
|
||||
the `Discovery plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_ or ``octoprint.plugins.cura``
|
||||
to change the log level of the `Cura plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_.
|
||||
the :ref:`Discovery plugin <sec-bundledplugins-discovery>` or ``octoprint.plugins.backup``
|
||||
to change the log level of the :ref:`Backup plugin <sec-bundledplugins-backup>`.
|
||||
* ``octoprint.slicing``: the slicing sub system
|
||||
|
||||
This list will be expanded when deemed necessary.
|
||||
|
||||
@@ -6,15 +6,6 @@ Events
|
||||
|
||||
.. contents::
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
|
||||
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
|
||||
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
|
||||
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
|
||||
to indicate what to do with the command contained.
|
||||
|
||||
.. _sec-events-configuration:
|
||||
|
||||
Configuration
|
||||
@@ -47,6 +38,13 @@ Example
|
||||
- event: PrintDone
|
||||
command: python ~/growl.py -t mygrowlserver -d "Completed {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event:
|
||||
- PrintStarted
|
||||
- PrintFailed
|
||||
- PrintDone
|
||||
- PrintCancelled
|
||||
command: python ~/growl.py -t mygrowlserver -d "Event {__eventname} ({name})" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event: Connected
|
||||
command:
|
||||
- M115
|
||||
@@ -62,6 +60,7 @@ Placeholders
|
||||
You can use the following generic placeholders in your event hooks:
|
||||
|
||||
* ``{__currentZ}``: the current Z position of the head if known, -1 if not available
|
||||
* ``{__eventname}`` : the name of the event hook being triggered
|
||||
* ``{__filename}`` : name of currently selected file, or ``NO FILE`` if no file is selected
|
||||
* ``{__filepath}`` : path in origin location of currently selected file, or ``NO FILE`` if no file is selected
|
||||
* ``{__fileorigin}`` : origin of currently selected file, or ``NO FILE`` if no file is selected
|
||||
@@ -85,6 +84,12 @@ and its origin via the placeholder ``{origin}``.
|
||||
Available Events
|
||||
================
|
||||
|
||||
.. note::
|
||||
|
||||
Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook <sec-plugins-hook-events-register_custom_events>`.
|
||||
|
||||
.. _sec-events-available_events-server:
|
||||
|
||||
Server
|
||||
------
|
||||
|
||||
@@ -118,6 +123,8 @@ ConnectivityChanged
|
||||
* ``old``: Old connectivity value (true for online, false for offline)
|
||||
* ``new``: New connectivity value (true for online, false for offline)
|
||||
|
||||
.. _sec-events-available_events-printer_commmunication:
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
@@ -141,7 +148,8 @@ Disconnected
|
||||
The server has disconnected from the printer
|
||||
|
||||
Error
|
||||
An error has occurred in the printer communication.
|
||||
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
|
||||
on the connection.
|
||||
|
||||
Payload:
|
||||
|
||||
@@ -156,6 +164,8 @@ PrinterStateChanged
|
||||
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
|
||||
* ``state_string``: Text representation of the new state.
|
||||
|
||||
.. _sec-events-available_events-file_handling:
|
||||
|
||||
File handling
|
||||
-------------
|
||||
|
||||
@@ -169,9 +179,7 @@ Upload
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's path within its storage location
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||
|
||||
FileAdded
|
||||
A file has been added to a storage.
|
||||
@@ -253,9 +261,7 @@ MetadataAnalysisStarted
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's path within its storage location
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||
|
||||
MetadataAnalysisFinished
|
||||
The metadata analysis of a file has finished.
|
||||
@@ -269,9 +275,7 @@ MetadataAnalysisFinished
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's path within its storage location
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
|
||||
|
||||
FileSelected
|
||||
A file has been selected for printing.
|
||||
@@ -284,10 +288,8 @@ FileSelected
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
|
||||
FileDeselected
|
||||
No file is selected any more for printing.
|
||||
@@ -311,6 +313,8 @@ TransferDone
|
||||
* ``local``: the file's name as stored locally
|
||||
* ``remote``: the file's name as stored on SD
|
||||
|
||||
.. _sec-events-available_events-printing:
|
||||
|
||||
Printing
|
||||
--------
|
||||
|
||||
@@ -322,13 +326,14 @@ PrintStarted
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``user``: the user who started the print job (if available)
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
|
||||
PrintFailed
|
||||
A print failed.
|
||||
@@ -338,13 +343,15 @@ PrintFailed
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``time``: the elapsed time of the print when it failed, in seconds (float)
|
||||
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
|
||||
PrintDone
|
||||
A print completed successfully.
|
||||
@@ -354,14 +361,14 @@ PrintDone
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``time``: the time needed for the print, in seconds (float)
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
|
||||
PrintCancelling
|
||||
The print is about to be cancelled.
|
||||
@@ -371,6 +378,9 @@ PrintCancelling
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``user``: the user who cancelled the print job (if available)
|
||||
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
|
||||
|
||||
PrintCancelled
|
||||
@@ -381,7 +391,12 @@ PrintCancelled
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``position``: the print head position at the time of cancelling, if available
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``time``: the elapsed time of the print when it was cancelled, in seconds (float)
|
||||
* ``user``: the user who cancelled the print job (if available)
|
||||
* ``position``: the print head position at the time of cancelling (if available, not available if recording of the
|
||||
position on cancel is disabled)
|
||||
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
|
||||
@@ -395,10 +410,8 @@ PrintCancelled
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
|
||||
PrintPaused
|
||||
The print has been paused.
|
||||
@@ -408,7 +421,11 @@ PrintPaused
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``position``: the print head position at the time of pausing, if available
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``user``: the user who paused the print job (if available)
|
||||
* ``position``: the print head position at the time of pausing (if available, not available if the recording of
|
||||
the position on pause is disabled or the pause is completely handled by the printer's firmware)
|
||||
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
|
||||
@@ -422,10 +439,8 @@ PrintPaused
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
|
||||
PrintResumed
|
||||
The print has been resumed.
|
||||
@@ -435,13 +450,16 @@ PrintResumed
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``size``: the file's size in bytes (if available)
|
||||
* ``owner``: the user who started the print job (if available)
|
||||
* ``user``: the user who resumed the print job (if available)
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
|
||||
* ``filename``: the file's name
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
.. _sec-events-available_events-gcode_processing:
|
||||
|
||||
GCODE processing
|
||||
----------------
|
||||
@@ -504,6 +522,8 @@ ToolChange
|
||||
* ``old``: old tool index
|
||||
* ``new``: new tool index
|
||||
|
||||
.. _sec-events-available_events-timelapses:
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
@@ -558,6 +578,8 @@ MovieFailed
|
||||
returned a non-0 return code, ``no_frames`` if no frames were captured that could be rendered
|
||||
to a timelapse, or ``unknown`` for any other reason of failure to render.
|
||||
|
||||
.. _sec-events-available_events-slicing:
|
||||
|
||||
Slicing
|
||||
-------
|
||||
|
||||
@@ -566,6 +588,7 @@ SlicingStarted
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -577,6 +600,7 @@ SlicingDone
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -589,6 +613,7 @@ SlicingCancelled
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -599,6 +624,7 @@ SlicingFailed
|
||||
|
||||
Payload:
|
||||
|
||||
* ``slicer``: the used slicer
|
||||
* ``stl``: the STL's filename
|
||||
* ``stl_location``: the STL's location
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
@@ -614,7 +640,7 @@ SlicingProfileAdded
|
||||
* ``profile``: the profile that was added
|
||||
|
||||
SlicingProfileModified
|
||||
A new slicing profile was modified.
|
||||
A slicing profile was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
@@ -629,8 +655,25 @@ SlicingProfileDeleted
|
||||
* ``slicer``: the slicer for which the profile was deleted
|
||||
* ``profile``: the profile that was deleted
|
||||
|
||||
.. _sec-events-available_events-settings:
|
||||
|
||||
Settings
|
||||
--------
|
||||
|
||||
SettingsUpdated
|
||||
The internal settings were updated.
|
||||
The settings were updated via the REST API.
|
||||
|
||||
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
|
||||
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
|
||||
|
||||
.. _sec-events-available_events-printer_profile:
|
||||
|
||||
Printer Profile
|
||||
--------
|
||||
|
||||
PrinterProfileModified
|
||||
A printer profile was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``identifier``: the identifier of the modified printer profile
|
||||
@@ -21,17 +21,23 @@ Commands, which are admin-only.
|
||||
|
||||
If Access Control is disabled, everything is directly accessible. **That also
|
||||
includes all administrative functionality as well as full control over the
|
||||
printer!**
|
||||
printer**, and without the need for an :ref:`API key <sec-api-general-authorization>`!
|
||||
|
||||
Upon first start a configuration wizard is provided which allows configuration
|
||||
of the first administrator account or alternatively disabling Access Control
|
||||
(which is **NOT** recommended for systems that are directly accessible via the
|
||||
Internet!).
|
||||
internet or other untrusted networks!).
|
||||
|
||||
.. hint::
|
||||
|
||||
If you plan to have your OctoPrint instance accessible over the internet,
|
||||
**always enable Access Control**.
|
||||
**always enable Access Control** and ideally **don't make it accessible to
|
||||
everyone over the internet but instead use a VPN** or at the very least
|
||||
HTTP basic authentication on a layer above OctoPrint.
|
||||
|
||||
A physical device that includes heaters and stepper motors really should not be
|
||||
publicly reachable by everyone with an internet connection, even with access
|
||||
control enabled.
|
||||
|
||||
.. _sec-features-access_control-rerunning_wizard:
|
||||
|
||||
|
||||
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
|
||||
.. code-block:: jinja
|
||||
:caption: Default ``disable_hotends`` snippet
|
||||
|
||||
{% if printer_profile.extruder.sharedNozzle %}
|
||||
M104 T0 S0
|
||||
{% else %}
|
||||
{% for tool in range(printer_profile.extruder.count) %}
|
||||
M104 T{{ tool }} S0
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
The ``disable_bed`` snippet is defined as follows:
|
||||
|
||||
|
||||
@@ -5,19 +5,20 @@ Safe mode
|
||||
*********
|
||||
|
||||
With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs
|
||||
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins instead of
|
||||
OctoPrint itself.
|
||||
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language
|
||||
packs instead of OctoPrint itself.
|
||||
|
||||
To allow an easier identification of these cases, OctoPrint 1.3.0 introduced safe mode. Starting
|
||||
OctoPrint in safe mode disables all plugins that are not bundled with OctoPrint, allowing to easier
|
||||
identify most cases where a third party plugin is the culprit of an observed issue.
|
||||
OctoPrint in safe mode disables all plugins (and starting with 1.3.13 also all language packs) that are
|
||||
not bundled with OctoPrint, allowing to easier identify most cases where a third party plugin or language
|
||||
pack is the culprit of an observed issue.
|
||||
|
||||
Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recovery from cases where
|
||||
a third party plugin causes the server to not start up or the web interface to not render or function
|
||||
correctly anymore.
|
||||
Additionally, OctoPrint allows uninstalling plugins and language packs in this mode, allowing recovery
|
||||
from cases where a third party addition causes the server to not start up or the web interface to not
|
||||
render or function correctly anymore.
|
||||
|
||||
Whenever reporting an issue with OctoPrint, please always attempt to reproduce it in safe mode as well to
|
||||
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party plugins.
|
||||
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party additions.
|
||||
|
||||
.. _sec-features-safemode-how:
|
||||
|
||||
@@ -73,11 +74,17 @@ 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`` (Windows) and
|
||||
``~/Library/Application Support/OctoPrint`` (MacOS).
|
||||
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint/plugins`` (Windows) and
|
||||
``~/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).
|
||||
* 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.
|
||||
* OctoPrint will still allow to manage language packs.
|
||||
* OctoPrint's web interface will display a notification to remind you that it is running in
|
||||
safe mode.
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 58 KiB |
@@ -11,7 +11,7 @@ and released under the `GNU Affero General Public License V3 <http://www.gnu.org
|
||||
|
||||
Its website can be found at `octoprint.org <https://octoprint.org/>`_.
|
||||
|
||||
The community forum is available at `discourse.octoprint.org <https://discourse.octoprint.org/>`_.
|
||||
The community forum is available at `community.octoprint.org <https://community.octoprint.org/>`_.
|
||||
|
||||
The FAQ can be accessed by following `faq.octoprint.org <https://faq.octoprint.org/>`_.
|
||||
|
||||
@@ -23,7 +23,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!
|
||||
.. note::
|
||||
|
||||
This documentation currently focuses primarily on developers and less on end users. If you are interested in
|
||||
helping to change this, please get in touch `on the forum <https://discourse.octoprint.org/>`_!
|
||||
helping to change this, please get in touch `on the forum <https://community.octoprint.org/>`_!
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
@@ -80,9 +80,13 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s
|
||||
|
||||
.. seealso::
|
||||
|
||||
`OctoPrint-ForceLogin <https://github.com/OctoPrint/OctoPrint-ForceLogin>`_
|
||||
A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the
|
||||
client library's :ref:`browser component <sec-jsclientlib-browser>` to login the user.
|
||||
:ref:`Application Key Plugin <sec-bundledplugins-appkeys>`
|
||||
A bundled plugin that implements an authorization workflow for third party clients. It adds various additional
|
||||
methods to the JS Client Library.
|
||||
:ref:`ForceLogin Plugin <sec-bundledplugins-forcelogin>`
|
||||
A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and
|
||||
various hooks. Utilizes the client library's :ref:`browser component <sec-jsclientlib-browser>` to login the
|
||||
user.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
|
||||
@@ -210,6 +210,64 @@
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.getChamberState(data, opts)
|
||||
|
||||
Retrieves the current printer chamber state/temperature information, and optionally also the temperature
|
||||
history.
|
||||
|
||||
The ``flags`` object can be used to specify the data to retrieve further via the following
|
||||
properties:
|
||||
|
||||
* ``history``: a boolean value to specify whether the temperature history should be included (``true``)
|
||||
or not (``false``), defaults to it not being included
|
||||
* ``limit``: an integer value to specify how many history entries to include
|
||||
|
||||
See :ref:`Retrieve the current bed state <sec-api-printer-chamberstate>` for more details.
|
||||
|
||||
:param object flags: Flags that further specify which data to retrieve, see above for details
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.setChamberTargetTemperature(target, opts)
|
||||
|
||||
Sets the given temperature on the printer's heated chamber (if available).
|
||||
|
||||
``target`` is expected to be the target temperature as a float value.
|
||||
|
||||
**Example:**
|
||||
|
||||
Set the chamber to 50°C.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.printer.setChamberTargetTemperature(50.0);
|
||||
|
||||
See the ``target`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
|
||||
|
||||
:param float target: The target to set
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.setChamberTemperatureOffset(offset, opts)
|
||||
|
||||
Sets the given temperature offset for the printer's heated chamber (if available).
|
||||
|
||||
``offset`` is expected to be the temperature offset to set.
|
||||
|
||||
**Example:**
|
||||
|
||||
Set the offset for the chamber to -5°C.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.printer.setChamberTemperatureOffset(-5);
|
||||
|
||||
See the ``offset`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
|
||||
|
||||
:param object offsets: The offsets to set
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.jog(amounts, opts)
|
||||
|
||||
Jogs the specified axes by the specified ``amounts``.
|
||||
|
||||
@@ -6,4 +6,10 @@ octoprint.util
|
||||
.. automodule:: octoprint.util
|
||||
:members:
|
||||
|
||||
.. _sec-modules-util-commandline:
|
||||
|
||||
octoprint.util.commandline
|
||||
--------------------------
|
||||
|
||||
.. automodule:: octoprint.util.commandline
|
||||
:members:
|
||||
@@ -3,7 +3,7 @@
|
||||
Helpers
|
||||
=======
|
||||
|
||||
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
|
||||
Helpers are methods that plugins can expose to other plugins in order to make common functionality available on the
|
||||
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
|
||||
|
||||
An example for providing some helper functions to the system can be found in the
|
||||
|
||||
@@ -208,6 +208,10 @@ octoprint.accesscontrol.appkey
|
||||
|
||||
.. py:function:: acl_appkey_hook(*args, **kwargs)
|
||||
|
||||
.. 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.
|
||||
|
||||
By handling this hook plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
|
||||
within the system.
|
||||
|
||||
@@ -380,10 +384,10 @@ octoprint.cli.commands
|
||||
OctoPrint's CLI.
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-comm-firmware-info:
|
||||
.. _sec-plugins-hook-comm-protocol-firmware-info:
|
||||
|
||||
octoprint.comm.firmware.info
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
octoprint.comm.protocol.firmware.info
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs)
|
||||
|
||||
@@ -402,14 +406,21 @@ octoprint.comm.firmware.info
|
||||
|
||||
``firmware_name`` will be ``Some Firmware Name`` in this case.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str firmware_name: The name of the parsed capability
|
||||
:param dict firmware_data: All data contained in the ``M115`` report
|
||||
|
||||
.. _sec-plugins-hook-comm-firmware-capabilities:
|
||||
.. _sec-plugins-hook-comm-protocol-firmware-capabilities:
|
||||
|
||||
octoprint.comm.firmware.capabilities
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
octoprint.comm.firmware.protocol.capabilities
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs)
|
||||
|
||||
@@ -421,6 +432,13 @@ octoprint.comm.firmware.capabilities
|
||||
|
||||
Note that hook handlers will be called once per received capability line.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str capability: The name of the parsed capability
|
||||
:param bool enabled: Whether the capability is reported as enabled or disabled
|
||||
@@ -440,6 +458,13 @@ octoprint.comm.protocol.action
|
||||
|
||||
No returned value is expected.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware.
|
||||
@@ -477,6 +502,13 @@ This describes actually two hooks:
|
||||
trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to
|
||||
:ref:`the action command hook <sec-plugins-hook-comm-protocol-action>`.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
|
||||
you will effectively block the send/receive loops, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a
|
||||
@@ -623,6 +655,13 @@ This describes actually four hooks:
|
||||
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
|
||||
to one already in the queue will give an error.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the send loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
The following hook handler replaces all ``M107`` ("Fan Off", deprecated) with an ``M106 S0`` ("Fan On" with speed
|
||||
@@ -658,6 +697,13 @@ octoprint.comm.protocol.gcode.received
|
||||
empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
|
||||
``return`` statement is used or just nothing is returned explicitly from the handler.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Looks for the response of an ``M115``, which contains information about the ``MACHINE_TYPE``, among other things.
|
||||
@@ -687,6 +733,13 @@ octoprint.comm.protocol.gcode.error
|
||||
Plugins might utilize this hook to handle errors generated by the printer that are recoverable in one way or
|
||||
the other and should not trigger the normal handling that assumes the worst.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the
|
||||
@@ -713,9 +766,10 @@ octoprint.comm.protocol.scripts
|
||||
make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match
|
||||
handled scripts. If not, None should be returned directly.
|
||||
|
||||
If the hook handler has something to add to the specified script, it may return a 2-tuple or a 3-tuple with the first entry
|
||||
If the hook handler has something to add to the specified script, it may return a 2-tuple, a 3-tuple or a 4-tuple with the first entry
|
||||
defining the prefix (what to *prepend* to the script in question), the second entry defining the postfix (what to
|
||||
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script. Both prefix and postfix can be None to signify that nothing should be prepended
|
||||
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script on third and additional tags to set on the
|
||||
commands on fourth position. Both prefix and postfix can be None to signify that nothing should be prepended
|
||||
respectively appended.
|
||||
|
||||
The returned prefix and postfix entries may be either iterables of script lines or a string including newlines of the script lines (which
|
||||
@@ -762,6 +816,13 @@ octoprint.comm.protocol.temperatures.received
|
||||
additional sanity checking to be applied and invalid values to be filtered out. If a handler returns an empty
|
||||
dictionary or ``None``, no further processing will take place.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C.
|
||||
@@ -847,6 +908,34 @@ octoprint.comm.transport.serial.factory
|
||||
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
|
||||
optionally ``baudrate`` and ``timeout`` attributes as described above.
|
||||
|
||||
.. _sec-plugins-hook-events-register_custom_events:
|
||||
|
||||
octoprint.events.register_custom_events
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: register_custom_events_hook(*args, **kwargs)
|
||||
|
||||
Return a list of custom :ref:`events <sec-events>` to register in the system for your plugin.
|
||||
|
||||
Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object
|
||||
will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_<IDENTIFIER>``. Their
|
||||
value will be prefixed with ``plugin_<identifier>_``.
|
||||
|
||||
Example:
|
||||
|
||||
Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events
|
||||
in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event``
|
||||
and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``.
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
def register_custom_events(*args, **kwargs):
|
||||
return ["my_custom_event", "my_other_custom_event"]
|
||||
|
||||
:return: A list of custom events to register
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-filemanager-analysis-factory:
|
||||
|
||||
octoprint.filemanager.analysis.factory
|
||||
@@ -1033,6 +1122,139 @@ octoprint.printer.estimation.factory
|
||||
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
|
||||
:rtype: class or function
|
||||
|
||||
.. _sec-plugins-hook-octoprint-printer-sdcardupload:
|
||||
|
||||
octoprint.printer.sdcardupload
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs)
|
||||
|
||||
Via this hook plugins can change the way files are being uploaded to the sd card of the printer.
|
||||
|
||||
Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback``
|
||||
or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not.
|
||||
|
||||
The ``start_callback`` has the following signature:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def start_callback(local_filename, remote_filename):
|
||||
# ...
|
||||
|
||||
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
|
||||
to be created on the ``sdcard`` storage.
|
||||
|
||||
``success_callback`` and ``failure_callback`` both have the following signature:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def success_or_failure_callback(local_filename, remote_filename, elapsed):
|
||||
# ...
|
||||
|
||||
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
|
||||
to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds.
|
||||
|
||||
If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard``
|
||||
storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to
|
||||
handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation
|
||||
will be called.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file
|
||||
is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its
|
||||
own thread, which is important in order to not block the main application!
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import threading
|
||||
import logging
|
||||
import time
|
||||
|
||||
def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
remote_name = printer._get_free_remote_name(filename)
|
||||
logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name))
|
||||
|
||||
sd_upload_started(filename, remote_name)
|
||||
|
||||
def process():
|
||||
logger.info("Sleeping 10s...")
|
||||
time.sleep(10)
|
||||
logger.info("And done!")
|
||||
sd_upload_succeeded(filename, remote_name, 10)
|
||||
|
||||
thread = threading.Thread(target=process)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return remote_name
|
||||
|
||||
__plugin_name__ = "No-op SDCard Upload Test"
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.printer.sdcardupload": nop_upload_to_sd
|
||||
}
|
||||
|
||||
.. versionadded:: 1.3.11
|
||||
|
||||
:param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from
|
||||
:param str filename: filename on the ``local`` storage
|
||||
:param str path: path of the file in the local file system
|
||||
:param function sd_upload_started: callback for when the upload started
|
||||
:param function sd_upload_success: callback for successful finish of upload
|
||||
:param function sd_upload_failure: callback for failure of upload
|
||||
:return: the name of the file on the ``sdcard`` storage or ``None``
|
||||
:rtype: string or ``None``
|
||||
|
||||
.. _sec-plugins-hook-server-http-after_request:
|
||||
|
||||
octoprint.server.api.after_request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: after_request_handlers_hook(*args, **kwargs)
|
||||
|
||||
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
|
||||
|
||||
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-before_request:
|
||||
|
||||
octoprint.server.api.before_request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: after_request_handlers_hook(*args, **kwargs)
|
||||
|
||||
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
|
||||
|
||||
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-access_validator:
|
||||
|
||||
octoprint.server.http.access_validator
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: access_validator_hook(request, *args, **kwargs)
|
||||
|
||||
Allows adding additional access validators to the default tornado routers.
|
||||
|
||||
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled
|
||||
"Force Login" plugin for a usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-bodysize:
|
||||
|
||||
octoprint.server.http.bodysize
|
||||
@@ -1107,6 +1329,14 @@ octoprint.server.http.routes
|
||||
view of the blueprint will thus not be reachable since processing of the request will directly be handed over
|
||||
to your defined handler class.
|
||||
|
||||
.. important::
|
||||
|
||||
If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_
|
||||
needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of
|
||||
:class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`,
|
||||
:class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler`
|
||||
already implement this mixin.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
@@ -1134,6 +1364,85 @@ octoprint.server.http.routes
|
||||
:return: a list of 3-tuples with additional routes as defined above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-authed:
|
||||
|
||||
octoprint.server.sockjs.authed
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
|
||||
|
||||
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-register:
|
||||
|
||||
octoprint.server.sockjs.register
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
|
||||
|
||||
Allows plugins to prevent a new :ref:`push socket client <sec-api-push>` to be registered to the system.
|
||||
|
||||
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
|
||||
signals to not register the client.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:return: whether to proceed with registration (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-emit:
|
||||
|
||||
octoprint.server.sockjs.emit
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
|
||||
|
||||
Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection <sec-api-push>`.
|
||||
|
||||
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object on which a message is about to be emitted
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:param string message: the message type about to be emitted
|
||||
:param dict payload: the payload of the message about to be emitted (may be None)
|
||||
:return: whether to proceed with sending the message (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-timelapse-extensions:
|
||||
|
||||
octoprint.timelapse.extensions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: timelapse_extension_hook(*args, **kwargs)
|
||||
|
||||
Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of
|
||||
additional file extensions.
|
||||
|
||||
**Example**
|
||||
|
||||
Allow the management of timelapse GIFs with extension ``gif``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_timelapse_extensions(*args, **kwargs):
|
||||
return ["gif"]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.timelapse.extensions": get_timelapse_extensions
|
||||
}
|
||||
|
||||
:return: a list of additional file extensions
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-ui-web-templatetypes:
|
||||
|
||||
octoprint.ui.web.templatetypes
|
||||
|
||||
@@ -68,11 +68,14 @@ calls are done is as follows:
|
||||
|
||||
* Plugins with a return value that is not ``None`` for :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`
|
||||
for the provided sorting context will be ordered among each other first. If the returned order number is equal for
|
||||
two or more implementations, the plugin's identifier will be the next sorting criteria.
|
||||
* After that follow plugins which returned ``None`` (the default). They are sorted by their identifier.
|
||||
two or more implementations, they will be sorted first by whether they come bundled with OctoPrint or not, then by
|
||||
their identifier.
|
||||
* After that follow plugins which returned ``None`` (the default). They are first sorted by whether they come bundled
|
||||
with OctoPrint or not, then by their identifier.
|
||||
|
||||
Example: Consider three plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
|
||||
``plugin_a``, ``plugin_b`` and ``plugin_c``. ``plugin_a`` doesn't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
|
||||
Example: Consider four plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
|
||||
``plugin_a``, ``plugin_b``, ``plugin_c`` and ``plugin_d``, the latter coming bundled with OctoPrint. ``plugin_a``
|
||||
and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
|
||||
``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise:
|
||||
|
||||
.. code-block:: python
|
||||
@@ -99,7 +102,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
|
||||
|
||||
class PluginB(octoprint.plugin.StartupPlugin):
|
||||
|
||||
def get_sorting_key(context):
|
||||
def get_sorting_key(self, context):
|
||||
if context == "StartupPlugin.on_startup":
|
||||
return 1
|
||||
return None
|
||||
@@ -120,7 +123,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
|
||||
|
||||
class PluginC(octoprint.plugin.StartupPlugin):
|
||||
|
||||
def get_sorting_key(context):
|
||||
def get_sorting_key(self, context):
|
||||
if context == "StartupPlugin.on_startup":
|
||||
return 1
|
||||
return None
|
||||
@@ -134,13 +137,45 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
|
||||
|
||||
__plugin_implementation__ = PluginC()
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: plugin_d.py
|
||||
|
||||
# in this example this is bundled with OctoPrint
|
||||
import octoprint.plugin
|
||||
|
||||
class PluginD(octoprint.plugin.StartupPlugin):
|
||||
|
||||
def on_startup(self, *args, **kwargs):
|
||||
self._logger.info("PluginD starting up")
|
||||
|
||||
def on_after_startup(self, *args, **kwargs):
|
||||
self._logger.info("PluginD started up")
|
||||
|
||||
__plugin_implementation__ = PluginD()
|
||||
|
||||
OctoPrint will detect that ``plugin_b`` and ``plugin_c`` define a order number, and since it's identical for both (``1``)
|
||||
will order both plugins based on their plugin identifier. ``plugin_a`` doesn't define a sort key and hence will be
|
||||
put after the other two. The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_a``.
|
||||
will order both plugins based first on their bundling status and then on their plugin identifier.
|
||||
``plugin_a`` and ``plugin_d`` don't define a sort key and hence will be
|
||||
put after the other two, with ``plugin_d`` coming *before* ``plugin_a`` since it comes bundled with OctoPrint.
|
||||
The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_d``, ``plugin_a``.
|
||||
|
||||
Now, the execution order of the ``on_after_startup`` method will be determined based on another sorting context,
|
||||
``StartupPlugin.on_after_startup`` for which all of the plugins return ``None``. Hence, the execution order of the
|
||||
``on_after_startup`` method will be purely ordered by plugin identifier, ``plugin_a``, ``plugin_b``, ``plugin_c``.
|
||||
``on_after_startup`` method will be ordered first by bundle status, then by plugin identifier: ``plugin_d``, ``plugin_a``, ``plugin_b``, ``plugin_c``.
|
||||
|
||||
This will result in the following messages to be generated:
|
||||
|
||||
.. code-block:: plain
|
||||
|
||||
Plugin B starting up
|
||||
Plugin C starting up
|
||||
Plugin D starting up
|
||||
Plugin A starting up
|
||||
Plugin D started up
|
||||
Plugin A started up
|
||||
Plugin B started up
|
||||
Plugin C started up
|
||||
|
||||
.. _sec-plugins-mixins-injectedproperties:
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# init/systemd files for OctoPrint.
|
||||
|
||||
Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different
|
||||
setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly.
|
||||
|
||||
## init
|
||||
|
||||
```
|
||||
octoprint.default => /etc/default/octoprint
|
||||
octoprint.init => /etc/init.d/octoprint
|
||||
```
|
||||
|
||||
## systemd
|
||||
|
||||
```
|
||||
octoprint.service => /etc/systemd/service/octoprint.service
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=The snappy web interface for your 3D printer
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=pi
|
||||
ExecStart=/home/pi/OctoPrint/venv/bin/octoprint
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -12,47 +12,57 @@ import octoprint_setuptools
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Supported python versions
|
||||
PYTHON_REQUIRES = ">=2.7.9,<3"
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
"flask>=0.10.1,<0.11",
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"werkzeug>=0.8.3,<0.9",
|
||||
"tornado==4.5.3",
|
||||
#"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a
|
||||
# vendored one
|
||||
"PyYAML>=3.10,<3.11",
|
||||
"Flask-Login>=0.2.11,<0.3",
|
||||
"Flask-Principal>=0.3.5,<0.4",
|
||||
"Flask-Babel>=0.9,<0.10",
|
||||
"Flask-Assets>=0.10,<0.11",
|
||||
"markdown>=2.6.9,<2.7",
|
||||
# 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
|
||||
|
||||
# anything below this should be checked on releases for new versions
|
||||
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"werkzeug>=0.15.1,<0.16",
|
||||
"cachelib>=0.1,<0.2",
|
||||
"PyYAML>=5.1,<6",
|
||||
"markdown>=3.0,<3.1",
|
||||
"pyserial>=3.4,<3.5",
|
||||
"netaddr>=0.7.19,<0.8",
|
||||
"watchdog>=0.8.3,<0.9",
|
||||
"sarge==0.1.4", # 0.1.5 introduced a breaking change with regards to the async keyword. Pinning
|
||||
# to 0.1.4 for now to work around this.
|
||||
"netifaces>=0.10.6,<0.11",
|
||||
"pylru>=1.0.9,<1.1",
|
||||
"rsa>=3.2.3,<3.3",
|
||||
"pkginfo>=1.4.2,<1.5",
|
||||
"requests>=2.18.4,<3",
|
||||
"semantic_version>=2.4.2,<2.5",
|
||||
"psutil>=5.4.6,<5.5",
|
||||
"Click>=6.2,<6.3",
|
||||
"watchdog>=0.9.0,<0.10",
|
||||
"sarge==0.1.5post0",
|
||||
"netifaces>=0.10.9,<0.11",
|
||||
"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",
|
||||
"Click>=7,<8",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
"chainmap>=1.0.2,<1.1",
|
||||
"future>=0.15.2,<0.16",
|
||||
"scandir>=1.3,<1.4",
|
||||
"websocket-client>=0.40.0,<0.41",
|
||||
"python-dateutil>=2.6.1,<2.7",
|
||||
"wrapt>=1.10.11,<1.11",
|
||||
"futures>=3.1.1,<3.2",
|
||||
"emoji>=0.4.5,<0.5",
|
||||
"monotonic>=1.3,<1.4",
|
||||
"frozendict>=1.2,<1.3"
|
||||
"chainmap>=1.0.3,<1.1",
|
||||
"future>=0.17.1,<0.18",
|
||||
"scandir>=1.10,<1.11",
|
||||
"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",
|
||||
"frozendict>=1.2,<1.3",
|
||||
"sentry-sdk==0.7.7",
|
||||
"typing>=3.6.6,<4",
|
||||
"filetype>=1.0.5,<2"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
@@ -64,7 +74,7 @@ EXTRA_REQUIRES = dict(
|
||||
develop=[
|
||||
# Testing dependencies
|
||||
"mock>=2.0.0,<3",
|
||||
"nose>=1.3.0,<1.4",
|
||||
"nose>=1.3.7,<1.4",
|
||||
"ddt",
|
||||
|
||||
# Documentation dependencies
|
||||
@@ -72,17 +82,15 @@ EXTRA_REQUIRES = dict(
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid>=0.3",
|
||||
"sphinx_rtd_theme",
|
||||
"readthedocs-sphinx-ext==0.5.7"
|
||||
],
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
plugins=[
|
||||
"cookiecutter>=1.4,<1.7"
|
||||
"cookiecutter>=1.6,<1.7"
|
||||
]
|
||||
)
|
||||
|
||||
# Additional requirements for setup
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
@@ -155,10 +163,10 @@ def params():
|
||||
long_description = read_file_contents(os.path.join(here, "README.md"))
|
||||
long_description_content_type = "text/markdown"
|
||||
|
||||
python_requires = PYTHON_REQUIRES
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
setup_requires = SETUP_REQUIRES
|
||||
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
@@ -189,7 +197,7 @@ def params():
|
||||
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
|
||||
|
||||
project_urls={
|
||||
"Community Forum": "https://discourse.octoprint.org",
|
||||
"Community Forum": "https://community.octoprint.org",
|
||||
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
|
||||
"Source": "https://github.com/foosel/OctoPrint",
|
||||
"Funding": "https://donate.octoprint.org"
|
||||
|
||||
@@ -103,8 +103,12 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
if callable(after_logging):
|
||||
after_logging(**kwargs)
|
||||
|
||||
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
|
||||
safe_mode = safe_mode or settings_safe_mode
|
||||
settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None
|
||||
settings_incomplete_startup_safemode = "incomplete_startup" \
|
||||
if settings.getBoolean(["server", "incompleteStartup"]) \
|
||||
and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) \
|
||||
else None
|
||||
safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode
|
||||
kwargs["safe_mode"] = safe_mode
|
||||
if callable(after_safe_mode):
|
||||
after_safe_mode(**kwargs)
|
||||
@@ -141,7 +145,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
connectivity_checker=connectivity_checker)
|
||||
except Exception as ex:
|
||||
raise FatalStartupError("Could not initialize settings manager", cause=ex)
|
||||
raise FatalStartupError("Could not initialize plugin manager", cause=ex)
|
||||
|
||||
kwargs["plugin_manager"] = plugin_manager
|
||||
if callable(after_plugin_manager):
|
||||
@@ -342,9 +346,12 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
|
||||
import os
|
||||
|
||||
# we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins
|
||||
import octoprint.plugins
|
||||
|
||||
logger = log.getLogger(__name__ + ".startup")
|
||||
|
||||
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
|
||||
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True),
|
||||
settings.getBaseFolder("plugins")]
|
||||
plugin_entry_points = ["octoprint.plugin"]
|
||||
plugin_disabled_list = settings.get(["plugins", "_disabled"])
|
||||
@@ -595,6 +602,9 @@ def main():
|
||||
# cut off stuff from the beginning
|
||||
args = args[-1 * sys_args_length:] if sys_args_length else []
|
||||
|
||||
from octoprint.util.fixes import patch_sarge_async_on_py2
|
||||
patch_sarge_async_on_py2()
|
||||
|
||||
from octoprint.cli import octo
|
||||
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
# 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")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import octoprint
|
||||
octoprint.main()
|
||||
@@ -1,3 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
# This file helps to compute a version number in source trees obtained from
|
||||
# git-archive tarball (such as those provided by githubs download-from-tag
|
||||
@@ -9,13 +11,14 @@
|
||||
# versioneer-0.15+dev (https://github.com/warner/python-versioneer)
|
||||
|
||||
"""Git implementation of _version.py."""
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
import errno
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import logging
|
||||
|
||||
|
||||
def get_keywords():
|
||||
@@ -41,7 +44,7 @@ def get_config():
|
||||
# _version.py
|
||||
cfg = VersioneerConfig()
|
||||
cfg.VCS = "git"
|
||||
cfg.style = "pep440-post"
|
||||
cfg.style = "pep440-tag"
|
||||
cfg.tag_prefix = ""
|
||||
cfg.parentdir_prefix = ""
|
||||
cfg.versionfile_source = "src/octoprint/_version.py"
|
||||
@@ -130,7 +133,7 @@ def git_get_keywords(versionfile_abs):
|
||||
# _version.py.
|
||||
keywords = {}
|
||||
try:
|
||||
f = open(versionfile_abs, "r")
|
||||
f = io.open(versionfile_abs, "rt", encoding="utf-8")
|
||||
for line in f.readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
@@ -156,11 +159,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
||||
if verbose:
|
||||
print("keywords are unexpanded, not using")
|
||||
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
|
||||
refs = set([r.strip() for r in refnames.strip("()").split(",")])
|
||||
refs = set(r.strip() for r in refnames.strip("()").split(","))
|
||||
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
|
||||
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
|
||||
TAG = "tag: "
|
||||
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
|
||||
tags = set(r[len(TAG):] for r in refs if r.startswith(TAG))
|
||||
if not tags:
|
||||
# Either we're using git < 1.8.3, or there really are no tags. We use
|
||||
# a heuristic: assume all version tags have a digit. The old git %d
|
||||
@@ -169,7 +172,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
||||
# between branches and tags. By ignoring refnames without digits, we
|
||||
# filter out many common branch names like "release" and
|
||||
# "stabilization", as well as "HEAD" and "master".
|
||||
tags = set([r for r in refs if re.search(r'\d', r)])
|
||||
tags = set(r for r in refs if re.search(r'\d', r))
|
||||
if verbose:
|
||||
print("discarding '%s', no digits" % ",".join(refs-tags))
|
||||
|
||||
@@ -254,7 +257,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
||||
abbrev_ref_out = run_command(GITS,
|
||||
["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if abbrev_ref_out is not None:
|
||||
if abbrev_ref_out is not None and abbrev_ref_out != "HEAD":
|
||||
pieces["branch"] = abbrev_ref_out.strip()
|
||||
|
||||
# now we have TAG-NUM-gHEX or HEX
|
||||
@@ -305,17 +308,18 @@ def git_parse_lookup_file(path):
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
|
||||
import re
|
||||
lookup = []
|
||||
with open(path, "r") as f:
|
||||
with io.open(path, "rt", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if '#' in line:
|
||||
line = line[:line.rindex("#")]
|
||||
line = line[:line.index("#")]
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
split_line = map(lambda x: x.strip(), line.split())
|
||||
split_line = list(map(lambda x: x.strip(), line.split()))
|
||||
if not len(split_line):
|
||||
continue
|
||||
|
||||
@@ -336,7 +340,8 @@ def git_parse_lookup_file(path):
|
||||
continue
|
||||
|
||||
lookup.append(entry)
|
||||
except:
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Versioneer problem")
|
||||
break
|
||||
return lookup
|
||||
|
||||
@@ -354,6 +359,9 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
|
||||
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
|
||||
|
||||
current_branch = stdout.strip()
|
||||
if current_branch == "HEAD":
|
||||
raise NotThisMethod("not on a branch")
|
||||
|
||||
for matcher, render, tag, ref_commit in lookup:
|
||||
if matcher.match(current_branch):
|
||||
if tag is None or ref_commit is None:
|
||||
@@ -441,6 +449,31 @@ def render_pep440(pieces):
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_tag(pieces):
|
||||
"""TAG[[.postDISTANCE].dev0+gHEX] -- Just the tag if not dirty, else more info
|
||||
|
||||
Useful for projects that want commit based tracking on some branches
|
||||
but have the master branch only report tags, to allow for commits that
|
||||
do not modify actual code (e.g. to .github/* or docs).
|
||||
|
||||
Exceptions:
|
||||
1: no tags. 0.postDISTANCE[.dev0]+gHEX
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".post%d" % pieces["distance"]
|
||||
rendered += ".dev0"
|
||||
rendered += "+g%s" % pieces["short"]
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
rendered += "+g%s" % pieces["short"]
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_pre(pieces):
|
||||
"""TAG[.post.devDISTANCE] -- No -dirty.
|
||||
|
||||
@@ -591,6 +624,8 @@ def render(pieces, style):
|
||||
rendered = render_pep440_old(pieces)
|
||||
elif style == "pep440-dev":
|
||||
rendered = render_pep440_dev(pieces)
|
||||
elif style == "pep440-tag":
|
||||
rendered = render_pep440_tag(pieces)
|
||||
elif style == "git-describe":
|
||||
rendered = render_git_describe(pieces)
|
||||
elif style == "git-describe-long":
|
||||
|
||||
@@ -137,9 +137,10 @@ from .dev import dev_commands
|
||||
from .client import client_commands
|
||||
from .config import config_commands
|
||||
from .analysis import analysis_commands
|
||||
from .user import user_commands
|
||||
|
||||
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands])
|
||||
@standard_options()
|
||||
@legacy_options
|
||||
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
|
||||
|
||||
@@ -34,6 +34,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
|
||||
import time
|
||||
import yaml
|
||||
from octoprint.util import monotonic_time
|
||||
from octoprint.util.gcodeInterpreter import gcode
|
||||
|
||||
throttle_callback = None
|
||||
@@ -52,7 +53,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
if len(offsets) < maxt:
|
||||
offsets += [(0, 0)] * (maxt - len(offsets))
|
||||
|
||||
start_time = time.time()
|
||||
start_time = monotonic_time()
|
||||
|
||||
progress_callback = None
|
||||
if progress:
|
||||
@@ -68,6 +69,9 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
max_extruders=maxt,
|
||||
g90_extruder=g90_extruder)
|
||||
|
||||
click.echo("DONE:{}s".format(time.time() - start_time))
|
||||
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))
|
||||
|
||||
if __name__ == "__main__":
|
||||
gcode_command()
|
||||
@@ -92,7 +92,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
continue
|
||||
result[name + self.sep + command.name] = command
|
||||
except:
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import sys
|
||||
|
||||
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
|
||||
|
||||
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode,
|
||||
def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode,
|
||||
ignore_blacklist, octoprint_daemon=None):
|
||||
"""Initializes the environment and starts up the server."""
|
||||
|
||||
@@ -26,6 +26,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
logger.info("Starting OctoPrint {}".format(__display_version__))
|
||||
if safe_mode:
|
||||
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
|
||||
if safe_mode == "flag":
|
||||
reason = "command line flag"
|
||||
elif safe_mode == "settings":
|
||||
reason = "setting in config.yaml"
|
||||
elif safe_mode == "incomplete_startup":
|
||||
reason = "problem during last startup"
|
||||
else:
|
||||
reason = "unknown"
|
||||
logger.info("Reason for safe mode: {}".format(reason))
|
||||
|
||||
if recorder and len(recorder):
|
||||
logger.info(get_divider_line("-", "Logged during platform initialization:"))
|
||||
@@ -82,7 +91,6 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
after_safe_mode=log_startup,
|
||||
after_environment_detector=log_register_rollover)
|
||||
|
||||
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
|
||||
|
||||
except FatalStartupError as e:
|
||||
@@ -102,6 +110,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
environment_detector=environment_detector,
|
||||
host=host,
|
||||
port=port,
|
||||
v6_only=v6_only,
|
||||
debug=debug,
|
||||
safe_mode=safe_mode,
|
||||
allow_root=allow_root,
|
||||
@@ -112,9 +121,13 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
|
||||
server_options = bulk_options([
|
||||
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
|
||||
help="Specify the host on which to bind the server."),
|
||||
help="Specify the host address on which to bind the server."),
|
||||
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
|
||||
help="Specify the port on which to bind the server."),
|
||||
click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."),
|
||||
click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."),
|
||||
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
|
||||
help="Specify the config file to use for configuring logging."),
|
||||
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
|
||||
@@ -124,7 +137,7 @@ server_options = bulk_options([
|
||||
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Disable processing of the plugin blacklist.")
|
||||
])
|
||||
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
|
||||
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6``
|
||||
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
|
||||
|
||||
daemon_options = bulk_options([
|
||||
@@ -154,11 +167,11 @@ def enable_safemode(ctx, **kwargs):
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the settings manager.", err=True)
|
||||
ctx.exit(-1)
|
||||
else:
|
||||
settings.setBoolean(["server", "startOnceInSafeMode"], True)
|
||||
settings.save()
|
||||
|
||||
settings.setBoolean(["server", "startOnceInSafeMode"], True)
|
||||
settings.save()
|
||||
|
||||
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
|
||||
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
|
||||
|
||||
|
||||
@server_commands.command(name="serve")
|
||||
@@ -173,6 +186,8 @@ def serve_command(ctx, **kwargs):
|
||||
|
||||
host = get_value("host")
|
||||
port = get_value("port")
|
||||
v4 = get_value("v4")
|
||||
v6 = get_value("v6")
|
||||
logging = get_value("logging")
|
||||
allow_root = get_value("allow_root")
|
||||
debug = get_value("debug")
|
||||
@@ -180,10 +195,13 @@ def serve_command(ctx, **kwargs):
|
||||
basedir = get_value("basedir")
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = get_value("safe_mode")
|
||||
safe_mode = "flag" if get_value("safe_mode") else None
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
run_server(basedir, configfile, host, port, debug,
|
||||
if v4 and not host:
|
||||
host = "0.0.0.0"
|
||||
|
||||
run_server(basedir, configfile, host, port, v6, debug,
|
||||
allow_root, logging, verbosity, safe_mode,
|
||||
ignore_blacklist)
|
||||
|
||||
@@ -210,6 +228,8 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
|
||||
host = get_value("host")
|
||||
port = get_value("port")
|
||||
v4 = get_value("v4")
|
||||
v6 = get_value("v6")
|
||||
logging = get_value("logging")
|
||||
allow_root = get_value("allow_root")
|
||||
debug = get_value("debug")
|
||||
@@ -218,9 +238,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
basedir = get_value("basedir")
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = get_value("safe_mode")
|
||||
safe_mode = "flag" if get_value("safe_mode") else None
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
if v4 and not host:
|
||||
host = "0.0.0.0"
|
||||
|
||||
if pid is None:
|
||||
click.echo("No path to a pidfile set",
|
||||
file=sys.stderr)
|
||||
@@ -228,14 +251,15 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
|
||||
from octoprint.daemon import Daemon
|
||||
class OctoPrintDaemon(Daemon):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity,
|
||||
safe_mode, ignore_blacklist):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config,
|
||||
verbosity, safe_mode, ignore_blacklist):
|
||||
Daemon.__init__(self, pidfile)
|
||||
|
||||
self._basedir = basedir
|
||||
self._configfile = configfile
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._v6_only = v6_only
|
||||
self._debug = debug
|
||||
self._allow_root = allow_root
|
||||
self._logging_config = logging_config
|
||||
@@ -244,12 +268,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
self._ignore_blacklist = ignore_blacklist
|
||||
|
||||
def run(self):
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
|
||||
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
|
||||
self._ignore_blacklist, octoprint_daemon=self)
|
||||
|
||||
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
|
||||
safe_mode, ignore_blacklist)
|
||||
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging,
|
||||
verbosity, safe_mode, ignore_blacklist)
|
||||
|
||||
if command == "start":
|
||||
octoprint_daemon.start()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# 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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import click
|
||||
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
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
#~~ "octoprint user" commands
|
||||
|
||||
|
||||
@click.group()
|
||||
def user_commands():
|
||||
pass
|
||||
|
||||
|
||||
@user_commands.group(name="user")
|
||||
@click.pass_context
|
||||
def user(ctx):
|
||||
"""
|
||||
User management.
|
||||
|
||||
Note that this currently only supports managing user accounts stored in the configured user manager, not any
|
||||
user managers added through plugins and the "octoprint.users.factory" hook.
|
||||
"""
|
||||
try:
|
||||
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
|
||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
|
||||
name = settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = get_class(name)
|
||||
manager = clazz(settings=settings)
|
||||
except Exception:
|
||||
click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
|
||||
manager = FilebasedUserManager(settings=settings)
|
||||
finally:
|
||||
manager.enabled = settings.getBoolean(["accessControl", "enabled"])
|
||||
|
||||
ctx.obj.user_manager = manager
|
||||
|
||||
except Exception:
|
||||
click.echo("Could not instantiate user manager", err=True)
|
||||
return
|
||||
|
||||
|
||||
@user.command(name="list")
|
||||
@click.pass_context
|
||||
def list_users_command(ctx):
|
||||
"""Lists user information"""
|
||||
users = ctx.obj.user_manager.getAllUsers()
|
||||
_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.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
|
||||
help="Sets admin role on user")
|
||||
@click.pass_context
|
||||
def add_user_command(ctx, username, password, is_admin):
|
||||
"""Add a new user."""
|
||||
try:
|
||||
ctx.obj.user_manager.addUser(username,
|
||||
password,
|
||||
roles=(("user", "admin") if is_admin else ("user",)),
|
||||
active=True)
|
||||
|
||||
user = ctx.obj.user_manager.findUser(username)
|
||||
if user:
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||
except UserAlreadyExists:
|
||||
click.echo("A user with the name {} does already exist!".format(username), err=True)
|
||||
|
||||
|
||||
@user.command(name="remove")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@click.pass_context
|
||||
def remove_user_command(ctx, username):
|
||||
"""Remove an existing user."""
|
||||
confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
|
||||
type=click.STRING)
|
||||
|
||||
if confirm.lower() == "yes":
|
||||
ctx.obj.user_manager.removeUser(username)
|
||||
click.echo("User {} removed.".format(username))
|
||||
else:
|
||||
click.echo("User {} not removed.".format(username))
|
||||
|
||||
|
||||
@user.command(name="password")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@click.password_option("--password", "password", help="New password for user")
|
||||
@click.pass_context
|
||||
def change_password_command(ctx, username, password):
|
||||
"""Change an existing user's password."""
|
||||
try:
|
||||
ctx.obj.user_manager.changeUserPassword(username, password)
|
||||
click.echo("Password changed for user {}.".format(username))
|
||||
except UnknownUser:
|
||||
click.echo("User {} does not exist!".format(username), err=True)
|
||||
|
||||
|
||||
@user.command(name="activate")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@click.pass_context
|
||||
def activate_command(ctx, username):
|
||||
"""Activate a user account."""
|
||||
try:
|
||||
ctx.obj.user_manager.changeUserActivation(username, True)
|
||||
click.echo("User {} activated.".format(username))
|
||||
|
||||
user = ctx.obj.user_manager.findUser(username)
|
||||
if user:
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||
except UnknownUser:
|
||||
click.echo("User {} does not exist!".format(username), err=True)
|
||||
|
||||
|
||||
@user.command(name="deactivate")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@click.pass_context
|
||||
def deactivate_command(ctx, username):
|
||||
"""Activate a user account."""
|
||||
try:
|
||||
ctx.obj.user_manager.changeUserActivation(username, False)
|
||||
click.echo("User {} activated.".format(username))
|
||||
|
||||
user = ctx.obj.user_manager.findUser(username)
|
||||
if user:
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||
except UnknownUser:
|
||||
click.echo("User {} does not exist!".format(username), err=True)
|
||||
|
||||
|
||||
def _print_list(users):
|
||||
click.echo("{} users registered in the system:".format(len(users)))
|
||||
for user in sorted(users, key=lambda x: 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")
|
||||
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import threading
|
||||
import yaml
|
||||
@@ -16,6 +15,7 @@ import psutil
|
||||
|
||||
from octoprint.plugin import EnvironmentDetectionPlugin
|
||||
from octoprint.util.platform import get_os
|
||||
from octoprint.util.version import get_python_version_string
|
||||
|
||||
class EnvironmentDetector(object):
|
||||
|
||||
@@ -25,10 +25,15 @@ class EnvironmentDetector(object):
|
||||
self._cache = None
|
||||
self._cache_lock = threading.RLock()
|
||||
|
||||
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
|
||||
except Exception:
|
||||
# just in case, see #3100...
|
||||
self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager")
|
||||
self._environment_plugins = []
|
||||
|
||||
@property
|
||||
def environment(self):
|
||||
with self._cache_lock:
|
||||
@@ -70,7 +75,7 @@ class EnvironmentDetector(object):
|
||||
|
||||
# determine python version
|
||||
try:
|
||||
result["version"] = platform.python_version()
|
||||
result["version"] = get_python_version_string()
|
||||
except:
|
||||
self._logger.exception("Error detecting python version")
|
||||
|
||||
@@ -120,7 +125,8 @@ class EnvironmentDetector(object):
|
||||
result[implementation._identifier] = additional
|
||||
except:
|
||||
self._logger.exception("Error while fetching additional "
|
||||
"environment data from plugin {}".format(implementation._identifier))
|
||||
"environment data from plugin {}".format(implementation._identifier),
|
||||
extra=dict(plugin=implementation._identifier))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ except ImportError:
|
||||
import Queue as queue
|
||||
import threading
|
||||
import collections
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.plugin
|
||||
@@ -23,7 +24,7 @@ _instance = None
|
||||
|
||||
|
||||
def all_events():
|
||||
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
|
||||
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)]
|
||||
|
||||
|
||||
class Events(object):
|
||||
@@ -119,6 +120,23 @@ class Events(object):
|
||||
# Settings
|
||||
SETTINGS_UPDATED = "SettingsUpdated"
|
||||
|
||||
@classmethod
|
||||
def register_event(cls, event, prefix=None):
|
||||
name = cls._to_identifier(event)
|
||||
if prefix:
|
||||
event = prefix + event
|
||||
name = cls._to_identifier(prefix) + name
|
||||
setattr(cls, name, event)
|
||||
return name, event
|
||||
|
||||
# based on https://stackoverflow.com/a/1176023
|
||||
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
|
||||
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
|
||||
|
||||
@classmethod
|
||||
def _to_identifier(cls, name):
|
||||
s1 = cls._first_cap_re.sub(r'\1_\2', name)
|
||||
return cls._all_cap_re.sub(r'\1_\2', s1).upper()
|
||||
|
||||
def eventManager():
|
||||
global _instance
|
||||
@@ -135,6 +153,7 @@ class EventManager(object):
|
||||
def __init__(self):
|
||||
self._registeredListeners = collections.defaultdict(list)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
|
||||
|
||||
self._startup_signaled = False
|
||||
self._shutdown_signaled = False
|
||||
@@ -156,19 +175,18 @@ class EventManager(object):
|
||||
self._shutdown_signaled = True
|
||||
|
||||
eventListeners = self._registeredListeners[event]
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
|
||||
|
||||
for listener in eventListeners:
|
||||
self._logger.debug("Sending action to %r" % listener)
|
||||
self._logger.debug("Sending action to {!r}".format(listener))
|
||||
try:
|
||||
listener(event, payload)
|
||||
except:
|
||||
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=(event, payload),
|
||||
initialized=True)
|
||||
args=(event, payload))
|
||||
self._logger.info("Event loop shut down")
|
||||
except:
|
||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
||||
@@ -211,7 +229,7 @@ class EventManager(object):
|
||||
|
||||
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.3.0 Remove again
|
||||
# TODO v1.4.0 Remove again
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
@@ -227,7 +245,7 @@ class EventManager(object):
|
||||
return
|
||||
|
||||
self._registeredListeners[event].append(callback)
|
||||
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
|
||||
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
|
||||
|
||||
def unsubscribe (self, event, callback):
|
||||
"""
|
||||
@@ -239,7 +257,7 @@ class EventManager(object):
|
||||
return
|
||||
|
||||
self._registeredListeners[event].remove(callback)
|
||||
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
|
||||
self._logger.debug("Unsubscribed listener {!r} for event {}".format(callback, event))
|
||||
|
||||
def join(self, timeout=None):
|
||||
self._worker.join(timeout)
|
||||
@@ -325,17 +343,24 @@ class CommandTrigger(GenericEventListener):
|
||||
self._logger.info("Disabled command trigger: {!r}".format(subscription))
|
||||
continue
|
||||
|
||||
event = subscription["event"]
|
||||
events = subscription["event"]
|
||||
command = subscription["command"]
|
||||
commandType = subscription["type"]
|
||||
debug = subscription["debug"] if "debug" in subscription else False
|
||||
|
||||
if not event in self._subscriptions.keys():
|
||||
self._subscriptions[event] = []
|
||||
self._subscriptions[event].append((command, commandType, debug))
|
||||
# "event" in the configuration can be a string, or
|
||||
# a list of strings. If it's the former, convert it
|
||||
# into the latter.
|
||||
if not isinstance(events, (tuple, list, set)):
|
||||
events = [events]
|
||||
|
||||
if not event in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
for event in events:
|
||||
if not event in self._subscriptions.keys():
|
||||
self._subscriptions[event] = []
|
||||
self._subscriptions[event].append((command, commandType, debug))
|
||||
|
||||
if not event in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
|
||||
self.subscribe(eventsToSubscribe)
|
||||
|
||||
@@ -355,9 +380,9 @@ class CommandTrigger(GenericEventListener):
|
||||
if isinstance(command, (tuple, list, set)):
|
||||
processedCommand = []
|
||||
for c in command:
|
||||
processedCommand.append(self._processCommand(c, payload))
|
||||
processedCommand.append(self._processCommand(c, event, payload))
|
||||
else:
|
||||
processedCommand = self._processCommand(command, payload)
|
||||
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)
|
||||
@@ -406,13 +431,14 @@ class CommandTrigger(GenericEventListener):
|
||||
self._logger.info("Executing GCode commands: %r" % command)
|
||||
self._printer.commands(commands)
|
||||
|
||||
def _processCommand(self, command, payload):
|
||||
def _processCommand(self, command, event, payload):
|
||||
"""
|
||||
Performs string substitutions in the command string based on a few current parameters.
|
||||
|
||||
The following substitutions are currently supported:
|
||||
|
||||
- {__currentZ} : current Z position of the print head, or -1 if not available
|
||||
- {__eventname} : the name of the event hook being triggered
|
||||
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
|
||||
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
|
||||
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
|
||||
@@ -434,6 +460,7 @@ class CommandTrigger(GenericEventListener):
|
||||
|
||||
params = {
|
||||
"__currentZ": "-1",
|
||||
"__eventname": event,
|
||||
"__filename": "NO FILE",
|
||||
"__filepath": "NO PATH",
|
||||
"__progress": "0",
|
||||
|
||||
@@ -17,6 +17,7 @@ from .destinations import FileDestinations
|
||||
from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
@@ -30,10 +31,6 @@ extensions = dict(
|
||||
|
||||
def full_extension_tree():
|
||||
result = dict(
|
||||
# extensions for 3d model files
|
||||
model=dict(
|
||||
stl=ContentTypeMapping(["stl"], "application/sla")
|
||||
),
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
|
||||
@@ -74,6 +71,18 @@ def full_extension_tree():
|
||||
else:
|
||||
return merged
|
||||
|
||||
slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
|
||||
for plugin in slicer_plugins:
|
||||
try:
|
||||
plugin_result = plugin.get_slicer_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:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from SlicerPlugin {name}".format(name=plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
|
||||
for name, hook in extension_tree_hooks.items():
|
||||
try:
|
||||
@@ -82,12 +91,14 @@ def full_extension_tree():
|
||||
continue
|
||||
result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger)
|
||||
except:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name))
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from hook {name}".format(name=name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
return result
|
||||
|
||||
def get_extensions(type, subtree=None):
|
||||
if not subtree:
|
||||
if subtree is None:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
@@ -101,7 +112,7 @@ def get_extensions(type, subtree=None):
|
||||
return None
|
||||
|
||||
def get_all_extensions(subtree=None):
|
||||
if not subtree:
|
||||
if subtree is None:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
result = []
|
||||
@@ -120,7 +131,7 @@ def get_all_extensions(subtree=None):
|
||||
return result
|
||||
|
||||
def get_path_for_extension(extension, subtree=None):
|
||||
if not subtree:
|
||||
if subtree is None:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
@@ -136,11 +147,11 @@ def get_path_for_extension(extension, subtree=None):
|
||||
return None
|
||||
|
||||
def get_content_type_mapping_for_extension(extension, subtree=None):
|
||||
if not subtree:
|
||||
if subtree is None:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
|
||||
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions
|
||||
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
|
||||
|
||||
if content_extension_matches or list_extension_matches:
|
||||
@@ -256,7 +267,7 @@ class FileManager(object):
|
||||
file_name = storage_manager.split_path(path)
|
||||
|
||||
# we'll use the default printer profile for the backlog since we don't know better
|
||||
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
|
||||
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None)
|
||||
if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority):
|
||||
counter += 1
|
||||
|
||||
@@ -319,25 +330,27 @@ class FileManager(object):
|
||||
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
reason=_error))
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
reason=_error))
|
||||
elif _cancelled:
|
||||
eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location))
|
||||
eventManager().fire(Events.SLICING_CANCELLED, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location))
|
||||
else:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta["hash"]
|
||||
hash = source_meta.get("hash", "n/a")
|
||||
|
||||
import io
|
||||
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}\n".format(**locals()).encode("ascii", "replace")),
|
||||
io.BytesIO(u";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)
|
||||
@@ -345,12 +358,13 @@ class FileManager(object):
|
||||
display=display, links=links, allow_overwrite=True,
|
||||
printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = time.time()
|
||||
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
time=end_time - start_time))
|
||||
end_time = octoprint.util.monotonic_time()
|
||||
eventManager().fire(Events.SLICING_DONE, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
time=end_time - start_time))
|
||||
|
||||
if callback is not None:
|
||||
if callback_args is None:
|
||||
@@ -370,9 +384,9 @@ class FileManager(object):
|
||||
|
||||
slicer = self._slicing_manager.get_slicer(slicer_name)
|
||||
|
||||
import time
|
||||
start_time = time.time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
|
||||
start_time = octoprint.util.monotonic_time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name,
|
||||
"stl": source_path,
|
||||
"stl_location": source_location,
|
||||
"gcode": dest_path,
|
||||
"gcode_location": dest_location,
|
||||
@@ -416,7 +430,8 @@ class FileManager(object):
|
||||
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")
|
||||
except: 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):
|
||||
@@ -424,7 +439,8 @@ class FileManager(object):
|
||||
try:
|
||||
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
|
||||
except:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier)
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier,
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
import threading
|
||||
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
|
||||
@@ -459,11 +475,11 @@ class FileManager(object):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
for hook in self._preprocessor_hooks.values():
|
||||
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:
|
||||
self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook))
|
||||
self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra=dict(plugin=name))
|
||||
continue
|
||||
|
||||
if hook_file_object is not None:
|
||||
@@ -476,12 +492,9 @@ class FileManager(object):
|
||||
|
||||
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
|
||||
|
||||
if analysis is None:
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
else:
|
||||
self._add_analysis_result(destination, path, analysis)
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
@@ -647,6 +660,8 @@ class FileManager(object):
|
||||
try:
|
||||
with open(self._recovery_file) 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:
|
||||
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
|
||||
@@ -700,7 +715,7 @@ class FileManager(object):
|
||||
def _on_analysis_finished(self, entry, result):
|
||||
self._add_analysis_result(entry.location, entry.path, result)
|
||||
|
||||
def _analysis_queue_entry(self, destination, path, printer_profile=None):
|
||||
def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
@@ -709,6 +724,6 @@ class FileManager(object):
|
||||
file_type = get_file_type(absolute_path)
|
||||
|
||||
if file_type:
|
||||
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile)
|
||||
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis)
|
||||
else:
|
||||
return None
|
||||
@@ -18,9 +18,11 @@ import time
|
||||
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import monotonic_time
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
|
||||
"""
|
||||
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
|
||||
for processing.
|
||||
@@ -33,6 +35,7 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio
|
||||
location (str): Location the file is located on.
|
||||
absolute_path (str): Absolute path on disk through which to access the file.
|
||||
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
|
||||
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
|
||||
"""
|
||||
|
||||
def __str__(self):
|
||||
@@ -107,7 +110,11 @@ class AnalysisQueue(object):
|
||||
|
||||
def _analysis_finished(self, entry, result):
|
||||
for callback in self._callbacks:
|
||||
callback(entry, result)
|
||||
try:
|
||||
callback(entry, result)
|
||||
except:
|
||||
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
"origin": entry.location,
|
||||
@@ -248,7 +255,7 @@ class AbstractAnalysisQueue(object):
|
||||
self._current_progress = 0
|
||||
|
||||
try:
|
||||
start_time = time.time()
|
||||
start_time = monotonic_time()
|
||||
self._logger.info("Starting analysis of {}".format(entry))
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
@@ -261,7 +268,7 @@ class AbstractAnalysisQueue(object):
|
||||
result = self._do_analysis(high_priority=high_priority)
|
||||
except TypeError:
|
||||
result = self._do_analysis()
|
||||
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, time.time() - start_time))
|
||||
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
|
||||
self._finished_callback(self._current, result)
|
||||
finally:
|
||||
self._current = None
|
||||
@@ -298,7 +305,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
- * **Key**
|
||||
* **Description**
|
||||
- * ``estimatedPrintTime``
|
||||
* Estimated time the file take to print, in minutes
|
||||
* Estimated time the file take to print, in seconds
|
||||
- * ``filament``
|
||||
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
|
||||
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
|
||||
@@ -341,6 +348,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
import sys
|
||||
import yaml
|
||||
|
||||
if self._current.analysis:
|
||||
return self._current.analysis
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
|
||||
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
@@ -364,7 +373,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
|
||||
|
||||
self._aborted = False
|
||||
p = sarge.run(command, async=True, stdout=sarge.Capture())
|
||||
p = sarge.run(command, async_=True, stdout=sarge.Capture())
|
||||
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
|
||||
@@ -8,9 +8,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
import os
|
||||
import pylru
|
||||
import shutil
|
||||
import re
|
||||
import pylru
|
||||
import copy
|
||||
|
||||
try:
|
||||
from os import scandir, walk
|
||||
@@ -19,7 +20,6 @@ except ImportError:
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
from contextlib import contextmanager
|
||||
from copy import deepcopy
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
@@ -28,7 +28,7 @@ from slugify import Slugify
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path, to_unicode
|
||||
from octoprint.util import is_hidden_path, to_unicode, timing
|
||||
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
@@ -485,6 +485,8 @@ class LocalFileStorage(StorageInterface):
|
||||
import threading
|
||||
self._metadata_lock_mutex = threading.RLock()
|
||||
self._metadata_locks = dict()
|
||||
self._persisted_metadata_lock_mutex = threading.RLock()
|
||||
self._persisted_metadata_locks = dict()
|
||||
|
||||
self._metadata_cache = pylru.lrucache(10)
|
||||
|
||||
@@ -883,6 +885,8 @@ class LocalFileStorage(StorageInterface):
|
||||
if not name in metadata:
|
||||
return
|
||||
|
||||
metadata = self._copied_metadata(metadata, name)
|
||||
|
||||
if not key in metadata[name] or overwrite:
|
||||
metadata[name][key] = data
|
||||
metadata_dirty = True
|
||||
@@ -907,6 +911,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if not key in metadata[name]:
|
||||
return
|
||||
|
||||
metadata = self._copied_metadata(metadata, name)
|
||||
del metadata[name][key]
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
@@ -1050,10 +1055,7 @@ class LocalFileStorage(StorageInterface):
|
||||
##~~ internals
|
||||
|
||||
def _add_history(self, name, path, data):
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
if not name in metadata:
|
||||
metadata[name] = dict()
|
||||
metadata = self._copied_metadata(self._get_metadata(path), name)
|
||||
|
||||
if not "hash" in metadata[name]:
|
||||
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
|
||||
@@ -1071,6 +1073,8 @@ class LocalFileStorage(StorageInterface):
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
metadata = self._copied_metadata(metadata, name)
|
||||
|
||||
try:
|
||||
metadata[name]["history"][index].update(data)
|
||||
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
|
||||
@@ -1084,6 +1088,8 @@ class LocalFileStorage(StorageInterface):
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
metadata = self._copied_metadata(metadata, name)
|
||||
|
||||
try:
|
||||
del metadata[name]["history"][index]
|
||||
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
|
||||
@@ -1093,9 +1099,9 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def _calculate_stats_from_history(self, name, path, metadata=None, save=True):
|
||||
if metadata is None:
|
||||
metadata = self._get_metadata(path)
|
||||
metadata = self._copied_metadata(self._get_metadata(path), name)
|
||||
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
if not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
# collect data from history
|
||||
@@ -1164,12 +1170,9 @@ class LocalFileStorage(StorageInterface):
|
||||
if file_type:
|
||||
file_type = file_type[0]
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
metadata = self._copied_metadata(self._get_metadata(path), name)
|
||||
metadata_dirty = False
|
||||
|
||||
if not name in metadata:
|
||||
metadata[name] = dict()
|
||||
|
||||
if not "hash" in metadata[name]:
|
||||
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
|
||||
|
||||
@@ -1241,13 +1244,10 @@ class LocalFileStorage(StorageInterface):
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _remove_links(self, name, path, links):
|
||||
metadata = self._get_metadata(path)
|
||||
metadata = self._copied_metadata(self._get_metadata(path), name)
|
||||
metadata_dirty = False
|
||||
|
||||
if not name in metadata or not "hash" in metadata[name]:
|
||||
hash = self._create_hash(os.path.join(path, name))
|
||||
else:
|
||||
hash = metadata[name]["hash"]
|
||||
hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name)))
|
||||
|
||||
for rel, data in links:
|
||||
if (rel == "model" or rel == "machinecode") and "name" in data:
|
||||
@@ -1255,6 +1255,7 @@ class LocalFileStorage(StorageInterface):
|
||||
ref_rel = "model" if rel == "machinecode" else "machinecode"
|
||||
for link in metadata[data["name"]]["links"]:
|
||||
if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash:
|
||||
metadata[data["name"]] = copy.deepcopy(metadata[data["name"]])
|
||||
metadata[data["name"]]["links"].remove(link)
|
||||
metadata_dirty = True
|
||||
|
||||
@@ -1330,10 +1331,14 @@ class LocalFileStorage(StorageInterface):
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
if not metadata_dirty:
|
||||
metadata = self._copied_metadata(metadata, entry_name)
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
else:
|
||||
if not metadata_dirty:
|
||||
metadata = self._copied_metadata(metadata, entry_name)
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
@@ -1363,10 +1368,14 @@ class LocalFileStorage(StorageInterface):
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
if not metadata_dirty:
|
||||
metadata = self._copied_metadata(metadata, entry_name)
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
elif entry_name != entry_display:
|
||||
if not metadata_dirty:
|
||||
metadata = self._copied_metadata(metadata, entry_name)
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
@@ -1450,6 +1459,8 @@ class LocalFileStorage(StorageInterface):
|
||||
entry_data["display"] = display_name
|
||||
|
||||
entry_data.update(additional_metadata)
|
||||
|
||||
metadata = copy.copy(metadata)
|
||||
metadata[entry] = entry_data
|
||||
|
||||
if save:
|
||||
@@ -1481,6 +1492,8 @@ class LocalFileStorage(StorageInterface):
|
||||
if not name in metadata:
|
||||
return
|
||||
|
||||
metadata = copy.copy(metadata)
|
||||
|
||||
if "hash" in metadata[name]:
|
||||
hash = metadata[name]["hash"]
|
||||
for m in metadata.values():
|
||||
@@ -1494,7 +1507,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def _update_metadata_entry(self, path, name, data):
|
||||
with self._get_metadata_lock(path):
|
||||
metadata = self._get_metadata(path)
|
||||
metadata = copy.copy(self._get_metadata(path))
|
||||
metadata[name] = data
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
@@ -1513,41 +1526,70 @@ class LocalFileStorage(StorageInterface):
|
||||
with self._get_metadata_lock(destination_path):
|
||||
self._update_metadata_entry(destination_path, destination_name, source_data)
|
||||
|
||||
def _get_metadata(self, path):
|
||||
with self._get_metadata_lock(path):
|
||||
if path in self._metadata_cache:
|
||||
return deepcopy(self._metadata_cache[path])
|
||||
def _get_metadata(self, path, force=False):
|
||||
import json
|
||||
|
||||
self._migrate_metadata(path)
|
||||
if not force:
|
||||
metadata = self._metadata_cache.get(path)
|
||||
if metadata:
|
||||
return metadata
|
||||
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
self._migrate_metadata(path)
|
||||
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
|
||||
metadata = None
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
if os.path.exists(metadata_path):
|
||||
with open(metadata_path) as f:
|
||||
try:
|
||||
import json
|
||||
metadata = json.load(f)
|
||||
except:
|
||||
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
|
||||
else:
|
||||
if isinstance(metadata, dict):
|
||||
self._metadata_cache[path] = deepcopy(metadata)
|
||||
return metadata
|
||||
|
||||
def valid_json(value):
|
||||
try:
|
||||
json.dumps(value, allow_nan=False)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
if isinstance(metadata, dict):
|
||||
old_size = len(metadata)
|
||||
metadata = { k: v for k, v in metadata.items() if valid_json(v) }
|
||||
metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) }
|
||||
new_size = len(metadata)
|
||||
if new_size != old_size:
|
||||
self._logger.info("Deleted {} stale or invalid entries from metadata for path {}".format(old_size - new_size,
|
||||
path))
|
||||
self._save_metadata(path, metadata)
|
||||
else:
|
||||
with self._get_metadata_lock(path):
|
||||
self._metadata_cache[path] = metadata
|
||||
return metadata
|
||||
else:
|
||||
return dict()
|
||||
|
||||
def _save_metadata(self, path, metadata):
|
||||
import json
|
||||
|
||||
with self._get_metadata_lock(path):
|
||||
self._metadata_cache[path] = metadata
|
||||
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
try:
|
||||
import json
|
||||
with atomic_write(metadata_path) as f:
|
||||
json.dump(metadata, f, indent=4, separators=(",", ": "))
|
||||
except:
|
||||
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
|
||||
else:
|
||||
self._metadata_cache[path] = deepcopy(metadata)
|
||||
|
||||
def _delete_metadata(self, path):
|
||||
with self._get_metadata_lock(path):
|
||||
if path in self._metadata_cache:
|
||||
del self._metadata_cache[path]
|
||||
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_files = (".metadata.json", ".metadata.yaml")
|
||||
for metadata_file in metadata_files:
|
||||
metadata_path = os.path.join(path, metadata_file)
|
||||
@@ -1556,15 +1598,19 @@ class LocalFileStorage(StorageInterface):
|
||||
os.remove(metadata_path)
|
||||
except:
|
||||
self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
|
||||
if path in self._metadata_cache:
|
||||
del self._metadata_cache[path]
|
||||
|
||||
@staticmethod
|
||||
def _copied_metadata(metadata, name):
|
||||
metadata = copy.copy(metadata)
|
||||
metadata[name] = copy.deepcopy(metadata.get(name, dict()))
|
||||
return metadata
|
||||
|
||||
def _migrate_metadata(self, path):
|
||||
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
|
||||
import yaml
|
||||
import json
|
||||
|
||||
with self._get_metadata_lock(path):
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
|
||||
metadata_path_json = os.path.join(path, ".metadata.json")
|
||||
|
||||
@@ -1574,7 +1620,10 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
if os.path.exists(metadata_path_json):
|
||||
# already migrated
|
||||
# TODO 1.3.10 Remove ".metadata.yaml" files
|
||||
try:
|
||||
os.remove(metadata_path_yaml)
|
||||
except:
|
||||
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
|
||||
return
|
||||
|
||||
with open(metadata_path_yaml) as f:
|
||||
@@ -1591,7 +1640,10 @@ class LocalFileStorage(StorageInterface):
|
||||
with atomic_write(metadata_path_json) as f:
|
||||
json.dump(metadata, f, indent=4, separators=(",", ": "))
|
||||
|
||||
# TODO 1.3.10 Remove ".metadata.yaml" files
|
||||
try:
|
||||
os.remove(metadata_path_yaml)
|
||||
except:
|
||||
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
|
||||
|
||||
@contextmanager
|
||||
def _get_metadata_lock(self, path):
|
||||
@@ -1613,3 +1665,24 @@ class LocalFileStorage(StorageInterface):
|
||||
del self._metadata_locks[path]
|
||||
else:
|
||||
self._metadata_locks[path] = (counter, lock)
|
||||
|
||||
@contextmanager
|
||||
def _get_persisted_metadata_lock(self, path):
|
||||
with self._persisted_metadata_lock_mutex:
|
||||
if path not in self._persisted_metadata_locks:
|
||||
import threading
|
||||
self._persisted_metadata_locks[path] = (0, threading.RLock())
|
||||
|
||||
counter, lock = self._persisted_metadata_locks[path]
|
||||
counter += 1
|
||||
self._persisted_metadata_locks[path] = (counter, lock)
|
||||
|
||||
yield lock
|
||||
|
||||
with self._persisted_metadata_lock_mutex:
|
||||
counter = self._persisted_metadata_locks[path][0]
|
||||
counter -= 1
|
||||
if counter <= 0:
|
||||
del self._persisted_metadata_locks[path]
|
||||
else:
|
||||
self._persisted_metadata_locks[path] = (counter, lock)
|
||||
@@ -3,6 +3,8 @@ from __future__ import absolute_import
|
||||
|
||||
from octoprint.logging import handlers
|
||||
|
||||
from typing import Union
|
||||
|
||||
def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args):
|
||||
"""
|
||||
Logs to the provided handler only.
|
||||
@@ -137,14 +139,17 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
return c * indent + " " + message
|
||||
|
||||
|
||||
def prefix_multilines(text, prefix=": "):
|
||||
def prefix_multilines(text, prefix=u": "):
|
||||
# type: (Union[unicode, bytes], unicode) -> unicode
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
lines = text.splitlines()
|
||||
if not lines:
|
||||
return ""
|
||||
return u""
|
||||
|
||||
if len(lines) == 1:
|
||||
return lines[0]
|
||||
return to_unicode(lines[0])
|
||||
|
||||
return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line,
|
||||
lines[1:]))
|
||||
return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line),
|
||||
lines[1:]))
|
||||
|
||||
@@ -21,6 +21,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import os
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
@@ -32,16 +33,6 @@ from octoprint.util import deprecated
|
||||
_instance = None
|
||||
|
||||
def _validate_plugin(phase, plugin_info):
|
||||
if phase == "after_load":
|
||||
if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin):
|
||||
# transform app plugin into hook
|
||||
import warnings
|
||||
warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning)
|
||||
|
||||
hooks = plugin_info.hooks
|
||||
if not "octoprint.accesscontrol.appkey" in hooks:
|
||||
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
|
||||
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
|
||||
return True
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None,
|
||||
@@ -94,7 +85,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
"octoprint.printer.factory"]
|
||||
"octoprint.printer.factory",
|
||||
"octoprint.timelapse.extensions"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
|
||||
@@ -167,7 +159,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
||||
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None,
|
||||
initialized=True):
|
||||
"""
|
||||
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
|
||||
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||
@@ -203,9 +196,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
|
||||
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
|
||||
is determined be presence of injected ``_identifier`` property.
|
||||
|
||||
initialized (boolean): Ignored.
|
||||
"""
|
||||
|
||||
if not isinstance(types, (list, tuple)):
|
||||
@@ -215,18 +206,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||
for plugin in plugins:
|
||||
if initialized and not hasattr(plugin, "_identifier"):
|
||||
if not hasattr(plugin, "_identifier"):
|
||||
continue
|
||||
|
||||
if hasattr(plugin, method):
|
||||
logger.debug("Calling {} on {}".format(method, plugin._identifier))
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(plugin._identifier, plugin, result)
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
|
||||
logger.exception("Error while calling plugin %s" % plugin._identifier, extra=dict(plugin=plugin._identifier))
|
||||
if error_callback:
|
||||
error_callback(plugin._identifier, plugin, exc)
|
||||
|
||||
@@ -302,6 +296,17 @@ class PluginSettings(object):
|
||||
.. method:: set_boolean(path, value, force=False)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it.
|
||||
|
||||
.. method:: save(force=False, trigger_event=False)
|
||||
|
||||
Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings
|
||||
will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated``
|
||||
:ref:`event <sec-events-available_events-settings>` to get triggered.
|
||||
|
||||
:param force: Force saving to ``config.yaml`` even if there are no changes.
|
||||
:type force: boolean
|
||||
:param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event <sec-events-available_events-settings>` on save.
|
||||
:type trigger_event: boolean
|
||||
"""
|
||||
|
||||
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
|
||||
|
||||
@@ -37,7 +37,9 @@ import inspect
|
||||
import pkg_resources
|
||||
import pkginfo
|
||||
|
||||
from past.builtins import basestring
|
||||
from past.builtins import unicode
|
||||
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
@@ -46,6 +48,7 @@ except ImportError:
|
||||
|
||||
EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version")
|
||||
FolderOrigin = namedtuple("FolderOrigin", "type, folder")
|
||||
ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder")
|
||||
|
||||
class PluginInfo(object):
|
||||
"""
|
||||
@@ -207,13 +210,13 @@ class PluginInfo(object):
|
||||
|
||||
def __str__(self):
|
||||
if self.version:
|
||||
return "{name} ({version})".format(name=self.name, version=self.version)
|
||||
return u"{name} ({version})".format(name=self.name, version=self.version)
|
||||
else:
|
||||
return self.name
|
||||
return to_unicode(self.name)
|
||||
|
||||
def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""),
|
||||
show_location=False, location_str=" - {location}",
|
||||
show_enabled=False, enabled_strs=("* ", " ", "X ")):
|
||||
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 ")):
|
||||
"""
|
||||
Long string representation of the plugin's information. Will return a string of the format ``<enabled><str(self)><bundled><location>``.
|
||||
|
||||
@@ -242,17 +245,19 @@ class PluginInfo(object):
|
||||
str: The long string representation of the plugin as described above
|
||||
"""
|
||||
if show_enabled:
|
||||
ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1])
|
||||
ret = to_unicode(enabled_strs[2]) if self.blacklisted \
|
||||
else (to_unicode(enabled_strs[0]) if self.enabled
|
||||
else to_unicode(enabled_strs[1]))
|
||||
else:
|
||||
ret = ""
|
||||
ret = u""
|
||||
|
||||
ret += str(self)
|
||||
ret += unicode(self)
|
||||
|
||||
if show_bundled:
|
||||
ret += bundled_strs[0] if self.bundled else bundled_strs[1]
|
||||
ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1])
|
||||
|
||||
if show_location and self.location:
|
||||
ret += location_str.format(location=self.location)
|
||||
ret += to_unicode(location_str).format(location=self.location)
|
||||
|
||||
return ret
|
||||
|
||||
@@ -652,7 +657,7 @@ class PluginManager(object):
|
||||
result_added.update(added)
|
||||
result_found += found
|
||||
except:
|
||||
self.logger.exception("Error fetching plugins from folders")
|
||||
self.logger.exception(u"Error fetching plugins from folders")
|
||||
|
||||
if self.plugin_entry_points:
|
||||
existing.update(result_added)
|
||||
@@ -663,7 +668,7 @@ class PluginManager(object):
|
||||
result_added.update(added)
|
||||
result_found += found
|
||||
except:
|
||||
self.logger.exception("Error fetching plugins from entry points")
|
||||
self.logger.exception(u"Error fetching plugins from entry points")
|
||||
|
||||
return result_added, result_found
|
||||
|
||||
@@ -674,15 +679,18 @@ class PluginManager(object):
|
||||
for folder in folders:
|
||||
try:
|
||||
flagged_readonly = False
|
||||
package = None
|
||||
if isinstance(folder, (list, tuple)):
|
||||
if len(folder) == 2:
|
||||
folder, flagged_readonly = folder
|
||||
elif len(folder) == 3:
|
||||
folder, package, flagged_readonly = folder
|
||||
else:
|
||||
continue
|
||||
actual_readonly = not os.access(folder, os.W_OK)
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
self.logger.warn(u"Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
for entry in scandir(folder):
|
||||
@@ -714,16 +722,23 @@ class PluginManager(object):
|
||||
|
||||
bundled = flagged_readonly
|
||||
|
||||
plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled)
|
||||
module_name = None
|
||||
if package:
|
||||
module_name = "{}.{}".format(package, key)
|
||||
|
||||
plugin = self._import_plugin_from_module(key, module_name=module_name, folder=folder, bundled=bundled)
|
||||
if plugin:
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
if module_name:
|
||||
plugin.origin = ModuleOrigin("module", module_name, folder)
|
||||
else:
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.enabled = False
|
||||
added[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
|
||||
self.logger.exception(u"Error processing folder entry {!r} from folder {}".format(entry, folder))
|
||||
except:
|
||||
self.logger.exception("Error processing folder {}".format(folder))
|
||||
self.logger.exception(u"Error processing folder {}".format(folder))
|
||||
|
||||
return added, found
|
||||
|
||||
@@ -753,8 +768,8 @@ class PluginManager(object):
|
||||
try:
|
||||
yield entry
|
||||
except:
|
||||
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?")
|
||||
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?")
|
||||
|
||||
for group in groups:
|
||||
for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)):
|
||||
@@ -773,7 +788,7 @@ class PluginManager(object):
|
||||
try:
|
||||
entry_point_metadata = EntryPointMetadata(entry_point)
|
||||
except:
|
||||
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
|
||||
self.logger.exception(u"Something went wrong while retrieving metadata for module {}".format(module_name))
|
||||
else:
|
||||
kwargs.update(dict(
|
||||
name=entry_point_metadata.name,
|
||||
@@ -803,7 +818,7 @@ class PluginManager(object):
|
||||
|
||||
added[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
|
||||
self.logger.exception(u"Error processing entry point {!r} for group {}".format(entry_point, group))
|
||||
|
||||
return added, found
|
||||
|
||||
@@ -818,7 +833,7 @@ class PluginManager(object):
|
||||
else:
|
||||
return None
|
||||
except:
|
||||
self.logger.warn("Could not locate plugin {key}".format(key=key))
|
||||
self.logger.warn(u"Could not locate plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
# Create a simple dummy entry first ...
|
||||
@@ -827,11 +842,11 @@ class PluginManager(object):
|
||||
plugin.bundled = bundled
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
self.logger.info("Plugin {} is disabled.".format(plugin))
|
||||
self.logger.info(u"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("Plugin {} is blacklisted.".format(plugin))
|
||||
self.logger.warn(u"Plugin {} is blacklisted.".format(plugin))
|
||||
plugin.blacklisted = True
|
||||
|
||||
if not plugin.validate("before_import", additional_validators=self.plugin_validators):
|
||||
@@ -839,12 +854,15 @@ class PluginManager(object):
|
||||
|
||||
# ... then create and return the real one
|
||||
return self._import_plugin(key, *module,
|
||||
name=name, version=version, summary=summary, author=author, url=url,
|
||||
module_name=module_name, name=name, 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, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
|
||||
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):
|
||||
try:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
if module_name:
|
||||
instance = imp.load_module(module_name, f, filename, description)
|
||||
else:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
plugin = PluginInfo(key, filename, instance,
|
||||
name=name,
|
||||
version=version,
|
||||
@@ -855,13 +873,13 @@ class PluginManager(object):
|
||||
parsed_metadata=parsed_metadata)
|
||||
plugin.bundled = bundled
|
||||
except:
|
||||
self.logger.exception("Error loading plugin {key}".format(key=key))
|
||||
self.logger.exception(u"Error loading plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
if plugin.check():
|
||||
return plugin
|
||||
else:
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
|
||||
self.logger.info(u"Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
def _is_plugin_disabled(self, key):
|
||||
@@ -881,7 +899,7 @@ class PluginManager(object):
|
||||
self.plugin_blacklist))
|
||||
|
||||
def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None):
|
||||
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(
|
||||
self.logger.info(u"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))
|
||||
))
|
||||
|
||||
@@ -925,7 +943,7 @@ class PluginManager(object):
|
||||
try:
|
||||
if plugin.loaded and not plugin.forced_disabled:
|
||||
if plugin.blacklisted:
|
||||
self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
self.logger.warn(u"Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
continue
|
||||
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
|
||||
except PluginNeedsRestart:
|
||||
@@ -938,9 +956,9 @@ class PluginManager(object):
|
||||
force_reload=force_reload)
|
||||
|
||||
if len(self.enabled_plugins) <= 0:
|
||||
self.logger.info("No plugins found")
|
||||
self.logger.info(u"No plugins found")
|
||||
else:
|
||||
self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
|
||||
self.logger.info(u"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()))
|
||||
@@ -948,7 +966,7 @@ class PluginManager(object):
|
||||
|
||||
def mark_plugin(self, name, **kwargs):
|
||||
if not name in self.plugins:
|
||||
self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals()))
|
||||
self.logger.debug(u"Trying to mark an unknown plugin {name}".format(**locals()))
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if value is None:
|
||||
@@ -967,7 +985,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("Trying to load an unknown plugin {name}".format(**locals()))
|
||||
self.logger.warn(u"Trying to load an unknown plugin {name}".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -982,15 +1000,15 @@ class PluginManager(object):
|
||||
self.on_plugin_loaded(name, plugin)
|
||||
plugin.loaded = True
|
||||
|
||||
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
|
||||
self.logger.debug(u"Loaded plugin {name}: {plugin}".format(**locals()))
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
except:
|
||||
self.logger.exception("There was an error loading plugin %s" % name)
|
||||
self.logger.exception(u"There was an error loading plugin %s" % name)
|
||||
|
||||
def unload_plugin(self, name):
|
||||
if not name in self.plugins:
|
||||
self.logger.warn("Trying to unload unknown plugin {name}".format(**locals()))
|
||||
self.logger.warn(u"Trying to unload unknown plugin {name}".format(**locals()))
|
||||
return
|
||||
|
||||
plugin = self.plugins[name]
|
||||
@@ -1010,11 +1028,11 @@ class PluginManager(object):
|
||||
|
||||
plugin.loaded = False
|
||||
|
||||
self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals()))
|
||||
self.logger.debug(u"Unloaded plugin {name}: {plugin}".format(**locals()))
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
except:
|
||||
self.logger.exception("There was an error unloading plugin {name}".format(**locals()))
|
||||
self.logger.exception(u"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:
|
||||
@@ -1024,7 +1042,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("Tried to enable plugin {name}, however it is not disabled".format(**locals()))
|
||||
self.logger.warn(u"Tried to enable plugin {name}, however it is not disabled".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -1060,13 +1078,13 @@ class PluginManager(object):
|
||||
plugin.implementation.on_plugin_enabled()
|
||||
self.on_plugin_enabled(name, plugin)
|
||||
|
||||
self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals()))
|
||||
self.logger.debug(u"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("Tried to disable plugin {name}, however it is not enabled".format(**locals()))
|
||||
self.logger.warn(u"Tried to disable plugin {name}, however it is not enabled".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -1081,7 +1099,7 @@ class PluginManager(object):
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
except:
|
||||
self.logger.exception("There was an error while disabling plugin {name}".format(**locals()))
|
||||
self.logger.exception(u"There was an error while disabling plugin {name}".format(**locals()))
|
||||
return False
|
||||
else:
|
||||
if name in self.enabled_plugins:
|
||||
@@ -1093,7 +1111,7 @@ class PluginManager(object):
|
||||
plugin.implementation.on_plugin_disabled()
|
||||
self.on_plugin_disabled(name, plugin)
|
||||
|
||||
self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals()))
|
||||
self.logger.debug(u"Disabled plugin {name}: {plugin}".format(**locals()))
|
||||
|
||||
return True
|
||||
|
||||
@@ -1105,7 +1123,7 @@ class PluginManager(object):
|
||||
try:
|
||||
callback, order = self._get_callback_and_order(definition)
|
||||
except ValueError as e:
|
||||
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
continue
|
||||
|
||||
self._plugin_hooks[hook].append((order, name, callback))
|
||||
@@ -1124,7 +1142,7 @@ class PluginManager(object):
|
||||
try:
|
||||
callback, order = self._get_callback_and_order(definition)
|
||||
except ValueError as e:
|
||||
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
continue
|
||||
|
||||
try:
|
||||
@@ -1271,7 +1289,7 @@ class PluginManager(object):
|
||||
additional_pre_inits=additional_pre_inits,
|
||||
additional_post_inits=additional_post_inits)
|
||||
|
||||
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||
self.logger.info(u"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:
|
||||
@@ -1326,7 +1344,7 @@ class PluginManager(object):
|
||||
try:
|
||||
return_value = factory(name, implementation)
|
||||
except:
|
||||
self.logger.exception("Exception while executing injection factory %r" % factory)
|
||||
self.logger.exception(u"Exception while executing injection factory %r" % factory)
|
||||
else:
|
||||
if return_value is not None:
|
||||
if isinstance(return_value, dict):
|
||||
@@ -1350,12 +1368,12 @@ class PluginManager(object):
|
||||
if isinstance(e, PluginLifecycleException):
|
||||
raise e
|
||||
else:
|
||||
self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals()))
|
||||
self.logger.exception(u"Exception while initializing plugin {name}, disabling it".format(**locals()))
|
||||
return False
|
||||
else:
|
||||
self.on_plugin_implementations_initialized(name, plugin)
|
||||
|
||||
self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals()))
|
||||
self.logger.debug(u"Initialized plugin mixin implementation for plugin {name}".format(**locals()))
|
||||
return True
|
||||
|
||||
|
||||
@@ -1372,7 +1390,7 @@ class PluginManager(object):
|
||||
self.logger.log(level, message)
|
||||
|
||||
if len(all_plugins) <= 0:
|
||||
_log("No plugins available")
|
||||
_log(u"No plugins available")
|
||||
else:
|
||||
formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
|
||||
bundled_strs=bundled_str,
|
||||
@@ -1380,9 +1398,9 @@ class PluginManager(object):
|
||||
location_str=location_str,
|
||||
show_enabled=show_enabled,
|
||||
enabled_strs=enabled_str),
|
||||
sorted(self.plugins.values(), key=lambda x: str(x).lower())))
|
||||
_log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
|
||||
plugins=formatted_plugins))
|
||||
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))
|
||||
|
||||
def get_plugin(self, identifier, require_enabled=True):
|
||||
"""
|
||||
@@ -1474,16 +1492,17 @@ class PluginManager(object):
|
||||
try:
|
||||
sorting_value = impl[1].get_sorting_key(sorting_context)
|
||||
except:
|
||||
self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
|
||||
self.logger.exception(u"Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
|
||||
|
||||
if sorting_value is not None:
|
||||
try:
|
||||
int(sorting_value)
|
||||
sorting_value = int(sorting_value)
|
||||
except ValueError:
|
||||
self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
|
||||
self.logger.warn(u"The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
|
||||
sorting_value = None
|
||||
|
||||
return sorting_value is None, sorting_value, impl[0]
|
||||
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 [impl[1] for impl in sorted(result, key=sort_func)]
|
||||
|
||||
@@ -1558,7 +1577,7 @@ class PluginManager(object):
|
||||
|
||||
for client in self.registered_clients:
|
||||
try: client(plugin, data)
|
||||
except: self.logger.exception("Exception while sending plugin data to client")
|
||||
except: self.logger.exception(u"Exception while sending plugin data to client")
|
||||
|
||||
def _sort_hooks(self, hook):
|
||||
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
|
||||
|
||||
@@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
class OctoPrintPlugin(Plugin):
|
||||
"""
|
||||
The parent class of all OctoPrint plugin mixins.
|
||||
@@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
|
||||
externally reachable, use :func:`on_after_startup` instead or additionally.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``StartupPlugin.on_startup``.
|
||||
|
||||
:param string host: the host the server will listen on, may be ``0.0.0.0``
|
||||
@@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
Called just after launch of the server, so when the listen loop is actually running already.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``StartupPlugin.on_after_startup``.
|
||||
"""
|
||||
|
||||
@@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
Called upon the imminent shutdown of OctoPrint.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``ShutdownPlugin.on_shutdown``.
|
||||
"""
|
||||
pass
|
||||
@@ -225,6 +234,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
js
|
||||
JavaScript files, such as additional view models
|
||||
jsclient
|
||||
JavaScript files containing additional parts for the JS Client Library (since 1.3.10)
|
||||
css
|
||||
CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode.
|
||||
less
|
||||
@@ -239,6 +250,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=['js/my_file.js', 'js/my_other_file.js'],
|
||||
clientjs=['clientjs/my_file.js'],
|
||||
css=['css/my_styles.css'],
|
||||
less=['less/my_styles.less']
|
||||
)
|
||||
@@ -782,7 +794,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
def get_ui_custom_etag(self):
|
||||
"""
|
||||
Allows to use a custom way to calculate the ETag, instead of the default method (hashing
|
||||
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
|
||||
OctoPrint's version, tracked file paths and ``LastModified`` value).
|
||||
|
||||
Returns:
|
||||
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
|
||||
@@ -1379,8 +1391,9 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_blueprint_protected(self):
|
||||
"""
|
||||
Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts
|
||||
access to the blueprint's dynamic methods, static files are always accessible without API key.
|
||||
Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring
|
||||
a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files
|
||||
are always accessible.
|
||||
"""
|
||||
|
||||
return True
|
||||
@@ -1799,6 +1812,10 @@ class EventHandlerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
Called by OctoPrint upon processing of a fired event on the platform.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
Arguments:
|
||||
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
|
||||
for possible values
|
||||
@@ -1837,8 +1854,9 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
The human readable name of the slicer. This will be displayed to the user during slicer selection.
|
||||
same_device
|
||||
True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same
|
||||
device will not be allowed to slice while a print is running due to performance reasons. Slice requests
|
||||
against slicers running on the same device will result in an error.
|
||||
device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a
|
||||
print is running due to performance reasons. Slice requests against slicers running on the same device and
|
||||
less than two cores will result in an error.
|
||||
progress_report
|
||||
``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise.
|
||||
source_file_types
|
||||
@@ -1861,6 +1879,21 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
destination_extensions=["gco", "gcode", "g"]
|
||||
)
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_slicer_extension_tree(self):
|
||||
"""
|
||||
Fetch additional entries to put into the extension tree for accepted files
|
||||
|
||||
By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support
|
||||
additional/other file types will want to override this.
|
||||
|
||||
For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook <sec-plugins-hook-filemanager-extensiontree>`.
|
||||
|
||||
Returns: (dict) a dictionary containing a valid extension subtree.
|
||||
"""
|
||||
from octoprint.filemanager import ContentTypeMapping
|
||||
return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla")))
|
||||
|
||||
def get_slicer_profiles(self, profile_path):
|
||||
"""
|
||||
Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer.
|
||||
@@ -1984,7 +2017,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information
|
||||
about the slicing job under the following keys:
|
||||
|
||||
_analysis
|
||||
analysis
|
||||
Analysis result of the generated machine code as returned by the slicer itself. This should match the
|
||||
data structure described for the analysis queue of the matching machine code format, e.g.
|
||||
:class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files.
|
||||
@@ -2043,20 +2076,3 @@ class ProgressPlugin(OctoPrintPlugin):
|
||||
:param int progress: Current progress as a value between 0 and 100
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class AppPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
Using the :class:`AppPlugin mixin` plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
|
||||
within the system.
|
||||
|
||||
.. deprecated:: 1.2.0
|
||||
|
||||
Refer to the :ref:`octoprint.accesscontrol.appkey hook <sec-plugins-hook-accesscontrol-appkey>` instead.
|
||||
|
||||
"""
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_additional_apps(self):
|
||||
return []
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
# make our plugins testable
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server import user_permission
|
||||
from octoprint.events import Events
|
||||
|
||||
import flask
|
||||
from flask_babel import gettext
|
||||
@@ -34,31 +35,57 @@ class Prompt(object):
|
||||
|
||||
|
||||
class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
COMMAND = "M876"
|
||||
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._prompt = None
|
||||
self._selection_command = None
|
||||
self._enable = "detected"
|
||||
self._command = None
|
||||
self._enable_emergency_sending = False
|
||||
self._enable_signal_support = False
|
||||
self._cap_prompt_support = False
|
||||
|
||||
def initialize(self):
|
||||
self._selection_command = self._settings.get([b"selection_command"])
|
||||
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"])
|
||||
|
||||
#~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/action_command_prompt.js"])
|
||||
return dict(js=["js/action_command_prompt.js"],
|
||||
clientjs=["clientjs/action_command_prompt.js"])
|
||||
|
||||
#~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support:
|
||||
self._printer.commands(["{command} P1".format(command=self._command)])
|
||||
elif event == Events.DISCONNECTED:
|
||||
self._close_prompt()
|
||||
|
||||
#~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(selection_command=None)
|
||||
return dict(enable="detected",
|
||||
command=self.COMMAND,
|
||||
enable_emergency_sending=True,
|
||||
enable_signal_support=True)
|
||||
|
||||
def on_settings_save(self, data):
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
self._selection_command = self._settings.get([b"selection_command"])
|
||||
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"])
|
||||
|
||||
#~ SimpleApiPlugin
|
||||
|
||||
@@ -98,10 +125,6 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
if not action.startswith(b"prompt_"):
|
||||
return
|
||||
|
||||
if self._selection_command is None:
|
||||
self._logger.info("Got a prompt command from the printer but no selection command is defined")
|
||||
return
|
||||
|
||||
parts = action.split(None, 1)
|
||||
if len(parts) == 1:
|
||||
action = parts[0]
|
||||
@@ -137,30 +160,66 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._close_prompt()
|
||||
self._prompt = None
|
||||
|
||||
#~ queuing handling
|
||||
|
||||
def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs):
|
||||
if gcode != self._command:
|
||||
return
|
||||
|
||||
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending:
|
||||
return
|
||||
|
||||
if not "S" in cmd:
|
||||
# we only force-send M876 Sx
|
||||
return
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode)
|
||||
|
||||
#~ capability reporting
|
||||
|
||||
def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs):
|
||||
if capability == self.CAP_PROMPT_SUPPORT and enabled:
|
||||
self._cap_prompt_support = True
|
||||
if self._enable == "detected" and self._enable_signal_support:
|
||||
self._printer.commands(["{command} P1".format(command=self._command)])
|
||||
|
||||
#~ prompt handling
|
||||
|
||||
def _show_prompt(self):
|
||||
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
|
||||
return
|
||||
|
||||
self._prompt.activate()
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(action="show",
|
||||
text=self._prompt.text,
|
||||
choices=self._prompt.choices))
|
||||
|
||||
def _close_prompt(self):
|
||||
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
|
||||
return
|
||||
|
||||
self._prompt = None
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(action="close"))
|
||||
|
||||
def _answer_prompt(self, choice):
|
||||
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
|
||||
return
|
||||
|
||||
self._close_prompt()
|
||||
self._printer.commands([self._selection_command.format(choice=choice)])
|
||||
self._printer.commands(["{command} S{choice}".format(command=self._command,
|
||||
choice=choice)])
|
||||
|
||||
|
||||
__plugin_name__ = "Action Command Prompt Support"
|
||||
__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
|
||||
"confirmation or selection prompts in OctoPrint")
|
||||
" confirmation or selection prompts in OctoPrint")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = ActionCommandPromptPlugin()
|
||||
__plugin_hooks__ = {
|
||||
b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
|
||||
var data = {
|
||||
choice: choice
|
||||
};
|
||||
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
|
||||
return OctoPrintActionCommandPromptClient;
|
||||
});
|
||||
@@ -1,36 +1,20 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
|
||||
var data = {
|
||||
choice: choice
|
||||
};
|
||||
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
|
||||
return OctoPrintActionCommandPromptClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function ActionCommandPromptViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self._modal = undefined;
|
||||
self.modal = ko.observable(undefined);
|
||||
|
||||
self.text = ko.observable();
|
||||
self.buttons = ko.observableArray([]);
|
||||
|
||||
self.active = ko.pureComputed(function() {
|
||||
return self.text() !== undefined;
|
||||
});
|
||||
self.visible = ko.pureComputed(function() {
|
||||
return self.modal() !== undefined;
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.isUser()) return;
|
||||
@@ -41,26 +25,35 @@ $(function() {
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
|
||||
self._showPrompt(data.text, data.choices);
|
||||
self.text(data.text);
|
||||
self.buttons(data.choices);
|
||||
self.showPrompt();
|
||||
} else {
|
||||
self.text(undefined);
|
||||
self.buttons([]);
|
||||
}
|
||||
};
|
||||
|
||||
self._showPrompt = function(text, buttons) {
|
||||
self.showPrompt = function() {
|
||||
var text = self.text();
|
||||
var buttons = self.buttons();
|
||||
|
||||
var opts = {
|
||||
title: gettext("Message from your printer"),
|
||||
message: text,
|
||||
selections: buttons,
|
||||
maycancel: true, // see #3171
|
||||
onselect: function(index) {
|
||||
if (index > -1) {
|
||||
self._select(index);
|
||||
}
|
||||
},
|
||||
onclose: function() {
|
||||
self._modal = undefined;
|
||||
self.modal(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
self._modal = showSelectionDialog(opts)
|
||||
self.modal(showSelectionDialog(opts));
|
||||
};
|
||||
|
||||
self._select = function(index) {
|
||||
@@ -68,8 +61,9 @@ $(function() {
|
||||
};
|
||||
|
||||
self._closePrompt = function() {
|
||||
if (self._modal) {
|
||||
self._modal.modal("hide");
|
||||
var modal = self.modal();
|
||||
if (modal) {
|
||||
modal.modal("hide");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -85,10 +79,14 @@ $(function() {
|
||||
|
||||
switch (data.action) {
|
||||
case "show": {
|
||||
self._showPrompt(data.text, data.choices);
|
||||
self.text(data.text);
|
||||
self.buttons(data.choices);
|
||||
self.showPrompt();
|
||||
break;
|
||||
}
|
||||
case "close": {
|
||||
self.text(undefined);
|
||||
self.buttons([]);
|
||||
self._closePrompt();
|
||||
break;
|
||||
}
|
||||
@@ -99,6 +97,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ActionCommandPromptViewModel,
|
||||
dependencies: ["loginStateViewModel"]
|
||||
dependencies: ["loginStateViewModel"],
|
||||
elements: ["#navbar_plugin_action_command_prompt"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
<a id="navbar_show_prompt" class="pull-right" style="display: none" href="javascript:void(0)" data-bind="click: function() { showPrompt(); }, visible: active() && !visible()" title="{{ _('Message from your printer')|edq }}">
|
||||
<i class="fa fa-commenting-o"></i>
|
||||
</a>
|
||||
@@ -2,10 +2,43 @@
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Selection Command') }}</label>
|
||||
<label class="control-label">{{ _('Enable support')}}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.selection_command">
|
||||
<div class="help-block">{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace <code>{choice}</code> with the index of the selected choice. E.g. <code>M876 S{choice}</code> will become <code>M123 S1</code>') }}</div>
|
||||
<label class="radio">
|
||||
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="detected" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('If detected as supported by the firmware (<code>PROMPT_SUPPORT</code> capability)') }}
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="always" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('Always') }}
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="never" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('Never') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="advanced_options">
|
||||
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Dialog command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.command">
|
||||
<div class="help-block">{{ _('Use this to define the dialog command. Default is <code>M876</code>. You normally should not have to change this.') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.action_command_prompt.enable_emergency_sending"> {{ _('Enable force sending of the configured command to bypass blocking firmware routines if detected as supported. You normally should not have to change this.') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.action_command_prompt.enable_signal_support"> {{ _('Enable signaling to the firmware that we support <code>prompt_*</code> actions if detected as supported. You normally should not have to change this.') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -22,7 +22,7 @@ from collections import OrderedDict
|
||||
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify
|
||||
from octoprint.util import utmify, monotonic_time
|
||||
from flask_babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
|
||||
@@ -351,10 +351,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
url = config["url"]
|
||||
try:
|
||||
start = time.time()
|
||||
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"], time.time() - start))
|
||||
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start))
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e)))
|
||||
@@ -372,15 +372,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
result = []
|
||||
if "entries" in feed:
|
||||
for entry in feed["entries"]:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
try:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
except:
|
||||
self._logger.exception("Error while converting entry from feed, skipping it")
|
||||
return result
|
||||
|
||||
def _to_internal_entry(self, entry, read_until=None):
|
||||
"""Convert feed entries to internal data structure."""
|
||||
|
||||
published = calendar.timegm(entry["published_parsed"])
|
||||
timestamp = entry.get("published_parsed",
|
||||
entry.get("updated_parsed",
|
||||
None))
|
||||
if timestamp is None:
|
||||
return None
|
||||
|
||||
published = calendar.timegm(timestamp)
|
||||
|
||||
read = True
|
||||
if read_until is not None:
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
|
||||
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements')|edq }}">
|
||||
<i class="fa" data-bind="css: {'fa-bell-o': !unread(), 'fa-bell': unread()}"></i>
|
||||
</a>
|
||||
@@ -0,0 +1,426 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import flask
|
||||
import threading
|
||||
import os
|
||||
import yaml
|
||||
import codecs
|
||||
import time
|
||||
from binascii import hexlify
|
||||
from collections import defaultdict
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
||||
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
||||
from octoprint.users import DummyUser
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
|
||||
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
|
||||
class AppAlreadyExists(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PendingDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
self.user_token = user_token
|
||||
self.created = monotonic_time()
|
||||
|
||||
if callable(timeout_callback):
|
||||
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
|
||||
self.poll_timeout.start()
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
user_id=self.user_id,
|
||||
user_token=self.user_token)
|
||||
|
||||
def __repr__(self):
|
||||
return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id,
|
||||
self.app_token,
|
||||
self.user_id,
|
||||
self.user_token)
|
||||
|
||||
|
||||
class ReadyDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
|
||||
@classmethod
|
||||
def for_pending(cls, pending, user_id):
|
||||
return cls(pending.app_id, pending.app_token, user_id)
|
||||
|
||||
def __repr__(self):
|
||||
return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id,
|
||||
self.app_token,
|
||||
self.user_id)
|
||||
|
||||
|
||||
class ActiveKey(object):
|
||||
def __init__(self, app_id, api_key, user_id):
|
||||
self.app_id = app_id
|
||||
self.api_key = api_key
|
||||
self.user_id = user_id
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key,
|
||||
user_id=self.user_id)
|
||||
|
||||
def internal(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key)
|
||||
|
||||
@classmethod
|
||||
def for_internal(cls, internal, user_id):
|
||||
return cls(internal["app_id"], internal["api_key"], user_id)
|
||||
|
||||
def __repr__(self):
|
||||
return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id,
|
||||
self.api_key,
|
||||
self.user_id)
|
||||
|
||||
|
||||
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._pending_decisions = []
|
||||
self._pending_lock = threading.RLock()
|
||||
|
||||
self._ready_decisions = []
|
||||
self._ready_lock = threading.RLock()
|
||||
|
||||
self._keys = defaultdict(list)
|
||||
self._keys_lock = threading.RLock()
|
||||
|
||||
self._key_path = None
|
||||
|
||||
def initialize(self):
|
||||
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
|
||||
self._load_keys()
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="usersettings", name=gettext("Application Keys")),
|
||||
dict(type="settings", name=gettext("Application Keys"))]
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/appkeys.js"],
|
||||
clientjs=["clientjs/appkeys.js"],
|
||||
less=["less/appkeys.less"],
|
||||
css=["css/appkeys.css"])
|
||||
|
||||
##~~ BlueprintPlugin mixin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def handle_probe(self):
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
def handle_request(self):
|
||||
data = flask.request.json
|
||||
if data is None:
|
||||
return flask.make_response("Missing key request", 400)
|
||||
|
||||
if not "app" in data:
|
||||
return flask.make_response("No app name provided", 400)
|
||||
|
||||
app_name = data["app"]
|
||||
user_id = None
|
||||
if "user" in data and data["user"]:
|
||||
user_id = data["user"]
|
||||
|
||||
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
|
||||
app_name=app_name,
|
||||
user_token=user_token,
|
||||
user_id=user_id))
|
||||
response = flask.jsonify(app_token=app_token)
|
||||
response.status_code = 201
|
||||
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
||||
@no_firstrun_access
|
||||
def handle_decision_poll(self, app_token):
|
||||
result = self._get_pending_by_app_token(app_token)
|
||||
if result:
|
||||
for pending_decision in result:
|
||||
pending_decision.poll_timeout.reset()
|
||||
|
||||
response = flask.jsonify(message="Awaiting decision")
|
||||
response.status_code = 202
|
||||
return response
|
||||
|
||||
result = self._get_decision(app_token)
|
||||
if result:
|
||||
return flask.jsonify(api_key=result)
|
||||
|
||||
return flask.abort(404)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
|
||||
@restricted_access
|
||||
def handle_decision(self, user_token):
|
||||
data = flask.request.json
|
||||
if not "decision" in data:
|
||||
return flask.make_response("No decision provided", 400)
|
||||
decision = data["decision"] in valid_boolean_trues
|
||||
user_id = current_user.get_name()
|
||||
|
||||
result = self._set_decision(user_token, decision, user_id)
|
||||
if not result:
|
||||
return flask.abort(404)
|
||||
|
||||
# Close access_request dialog for this request on all open OctoPrint connections
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
return False # No API key required to request API access
|
||||
|
||||
##~~ SimpleApiPlugin mixin
|
||||
|
||||
def get_api_commands(self):
|
||||
return dict(generate=["app"],
|
||||
revoke=["key"])
|
||||
|
||||
def on_api_get(self, request):
|
||||
user_id = current_user.get_name()
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
|
||||
keys = self._all_api_keys()
|
||||
else:
|
||||
keys = self._api_keys_for_user(user_id)
|
||||
|
||||
return flask.jsonify(keys=map(lambda x: x.external(), keys),
|
||||
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
user_id = current_user.get_name()
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if command == "revoke":
|
||||
api_key = data.get("key")
|
||||
if not api_key:
|
||||
return flask.abort(400)
|
||||
|
||||
if not admin_permission.can():
|
||||
user_for_key = self._user_for_api_key(api_key)
|
||||
if user_for_key is None or user_for_key.user_id != user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
self._delete_api_key(api_key)
|
||||
|
||||
elif command == "generate":
|
||||
# manual generateKey
|
||||
app_name = data.get("app")
|
||||
if not app_name:
|
||||
return flask.abort(400)
|
||||
|
||||
self._add_api_key(user_id, app_name.strip())
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
##~~ key validator hook
|
||||
|
||||
def validate_api_key(self, api_key, *args, **kwargs):
|
||||
return self._user_for_api_key(api_key)
|
||||
|
||||
##~~ Helpers
|
||||
|
||||
def _add_pending_decision(self, app_name, user_id=None):
|
||||
app_token = self._generate_key()
|
||||
user_token = self._generate_key()
|
||||
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
|
||||
timeout_callback=self._expire_pending))
|
||||
|
||||
return app_token, user_token
|
||||
|
||||
def _get_pending_by_app_token(self, app_token):
|
||||
result = []
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.app_token == app_token:
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _get_pending_by_user_id(self, user_id):
|
||||
result = []
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.user_id == user_id or data.user_id is None:
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _expire_pending(self, user_token):
|
||||
with self._pending_lock:
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
len_after = len(self._pending_decisions)
|
||||
|
||||
if len_after < len_before:
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
|
||||
def _remove_stale_pending(self):
|
||||
with self._pending_lock:
|
||||
cutoff = monotonic_time() - CUTOFF_TIME
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.created >= cutoff,
|
||||
self._pending_decisions)
|
||||
len_after = len(self._pending_decisions)
|
||||
if len_after < len_before:
|
||||
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
|
||||
|
||||
def _set_decision(self, user_token, decision, user_id):
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
|
||||
pending = data
|
||||
break
|
||||
else:
|
||||
return False # not found
|
||||
|
||||
if decision:
|
||||
with self._ready_lock:
|
||||
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
|
||||
|
||||
with self._pending_lock:
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
|
||||
return True
|
||||
|
||||
def _get_decision(self, app_token):
|
||||
self._remove_stale_pending()
|
||||
|
||||
with self._ready_lock:
|
||||
for data in self._ready_decisions:
|
||||
if data.app_token == app_token:
|
||||
decision = data
|
||||
break
|
||||
else:
|
||||
return False # not found
|
||||
|
||||
api_key = self._add_api_key(decision.user_id, decision.app_id)
|
||||
|
||||
with self._ready_lock:
|
||||
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
|
||||
|
||||
return api_key
|
||||
|
||||
def _add_api_key(self, user_id, app_name):
|
||||
with self._keys_lock:
|
||||
for key in self._keys[user_id]:
|
||||
if key.app_id.lower() == app_name.lower():
|
||||
return key.api_key
|
||||
|
||||
key = ActiveKey(app_name, self._generate_key(), user_id)
|
||||
self._keys[user_id].append(key)
|
||||
self._save_keys()
|
||||
return key.api_key
|
||||
|
||||
def _delete_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
self._keys[user_id] = filter(lambda x: x.api_key != api_key, data)
|
||||
self._save_keys()
|
||||
|
||||
def _user_for_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
if filter(lambda x: x.api_key == api_key, data):
|
||||
if self._user_manager.enabled:
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
elif user_id == "dummy":
|
||||
return DummyUser()
|
||||
return None
|
||||
|
||||
def _api_keys_for_user(self, user_id):
|
||||
with self._keys_lock:
|
||||
return self._keys[user_id]
|
||||
|
||||
def _all_api_keys(self):
|
||||
with self._keys_lock:
|
||||
result = []
|
||||
for user_id, keys in self._keys.items():
|
||||
result += keys
|
||||
return result
|
||||
|
||||
def _generate_key(self):
|
||||
return hexlify(os.urandom(16))
|
||||
|
||||
def _load_keys(self):
|
||||
with self._keys_lock:
|
||||
if not os.path.exists(self._key_path):
|
||||
return
|
||||
|
||||
try:
|
||||
with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
|
||||
persisted = yaml.safe_load(f)
|
||||
except:
|
||||
self._logger.exception("Could not load application keys from {}".format(self._key_path))
|
||||
return
|
||||
|
||||
if not isinstance(persisted, dict):
|
||||
return
|
||||
|
||||
keys = defaultdict(list)
|
||||
for user_id, persisted_keys in persisted.items():
|
||||
keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
|
||||
self._keys = keys
|
||||
|
||||
def _save_keys(self):
|
||||
with self._keys_lock:
|
||||
to_persist = dict()
|
||||
for user_id, keys in self._keys.items():
|
||||
to_persist[user_id] = [x.internal() for x in keys]
|
||||
|
||||
try:
|
||||
with atomic_write(self._key_path) as f:
|
||||
yaml.safe_dump(to_persist, f)
|
||||
except:
|
||||
self._logger.exception("Could not write application keys to {}".format(self._key_path))
|
||||
|
||||
__plugin_name__ = u"Application Keys Plugin"
|
||||
__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys"
|
||||
__plugin_author__ = u"Gina Häußge, Aldo Hoeben"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to "
|
||||
u"obtain an API key without you manually copy-pasting it.")
|
||||
__plugin_implementation__ = AppKeysPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintAppKeysClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
|
||||
return this.base.simpleApiGet("appkeys", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
|
||||
return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.probe = function(opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
|
||||
return this.requestForUser(app, undefined, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
|
||||
var deferred = $.Deferred();
|
||||
var client = this;
|
||||
|
||||
client.probe()
|
||||
.done(function() {
|
||||
client.requestForUser(app, user)
|
||||
.done(function(response) {
|
||||
var token = response.app_token;
|
||||
if (!token) {
|
||||
// no token received, something went wrong
|
||||
deferred.reject();
|
||||
return;
|
||||
}
|
||||
|
||||
var interval = 1000;
|
||||
var poll = function() {
|
||||
client.checkDecision(token)
|
||||
.done(function(response) {
|
||||
if (response.api_key) {
|
||||
// got a decision, resolve the promise
|
||||
deferred.resolve(response.api_key);
|
||||
} else {
|
||||
// no decision yet, poll a bit more
|
||||
deferred.notify();
|
||||
window.setTimeout(poll, interval);
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
};
|
||||
window.setTimeout(poll, interval);
|
||||
})
|
||||
.fail(function() {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
})
|
||||
.fail(function() {
|
||||
// workflow unsupported
|
||||
deferred.reject();
|
||||
});
|
||||
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient);
|
||||
return OctoPrintAppKeysClient;
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}
|
||||
@@ -0,0 +1,308 @@
|
||||
$(function() {
|
||||
function UserAppKeysViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.userkeys",
|
||||
{
|
||||
"app": function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
|
||||
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"app",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
);
|
||||
self.pending = {};
|
||||
self.openRequests = {};
|
||||
|
||||
self.editorApp = ko.observable();
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getKeys()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
self.pending = response.pending;
|
||||
_.each(self.pending, function(data, token) {
|
||||
self.openRequests[token] = self.promptForAccess(data.app_id, token);
|
||||
})
|
||||
};
|
||||
|
||||
self.generateKey = function() {
|
||||
return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
|
||||
.done(self.requestData)
|
||||
.done(function() {
|
||||
self.editorApp("");
|
||||
});
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.allowApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, true)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.denyApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, false)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.promptForAccess = function(app, token) {
|
||||
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
|
||||
message = _.sprintf(message, {app: app});
|
||||
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
|
||||
return new PNotify({
|
||||
title: gettext("Access Request"),
|
||||
text: message,
|
||||
hide: false,
|
||||
icon: "fa fa-key",
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Allow"),
|
||||
click: function(notice) {
|
||||
self.allowApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}, {
|
||||
text: gettext("Deny"),
|
||||
click: function(notice) {
|
||||
self.denyApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
},
|
||||
buttons: {
|
||||
sticker: false,
|
||||
closer: false
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onUserSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "appkeys") {
|
||||
return;
|
||||
}
|
||||
|
||||
var app, token, user;
|
||||
|
||||
if (data.type === "request_access" && self.loginState.isUser()) {
|
||||
app = data.app_name;
|
||||
token = data.user_token;
|
||||
user = data.user_id;
|
||||
|
||||
if (user && user !== self.loginState.username()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.pending[token] !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.openRequests[token] = self.promptForAccess(app, token);
|
||||
|
||||
} else if (data.type === "end_request") {
|
||||
token = data.user_token;
|
||||
|
||||
if (self.openRequests[token] !== undefined) {
|
||||
// another instance responded to the access request before the current user did
|
||||
if (self.openRequests[token].state !== "closed") {
|
||||
self.openRequests[token].remove();
|
||||
}
|
||||
delete self.openRequests[token]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function AllAppKeysViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.allkeys",
|
||||
{
|
||||
"user_app": function (a, b) {
|
||||
// sorts ascending, first by user, then by app
|
||||
if (a["user_id"] > b["user_id"]) return 1;
|
||||
if (a["user_id"] < b["user_id"]) return -1;
|
||||
|
||||
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
|
||||
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"user_app",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
self.users = ko.observableArray([]);
|
||||
self.apps = ko.observableArray([]);
|
||||
|
||||
self.markedForDeletion = ko.observableArray([]);
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getAllKeys()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
|
||||
var users = [];
|
||||
var apps = [];
|
||||
_.each(response.keys, function(key) {
|
||||
users.push(key.user_id);
|
||||
apps.push(key.app_id.toLowerCase());
|
||||
});
|
||||
|
||||
users = _.uniq(users);
|
||||
users.sort();
|
||||
self.users(users);
|
||||
|
||||
apps = _.uniq(apps);
|
||||
apps.sort();
|
||||
self.apps(apps);
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.revokeMarked = function() {
|
||||
var perform = function() {
|
||||
self._bulkRevoke(self.markedForDeletion())
|
||||
.done(function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markAllOnPageForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
|
||||
};
|
||||
|
||||
self.markAllForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
|
||||
};
|
||||
|
||||
self.markAllByUserForDeletion = function(user) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
|
||||
};
|
||||
|
||||
self.markAllByAppForDeletion = function(app) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); })
|
||||
};
|
||||
|
||||
self.markAllByFilterForDeletion = function(filter) {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))));
|
||||
};
|
||||
|
||||
self.clearMarked = function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
};
|
||||
|
||||
self._bulkRevoke = function(keys) {
|
||||
var title, message, handler;
|
||||
|
||||
title = gettext("Revoking application keys");
|
||||
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length});
|
||||
handler = function(key) {
|
||||
return OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: keys.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(keys, function(key) {
|
||||
var request = handler(key);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UserAppKeysViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#usersettings_plugin_appkeys"]
|
||||
]);
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AllAppKeysViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#settings_plugin_appkeys"]
|
||||
])
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
#settings_plugin_appkeys_userkeys_table,
|
||||
#settings_plugin_appkeys_allkeys_table {
|
||||
.settings_plugin_appkeys_app {
|
||||
}
|
||||
.settings_plugin_appkeys_actions {
|
||||
width: 75px;
|
||||
text-align: center;
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
}
|
||||
.settings_plugin_appkeys_user {
|
||||
width: 100px;
|
||||
}
|
||||
.settings_plugin_appkeys_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<div data-bind="visible: keys.allSize() <= 0">
|
||||
<p>{{ _('There are no application keys registered yet.') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: keys.allSize() > 0">
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllOnPageForDeletion">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllForDeletion">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li class="dropdown-submenu">
|
||||
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by user...') }}</a>
|
||||
<ul class="dropdown-menu" data-bind="foreach: users">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByUserForDeletion($data) }, text: $data"></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="dropdown-submenu">
|
||||
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by app...') }}</a>
|
||||
<ul class="dropdown-menu" data-bind="foreach: apps">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByAppForDeletion($data) }, text: $data"></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarked">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: revokeMarked, enable: markedForDeletion().length > 0">{{ _('Revoke selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_allkeys_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_appkeys_checkbox"></th>
|
||||
<th class="settings_plugin_appkeys_user">{{ _('User') }}</th>
|
||||
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
|
||||
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_checkbox"><input type="checkbox" data-bind="value: api_key, checked: $root.markedForDeletion"></td>
|
||||
<td class="settings_plugin_appkeys_user"><span data-bind="text: user_id"></span></td>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard')|edq }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke')|edq }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: keys.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,49 @@
|
||||
<legend>{{ _('Registered application keys') }}</legend>
|
||||
|
||||
<div data-bind="visible: keys.allSize() <= 0">
|
||||
<p>{{ _('There are no application keys registered yet.') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: keys.allSize() > 0">
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_userkeys_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
|
||||
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard')|edq }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke')|edq }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: keys.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('Manually generate an application key') }}</legend>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Application identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" data-bind="value: editorApp">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="click: generateKey">{{ _('Generate') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,960 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.plugin.core import FolderOrigin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import is_os_compatible
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
try:
|
||||
import zlib # check if zlib is available
|
||||
except ImportError:
|
||||
zlib = None
|
||||
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import codecs
|
||||
import flask
|
||||
import logging
|
||||
import os
|
||||
import requests
|
||||
import sarge
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
import json
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
|
||||
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
|
||||
|
||||
BACKUP_FILE_PREFIX = "octoprint-backup"
|
||||
|
||||
BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S"
|
||||
|
||||
def build_backup_filename():
|
||||
return "{}-{}.zip".format(BACKUP_FILE_PREFIX,
|
||||
time.strftime(BACKUP_DATE_TIME_FMT))
|
||||
|
||||
|
||||
class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin):
|
||||
|
||||
_pip_caller = None
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._in_progress = []
|
||||
self._in_progress_lock = threading.RLock()
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
self._clean_dir_backup(self._settings._basedir,
|
||||
on_log_progress=self._logger.info)
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/backup.js"],
|
||||
clientjs=["clientjs/backup.js"],
|
||||
css=["css/backup.css"],
|
||||
less=["less/backup.less"])
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="settings", name=gettext(u"Backup & Restore"))]
|
||||
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_state(self):
|
||||
backups = self._get_backups()
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(backups=backups,
|
||||
backup_in_progress=len(self._in_progress) > 0,
|
||||
unknown_plugins=unknown_plugins,
|
||||
restore_supported=is_os_compatible(["!windows"]))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_unknown_plugins(self):
|
||||
# TODO add caching
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(unknown_plugins=unknown_plugins)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def delete_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
pass
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_backups(self):
|
||||
backups = self._get_backups()
|
||||
return flask.jsonify(backups=backups)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def create_backup(self):
|
||||
backup_file = build_backup_filename()
|
||||
|
||||
data = flask.request.json
|
||||
exclude = data.get("exclude", [])
|
||||
|
||||
def on_backup_start(name, temporary_path, exclude):
|
||||
self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path,
|
||||
u",".join(exclude) if len(exclude) else "-"))
|
||||
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.append(name)
|
||||
self._send_client_message("backup_started", payload=dict(name=name))
|
||||
|
||||
def on_backup_done(name, final_path, exclude):
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.remove(name)
|
||||
self._send_client_message("backup_done", payload=dict(name=name))
|
||||
|
||||
self._logger.info(u"... done creating backup zip.")
|
||||
|
||||
def on_backup_error(name, exc_info):
|
||||
with self._in_progress_lock:
|
||||
try:
|
||||
self._in_progress.remove(name)
|
||||
except ValueError:
|
||||
# we'll ignore that
|
||||
pass
|
||||
|
||||
self._send_client_message("backup_error", payload=dict(name=name,
|
||||
error=u"{}".format(exc_info[1])))
|
||||
self._logger.error(u"Error while creating backup zip", exc_info=exc_info)
|
||||
|
||||
thread = threading.Thread(target=self._create_backup,
|
||||
args=(backup_file,),
|
||||
kwargs=dict(exclude=exclude,
|
||||
settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_backup_start=on_backup_start,
|
||||
on_backup_done=on_backup_done,
|
||||
on_backup_error=on_backup_error))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
response = flask.jsonify(started=True,
|
||||
name=backup_file)
|
||||
response.status_code = 201
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def delete_backup(self, filename):
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
full_path = os.path.realpath(os.path.join(backup_folder, filename))
|
||||
if full_path.startswith(backup_folder) \
|
||||
and os.path.exists(full_path) \
|
||||
and not is_hidden_path(full_path):
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except:
|
||||
self._logger.exception(u"Could not delete {}".format(filename))
|
||||
raise
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def perform_restore(self):
|
||||
if not is_os_compatible(["!windows"]):
|
||||
return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400)
|
||||
|
||||
input_name = "file"
|
||||
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
||||
|
||||
if input_upload_path in flask.request.values:
|
||||
# file to restore was uploaded
|
||||
path = flask.request.values[input_upload_path]
|
||||
|
||||
elif flask.request.json and "path" in flask.request.json:
|
||||
# existing backup is supposed to be restored
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"]))
|
||||
if not path.startswith(backup_folder) \
|
||||
or not os.path.exists(path) \
|
||||
or is_hidden_path(path):
|
||||
return flask.abort(404)
|
||||
|
||||
else:
|
||||
return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400)
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def on_log(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", dict(line=line, type="stdout"))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
|
||||
octoprint_compatible=octoprint_compatible,
|
||||
os_compatible=os_compatible))
|
||||
continue
|
||||
|
||||
self._logger.info(u"Installing plugin {}".format(plugin["id"]))
|
||||
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=on_log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
self._send_client_message("unknown_plugins", payload=dict(plugins=plugins))
|
||||
|
||||
def on_log_progress(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stdout"))
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
self._logger.error(line, exc_info=exc_info)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stderr"))
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr"))
|
||||
|
||||
def on_restore_start(path):
|
||||
self._send_client_message("restore_started")
|
||||
|
||||
def on_restore_done(path):
|
||||
self._send_client_message("restore_done")
|
||||
|
||||
def on_restore_failed(path):
|
||||
self._send_client_message("restore_failed")
|
||||
|
||||
def on_invalid_backup(line):
|
||||
on_log_error(line)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
archive.close()
|
||||
shutil.copy(path, archive.name)
|
||||
path = archive.name
|
||||
|
||||
# noinspection PyTypeChecker
|
||||
thread = threading.Thread(target=self._restore_backup,
|
||||
args=(path,),
|
||||
kwargs=dict(settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_invalid_backup=on_invalid_backup,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_restore_start=on_restore_start,
|
||||
on_restore_done=on_restore_done,
|
||||
on_restore_failed=on_restore_failed))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return flask.jsonify(started=True)
|
||||
|
||||
##~~ tornado hook
|
||||
|
||||
def route_hook(self, *args, **kwargs):
|
||||
from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.server import app
|
||||
from octoprint.server.util.tornado import access_validation_factory
|
||||
from octoprint.server.util.flask import admin_validator
|
||||
|
||||
return [
|
||||
(r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(),
|
||||
as_attachment=True,
|
||||
path_validation=path_validation_factory(lambda path: not is_hidden_path(path),
|
||||
status_code=404),
|
||||
access_validation=access_validation_factory(app, admin_validator)))
|
||||
]
|
||||
|
||||
def bodysize_hook(self, current_max_body_sizes, *args, **kwargs):
|
||||
# max upload size of 1GB for the restore endpoint
|
||||
return [("POST", r"/restore", 1024 * 1024 * 1024)]
|
||||
|
||||
##~~ CLI hook
|
||||
|
||||
def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
import click
|
||||
|
||||
@click.command("backup")
|
||||
@click.option("--exclude", multiple=True,
|
||||
help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or "
|
||||
"'timelapse' to exclude timelapses.")
|
||||
def backup_command(exclude):
|
||||
"""
|
||||
Creates a new backup.
|
||||
"""
|
||||
|
||||
backup_file = build_backup_filename()
|
||||
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
|
||||
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
click.echo("Creating backup at {}, please wait...".format(backup_file))
|
||||
self._create_backup(backup_file,
|
||||
exclude=exclude,
|
||||
settings=settings,
|
||||
plugin_manager=cli_group.plugin_manager,
|
||||
datafolder=datafolder)
|
||||
click.echo("Done.")
|
||||
|
||||
@click.command("restore")
|
||||
@click.argument("path")
|
||||
def restore_command(path):
|
||||
"""
|
||||
Restores an existing backup from the backup zip provided as argument.
|
||||
|
||||
OctoPrint does not need to run for this to proceed.
|
||||
"""
|
||||
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
|
||||
plugin_manager = cli_group.plugin_manager
|
||||
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
# register plugin manager plugin setting overlays
|
||||
plugin_info = plugin_manager.get_plugin_info("pluginmanager")
|
||||
if plugin_info and plugin_info.implementation:
|
||||
default_settings_overlay = dict(plugins=dict())
|
||||
default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults()
|
||||
settings.add_overlay(default_settings_overlay, at_end=True)
|
||||
|
||||
if not os.path.isabs(path):
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
path = os.path.join(datafolder, path)
|
||||
|
||||
if not os.path.exists(path):
|
||||
click.echo(u"Backup {} does not exist".format(path), err=True)
|
||||
sys.exit(-1)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
archive.close()
|
||||
shutil.copy(path, archive.name)
|
||||
path = archive.name
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def log(line):
|
||||
click.echo(u"\t{}".format(line))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
continue
|
||||
|
||||
click.echo(u"Installing plugin {}".format(plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.")
|
||||
for plugin in plugins:
|
||||
click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
|
||||
|
||||
def on_log_progress(line):
|
||||
click.echo(line)
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
click.echo(line, err=True)
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
click.echo(line.rstrip(), err=True)
|
||||
|
||||
if self._restore_backup(path,
|
||||
settings=settings,
|
||||
plugin_manager=plugin_manager,
|
||||
datafolder=datafolder,
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_invalid_backup=on_log_error):
|
||||
click.echo(u"Restored from {}".format(path))
|
||||
else:
|
||||
click.echo(u"Restoring from {} failed".format(path), err=True)
|
||||
|
||||
return [backup_command, restore_command]
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def _get_backups(self):
|
||||
backups = []
|
||||
for entry in scandir(self.get_plugin_data_folder()):
|
||||
if is_hidden_path(entry.path):
|
||||
continue
|
||||
if not entry.is_file():
|
||||
continue
|
||||
if not entry.name.endswith(".zip"):
|
||||
continue
|
||||
|
||||
backups.append(dict(name=entry.name,
|
||||
date=entry.stat().st_mtime,
|
||||
size=entry.stat().st_size,
|
||||
url=flask.url_for("index") + "plugin/backup/download/" + entry.name))
|
||||
return backups
|
||||
|
||||
def _get_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
if os.path.exists(data_file):
|
||||
try:
|
||||
with codecs.open(data_file, mode="r", encoding="utf-8") as f:
|
||||
unknown_plugins = json.load(f)
|
||||
|
||||
assert isinstance(unknown_plugins, list)
|
||||
assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins))
|
||||
|
||||
installed_plugins = self._plugin_manager.plugins
|
||||
unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
|
||||
if not unknown_plugins:
|
||||
# no plugins left uninstalled, delete data file
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return unknown_plugins
|
||||
except:
|
||||
self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file))
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def _clean_dir_backup(cls, basedir,
|
||||
on_log_progress=None):
|
||||
basedir_backup = basedir + ".bck"
|
||||
|
||||
if os.path.exists(basedir_backup):
|
||||
def remove_bck():
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Found config folder backup from prior restore, deleting it...")
|
||||
shutil.rmtree(basedir_backup)
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"... deleted.")
|
||||
|
||||
thread = threading.Thread(target=remove_bck)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
@classmethod
|
||||
def _get_disk_size(cls, path, ignored=None):
|
||||
if ignored is None:
|
||||
ignored = []
|
||||
|
||||
if path in ignored:
|
||||
return 0
|
||||
|
||||
total = 0
|
||||
for entry in scandir(path):
|
||||
if entry.is_dir():
|
||||
total += cls._get_disk_size(entry.path, ignored=ignored)
|
||||
elif entry.is_file():
|
||||
total += entry.stat().st_size
|
||||
return total
|
||||
|
||||
@classmethod
|
||||
def _free_space(cls, path, size):
|
||||
from psutil import disk_usage
|
||||
return disk_usage(path).free > size
|
||||
|
||||
@classmethod
|
||||
def _get_plugin_repository_data(cls, url, logger=None):
|
||||
if logger is None:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
except:
|
||||
logger.exception(u"Error while fetching the plugin repository data from {}".format(url))
|
||||
return dict()
|
||||
|
||||
from octoprint.plugins.pluginmanager import map_repository_entry
|
||||
return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()))
|
||||
|
||||
@classmethod
|
||||
def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None):
|
||||
if pip_args is None:
|
||||
pip_args = []
|
||||
|
||||
if on_log is None:
|
||||
on_log = logging.getLogger(__name__).info
|
||||
|
||||
# prepare pip caller
|
||||
def log(prefix, *lines):
|
||||
for line in lines:
|
||||
on_log(u"{} {}".format(prefix, line.rstrip()))
|
||||
|
||||
def log_call(*lines):
|
||||
log(u">", *lines)
|
||||
|
||||
def log_stdout(*lines):
|
||||
log(u"<", *lines)
|
||||
|
||||
def log_stderr(*lines):
|
||||
log(u"!", *lines)
|
||||
|
||||
if cls._pip_caller is None:
|
||||
cls._pip_caller = LocalPipCaller(force_user=force_user)
|
||||
|
||||
cls._pip_caller.on_log_call = log_call
|
||||
cls._pip_caller.on_log_stdout = log_stdout
|
||||
cls._pip_caller.on_log_stderr = log_stderr
|
||||
|
||||
# install plugin
|
||||
pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir']
|
||||
|
||||
if plugin.get("follow_dependency_links"):
|
||||
pip.append("--process-dependency-links")
|
||||
|
||||
if force_user:
|
||||
pip.append("--user")
|
||||
|
||||
if pip_args:
|
||||
pip += pip_args
|
||||
|
||||
cls._pip_caller.execute(*pip)
|
||||
|
||||
@classmethod
|
||||
def _create_backup(cls, name,
|
||||
exclude=None,
|
||||
settings=None,
|
||||
plugin_manager=None,
|
||||
datafolder=None,
|
||||
on_backup_start=None,
|
||||
on_backup_done=None,
|
||||
on_backup_error=None):
|
||||
exclude_by_default = ("generated", "logs", "watched",)
|
||||
|
||||
try:
|
||||
if exclude is None:
|
||||
exclude = []
|
||||
if not isinstance(exclude, list):
|
||||
exclude = list(exclude)
|
||||
|
||||
if "timelapse" in exclude:
|
||||
exclude.append("timelapse_tmp")
|
||||
|
||||
configfile = settings._configfile
|
||||
basedir = settings._basedir
|
||||
|
||||
temporary_path = os.path.join(datafolder, ".{}".format(name))
|
||||
final_path = os.path.join(datafolder, name)
|
||||
|
||||
own_folder = datafolder
|
||||
defaults = [os.path.join(basedir, "config.yaml"),] + \
|
||||
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
|
||||
|
||||
# check how much many bytes we are about to backup
|
||||
size = os.stat(configfile).st_size
|
||||
for folder in default_settings["folder"].keys():
|
||||
if folder in exclude or folder in exclude_by_default:
|
||||
continue
|
||||
size += cls._get_disk_size(settings.global_get_basefolder(folder),
|
||||
ignored=[own_folder,])
|
||||
size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,])
|
||||
|
||||
# since we can't know the compression ratio beforehand, we assume we need the same amount of space
|
||||
if not cls._free_space(os.path.dirname(temporary_path), size):
|
||||
raise InsufficientSpace()
|
||||
|
||||
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
|
||||
|
||||
if callable(on_backup_start):
|
||||
on_backup_start(name, temporary_path, exclude)
|
||||
|
||||
with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip:
|
||||
def add_to_zip(source, target, ignored=None):
|
||||
if ignored is None:
|
||||
ignored = []
|
||||
|
||||
if source in ignored:
|
||||
return
|
||||
|
||||
if os.path.isdir(source):
|
||||
for entry in scandir(source):
|
||||
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
|
||||
elif os.path.isfile(source):
|
||||
zip.write(source, arcname=target)
|
||||
|
||||
# add metadata
|
||||
metadata = dict(version=get_octoprint_version_string(),
|
||||
excludes=exclude)
|
||||
zip.writestr("metadata.json", json.dumps(metadata))
|
||||
|
||||
# backup current config file
|
||||
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
|
||||
|
||||
# backup configured folder paths
|
||||
for folder in default_settings["folder"].keys():
|
||||
if folder in exclude or folder in exclude_by_default:
|
||||
continue
|
||||
|
||||
add_to_zip(settings.global_get_basefolder(folder),
|
||||
"basedir/" + folder.replace("_", "/"),
|
||||
ignored=[own_folder,])
|
||||
|
||||
# backup anything else that might be lying around in our basedir
|
||||
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
|
||||
|
||||
# add list of installed plugins
|
||||
plugins = []
|
||||
plugin_folder = settings.global_get_basefolder("plugins")
|
||||
for key, plugin in plugin_manager.plugins.items():
|
||||
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
|
||||
# ignore anything bundled or from the plugins folder we already include in the backup
|
||||
continue
|
||||
|
||||
plugins.append(dict(key=plugin.key,
|
||||
name=plugin.name,
|
||||
url=plugin.url))
|
||||
|
||||
if len(plugins):
|
||||
zip.writestr("plugin_list.json", json.dumps(plugins))
|
||||
|
||||
shutil.move(temporary_path, final_path)
|
||||
|
||||
if callable(on_backup_done):
|
||||
on_backup_done(name, final_path, exclude)
|
||||
except:
|
||||
if callable(on_backup_error):
|
||||
exc_info = sys.exc_info()
|
||||
try:
|
||||
on_backup_error(name, exc_info)
|
||||
finally:
|
||||
del exc_info
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def _restore_backup(cls, path,
|
||||
settings=None,
|
||||
plugin_manager=None,
|
||||
datafolder=None,
|
||||
on_install_plugins=None,
|
||||
on_report_unknown_plugins=None,
|
||||
on_invalid_backup=None,
|
||||
on_log_progress=None,
|
||||
on_log_error=None,
|
||||
on_restore_start=None,
|
||||
on_restore_done=None,
|
||||
on_restore_failed=None):
|
||||
if not is_os_compatible(["!windows"]):
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Restore is not supported on this operating system")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
basedir = settings._basedir
|
||||
cls._clean_dir_backup(basedir,
|
||||
on_log_progress=on_log_progress)
|
||||
|
||||
plugin_repo = dict()
|
||||
repo_url = settings.global_get(["plugins", "pluginmanager", "repository"])
|
||||
if repo_url:
|
||||
plugin_repo = cls._get_plugin_repository_data(repo_url)
|
||||
|
||||
if callable(on_restore_start):
|
||||
on_restore_start(path)
|
||||
|
||||
try:
|
||||
|
||||
with zipfile.ZipFile(path, "r") as zip:
|
||||
# read metadata
|
||||
try:
|
||||
metadata_zipinfo = zip.getinfo("metadata.json")
|
||||
except KeyError:
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
metadata_bytes = zip.read(metadata_zipinfo)
|
||||
metadata = json.loads(metadata_bytes)
|
||||
|
||||
backup_version = get_comparable_version(metadata["version"], base=True)
|
||||
if backup_version > get_octoprint_version(base=True):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
# unzip to temporary folder
|
||||
temp = tempfile.mkdtemp()
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacking backup to {}...".format(temp))
|
||||
abstemp = os.path.abspath(temp)
|
||||
for member in zip.infolist():
|
||||
abspath = os.path.abspath(os.path.join(temp, member.filename))
|
||||
if abspath.startswith(abstemp):
|
||||
zip.extract(member, temp)
|
||||
|
||||
# sanity check
|
||||
configfile = os.path.join(temp, "basedir", "config.yaml")
|
||||
if not os.path.exists(configfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks config.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
import yaml
|
||||
|
||||
with codecs.open(configfile) as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
|
||||
if configdata.get("accessControl", dict()).get("enabled", True):
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks users.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacked")
|
||||
|
||||
# install available plugins
|
||||
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:
|
||||
plugins = json.load(f)
|
||||
|
||||
known_plugins = []
|
||||
unknown_plugins = []
|
||||
if plugins:
|
||||
if plugin_repo:
|
||||
for plugin in plugins:
|
||||
if plugin["key"] in plugin_manager.plugins:
|
||||
# already installed
|
||||
continue
|
||||
|
||||
if plugin["key"] in plugin_repo:
|
||||
# not installed, can be installed from repository url
|
||||
known_plugins.append(plugin_repo[plugin["key"]])
|
||||
else:
|
||||
# not installed, not installable
|
||||
unknown_plugins.append(plugin)
|
||||
|
||||
else:
|
||||
# no repo, all plugins are not installable
|
||||
unknown_plugins = plugins
|
||||
|
||||
if callable(on_log_progress):
|
||||
if known_plugins:
|
||||
on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins))))
|
||||
if unknown_plugins:
|
||||
on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins))))
|
||||
|
||||
if callable(on_install_plugins):
|
||||
on_install_plugins(known_plugins)
|
||||
|
||||
if callable(on_report_unknown_plugins):
|
||||
on_report_unknown_plugins(unknown_plugins)
|
||||
|
||||
# move config data
|
||||
basedir_backup = basedir + ".bck"
|
||||
basedir_extracted = os.path.join(temp, "basedir")
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
|
||||
shutil.move(basedir, basedir_backup)
|
||||
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
|
||||
shutil.move(basedir_extracted, basedir)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
|
||||
on_log_error(u"Rolling back old config data")
|
||||
|
||||
shutil.move(basedir_backup, basedir)
|
||||
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if unknown_plugins:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Writing info file about unknown plugins")
|
||||
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f:
|
||||
json.dump(unknown_plugins, f)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
|
||||
exc_info = sys.exc_info())
|
||||
|
||||
finally:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary unpacked folder")
|
||||
shutil.rmtree(temp)
|
||||
|
||||
except:
|
||||
exc_info = sys.exc_info()
|
||||
try:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while running restore", exc_info=exc_info)
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
finally:
|
||||
del exc_info
|
||||
return False
|
||||
|
||||
finally:
|
||||
# remove zip
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary zip")
|
||||
os.remove(path)
|
||||
|
||||
# restart server
|
||||
if restart_command:
|
||||
import sarge
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Restarting...")
|
||||
if callable(on_restore_done):
|
||||
on_restore_done(path)
|
||||
|
||||
try:
|
||||
sarge.run(restart_command, async_=True)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restarting via command {}".format(restart_command),
|
||||
exc_info=sys.exc_info())
|
||||
on_log_error(u"Please restart OctoPrint manually")
|
||||
return False
|
||||
|
||||
else:
|
||||
if callable(on_restore_done):
|
||||
on_restore_done(path)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _send_client_message(self, message, payload=None):
|
||||
if payload is None:
|
||||
payload = dict()
|
||||
payload["type"] = message
|
||||
self._plugin_manager.send_plugin_message(self._identifier, payload)
|
||||
|
||||
|
||||
|
||||
class InsufficientSpace(Exception):
|
||||
pass
|
||||
|
||||
__plugin_name__ = u"Backup & Restore"
|
||||
__plugin_author__ = u"Gina Häußge"
|
||||
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
|
||||
u"& restore your OctoPrint settings and data.")
|
||||
__plugin_license__ = u"AGPLv3"
|
||||
__plugin_implementation__ = BackupPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
|
||||
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
|
||||
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintBackupClient = function(base) {
|
||||
this.base = base;
|
||||
this.url = this.base.getBlueprintUrl("backup");
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.url, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
|
||||
exclude = exclude || [];
|
||||
|
||||
var data = {
|
||||
exclude: exclude
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url + "backup", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
|
||||
return this.base.delete(this.url + "backup/" + backup, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
|
||||
var data = {
|
||||
path: backup
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url + "restore", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) {
|
||||
data = data || {};
|
||||
|
||||
var filename = data.filename || undefined;
|
||||
return this.base.upload(this.url + "restore", file, filename, data);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) {
|
||||
return this.base.delete(this.url + "unknown_plugins", opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient);
|
||||
return OctoPrintBackupClient;
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
|
||||
@@ -0,0 +1,289 @@
|
||||
$(function() {
|
||||
function BackupViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
self.backups = new ItemListHelper(
|
||||
"plugin.backup.backups",
|
||||
{
|
||||
"date": function (a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"date",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
|
||||
self.markedForBackupDeletion = ko.observableArray([]);
|
||||
|
||||
self.excludeFromBackup = ko.observableArray([]);
|
||||
self.backupInProgress = ko.observable(false);
|
||||
self.restoreSupported = ko.observable(true);
|
||||
|
||||
self.backupUploadButton = $("#settings-backup-upload");
|
||||
self.backupUploadData = undefined;
|
||||
self.backupUploadButton.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
if (data.files.length === 0) {
|
||||
// no files? ignore
|
||||
return false;
|
||||
}
|
||||
|
||||
self.backupUploadName(data.files[0].name);
|
||||
self.backupUploadData = data;
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.backupUploadName(undefined);
|
||||
self.backupUploadData = undefined;
|
||||
}
|
||||
});
|
||||
self.backupUploadName = ko.observable();
|
||||
self.restoreInProgress = ko.observable(false);
|
||||
self.restoreTitle = ko.observable();
|
||||
self.restoreDialog = undefined;
|
||||
self.restoreOutput = undefined;
|
||||
self.unknownPlugins = ko.observableArray([]);
|
||||
|
||||
self.loglines = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.backup.get()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.backups.updateItems(response.backups);
|
||||
self.unknownPlugins(response.unknown_plugins);
|
||||
self.restoreSupported(response.restore_supported);
|
||||
};
|
||||
|
||||
self.createBackup = function() {
|
||||
var excluded = self.excludeFromBackup();
|
||||
OctoPrint.plugins.backup.createBackup(excluded)
|
||||
.done(function() {
|
||||
self.excludeFromBackup([]);
|
||||
})
|
||||
};
|
||||
|
||||
self.removeBackup = function(backup) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteBackup(backup)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.restoreBackup = function(backup) {
|
||||
if (!self.restoreSupported()) return;
|
||||
|
||||
var perform = function() {
|
||||
self.restoreInProgress(true);
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: "Preparing to restore...", stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.performRestoreFromUpload = function() {
|
||||
if (self.backupUploadData === undefined) return;
|
||||
|
||||
var perform = function() {
|
||||
self.restoreInProgress(true);
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
|
||||
self.backupUploadData.submit();
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.deleteUnknownPluginRecord = function() {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteUnknownPlugins()
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markFilesOnPage = function() {
|
||||
self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
|
||||
};
|
||||
|
||||
self.markAllFiles = function() {
|
||||
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedFiles = function() {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.removeMarkedFiles = function() {
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForBackupDeletion())
|
||||
.done(function() {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
|
||||
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "backup") return;
|
||||
|
||||
if (data.type === "backup_done") {
|
||||
self.requestData();
|
||||
self.backupInProgress(false);
|
||||
new PNotify({
|
||||
title: gettext("Backup created successfully"),
|
||||
type: "success"
|
||||
});
|
||||
} else if (data.type === "backup_started") {
|
||||
self.backupInProgress(true);
|
||||
} else if (data.type === "backup_error") {
|
||||
self.requestData();
|
||||
self.backupInProgress(false);
|
||||
new PNotify({
|
||||
title: gettext("Creating the backup failed"),
|
||||
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
} else if (data.type === "restore_started") {
|
||||
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
} else if (data.type === "restore_failed") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "restore_done") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "installing_plugin") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: 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}),
|
||||
stream: "stderr"
|
||||
});
|
||||
} else if (data.type === "unknown_plugins") {
|
||||
if (data.plugins.length > 0) {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"});
|
||||
_.each(data.plugins, function(plugin) {
|
||||
self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"});
|
||||
});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.unknownPlugins(data.plugins);
|
||||
}
|
||||
} else if (data.type === "logline") {
|
||||
self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream}));
|
||||
self._scrollRestoreOutputToEnd();
|
||||
}
|
||||
};
|
||||
|
||||
self._scrollRestoreOutputToEnd = function() {
|
||||
self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height());
|
||||
};
|
||||
|
||||
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
};
|
||||
|
||||
self._bulkRemove = function(files) {
|
||||
var title, message, handler;
|
||||
|
||||
title = gettext("Deleting backups");
|
||||
message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
|
||||
handler = function(filename) {
|
||||
return OctoPrint.plugins.backup.deleteBackup(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: files.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function(filename) {
|
||||
var request = handler(filename);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: BackupViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#settings_plugin_backup"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
#settings_plugin_backup_backup_table {
|
||||
.settings_plugin_backup_name {
|
||||
}
|
||||
.settings_plugin_backup_actions {
|
||||
width: 75px;
|
||||
text-align: center;
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
}
|
||||
.settings_plugin_backup_date {
|
||||
width: 200px;
|
||||
text-align: right;
|
||||
}
|
||||
.settings_plugin_backup_size {
|
||||
width: 100px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.settings_plugin_backup_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_backup_restoredialog_output {
|
||||
.message {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.error {
|
||||
font-weight: bold;
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.stdout {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.stderr {
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.call {
|
||||
color: #000099;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
<div class="alert" data-bind="visible: unknownPlugins().length > 0">
|
||||
{% trans %}
|
||||
Some plugins during the last restore could not be identified and hence not automatically installed.
|
||||
Please install them manually, they are listed below including their stated homepages:
|
||||
{% endtrans %}
|
||||
<ul data-bind="foreach: unknownPlugins">
|
||||
<li><span data-bind="text: name"></span>: <a data-bind="text: url, attr: {href: url}" target="_blank" rel="noreferrer noopener"></a></li>
|
||||
</ul>
|
||||
<small><a href="javascript:void(0)" data-bind="click: deleteUnknownPluginRecord">{{ _('Delete record of unknown plugins') }}</a></small>
|
||||
</div>
|
||||
|
||||
|
||||
<h3>{{ _('Existing backups') }}</h3>
|
||||
|
||||
<div data-bind="visible: backups.allSize() <= 0">
|
||||
<p>{{ _('There are no backups. Maybe create one below?') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: backups.allSize() > 0">
|
||||
<p>{{ _('These are the backups of your settings and files that already exist on this OctoPrint instance. You may delete, download or restore them.') }}</p>
|
||||
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForBackupDeletion().length > 0">{{ _('Delete selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_backup_backup_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_backup_checkbox"></th>
|
||||
<th class="settings_plugin_backup_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_backup_date">{{ _('Date') }}</th>
|
||||
<th class="settings_plugin_backup_size">{{ _('Size') }}</th>
|
||||
<th class="settings_plugin_backup_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: backups.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_backup_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForBackupDeletion"></td>
|
||||
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
|
||||
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
|
||||
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete')|edq }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a> | <a href="javascript:void(0)" title="{{ _('Download')|edq }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()"> | <a href="javascript:void(0)" title="{{ _('Restore')|edq }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: backups.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: backups.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: backups.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.backups.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.backups.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: backups.currentPage() === backups.lastPage()}"><a href="javascript:void(0)" data-bind="click: backups.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Create backup') }}</h3>
|
||||
|
||||
<p>{{ _('Create a new backup of the current state.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: 'timelapse', checked: excludeFromBackup"> {{ _('Exclude timelapses from backup') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: createBackup"><i class="fa fa-spinner fa-spin" data-bind="visible: backupInProgress"></i> {{ _('Create backup now') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div data-bind="visible: restoreSupported()">
|
||||
<h3>{{ _('Restore from uploaded backup') }}</h3>
|
||||
|
||||
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Backup file') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="btn fileinput-button">
|
||||
<span>{{ _('Browse...') }}</span>
|
||||
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
|
||||
</span>
|
||||
<span class="add-on" data-bind="text: backupUploadName"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div data-bind="visible: !restoreSupported()">
|
||||
{{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to <a href="%(url)s" target="_blank" rel="noopener noreferrer">restore your backups manually for now</a>.', url='https://faq.octoprint.org/manual-restore') }}
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_backup_restoredialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<h3>{{ _('Restoring from backup...') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_backup_restoredialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.restoreInProgress()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -170,10 +170,6 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
|
||||
};
|
||||
@@ -252,10 +248,6 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required;
|
||||
};
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
<h3>{{ _('Access Control') }}</h3>
|
||||
|
||||
{% trans %}<p>
|
||||
{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}<p>
|
||||
<strong>Please read the following, it is very important for your printer's health!</strong>
|
||||
</p>
|
||||
<p>
|
||||
OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
|
||||
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
|
||||
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
|
||||
malicious intent - to gain access to your printer</strong> via an untrustworthy network
|
||||
and using it in such a way that it is damaged or worse (i.e. causes a fire).
|
||||
</p>
|
||||
<p>
|
||||
If you plan on accessing OctoPrint remotely over the internet, <strong>you should not only rely on the built-in
|
||||
Access Control mechanisms</strong> however -
|
||||
<a href="{{ safe_remote_url }}" target="_blank" rel="noopener noreferrer">take additional precautions</a>.
|
||||
Your OctoPrint enabled printer is a critical home appliance you really should not give anyone who happens to be
|
||||
connected to the internet access to - even read-only! <strong>An instance available publicly on the internet
|
||||
will be found, and people will try to break it open.</strong>
|
||||
</p>
|
||||
<p>
|
||||
It looks like you haven't configured access control yet. Please <strong>set up a username and password</strong> for the
|
||||
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
|
||||
@@ -36,12 +44,12 @@
|
||||
</div>
|
||||
</form>
|
||||
{% trans %}<p>
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy local network and you don't
|
||||
need Access Control for other reasons, you may alternatively disable Access Control. You should only
|
||||
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
|
||||
<strong>Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!</strong>
|
||||
</p>{% endtrans %}
|
||||
|
||||
<div class="row-fluid">
|
||||
|
||||