Compare commits
87
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
112a8b9c8b | ||
|
|
98b692d845 | ||
|
|
a657ebd528 | ||
|
|
e628aedbc1 | ||
|
|
38fce1665b | ||
|
|
f51a98768c | ||
|
|
4d04c323f6 | ||
|
|
94116bfd53 | ||
|
|
a05761e63f | ||
|
|
89469d38ae | ||
|
|
bd2616e888 | ||
|
|
02e996436d | ||
|
|
a3f2e0b56c | ||
|
|
d60cab1962 | ||
|
|
b01e327f9d | ||
|
|
09af2813d0 | ||
|
|
13260fa219 | ||
|
|
8292408c79 | ||
|
|
9165f83084 | ||
|
|
c2ef371089 | ||
|
|
ac129a2576 | ||
|
|
db8d420860 | ||
|
|
7d7cbb1760 | ||
|
|
89979f1bee | ||
|
|
bd241e8e6c | ||
|
|
7939b0ae4d | ||
|
|
6b57ba2d7d | ||
|
|
2c5465f9a6 | ||
|
|
1565129cfb | ||
|
|
b8d4a58207 | ||
|
|
900f03dc8a | ||
|
|
0c4c4a9d18 | ||
|
|
ff4ed38329 | ||
|
|
5f78ab7b73 | ||
|
|
6556d555bd | ||
|
|
d318ff82b8 | ||
|
|
ff53a826f9 | ||
|
|
d79e777911 | ||
|
|
335e635ec7 | ||
|
|
a5754a8552 | ||
|
|
a8c91ff6ba | ||
|
|
6285fd8010 | ||
|
|
799aedcaed | ||
|
|
de42ce73f7 | ||
|
|
962e09906e | ||
|
|
f607f55683 | ||
|
|
1b45047826 | ||
|
|
edd4d90b12 | ||
|
|
0a3ad8a880 | ||
|
|
82615791a2 | ||
|
|
2b5af2c36a | ||
|
|
b2e50e13d4 | ||
|
|
cb4404a833 | ||
|
|
38bb81cfe7 | ||
|
|
1667f9bd52 | ||
|
|
1ec61a9fe6 | ||
|
|
98c84b6bb9 | ||
|
|
76f48b3b13 | ||
|
|
8596ae5c4a | ||
|
|
c1482eaacd | ||
|
|
e23fe4a925 | ||
|
|
2f08b90200 | ||
|
|
68ca2c5e51 | ||
|
|
343195477b | ||
|
|
4caf4ef09b | ||
|
|
0325628693 | ||
|
|
e14c00f135 | ||
|
|
b0a4a49f99 | ||
|
|
5b4839369e | ||
|
|
1ff02b9f1c | ||
|
|
e2c1fa3d43 | ||
|
|
39a466e316 | ||
|
|
9e940eacc3 | ||
|
|
2e38f237de | ||
|
|
7f36ffdafd | ||
|
|
39b2da3230 | ||
|
|
c489829efb | ||
|
|
e30e129e2a | ||
|
|
32d5b25013 | ||
|
|
6227a0dfb9 | ||
|
|
e234c6146e | ||
|
|
c146731e5a | ||
|
|
5ee242be4a | ||
|
|
556878a774 | ||
|
|
00aa4876e9 | ||
|
|
2f89082df2 | ||
|
|
108db045ce |
No files matched your search
@@ -0,0 +1,135 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: Create a report to help improve OctoPrint
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
READ THE FOLLOWING FIRST:
|
||||||
|
|
||||||
|
If not already done, please read the the Contribution Guidelines that
|
||||||
|
are linked to the right under "Helpful resources" > "Contributing".
|
||||||
|
|
||||||
|
Also read the FAQ: https://faq.octoprint.org
|
||||||
|
|
||||||
|
This is a bug and feature tracker, please only use it to report bugs
|
||||||
|
or request features within OctoPrint (not OctoPi, not any OctoPrint
|
||||||
|
plugins and not unofficial OctoPrint versions).
|
||||||
|
|
||||||
|
Do not seek support here ("I need help with ...", "I have a
|
||||||
|
question ..."), that belongs on the community forum at
|
||||||
|
discourse.octoprint.org, NOT here.
|
||||||
|
|
||||||
|
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||||
|
reports fully fill out the bug reporting template (if you don't know
|
||||||
|
where to find some information - it's all described in the Contribution
|
||||||
|
Guidelines linked up there in the big yellow box).
|
||||||
|
|
||||||
|
When reporting a bug do NOT delete ANY lines from the template.
|
||||||
|
|
||||||
|
Make sure any bug you want to report is still present with the CURRENT
|
||||||
|
OctoPrint version and that it does not vanish when you start OctoPrint
|
||||||
|
in safe mode - how to do that is also explained in the Contribution
|
||||||
|
Guidelines linked up there in the big yellow box.
|
||||||
|
|
||||||
|
Thank you!
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### What were you doing?
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Please be as specific as possible here. The maintainers will need to
|
||||||
|
reproduce your issue in order to fix it and that is not possible if they
|
||||||
|
don't know what you did to get it to happen in the first place.
|
||||||
|
|
||||||
|
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||||
|
-->
|
||||||
|
|
||||||
|
1. Go to '...'
|
||||||
|
2. Click on '....'
|
||||||
|
3. Scroll down to '....'
|
||||||
|
4. See error
|
||||||
|
|
||||||
|
<!--
|
||||||
|
If you encountered a problem with specific files of any sorts, make sure
|
||||||
|
to also include a link to a file with which to reproduce the problem.
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### What did you expect to happen?
|
||||||
|
|
||||||
|
#### What happened instead?
|
||||||
|
|
||||||
|
#### Did the same happen when running OctoPrint in safe mode?
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Test if you can reproduce your problem in safe mode. You can find information
|
||||||
|
on how to enable safe mode in the Contribution Guidelines.
|
||||||
|
|
||||||
|
If you can't reproduce in safe mode, this is a bug with one of your
|
||||||
|
installed third party plugins. Don't open a ticket here!
|
||||||
|
|
||||||
|
If you can't test this in safe mode, state why.
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### Version of OctoPrint
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### Operating System running OctoPrint
|
||||||
|
|
||||||
|
<!--
|
||||||
|
OctoPi, Linux, Windows, MacOS, something else? With version please.
|
||||||
|
OctoPi's version can be found in /etc/octopi_version or in the lower left
|
||||||
|
corner of the web interface.
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### Printer model & used firmware incl. version
|
||||||
|
|
||||||
|
<!--
|
||||||
|
If applicable, always include if unsure.
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### Browser and version of browser, operating system running browser
|
||||||
|
|
||||||
|
<!--
|
||||||
|
If applicable, always include if unsure.
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### Link to octoprint.log
|
||||||
|
|
||||||
|
<!--
|
||||||
|
On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
|
||||||
|
|
||||||
|
The Contribution Guidelines tell you where to find that.
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### Link to contents of terminal tab or serial.log
|
||||||
|
|
||||||
|
<!--
|
||||||
|
On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||||
|
reporting communication issues. Never truncate.
|
||||||
|
|
||||||
|
serial.log is usually not written due to performance reasons and must be
|
||||||
|
enabled explicitly. Provide at the very least the FULL contents of your
|
||||||
|
terminal tab at the time of the bug occurrence, even if you do not have
|
||||||
|
a serial.log (which the Contribution Guidelines tell you where to find).
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### Link to contents of Javascript console in the browser
|
||||||
|
|
||||||
|
<!--
|
||||||
|
On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||||
|
always include if unsure or reporting UI issues.
|
||||||
|
|
||||||
|
The Contribution Guidelines tell you where to find that.
|
||||||
|
-->
|
||||||
|
|
||||||
|
#### Screenshot(s)/video(s) showing the problem:
|
||||||
|
|
||||||
|
<!--
|
||||||
|
If applicable. Always include if unsure or reporting UI issues.
|
||||||
|
-->
|
||||||
|
|
||||||
|
I have read the FAQ.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
name: Feature request
|
||||||
|
about: Suggest an idea for this project
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Please make sure to add [Request] to your issue's title. Thank you!
|
||||||
|
-->
|
||||||
|
|
||||||
|
**Is your feature request related to a problem? Please describe.**
|
||||||
|
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||||
|
|
||||||
|
**Describe the solution you'd like**
|
||||||
|
A clear and concise description of what you want to happen.
|
||||||
|
|
||||||
|
**Describe alternatives you've considered**
|
||||||
|
A clear and concise description of any alternative solutions or features you've considered.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context or screenshots about the feature request here.
|
||||||
+3
-3
@@ -24,10 +24,10 @@ maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
|||||||
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||||
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||||
|
|
||||||
# staging/maintenance is currently the branch for preparation of 1.3.9rc5
|
# staging/maintenance is currently the branch for preparation of 1.3.10rc5
|
||||||
# so is regressionfix/...
|
# so is regressionfix/...
|
||||||
staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
|
staging/maintenance 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
|
||||||
regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
|
regressionfix/.* 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
|
||||||
|
|
||||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||||
@@ -91,7 +91,9 @@ date of first contribution):
|
|||||||
* [Ganey](https://github.com/ganey)
|
* [Ganey](https://github.com/ganey)
|
||||||
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
||||||
* [Andy Castille](https://github.com/klikini)
|
* [Andy Castille](https://github.com/klikini)
|
||||||
|
* [Gaston Dombiak](https://github.com/gdombiak)
|
||||||
* [Brad Fisher](https://github.com/bradcfisher)
|
* [Brad Fisher](https://github.com/bradcfisher)
|
||||||
|
* [Aldo Hoeben](https://github.com/fieldofview)
|
||||||
|
|
||||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||||
|
|||||||
+139
-1017
File diff suppressed because it is too large.
Load diff
+8
-14
@@ -6,25 +6,23 @@ thanks to everyone who contributed!
|
|||||||
|
|
||||||
## Patreon Patrons
|
## Patreon Patrons
|
||||||
|
|
||||||
|
* Andre Bubel
|
||||||
* Andrew Moorby
|
* Andrew Moorby
|
||||||
* Arnljot Arntsen
|
* Arnljot Arntsen
|
||||||
* Boris Hussein
|
* Boris Hussein
|
||||||
* Brad Jackson
|
* Brad Jackson
|
||||||
* Brian E. Tyler
|
|
||||||
* Christian Petropolis
|
* Christian Petropolis
|
||||||
* Christian Wolf
|
* Christian Wolf
|
||||||
* COLLE+McVOY
|
* COLLE+McVOY
|
||||||
* D Brian Kimmel
|
* D Brian Kimmel
|
||||||
* DeltaMaker 3D Printers
|
* DeltaMaker 3D Printers
|
||||||
* E3D BigBox
|
* E3D BigBox
|
||||||
|
* Eric Betts
|
||||||
|
* Eric Slape
|
||||||
* Ernesto Martinez
|
* Ernesto Martinez
|
||||||
* F. Kunsmann
|
|
||||||
* Frank Sander
|
* Frank Sander
|
||||||
* George Robles
|
* George Robles
|
||||||
* günter weber
|
* Jared Go
|
||||||
* Hydra Research LLC
|
|
||||||
* James Seigel
|
|
||||||
* Jeff Moe
|
|
||||||
* Jeff Renfer
|
* Jeff Renfer
|
||||||
* Jefferson Hunt
|
* Jefferson Hunt
|
||||||
* Jeremiah Avery
|
* Jeremiah Avery
|
||||||
@@ -35,29 +33,25 @@ thanks to everyone who contributed!
|
|||||||
* Kaile Riser
|
* Kaile Riser
|
||||||
* Kale Stedman
|
* Kale Stedman
|
||||||
* Kazuhiro Ogura
|
* Kazuhiro Ogura
|
||||||
* Kodama Inc.
|
* LA 3D Printer Repair
|
||||||
* Lewis Newby
|
* Lewis Newby
|
||||||
* LulzBot®
|
* LulzBot®
|
||||||
* Makespace Madrid
|
* Makespace Madrid
|
||||||
* Mark Walker
|
* Mark Walker
|
||||||
* Martin Beattie
|
|
||||||
* Michael Aumock
|
* Michael Aumock
|
||||||
* Miles Flavel
|
* Miles Flavel
|
||||||
* mitchell hirsch
|
* Mosaic Manufacturing
|
||||||
* Noe Ruiz
|
|
||||||
* Patrick McGinnis
|
* Patrick McGinnis
|
||||||
|
* Prof Yuh Wen Chen
|
||||||
* Randy C. Will
|
* Randy C. Will
|
||||||
* Robert Gusek
|
* Robert Gusek
|
||||||
* Roger Strolz
|
* Roger Strolz
|
||||||
* Roy Cortes
|
|
||||||
* Rudolff Vang
|
|
||||||
* Samer Najia
|
* Samer Najia
|
||||||
* Simon Hallam
|
* Simon Hallam
|
||||||
* Stefan Krister
|
* Stefan Krister
|
||||||
* Sven Mueller
|
* Sven Mueller
|
||||||
* Symbiotic Devices
|
|
||||||
* Thomas Hatley
|
* Thomas Hatley
|
||||||
* Timothy D Hoogland
|
* Timothy D Hoogland
|
||||||
* Trent Shumay
|
* Trent Shumay
|
||||||
|
|
||||||
and 1351 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
and 1446 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||||
@@ -219,7 +219,7 @@ Issue a print head command
|
|||||||
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
|
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
|
* ``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
|
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
|
home
|
||||||
Homes the print head in all of the given axes. Additional parameters are:
|
Homes the print head in all of the given axes. Additional parameters are:
|
||||||
@@ -362,6 +362,8 @@ Issue a tool command
|
|||||||
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
|
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.
|
* ``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
|
flowrate
|
||||||
Changes the flow rate factor to apply to extrusion of the tool.
|
Changes the flow rate factor to apply to extrusion of the tool.
|
||||||
|
|||||||
@@ -40,15 +40,18 @@ 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
|
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.
|
enters their username which is also their user ID into the App.
|
||||||
2. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
|
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.
|
authorization process.
|
||||||
3. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
|
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`.
|
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
|
||||||
4. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
|
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.
|
signals that no decision has been made yet.
|
||||||
5. The User either accepts or denies the access request which makes the Webinterface send a
|
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.
|
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
|
||||||
6. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
|
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
|
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
|
||||||
an HTTP :http:statuscode:`404`.
|
an HTTP :http:statuscode:`404`.
|
||||||
|
|
||||||
@@ -61,31 +64,35 @@ of the following steps:
|
|||||||
participant Webinterface
|
participant Webinterface
|
||||||
participant Server
|
participant Server
|
||||||
|
|
||||||
note over User, Server: Step 1 & 2
|
note over User, Server: Step 1, 2 & 3
|
||||||
|
|
||||||
User->>App: enters URL of instance to connect to
|
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
|
||||||
|
|
||||||
alt Limit to specific user
|
|
||||||
User->>App: enters user_id
|
|
||||||
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
|
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
|
||||||
else
|
|
||||||
App->>Server: POST /plugin/appkeys/request, (app_name)
|
|
||||||
end
|
|
||||||
|
|
||||||
note over User, Server: Step 3
|
note over User, Server: Step 4
|
||||||
|
|
||||||
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
|
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
|
||||||
Webinterface-->>User: Display confirmation dialog
|
Webinterface-->>User: Display confirmation dialog
|
||||||
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
|
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
|
||||||
|
|
||||||
note over User, Server: Step 4
|
note over User, Server: Step 5
|
||||||
|
|
||||||
loop
|
loop Poll for decision
|
||||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||||
Server->>App: 202
|
Server->>App: 202
|
||||||
end
|
end
|
||||||
|
|
||||||
note over User, Server: Step 5 & 6
|
note over User, Server: Step 6 & 7
|
||||||
|
|
||||||
alt User accepts
|
alt User accepts
|
||||||
|
|
||||||
@@ -105,11 +112,27 @@ of the following steps:
|
|||||||
|
|
||||||
end
|
end
|
||||||
|
|
||||||
|
end
|
||||||
|
|
||||||
.. _sec-bundledplugins-appkeys-api:
|
.. _sec-bundledplugins-appkeys-api:
|
||||||
|
|
||||||
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:
|
.. _sec-bundledplugins-appkeys-api-startauthprocess:
|
||||||
|
|
||||||
Start authorization process
|
Start authorization process
|
||||||
@@ -131,12 +154,6 @@ Start authorization process
|
|||||||
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
|
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
|
||||||
is logged in on.
|
is logged in on.
|
||||||
|
|
||||||
.. note::
|
|
||||||
|
|
||||||
If this endpoint produces an HTTP :http:statuscode:`404` and the instance URL is correct, the bundled
|
|
||||||
Application Keys Plugin has in all likelihood been disabled by the user. Fall back on manual API key copy-pasting
|
|
||||||
by the user.
|
|
||||||
|
|
||||||
:json app: application identifier to use for the request, case insensitive
|
:json app: application identifier to use for the request, case insensitive
|
||||||
:json user: optional user id to restrict the decision to the specified user
|
: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
|
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
|
||||||
@@ -154,6 +171,11 @@ Poll for decision on existing request
|
|||||||
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
|
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.
|
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 200: access granted, API key in response body
|
||||||
:status 202: no decision has been made yet, continue polling
|
:status 202: no decision has been made yet, continue polling
|
||||||
:status 404: access denied or request timed out
|
:status 404: access denied or request timed out
|
||||||
@@ -452,6 +474,15 @@ JavaScript Client Library
|
|||||||
:param object opts: Additional options for the request
|
:param object opts: Additional options for the request
|
||||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
: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)
|
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
|
||||||
|
|
||||||
Starts a new authorization request for the provided ``app`` identifier.
|
Starts a new authorization request for the provided ``app`` identifier.
|
||||||
@@ -481,9 +512,10 @@ JavaScript Client Library
|
|||||||
|
|
||||||
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
|
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
|
||||||
|
|
||||||
Convenience function that issues a request and then automatically starts polling for a decision on the returned
|
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
|
||||||
polling endpoint every 1s, until either a positive or negative decision is returned. On success the returned
|
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
|
||||||
promise is resolved with the generated API key as argument.
|
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**
|
**Example usage**
|
||||||
|
|
||||||
|
|||||||
@@ -562,6 +562,9 @@ Use the following settings to enable or disable OctoPrint features:
|
|||||||
- M117
|
- M117
|
||||||
- M118
|
- M118
|
||||||
|
|
||||||
|
# whether G90/G91 also influence absolute/relative mode of extruders
|
||||||
|
g90InfluencesExtruder: false
|
||||||
|
|
||||||
.. _sec-configuration-config_yaml-folder:
|
.. _sec-configuration-config_yaml-folder:
|
||||||
|
|
||||||
Folder
|
Folder
|
||||||
@@ -1058,6 +1061,15 @@ Use the following settings to configure the server:
|
|||||||
# How many days to leave unused entries in the preemptive cache config
|
# How many days to leave unused entries in the preemptive cache config
|
||||||
until: 7
|
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::
|
.. note::
|
||||||
|
|
||||||
|
|||||||
@@ -338,6 +338,8 @@ PrintFailed
|
|||||||
* ``name``: the file's name
|
* ``name``: the file's name
|
||||||
* ``path``: the file's path within its storage location
|
* ``path``: the file's path within its storage location
|
||||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||||
|
* ``time``: the elapsed time of the print when it failed, in seconds (float)
|
||||||
|
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
|
||||||
|
|
||||||
.. deprecated:: 1.3.0
|
.. deprecated:: 1.3.0
|
||||||
|
|
||||||
|
|||||||
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
|
|||||||
.. code-block:: jinja
|
.. code-block:: jinja
|
||||||
:caption: Default ``disable_hotends`` snippet
|
:caption: Default ``disable_hotends`` snippet
|
||||||
|
|
||||||
|
{% if printer_profile.extruder.sharedNozzle %}
|
||||||
|
M104 T0 S0
|
||||||
|
{% else %}
|
||||||
{% for tool in range(printer_profile.extruder.count) %}
|
{% for tool in range(printer_profile.extruder.count) %}
|
||||||
M104 T{{ tool }} S0
|
M104 T{{ tool }} S0
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
The ``disable_bed`` snippet is defined as follows:
|
The ``disable_bed`` snippet is defined as follows:
|
||||||
|
|
||||||
|
|||||||
@@ -6,4 +6,10 @@ octoprint.util
|
|||||||
.. automodule:: octoprint.util
|
.. automodule:: octoprint.util
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
.. _sec-modules-util-commandline:
|
||||||
|
|
||||||
|
octoprint.util.commandline
|
||||||
|
--------------------------
|
||||||
|
|
||||||
|
.. automodule:: octoprint.util.commandline
|
||||||
|
:members:
|
||||||
@@ -1238,6 +1238,20 @@ octoprint.server.http.routes
|
|||||||
:return: a list of 3-tuples with additional routes as defined above
|
:return: a list of 3-tuples with additional routes as defined above
|
||||||
:rtype: list
|
: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:
|
.. _sec-plugins-hook-server-sockjs-register:
|
||||||
|
|
||||||
octoprint.server.sockjs.register
|
octoprint.server.sockjs.register
|
||||||
|
|||||||
@@ -17,47 +17,44 @@ PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11
|
|||||||
|
|
||||||
# Requirements for our application
|
# Requirements for our application
|
||||||
INSTALL_REQUIRES = [
|
INSTALL_REQUIRES = [
|
||||||
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
|
"flask>=0.10.1,<0.11",
|
||||||
# changes that might affect plugins, or due to other observed problems
|
"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
|
||||||
"flask>=0.10.1,<0.11", # newer versions require newer Jinja versions
|
# version, hence we need to pin to a lower version for now. See #1697
|
||||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||||
# guarantee backwards compatibility for plugins and such with that
|
"werkzeug>=0.8.3,<0.9",
|
||||||
# version, hence we need to pin to a lower version for now. See #1697
|
"tornado==4.5.3",
|
||||||
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
|
#"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a
|
||||||
"Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3
|
# vendored one
|
||||||
|
"PyYAML>=3.10,<3.11",
|
||||||
# anything below this should be checked on releases for new versions
|
"Flask-Login>=0.2.11,<0.3",
|
||||||
|
"Flask-Principal>=0.3.5,<0.4",
|
||||||
"Flask-Principal>=0.4,<0.5",
|
"Flask-Babel>=0.9,<0.10",
|
||||||
"Flask-Babel>=0.12,<0.13",
|
"Flask-Assets>=0.10,<0.11",
|
||||||
"Flask-Assets>=0.12,<0.13",
|
"markdown>=2.6.9,<2.7",
|
||||||
"werkzeug>=0.14.1,<0.15",
|
|
||||||
"PyYAML>=3.13,<4",
|
|
||||||
"markdown>=3.0,<3.1",
|
|
||||||
"pyserial>=3.4,<3.5",
|
"pyserial>=3.4,<3.5",
|
||||||
"netaddr>=0.7.19,<0.8",
|
"netaddr>=0.7.19,<0.8",
|
||||||
"watchdog>=0.9.0,<0.10",
|
"watchdog>=0.8.3,<0.9",
|
||||||
"sarge==0.1.5post0",
|
"sarge==0.1.5post0",
|
||||||
"netifaces>=0.10.7,<0.11",
|
"netifaces>=0.10.6,<0.11",
|
||||||
"pylru>=1.1,<1.2",
|
"pylru>=1.0.9,<1.1",
|
||||||
"rsa>=4.0,<5",
|
"rsa>=3.2.3,<3.3",
|
||||||
"pkginfo>=1.4.2,<1.5",
|
"pkginfo>=1.4.2,<1.5",
|
||||||
"requests>=2.20.0,<3",
|
"requests>=2.18.4,<3",
|
||||||
"semantic_version>=2.6,<2.7",
|
"semantic_version>=2.4.2,<2.5",
|
||||||
"psutil>=5.4.8,<5.5",
|
"psutil>=5.4.6,<5.5",
|
||||||
"Click>=7,<8",
|
"Click>=6.2,<6.3",
|
||||||
"awesome-slugify>=1.6.5,<1.7",
|
"awesome-slugify>=1.6.5,<1.7",
|
||||||
"feedparser>=5.2.1,<5.3",
|
"feedparser>=5.2.1,<5.3",
|
||||||
"chainmap>=1.0.2,<1.1",
|
"chainmap>=1.0.2,<1.1",
|
||||||
"future>=0.17,<0.18",
|
"future>=0.15.2,<0.16",
|
||||||
"scandir>=1.9,<1.10",
|
"scandir>=1.3,<1.4",
|
||||||
"websocket-client>=0.53,<0.54",
|
"websocket-client>=0.40.0,<0.41",
|
||||||
"python-dateutil>=2.7.5,<2.8",
|
"python-dateutil>=2.6.1,<2.7",
|
||||||
"wrapt>=1.10.11,<1.11",
|
"wrapt>=1.10.11,<1.11",
|
||||||
"futures>=3.2,<3.3",
|
"futures>=3.1.1,<3.2",
|
||||||
"emoji>=0.5.1,<0.6",
|
"emoji>=0.4.5,<0.5",
|
||||||
"monotonic>=1.5,<1.6",
|
"monotonic>=1.3,<1.4",
|
||||||
"frozendict>=1.2,<1.3"
|
"frozendict>=1.2,<1.3"
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -70,11 +67,11 @@ EXTRA_REQUIRES = dict(
|
|||||||
develop=[
|
develop=[
|
||||||
# Testing dependencies
|
# Testing dependencies
|
||||||
"mock>=2.0.0,<3",
|
"mock>=2.0.0,<3",
|
||||||
"nose>=1.3.7,<1.4",
|
"nose>=1.3.0,<1.4",
|
||||||
"ddt",
|
"ddt",
|
||||||
|
|
||||||
# Documentation dependencies
|
# Documentation dependencies
|
||||||
"sphinx>=1.8.1,<1.9",
|
"sphinx>=1.6,<1.7",
|
||||||
"sphinxcontrib-httpdomain",
|
"sphinxcontrib-httpdomain",
|
||||||
"sphinxcontrib-mermaid>=0.3",
|
"sphinxcontrib-mermaid>=0.3",
|
||||||
"sphinx_rtd_theme",
|
"sphinx_rtd_theme",
|
||||||
@@ -82,7 +79,7 @@ EXTRA_REQUIRES = dict(
|
|||||||
|
|
||||||
# Dependencies for developing OctoPrint plugins
|
# Dependencies for developing OctoPrint plugins
|
||||||
plugins=[
|
plugins=[
|
||||||
"cookiecutter>=1.6,<1.7"
|
"cookiecutter>=1.4,<1.7"
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -595,6 +595,9 @@ def main():
|
|||||||
# cut off stuff from the beginning
|
# cut off stuff from the beginning
|
||||||
args = args[-1 * sys_args_length:] if sys_args_length else []
|
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
|
from octoprint.cli import octo
|
||||||
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
|
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
|
import threading
|
||||||
|
|
||||||
from octoprint.settings import settings as s
|
from octoprint.settings import settings as s
|
||||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||||
@@ -168,7 +169,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
|||||||
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
|
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
|
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
|
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||||
@@ -206,7 +208,6 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
|||||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
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
|
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
|
||||||
is determined be presence of injected ``_identifier`` property.
|
is determined be presence of injected ``_identifier`` property.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not isinstance(types, (list, tuple)):
|
if not isinstance(types, (list, tuple)):
|
||||||
@@ -216,18 +217,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
|||||||
if kwargs is None:
|
if kwargs is None:
|
||||||
kwargs = dict()
|
kwargs = dict()
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||||
for plugin in plugins:
|
for plugin in plugins:
|
||||||
if initialized and not hasattr(plugin, "_identifier"):
|
if initialized and not hasattr(plugin, "_identifier"):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if hasattr(plugin, method):
|
if hasattr(plugin, method):
|
||||||
|
logger.debug("Calling {} on {}".format(method, plugin._identifier))
|
||||||
try:
|
try:
|
||||||
result = getattr(plugin, method)(*args, **kwargs)
|
result = getattr(plugin, method)(*args, **kwargs)
|
||||||
if callback:
|
if callback:
|
||||||
callback(plugin._identifier, plugin, result)
|
callback(plugin._identifier, plugin, result)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
|
logger.exception("Error while calling plugin %s" % plugin._identifier)
|
||||||
if error_callback:
|
if error_callback:
|
||||||
error_callback(plugin._identifier, plugin, exc)
|
error_callback(plugin._identifier, plugin, exc)
|
||||||
|
|
||||||
|
|||||||
@@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
|||||||
|
|
||||||
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
|
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
|
||||||
|
|
||||||
# noinspection PyCompatibility
|
|
||||||
from past.builtins import basestring
|
|
||||||
|
|
||||||
class OctoPrintPlugin(Plugin):
|
class OctoPrintPlugin(Plugin):
|
||||||
"""
|
"""
|
||||||
The parent class of all OctoPrint plugin mixins.
|
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
|
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.
|
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``.
|
The relevant sorting context is ``StartupPlugin.on_startup``.
|
||||||
|
|
||||||
:param string host: the host the server will listen on, may be ``0.0.0.0``
|
: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.
|
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``.
|
The relevant sorting context is ``StartupPlugin.on_after_startup``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
|
|||||||
"""
|
"""
|
||||||
Called upon the imminent shutdown of OctoPrint.
|
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``.
|
The relevant sorting context is ``ShutdownPlugin.on_shutdown``.
|
||||||
"""
|
"""
|
||||||
pass
|
pass
|
||||||
@@ -1802,6 +1811,10 @@ class EventHandlerPlugin(OctoPrintPlugin):
|
|||||||
"""
|
"""
|
||||||
Called by OctoPrint upon processing of a fired event on the platform.
|
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:
|
Arguments:
|
||||||
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
|
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
|
||||||
for possible values
|
for possible values
|
||||||
|
|||||||
@@ -15,24 +15,28 @@ import octoprint.plugin
|
|||||||
from octoprint.settings import valid_boolean_trues
|
from octoprint.settings import valid_boolean_trues
|
||||||
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
||||||
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
||||||
from octoprint.util import atomic_write, monotonic_time
|
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
|
||||||
|
|
||||||
|
|
||||||
CUTOFF_TIME = 10 * 60 # 10min
|
CUTOFF_TIME = 10 * 60 # 10min
|
||||||
|
POLL_TIMEOUT = 5 # 5 seconds
|
||||||
|
|
||||||
class AppAlreadyExists(Exception):
|
class AppAlreadyExists(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class PendingDecision(object):
|
class PendingDecision(object):
|
||||||
def __init__(self, app_id, app_token, user_id, user_token):
|
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
|
||||||
self.app_id = app_id
|
self.app_id = app_id
|
||||||
self.app_token = app_token
|
self.app_token = app_token
|
||||||
self.user_id = user_id
|
self.user_id = user_id
|
||||||
self.user_token = user_token
|
self.user_token = user_token
|
||||||
self.created = monotonic_time()
|
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):
|
def external(self):
|
||||||
return dict(app_id=self.app_id,
|
return dict(app_id=self.app_id,
|
||||||
user_id=self.user_id,
|
user_id=self.user_id,
|
||||||
@@ -107,6 +111,11 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
|||||||
|
|
||||||
##~~ BlueprintPlugin mixin
|
##~~ 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"])
|
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
def handle_request(self):
|
def handle_request(self):
|
||||||
@@ -126,14 +135,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
|||||||
user_token=user_token,
|
user_token=user_token,
|
||||||
user_id=user_id))
|
user_id=user_id))
|
||||||
response = flask.jsonify(app_token=app_token)
|
response = flask.jsonify(app_token=app_token)
|
||||||
response.status_code = 202
|
response.status_code = 201
|
||||||
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
|
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
|
||||||
return response
|
return response
|
||||||
|
|
||||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
def handle_decision_poll(self, app_token):
|
def handle_decision_poll(self, app_token):
|
||||||
if self._is_pending(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 = flask.jsonify(message="Awaiting decision")
|
||||||
response.status_code = 202
|
response.status_code = 202
|
||||||
return response
|
return response
|
||||||
@@ -157,6 +170,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
|||||||
if not result:
|
if not result:
|
||||||
return flask.abort(404)
|
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
|
return NO_CONTENT
|
||||||
|
|
||||||
def is_blueprint_protected(self):
|
def is_blueprint_protected(self):
|
||||||
@@ -179,7 +198,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
|||||||
keys = self._api_keys_for_user(user_id)
|
keys = self._api_keys_for_user(user_id)
|
||||||
|
|
||||||
return flask.jsonify(keys=map(lambda x: x.external(), keys),
|
return flask.jsonify(keys=map(lambda x: x.external(), keys),
|
||||||
pending=dict((x.user_token, x.external()) for x in self._get_pending(user_id)))
|
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):
|
def on_api_command(self, command, data):
|
||||||
user_id = current_user.get_name()
|
user_id = current_user.get_name()
|
||||||
@@ -221,20 +240,21 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
|||||||
|
|
||||||
with self._pending_lock:
|
with self._pending_lock:
|
||||||
self._remove_stale_pending()
|
self._remove_stale_pending()
|
||||||
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token))
|
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
|
||||||
|
timeout_callback=self._expire_pending))
|
||||||
|
|
||||||
return app_token, user_token
|
return app_token, user_token
|
||||||
|
|
||||||
def _is_pending(self, app_token):
|
def _get_pending_by_app_token(self, app_token):
|
||||||
|
result = []
|
||||||
with self._pending_lock:
|
with self._pending_lock:
|
||||||
self._remove_stale_pending()
|
self._remove_stale_pending()
|
||||||
for data in self._pending_decisions:
|
for data in self._pending_decisions:
|
||||||
if data.app_token == app_token:
|
if data.app_token == app_token:
|
||||||
return True
|
result.append(data)
|
||||||
|
return result
|
||||||
|
|
||||||
return False
|
def _get_pending_by_user_id(self, user_id):
|
||||||
|
|
||||||
def _get_pending(self, user_id):
|
|
||||||
result = []
|
result = []
|
||||||
with self._pending_lock:
|
with self._pending_lock:
|
||||||
self._remove_stale_pending()
|
self._remove_stale_pending()
|
||||||
@@ -243,6 +263,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
|||||||
result.append(data)
|
result.append(data)
|
||||||
return result
|
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):
|
def _remove_stale_pending(self):
|
||||||
with self._pending_lock:
|
with self._pending_lock:
|
||||||
cutoff = monotonic_time() - CUTOFF_TIME
|
cutoff = monotonic_time() - CUTOFF_TIME
|
||||||
|
|||||||
@@ -29,6 +29,10 @@
|
|||||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!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) {
|
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
|
||||||
return this.requestForUser(app, undefined, opts);
|
return this.requestForUser(app, undefined, opts);
|
||||||
};
|
};
|
||||||
@@ -45,37 +49,44 @@
|
|||||||
var deferred = $.Deferred();
|
var deferred = $.Deferred();
|
||||||
var client = this;
|
var client = this;
|
||||||
|
|
||||||
client.requestForUser(app, user)
|
client.probe()
|
||||||
.done(function(response) {
|
.done(function() {
|
||||||
var token = response.app_token;
|
client.requestForUser(app, user)
|
||||||
if (!token) {
|
.done(function(response) {
|
||||||
// no token received, something went wrong
|
var token = response.app_token;
|
||||||
deferred.reject();
|
if (!token) {
|
||||||
return;
|
// no token received, something went wrong
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
deferred.reject();
|
||||||
});
|
return;
|
||||||
};
|
}
|
||||||
window.setTimeout(poll, interval);
|
|
||||||
|
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() {
|
.fail(function() {
|
||||||
// something went wrong
|
// workflow unsupported
|
||||||
deferred.reject();
|
deferred.reject();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ from octoprint.plugin.core import FolderOrigin
|
|||||||
from octoprint.server import admin_permission, NO_CONTENT
|
from octoprint.server import admin_permission, NO_CONTENT
|
||||||
from octoprint.server.util.flask import restricted_access
|
from octoprint.server.util.flask import restricted_access
|
||||||
from octoprint.util import is_hidden_path
|
from octoprint.util import is_hidden_path
|
||||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version
|
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
|
||||||
|
from octoprint.util.platform import is_os_compatible
|
||||||
from octoprint.util.pip import LocalPipCaller
|
from octoprint.util.pip import LocalPipCaller
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -83,7 +84,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
unknown_plugins = self._get_unknown_plugins()
|
unknown_plugins = self._get_unknown_plugins()
|
||||||
return flask.jsonify(backups=backups,
|
return flask.jsonify(backups=backups,
|
||||||
backup_in_progress=len(self._in_progress) > 0,
|
backup_in_progress=len(self._in_progress) > 0,
|
||||||
unknown_plugins=unknown_plugins)
|
unknown_plugins=unknown_plugins,
|
||||||
|
restore_supported=is_os_compatible(["!windows"]))
|
||||||
|
|
||||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
|
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
|
||||||
@admin_permission.require(403)
|
@admin_permission.require(403)
|
||||||
@@ -135,6 +137,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
|
|
||||||
self._logger.info(u"... done creating backup zip.")
|
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,
|
thread = threading.Thread(target=self._create_backup,
|
||||||
args=(backup_file,),
|
args=(backup_file,),
|
||||||
@@ -143,7 +156,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
plugin_manager=self._plugin_manager,
|
plugin_manager=self._plugin_manager,
|
||||||
datafolder=self.get_plugin_data_folder(),
|
datafolder=self.get_plugin_data_folder(),
|
||||||
on_backup_start=on_backup_start,
|
on_backup_start=on_backup_start,
|
||||||
on_backup_done=on_backup_done))
|
on_backup_done=on_backup_done,
|
||||||
|
on_backup_error=on_backup_error))
|
||||||
thread.daemon = True
|
thread.daemon = True
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
@@ -172,6 +186,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
@admin_permission.require(403)
|
@admin_permission.require(403)
|
||||||
@restricted_access
|
@restricted_access
|
||||||
def perform_restore(self):
|
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_name = "file"
|
||||||
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
||||||
|
|
||||||
@@ -200,8 +217,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
self._send_client_message("logline", dict(line=line, type="stdout"))
|
self._send_client_message("logline", dict(line=line, type="stdout"))
|
||||||
|
|
||||||
for plugin in plugins:
|
for plugin in plugins:
|
||||||
octoprint_compatible = plugin["compatibility"]["octoprint"]
|
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||||
os_compatible = plugin["compatibility"]["os"]
|
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
|
||||||
compatible = octoprint_compatible and os_compatible
|
compatible = octoprint_compatible and os_compatible
|
||||||
if not compatible:
|
if not compatible:
|
||||||
if not octoprint_compatible and not os_compatible:
|
if not octoprint_compatible and not os_compatible:
|
||||||
@@ -251,6 +268,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
def on_restore_failed(path):
|
def on_restore_failed(path):
|
||||||
self._send_client_message("restore_failed")
|
self._send_client_message("restore_failed")
|
||||||
|
|
||||||
|
def on_invalid_backup(line):
|
||||||
|
on_log_error(line)
|
||||||
|
|
||||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||||
archive.close()
|
archive.close()
|
||||||
shutil.copy(path, archive.name)
|
shutil.copy(path, archive.name)
|
||||||
@@ -264,6 +284,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
datafolder=self.get_plugin_data_folder(),
|
datafolder=self.get_plugin_data_folder(),
|
||||||
on_install_plugins=on_install_plugins,
|
on_install_plugins=on_install_plugins,
|
||||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||||
|
on_invalid_backup=on_invalid_backup,
|
||||||
on_log_progress=on_log_progress,
|
on_log_progress=on_log_progress,
|
||||||
on_log_error=on_log_error,
|
on_log_error=on_log_error,
|
||||||
on_restore_start=on_restore_start,
|
on_restore_start=on_restore_start,
|
||||||
@@ -372,8 +393,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
click.echo(u"\t{}".format(line))
|
click.echo(u"\t{}".format(line))
|
||||||
|
|
||||||
for plugin in plugins:
|
for plugin in plugins:
|
||||||
octoprint_compatible = plugin["compatibility"]["octoprint"]
|
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||||
os_compatible = plugin["compatibility"]["os"]
|
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
|
||||||
compatible = octoprint_compatible and os_compatible
|
compatible = octoprint_compatible and os_compatible
|
||||||
if not compatible:
|
if not compatible:
|
||||||
if not octoprint_compatible and not os_compatible:
|
if not octoprint_compatible and not os_compatible:
|
||||||
@@ -420,7 +441,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
on_install_plugins=on_install_plugins,
|
on_install_plugins=on_install_plugins,
|
||||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||||
on_log_progress=on_log_progress,
|
on_log_progress=on_log_progress,
|
||||||
on_log_error=on_log_error):
|
on_log_error=on_log_error,
|
||||||
|
on_invalid_backup=on_log_error):
|
||||||
click.echo(u"Restored from {}".format(path))
|
click.echo(u"Restored from {}".format(path))
|
||||||
else:
|
else:
|
||||||
click.echo(u"Restoring from {} failed".format(path), err=True)
|
click.echo(u"Restoring from {} failed".format(path), err=True)
|
||||||
@@ -571,81 +593,95 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
plugin_manager=None,
|
plugin_manager=None,
|
||||||
datafolder=None,
|
datafolder=None,
|
||||||
on_backup_start=None,
|
on_backup_start=None,
|
||||||
on_backup_done=None):
|
on_backup_done=None,
|
||||||
if exclude is None:
|
on_backup_error=None):
|
||||||
exclude = []
|
try:
|
||||||
|
if exclude is None:
|
||||||
|
exclude = []
|
||||||
|
|
||||||
configfile = settings._configfile
|
configfile = settings._configfile
|
||||||
basedir = settings._basedir
|
basedir = settings._basedir
|
||||||
|
|
||||||
temporary_path = os.path.join(datafolder, ".{}".format(name))
|
temporary_path = os.path.join(datafolder, ".{}".format(name))
|
||||||
final_path = os.path.join(datafolder, name)
|
final_path = os.path.join(datafolder, name)
|
||||||
|
|
||||||
size = cls._get_disk_size(basedir)
|
size = cls._get_disk_size(basedir)
|
||||||
if not cls._free_space(os.path.dirname(temporary_path), size):
|
if not cls._free_space(os.path.dirname(temporary_path), size):
|
||||||
raise InsufficientSpace()
|
raise InsufficientSpace()
|
||||||
|
|
||||||
own_folder = datafolder
|
own_folder = datafolder
|
||||||
defaults = [os.path.join(basedir, "config.yaml"),] + \
|
defaults = [os.path.join(basedir, "config.yaml"),] + \
|
||||||
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
|
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
|
||||||
|
|
||||||
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
|
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
|
||||||
|
|
||||||
if callable(on_backup_start):
|
if callable(on_backup_start):
|
||||||
on_backup_start(name, temporary_path, exclude)
|
on_backup_start(name, temporary_path, exclude)
|
||||||
|
|
||||||
with zipfile.ZipFile(temporary_path, "w", compression) as zip:
|
with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip:
|
||||||
def add_to_zip(source, target, ignored=None):
|
def add_to_zip(source, target, ignored=None):
|
||||||
if ignored is None:
|
if ignored is None:
|
||||||
ignored = []
|
ignored = []
|
||||||
|
|
||||||
if source in ignored:
|
if source in ignored:
|
||||||
return
|
return
|
||||||
|
|
||||||
if os.path.isdir(source):
|
if os.path.isdir(source):
|
||||||
for entry in scandir(source):
|
for entry in scandir(source):
|
||||||
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
|
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
|
||||||
elif os.path.isfile(source):
|
elif os.path.isfile(source):
|
||||||
zip.write(source, arcname=target)
|
zip.write(source, arcname=target)
|
||||||
|
|
||||||
# add metadata
|
# add metadata
|
||||||
metadata = dict(version=get_octoprint_version_string(),
|
metadata = dict(version=get_octoprint_version_string(),
|
||||||
excludes=exclude)
|
excludes=exclude)
|
||||||
zip.writestr("metadata.json", json.dumps(metadata))
|
zip.writestr("metadata.json", json.dumps(metadata))
|
||||||
|
|
||||||
# backup current config file
|
# backup current config file
|
||||||
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
|
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
|
||||||
|
|
||||||
# backup configured folder paths
|
# backup configured folder paths
|
||||||
for folder in default_settings["folder"].keys():
|
for folder in default_settings["folder"].keys():
|
||||||
if folder in exclude:
|
if folder in exclude:
|
||||||
continue
|
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
|
if folder in ("generated", "logs", "watched",):
|
||||||
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
|
continue
|
||||||
|
|
||||||
# add list of installed plugins
|
add_to_zip(settings.global_get_basefolder(folder),
|
||||||
plugins = []
|
"basedir/" + folder.replace("_", "/"),
|
||||||
plugin_folder = settings.global_get_basefolder("plugins")
|
ignored=[own_folder,])
|
||||||
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,
|
# backup anything else that might be lying around in our basedir
|
||||||
name=plugin.name,
|
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
|
||||||
url=plugin.url))
|
|
||||||
|
|
||||||
if len(plugins):
|
# add list of installed plugins
|
||||||
zip.writestr("plugin_list.json", json.dumps(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
|
||||||
|
|
||||||
os.rename(temporary_path, final_path)
|
plugins.append(dict(key=plugin.key,
|
||||||
|
name=plugin.name,
|
||||||
|
url=plugin.url))
|
||||||
|
|
||||||
if callable(on_backup_done):
|
if len(plugins):
|
||||||
on_backup_done(name, final_path, exclude)
|
zip.writestr("plugin_list.json", json.dumps(plugins))
|
||||||
|
|
||||||
|
os.rename(temporary_path, final_path)
|
||||||
|
|
||||||
|
if callable(on_backup_done):
|
||||||
|
on_backup_done(name, final_path, exclude)
|
||||||
|
except:
|
||||||
|
if callable(on_backup_error):
|
||||||
|
exc_info = sys.exc_info()
|
||||||
|
try:
|
||||||
|
on_backup_error(name, exc_info)
|
||||||
|
finally:
|
||||||
|
del exc_info
|
||||||
|
raise
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _restore_backup(cls, path,
|
def _restore_backup(cls, path,
|
||||||
@@ -660,6 +696,13 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
on_restore_start=None,
|
on_restore_start=None,
|
||||||
on_restore_done=None,
|
on_restore_done=None,
|
||||||
on_restore_failed=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"])
|
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||||
|
|
||||||
basedir = settings._basedir
|
basedir = settings._basedir
|
||||||
@@ -683,15 +726,19 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
except KeyError:
|
except KeyError:
|
||||||
if callable(on_invalid_backup):
|
if callable(on_invalid_backup):
|
||||||
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
|
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
|
||||||
|
if callable(on_restore_failed):
|
||||||
|
on_restore_failed(path)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
metadata_bytes = zip.read(metadata_zipinfo)
|
metadata_bytes = zip.read(metadata_zipinfo)
|
||||||
metadata = json.loads(metadata_bytes)
|
metadata = json.loads(metadata_bytes)
|
||||||
|
|
||||||
backup_version = get_comparable_version(metadata["version"])
|
backup_version = get_comparable_version(metadata["version"], base=True)
|
||||||
if backup_version > get_octoprint_version():
|
if backup_version > get_octoprint_version(base=True):
|
||||||
if callable(on_invalid_backup):
|
if callable(on_invalid_backup):
|
||||||
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
|
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
|
return False
|
||||||
|
|
||||||
# unzip to temporary folder
|
# unzip to temporary folder
|
||||||
@@ -710,6 +757,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
if not os.path.exists(configfile):
|
if not os.path.exists(configfile):
|
||||||
if callable(on_invalid_backup):
|
if callable(on_invalid_backup):
|
||||||
on_invalid_backup(u"Backup lacks config.yaml")
|
on_invalid_backup(u"Backup lacks config.yaml")
|
||||||
|
if callable(on_restore_failed):
|
||||||
|
on_restore_failed(path)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
@@ -722,6 +771,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
if not os.path.exists(userfile):
|
if not os.path.exists(userfile):
|
||||||
if callable(on_invalid_backup):
|
if callable(on_invalid_backup):
|
||||||
on_invalid_backup(u"Backup lacks users.yaml")
|
on_invalid_backup(u"Backup lacks users.yaml")
|
||||||
|
if callable(on_restore_failed):
|
||||||
|
on_restore_failed(path)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if callable(on_log_progress):
|
if callable(on_log_progress):
|
||||||
@@ -808,10 +859,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
shutil.rmtree(temp)
|
shutil.rmtree(temp)
|
||||||
|
|
||||||
except:
|
except:
|
||||||
if callable(on_log_error):
|
exc_info = sys.exc_info()
|
||||||
on_log_error(u"Error while running restore", exc_info=sys.exc_info())
|
try:
|
||||||
if callable(on_restore_failed):
|
if callable(on_log_error):
|
||||||
on_restore_failed(path)
|
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
|
return False
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
@@ -826,6 +881,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
|
|
||||||
if callable(on_log_progress):
|
if callable(on_log_progress):
|
||||||
on_log_progress(u"Restarting...")
|
on_log_progress(u"Restarting...")
|
||||||
|
if callable(on_restore_done):
|
||||||
|
on_restore_done(path)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
sarge.run(restart_command, async_=True)
|
sarge.run(restart_command, async_=True)
|
||||||
except:
|
except:
|
||||||
@@ -835,8 +893,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
on_log_error(u"Please restart OctoPrint manually")
|
on_log_error(u"Please restart OctoPrint manually")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if callable(on_restore_done):
|
else:
|
||||||
on_restore_done(path)
|
if callable(on_restore_done):
|
||||||
|
on_restore_done(path)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ $(function() {
|
|||||||
|
|
||||||
self.excludeFromBackup = ko.observableArray([]);
|
self.excludeFromBackup = ko.observableArray([]);
|
||||||
self.backupInProgress = ko.observable(false);
|
self.backupInProgress = ko.observable(false);
|
||||||
|
self.restoreSupported = ko.observable(true);
|
||||||
|
|
||||||
self.backupUploadButton = $("#settings-backup-upload");
|
self.backupUploadButton = $("#settings-backup-upload");
|
||||||
self.backupUploadData = undefined;
|
self.backupUploadData = undefined;
|
||||||
@@ -66,6 +67,7 @@ $(function() {
|
|||||||
self.fromResponse = function(response) {
|
self.fromResponse = function(response) {
|
||||||
self.backups.updateItems(response.backups);
|
self.backups.updateItems(response.backups);
|
||||||
self.unknownPlugins(response.unknown_plugins);
|
self.unknownPlugins(response.unknown_plugins);
|
||||||
|
self.restoreSupported(response.restore_supported);
|
||||||
};
|
};
|
||||||
|
|
||||||
self.createBackup = function() {
|
self.createBackup = function() {
|
||||||
@@ -88,7 +90,15 @@ $(function() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.restoreBackup = function(backup) {
|
self.restoreBackup = function(backup) {
|
||||||
|
if (!self.restoreSupported()) return;
|
||||||
|
|
||||||
var perform = function() {
|
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);
|
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||||
};
|
};
|
||||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
||||||
@@ -99,6 +109,12 @@ $(function() {
|
|||||||
if (self.backupUploadData === undefined) return;
|
if (self.backupUploadData === undefined) return;
|
||||||
|
|
||||||
var perform = function() {
|
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();
|
self.backupUploadData.submit();
|
||||||
};
|
};
|
||||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
||||||
@@ -155,14 +171,24 @@ $(function() {
|
|||||||
if (data.type === "backup_done") {
|
if (data.type === "backup_done") {
|
||||||
self.requestData();
|
self.requestData();
|
||||||
self.backupInProgress(false);
|
self.backupInProgress(false);
|
||||||
|
new PNotify({
|
||||||
|
title: gettext("Backup created successfully"),
|
||||||
|
type: "success"
|
||||||
|
});
|
||||||
} else if (data.type === "backup_started") {
|
} else if (data.type === "backup_started") {
|
||||||
self.backupInProgress(true);
|
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") {
|
} else if (data.type === "restore_started") {
|
||||||
self.restoreInProgress(true);
|
|
||||||
self.loglines.removeAll();
|
|
||||||
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
|
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
|
||||||
self.loglines.push({line: " ", stream: "message"});
|
self.loglines.push({line: " ", stream: "message"});
|
||||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
|
||||||
} else if (data.type === "restore_failed") {
|
} else if (data.type === "restore_failed") {
|
||||||
self.loglines.push({line: " ", stream: "message"});
|
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.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
|
||||||
|
|||||||
@@ -46,7 +46,7 @@
|
|||||||
<td class="settings_plugin_backup_name" data-bind="text: name"></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_date" data-bind="text: formatDate(date)"></td>
|
||||||
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
|
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
|
||||||
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a> | <a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a> | <a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></td>
|
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a> | <a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()"> | <a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -91,30 +91,36 @@
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<h3>{{ _('Restore from uploaded backup') }}</h3>
|
<div data-bind="visible: restoreSupported()">
|
||||||
|
<h3>{{ _('Restore from uploaded backup') }}</h3>
|
||||||
|
|
||||||
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
|
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
|
||||||
|
|
||||||
<form class="form-horizontal">
|
<form class="form-horizontal">
|
||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
<label class="control-label">{{ _('Backup file') }}</label>
|
<label class="control-label">{{ _('Backup file') }}</label>
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
<div class="input-prepend">
|
<div class="input-prepend">
|
||||||
<span class="btn fileinput-button">
|
<span class="btn fileinput-button">
|
||||||
<span>{{ _('Browse...') }}</span>
|
<span>{{ _('Browse...') }}</span>
|
||||||
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
|
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
|
||||||
</span>
|
</span>
|
||||||
<span class="add-on" data-bind="text: backupUploadName"></span>
|
<span class="add-on" data-bind="text: backupUploadName"></span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
<div class="controls">
|
<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>
|
<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>
|
</div>
|
||||||
</div>
|
</form>
|
||||||
</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 id="settings_plugin_backup_restoredialog" class="modal hide fade">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
|
|||||||
@@ -10,9 +10,18 @@ import flask
|
|||||||
import flask_login
|
import flask_login
|
||||||
from flask_babel import gettext
|
from flask_babel import gettext
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
import threading
|
||||||
|
|
||||||
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
||||||
octoprint.plugin.TemplatePlugin,
|
octoprint.plugin.TemplatePlugin,
|
||||||
octoprint.plugin.AssetPlugin):
|
octoprint.plugin.AssetPlugin):
|
||||||
|
MAX_BACKLOG_LEN = 100
|
||||||
|
|
||||||
|
# noinspection PyMissingConstructor
|
||||||
|
def __init__(self):
|
||||||
|
self._message_backlog = defaultdict(list)
|
||||||
|
self._message_backlog_mutex = threading.RLock()
|
||||||
|
|
||||||
def get_assets(self):
|
def get_assets(self):
|
||||||
return dict(
|
return dict(
|
||||||
@@ -85,6 +94,9 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
|||||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||||
# ACL hasn't been configured yet, make an exception
|
# ACL hasn't been configured yet, make an exception
|
||||||
return
|
return
|
||||||
|
elif not self._user_manager.enabled:
|
||||||
|
# ACL isn't enabled
|
||||||
|
return
|
||||||
|
|
||||||
if flask.request.endpoint in ("api.login",):
|
if flask.request.endpoint in ("api.login",):
|
||||||
return
|
return
|
||||||
@@ -99,6 +111,9 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
|||||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||||
# ACL hasn't been configured yet, make an exception
|
# ACL hasn't been configured yet, make an exception
|
||||||
return
|
return
|
||||||
|
elif not self._user_manager.enabled:
|
||||||
|
# ACL isn't enabled
|
||||||
|
return
|
||||||
|
|
||||||
import tornado.web
|
import tornado.web
|
||||||
from octoprint.server.util.flask import get_flask_user_from_request
|
from octoprint.server.util.flask import get_flask_user_from_request
|
||||||
@@ -111,18 +126,43 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
|||||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||||
# ACL hasn't been configured yet, make an exception
|
# ACL hasn't been configured yet, make an exception
|
||||||
return True
|
return True
|
||||||
|
elif not self._user_manager.enabled:
|
||||||
|
# ACL isn't enabled
|
||||||
|
return True
|
||||||
|
|
||||||
return user is not None and not user.is_anonymous() and user.is_active()
|
return user is not None and not user.is_anonymous() and user.is_active()
|
||||||
|
|
||||||
|
def socket_authed(self, socket, user):
|
||||||
|
with self._message_backlog_mutex:
|
||||||
|
backlog = self._message_backlog.pop(socket, [])
|
||||||
|
|
||||||
|
if len(backlog):
|
||||||
|
for message, payload in backlog:
|
||||||
|
socket._do_emit(message, payload)
|
||||||
|
self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog)))
|
||||||
|
|
||||||
def socket_emit_validator(self, socket, user, message, payload):
|
def socket_emit_validator(self, socket, user, message, payload):
|
||||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||||
# ACL hasn't been configured yet, make an exception
|
# ACL hasn't been configured yet, make an exception
|
||||||
return True
|
return True
|
||||||
|
elif not self._user_manager.enabled:
|
||||||
|
# ACL isn't enabled
|
||||||
|
return True
|
||||||
|
|
||||||
if message in ("connected", "reauthRequired"):
|
if message in ("connected", "reauthRequired"):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return user is not None and not user.is_anonymous() and user.is_active()
|
if user is not None and not user.is_anonymous() and user.is_active():
|
||||||
|
return True
|
||||||
|
|
||||||
|
with self._message_backlog_mutex:
|
||||||
|
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
|
||||||
|
self._message_backlog[socket].append((message, payload))
|
||||||
|
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
|
||||||
|
else:
|
||||||
|
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
__plugin_name__ = "Force Login"
|
__plugin_name__ = "Force Login"
|
||||||
@@ -138,5 +178,6 @@ __plugin_hooks__ = {
|
|||||||
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
|
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
|
||||||
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
|
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
|
||||||
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
|
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
|
||||||
|
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
|
||||||
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
|
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
|
||||||
}
|
}
|
||||||
@@ -35,10 +35,9 @@ _FLAG_PAST_UNDERVOLTAGE = 1 << 16
|
|||||||
_FLAG_PAST_FREQ_CAPPED = 1 << 17
|
_FLAG_PAST_FREQ_CAPPED = 1 << 17
|
||||||
_FLAG_PAST_THROTTLED = 1 << 18
|
_FLAG_PAST_THROTTLED = 1 << 18
|
||||||
|
|
||||||
|
|
||||||
class ThrottleState(object):
|
class ThrottleState(object):
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_value(cls, value):
|
def from_value(cls, value=0):
|
||||||
if value == 0:
|
if value == 0:
|
||||||
return ThrottleState()
|
return ThrottleState()
|
||||||
|
|
||||||
@@ -47,10 +46,12 @@ class ThrottleState(object):
|
|||||||
throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED,
|
throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED,
|
||||||
past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
|
past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
|
||||||
past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
|
past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
|
||||||
past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED)
|
past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
|
||||||
|
raw_value=value)
|
||||||
return ThrottleState(**kwargs)
|
return ThrottleState(**kwargs)
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
|
self._raw_value = kwargs.get('raw_value', -1)
|
||||||
self._undervoltage = False
|
self._undervoltage = False
|
||||||
self._freq_capped = False
|
self._freq_capped = False
|
||||||
self._throttled = False
|
self._throttled = False
|
||||||
@@ -111,7 +112,8 @@ class ThrottleState(object):
|
|||||||
and self._past_throttled == other._past_throttled
|
and self._past_throttled == other._past_throttled
|
||||||
|
|
||||||
def as_dict(self):
|
def as_dict(self):
|
||||||
return dict(current_undervoltage=self.current_undervoltage,
|
return dict(raw_value=self._raw_value,
|
||||||
|
current_undervoltage=self.current_undervoltage,
|
||||||
past_undervoltage=self.past_undervoltage,
|
past_undervoltage=self.past_undervoltage,
|
||||||
current_overheat=self.current_overheat,
|
current_overheat=self.current_overheat,
|
||||||
past_overheat=self.past_overheat,
|
past_overheat=self.past_overheat,
|
||||||
@@ -242,6 +244,16 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
|||||||
def _check_throttled_state_condition(self):
|
def _check_throttled_state_condition(self):
|
||||||
return self._throttle_functional
|
return self._throttle_functional
|
||||||
|
|
||||||
|
def get_throttle_state(self, run_now=False):
|
||||||
|
"""Exposed as public helper."""
|
||||||
|
if run_now:
|
||||||
|
self._check_throttled_state()
|
||||||
|
|
||||||
|
if not self._throttle_functional:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return self._throttle_state.as_dict()
|
||||||
|
|
||||||
def _check_throttled_state(self):
|
def _check_throttled_state(self):
|
||||||
command = self._settings.get(["vcgencmd_throttle_check_command"])
|
command = self._settings.get(["vcgencmd_throttle_check_command"])
|
||||||
|
|
||||||
@@ -278,6 +290,7 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
|||||||
|
|
||||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
|
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
|
||||||
state=self._throttle_state.as_dict()))
|
state=self._throttle_state.as_dict()))
|
||||||
|
self._event_bus.fire("plugin_pi_support_throttle_state", self._throttle_state.as_dict())
|
||||||
|
|
||||||
|
|
||||||
__plugin_name__ = "Pi Support Plugin"
|
__plugin_name__ = "Pi Support Plugin"
|
||||||
@@ -299,5 +312,9 @@ def __plugin_check__():
|
|||||||
return "raspberry pi" in proc_dt_model.lower()
|
return "raspberry pi" in proc_dt_model.lower()
|
||||||
|
|
||||||
def __plugin_load__():
|
def __plugin_load__():
|
||||||
|
plugin = PiSupportPlugin()
|
||||||
global __plugin_implementation__
|
global __plugin_implementation__
|
||||||
__plugin_implementation__ = PiSupportPlugin()
|
__plugin_implementation__ = plugin
|
||||||
|
|
||||||
|
global __plugin_helpers__
|
||||||
|
__plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state)
|
||||||
@@ -27,7 +27,7 @@ $(function() {
|
|||||||
|
|
||||||
var octoPrintVersion = $(".footer span.version");
|
var octoPrintVersion = $(".footer span.version");
|
||||||
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
|
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
|
||||||
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>")
|
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>");
|
||||||
$(octoPiVersion).insertAfter(octoPrintVersion);
|
$(octoPiVersion).insertAfter(octoPrintVersion);
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
@@ -41,11 +41,34 @@ $(function() {
|
|||||||
self.pastIssue(state.past_issue);
|
self.pastIssue(state.past_issue);
|
||||||
};
|
};
|
||||||
|
|
||||||
self.issuePopoverContent = function() {
|
self.popoverContent = ko.pureComputed(function() {
|
||||||
return "<p><strong><i class=\"fa fa-bolt\"></i><i class=\"fa fa-exclamation\"></i></strong></strong> - " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "</p>"
|
var undervoltageParagraphClasses = "muted";
|
||||||
+ "<p><strong><i class=\"fa fa-thermometer-full\"></i><i class=\"fa fa-exclamation\"></i></strong> - " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "</p>"
|
var undervoltageSymbolClasses = "";
|
||||||
+ "<p>" + gettext("A blinking icon indicates an acute issue!") + "</p>"
|
|
||||||
};
|
var overheatParagraphClasses = "muted";
|
||||||
|
var overheatSymbolClasses = "";
|
||||||
|
|
||||||
|
if (self.currentUndervoltage()) {
|
||||||
|
undervoltageSymbolClasses = "text-error pi_support_state_pulsate";
|
||||||
|
undervoltageParagraphClasses = "";
|
||||||
|
} else if (self.pastUndervoltage()) {
|
||||||
|
undervoltageSymbolClasses = "text-error";
|
||||||
|
undervoltageParagraphClasses = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self.currentOverheat()) {
|
||||||
|
overheatSymbolClasses = "text-error pi_support_state_pulsate";
|
||||||
|
overheatParagraphClasses = "";
|
||||||
|
} else if (self.pastOverheat()) {
|
||||||
|
overheatSymbolClasses = "text-error";
|
||||||
|
overheatParagraphClasses = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
return "<p class='" + undervoltageParagraphClasses + "'><strong class='" + undervoltageSymbolClasses + "'><i class=\"fa fa-bolt\"></i><i class=\"fa fa-exclamation\"></i></strong></strong> - " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "</p>"
|
||||||
|
+ "<p class='" + overheatParagraphClasses + "'><strong class='" + overheatSymbolClasses + "'><i class=\"fa fa-thermometer-full\"></i><i class=\"fa fa-exclamation\"></i></strong> - " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "</p>"
|
||||||
|
+ "<p>" + gettext("A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up.") + "</p>"
|
||||||
|
+ "<p><small>" + gettext("Click the symbol in the navbar for more information.") + "</small></p>";
|
||||||
|
});
|
||||||
|
|
||||||
self.onStartup = function() {
|
self.onStartup = function() {
|
||||||
self.requestData();
|
self.requestData();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
<a href="javascript:void(0)" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('Issues reported by the Pi') }}', html: true, content: issuePopoverContent(), trigger: 'hover' }" style="display: none">
|
<a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('What do the symbols mean?') }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
|
||||||
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage') }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
|
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage') }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
|
||||||
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat') }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
|
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat') }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
|
||||||
</a>
|
</a>
|
||||||
@@ -36,9 +36,19 @@ ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower()
|
|||||||
CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower()
|
CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower()
|
||||||
CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower()
|
CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower()
|
||||||
|
|
||||||
|
# Creality Ender 3
|
||||||
|
ENDER3_AUTHOR = " | Author: (Ender3)".lower()
|
||||||
|
ENDER3_RECEIVED_TEST = lambda line: line and ENDER3_AUTHOR in line.lower()
|
||||||
|
|
||||||
|
# iMe on Micro3D
|
||||||
|
IME_M115_TEST = lambda name, data: name and name.lower().startswith("ime")
|
||||||
|
|
||||||
# Malyan M200 aka Monoprice Select Mini
|
# Malyan M200 aka Monoprice Select Mini
|
||||||
MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200"
|
MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200"
|
||||||
|
|
||||||
|
# Stock Micro3D
|
||||||
|
MICRO3D_M115_TEST = lambda name, data: name and name.lower().startswith("micro3d")
|
||||||
|
|
||||||
# Any Repetier versions < 0.92
|
# Any Repetier versions < 0.92
|
||||||
REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92")
|
REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92")
|
||||||
|
|
||||||
@@ -46,11 +56,12 @@ REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startsw
|
|||||||
THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled
|
THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled
|
||||||
|
|
||||||
SAFETY_CHECKS = {
|
SAFETY_CHECKS = {
|
||||||
"firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST, REPETIER_BEFORE_092_M115_TEST),
|
"firmware-unsafe": dict(m115=(ANETA8_M115_TEST, IME_M115_TEST, MALYANM200_M115_TEST, MICRO3D_M115_TEST,
|
||||||
received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST),
|
REPETIER_BEFORE_092_M115_TEST),
|
||||||
|
received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST, ENDER3_RECEIVED_TEST),
|
||||||
cap=(THERMAL_PROTECTION_CAP_TEST,),
|
cap=(THERMAL_PROTECTION_CAP_TEST,),
|
||||||
message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \
|
message=gettext(u"Your printer's firmware is known to lack mandatory safety features (e.g. "
|
||||||
u"thermal runaway protection). This is a fire risk.")
|
u"thermal runaway protection). This is a fire risk."))
|
||||||
}
|
}
|
||||||
|
|
||||||
def extract_repetier_version(name):
|
def extract_repetier_version(name):
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ $(function() {
|
|||||||
self.fromResponse = function(data) {
|
self.fromResponse = function(data) {
|
||||||
var warnings = [];
|
var warnings = [];
|
||||||
_.each(data, function(message, warning_type) {
|
_.each(data, function(message, warning_type) {
|
||||||
warnings.push({type: warning_type, message: message});
|
warnings.push({type: warning_type, message: gettext(message)});
|
||||||
});
|
});
|
||||||
self.warnings(warnings);
|
self.warnings(warnings);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
self._version_cache_dirty = False
|
self._version_cache_dirty = False
|
||||||
self._version_cache_timestamp = None
|
self._version_cache_timestamp = None
|
||||||
|
|
||||||
self._environment_supported = False
|
self._environment_supported = True
|
||||||
self._environment_versions = dict()
|
self._environment_versions = dict()
|
||||||
self._environment_ready = threading.Event()
|
self._environment_ready = threading.Event()
|
||||||
|
|
||||||
@@ -99,15 +99,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
self._console_logger.propagate = False
|
self._console_logger.propagate = False
|
||||||
|
|
||||||
def on_after_startup(self):
|
def on_after_startup(self):
|
||||||
# refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from
|
self._check_environment()
|
||||||
# the server startup
|
self.get_current_versions()
|
||||||
def fetch_data():
|
|
||||||
self.get_current_versions()
|
|
||||||
self._check_environment()
|
|
||||||
|
|
||||||
thread = threading.Thread(target=fetch_data)
|
|
||||||
thread.daemon = True
|
|
||||||
thread.start()
|
|
||||||
|
|
||||||
def _get_configured_checks(self):
|
def _get_configured_checks(self):
|
||||||
with self._configured_checks_mutex:
|
with self._configured_checks_mutex:
|
||||||
@@ -117,6 +110,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
|
|
||||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||||
check_providers = self._settings.get(["check_providers"], merged=True)
|
check_providers = self._settings.get(["check_providers"], merged=True)
|
||||||
|
if not isinstance(check_providers, dict):
|
||||||
|
check_providers = dict()
|
||||||
|
|
||||||
effective_configs = dict()
|
effective_configs = dict()
|
||||||
|
|
||||||
for name, hook in update_check_hooks.items():
|
for name, hook in update_check_hooks.items():
|
||||||
@@ -513,7 +509,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
force = flask.request.values.get("force", "false") in octoprint.settings.valid_boolean_trues
|
force = flask.request.values.get("force", "false") in octoprint.settings.valid_boolean_trues
|
||||||
|
|
||||||
def view():
|
def view():
|
||||||
self._environment_ready.wait()
|
self._environment_ready.wait(timeout=30.0)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._environment = None
|
self._environment = None
|
||||||
|
self._throttle_state = None
|
||||||
|
self._helpers_get_throttle_state = None
|
||||||
self._printer_connection_parameters = None
|
self._printer_connection_parameters = None
|
||||||
self._url = None
|
self._url = None
|
||||||
self._ping_worker = None
|
self._ping_worker = None
|
||||||
@@ -60,7 +62,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
printjob=True,
|
printjob=True,
|
||||||
plugin=True,
|
plugin=True,
|
||||||
update=True,
|
update=True,
|
||||||
printer=True))
|
printer=True,
|
||||||
|
throttled=True))
|
||||||
|
|
||||||
def get_settings_restricted_paths(self):
|
def get_settings_restricted_paths(self):
|
||||||
return dict(admin=[["enabled"], ["unique_id"], ["events"]],
|
return dict(admin=[["enabled"], ["unique_id"], ["events"]],
|
||||||
@@ -84,13 +87,19 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
##~~ StartupPlugin
|
##~~ StartupPlugin
|
||||||
|
|
||||||
def on_after_startup(self):
|
def on_after_startup(self):
|
||||||
self._track_startup()
|
|
||||||
|
|
||||||
ping = self._settings.get_int(["ping"])
|
ping = self._settings.get_int(["ping"])
|
||||||
if ping:
|
if ping:
|
||||||
self._ping_worker = RepeatedTimer(ping, self._track_ping)
|
self._ping_worker = RepeatedTimer(ping, self._track_ping)
|
||||||
self._ping_worker.start()
|
self._ping_worker.start()
|
||||||
|
|
||||||
|
# cautiously look for the get_throttled helper from pi_support
|
||||||
|
pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled")
|
||||||
|
if pi_helper and 'get_throttled' in pi_helper:
|
||||||
|
self._helpers_get_throttle_state = pi_helper['get_throttled']
|
||||||
|
|
||||||
|
# now that we have everything set up, phone home.
|
||||||
|
self._track_startup()
|
||||||
|
|
||||||
##~~ ShutdownPlugin
|
##~~ ShutdownPlugin
|
||||||
|
|
||||||
def on_shutdown(self):
|
def on_shutdown(self):
|
||||||
@@ -101,8 +110,11 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
def on_event(self, event, payload):
|
def on_event(self, event, payload):
|
||||||
if event.startswith("plugin_pluginmanager_"):
|
if event.startswith("plugin_pluginmanager_"):
|
||||||
self._track_plugin_event(event, payload)
|
self._track_plugin_event(event, payload)
|
||||||
if event.startswith("plugin_softwareupdate_"):
|
elif event.startswith("plugin_softwareupdate_"):
|
||||||
self._track_update_event(event, payload)
|
self._track_update_event(event, payload)
|
||||||
|
elif event in ("plugin_pi_support_throttle_state",):
|
||||||
|
self._throttle_state = payload
|
||||||
|
self._track_throttle_event(event, payload)
|
||||||
elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
|
elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
|
||||||
self._track_printjob_event(event, payload)
|
self._track_printjob_event(event, payload)
|
||||||
elif event in (Events.CONNECTED,):
|
elif event in (Events.CONNECTED,):
|
||||||
@@ -124,7 +136,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
##~~ AssetPlugin
|
##~~ AssetPlugin
|
||||||
|
|
||||||
def get_assets(self):
|
def get_assets(self):
|
||||||
return dict(js=["js/tracking.js"])
|
return dict(js=["js/usage.js"])
|
||||||
|
|
||||||
##~~ WizardPlugin
|
##~~ WizardPlugin
|
||||||
|
|
||||||
@@ -162,6 +174,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
|
|
||||||
if b"plugins" in self._environment and b"pi_support" in self._environment[b"plugins"]:
|
if b"plugins" in self._environment and b"pi_support" in self._environment[b"plugins"]:
|
||||||
payload[b"pi_model"] = self._environment[b"plugins"][b"pi_support"][b"model"]
|
payload[b"pi_model"] = self._environment[b"plugins"][b"pi_support"][b"model"]
|
||||||
|
|
||||||
if b"octopi_version" in self._environment[b"plugins"][b"pi_support"]:
|
if b"octopi_version" in self._environment[b"plugins"][b"pi_support"]:
|
||||||
payload[b"octopi_version"] = self._environment[b"plugins"][b"pi_support"][b"octopi_version"]
|
payload[b"octopi_version"] = self._environment[b"plugins"][b"pi_support"][b"octopi_version"]
|
||||||
|
|
||||||
@@ -195,12 +208,32 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
elif event.endswith("_update_failed"):
|
elif event.endswith("_update_failed"):
|
||||||
self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
|
self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
|
||||||
|
|
||||||
|
def _track_throttle_event(self, event, payload):
|
||||||
|
if not self._settings.get_boolean(["events", "throttled"]):
|
||||||
|
return
|
||||||
|
|
||||||
|
args = dict(throttled_now=payload[b"current_issue"],
|
||||||
|
throttled_past=payload[b"past_issue"],
|
||||||
|
throttled_mask=payload[b"raw_value"],
|
||||||
|
throttled_voltage_now=payload[b"current_undervoltage"],
|
||||||
|
throttled_voltage_past=payload[b"past_undervoltage"],
|
||||||
|
throttled_overheat_now=payload[b"current_overheat"],
|
||||||
|
throttled_overheat_past=payload[b"past_overheat"])
|
||||||
|
|
||||||
|
if payload[b"current_issue"]:
|
||||||
|
track_event = "system_throttled"
|
||||||
|
else:
|
||||||
|
track_event = "system_unthrottled"
|
||||||
|
|
||||||
|
if track_event is not None:
|
||||||
|
self._track(track_event, **args)
|
||||||
|
|
||||||
def _track_printjob_event(self, event, payload):
|
def _track_printjob_event(self, event, payload):
|
||||||
if not self._settings.get_boolean(["events", "printjob"]):
|
if not self._settings.get_boolean(["events", "printjob"]):
|
||||||
return
|
return
|
||||||
|
|
||||||
sha = hashlib.sha1()
|
sha = hashlib.sha1()
|
||||||
sha.update(payload.get("name"))
|
sha.update(payload.get("path"))
|
||||||
sha.update(self._settings.get([b"unique_id"]))
|
sha.update(self._settings.get([b"unique_id"]))
|
||||||
|
|
||||||
track_event = None
|
track_event = None
|
||||||
@@ -216,10 +249,27 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
args[b"elapsed"] = elapsed
|
args[b"elapsed"] = elapsed
|
||||||
track_event = "print_done"
|
track_event = "print_done"
|
||||||
elif event == Events.PRINT_FAILED:
|
elif event == Events.PRINT_FAILED:
|
||||||
|
try:
|
||||||
|
elapsed = int(payload.get(b"time"))
|
||||||
|
except ValueError:
|
||||||
|
elapsed = "unknown"
|
||||||
|
args[b"elapsed"] = elapsed
|
||||||
|
args[b"reason"] = payload.get(b"reason", "unknown")
|
||||||
track_event = "print_failed"
|
track_event = "print_failed"
|
||||||
elif event == Events.PRINT_CANCELLED:
|
elif event == Events.PRINT_CANCELLED:
|
||||||
track_event = "print_cancelled"
|
track_event = "print_cancelled"
|
||||||
|
|
||||||
|
if callable(self._helpers_get_throttle_state):
|
||||||
|
try:
|
||||||
|
throttle_state = self._helpers_get_throttle_state(run_now=True)
|
||||||
|
if throttle_state and (throttle_state.get(b"current_issue", False) or throttle_state.get(b"past_issue", False)):
|
||||||
|
args[b"throttled_now"] = throttle_state[b"current_issue"]
|
||||||
|
args[b"throttled_past"] = throttle_state[b"past_issue"]
|
||||||
|
args[b"throttled_mask"] = throttle_state[b"raw_value"]
|
||||||
|
except:
|
||||||
|
# ignored
|
||||||
|
pass
|
||||||
|
|
||||||
if track_event is not None:
|
if track_event is not None:
|
||||||
self._track(track_event, **args)
|
self._track(track_event, **args)
|
||||||
|
|
||||||
@@ -246,15 +296,18 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
|
|
||||||
server = self._settings.get([b"server"])
|
server = self._settings.get([b"server"])
|
||||||
url = server.format(id=self._settings.get([b"unique_id"]), event=event)
|
url = server.format(id=self._settings.get([b"unique_id"]), event=event)
|
||||||
|
# Don't print the URL or UUID! That would expose the UUID in forums/tickets
|
||||||
|
# if pasted. It's okay for the user to know their uuid, but it shouldn't be shared.
|
||||||
|
|
||||||
headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())}
|
headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())}
|
||||||
try:
|
try:
|
||||||
params = urlencode(kwargs, doseq=True).replace("+", "%20")
|
params = urlencode(kwargs, doseq=True).replace("+", "%20")
|
||||||
|
|
||||||
requests.get(url,
|
requests.get(url,
|
||||||
params=params,
|
params=params,
|
||||||
timeout=3.1,
|
timeout=3.1,
|
||||||
headers=headers)
|
headers=headers)
|
||||||
self._logger.debug("Sent tracking event to {}".format(url))
|
self._logger.info("Sent tracking event {}, payload: {!r}".format(event, kwargs))
|
||||||
except:
|
except:
|
||||||
if self._logger.isEnabledFor(logging.DEBUG):
|
if self._logger.isEnabledFor(logging.DEBUG):
|
||||||
self._logger.exception("Error while sending event to anonymous usage tracking".format(url))
|
self._logger.exception("Error while sending event to anonymous usage tracking".format(url))
|
||||||
@@ -263,7 +316,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
|||||||
|
|
||||||
__plugin_name__ = "Anonymous Usage Tracking"
|
__plugin_name__ = "Anonymous Usage Tracking"
|
||||||
__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked"
|
__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked"
|
||||||
__plugin_homepage__ = "https://tracking.octoprint.org"
|
__plugin_url__ = "https://tracking.octoprint.org"
|
||||||
__plugin_author__ = "Gina Häußge"
|
__plugin_author__ = "Gina Häußge"
|
||||||
|
|
||||||
__plugin_implementation__ = TrackingPlugin()
|
__plugin_implementation__ = TrackingPlugin()
|
||||||
+24
-8
@@ -1,5 +1,5 @@
|
|||||||
$(function() {
|
$(function() {
|
||||||
function TrackingViewModel(parameters) {
|
function UsageViewModel(parameters) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
self.settingsViewModel = parameters[0];
|
self.settingsViewModel = parameters[0];
|
||||||
@@ -7,16 +7,16 @@ $(function() {
|
|||||||
self.setup = ko.observable(false);
|
self.setup = ko.observable(false);
|
||||||
|
|
||||||
self.decision = ko.observable();
|
self.decision = ko.observable();
|
||||||
|
self.active = ko.observable();
|
||||||
self.required = false;
|
self.required = false;
|
||||||
self.active = false;
|
|
||||||
|
|
||||||
self.enableTracking = function() {
|
self.enableUsage = function() {
|
||||||
self.settingsViewModel.settings.plugins.tracking.enabled(true);
|
self.settingsViewModel.settings.plugins.tracking.enabled(true);
|
||||||
self.decision(true);
|
self.decision(true);
|
||||||
self._sendData();
|
self._sendData();
|
||||||
};
|
};
|
||||||
|
|
||||||
self.disableTracking = function() {
|
self.disableUsage = function() {
|
||||||
self.settingsViewModel.settings.plugins.tracking.enabled(false);
|
self.settingsViewModel.settings.plugins.tracking.enabled(false);
|
||||||
self.decision(false);
|
self.decision(false);
|
||||||
self._sendData();
|
self._sendData();
|
||||||
@@ -45,7 +45,7 @@ $(function() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||||
return self.active;
|
return self.active();
|
||||||
};
|
};
|
||||||
|
|
||||||
self.onWizardDetails = function(response) {
|
self.onWizardDetails = function(response) {
|
||||||
@@ -68,17 +68,33 @@ $(function() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
self.active = true;
|
self.active(true);
|
||||||
self.settingsViewModel.saveData(data)
|
self.settingsViewModel.saveData(data)
|
||||||
.done(function() {
|
.done(function() {
|
||||||
self.setup(true);
|
self.setup(true);
|
||||||
self.active = false;
|
self.active(false);
|
||||||
|
})
|
||||||
|
.fail(function() {
|
||||||
|
self.decision(false);
|
||||||
|
self.setup(true);
|
||||||
|
self.active(false);
|
||||||
|
|
||||||
|
var message = gettext("Please open a <a href='%(bugreport)s' target='_blank' rel='noopener noreferrer'>" +
|
||||||
|
"bug report</a> on this. Make sure to include all requested information, including your " +
|
||||||
|
"<a href='%(jsconsole)s' target='_blank' rel='noopener noreferrer'>JS console</a> and " +
|
||||||
|
"<code>octoprint.log</code>.");
|
||||||
|
new PNotify({
|
||||||
|
title: gettext("Something went wrong"),
|
||||||
|
text: _.sprintf(message, {bugreport: "https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#how-to-file-a-bug-report", jsconsole: "https://webmasters.stackexchange.com/a/77337"}),
|
||||||
|
type: "error",
|
||||||
|
hide: false
|
||||||
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
OCTOPRINT_VIEWMODELS.push([
|
OCTOPRINT_VIEWMODELS.push([
|
||||||
TrackingViewModel,
|
UsageViewModel,
|
||||||
["settingsViewModel"],
|
["settingsViewModel"],
|
||||||
"#wizard_plugin_tracking"
|
"#wizard_plugin_tracking"
|
||||||
]);
|
]);
|
||||||
@@ -37,6 +37,9 @@
|
|||||||
<label class="checkbox">
|
<label class="checkbox">
|
||||||
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.update"> {{ _('OctoPrint or a plugin updated successfully or unsuccessfully') }}
|
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.update"> {{ _('OctoPrint or a plugin updated successfully or unsuccessfully') }}
|
||||||
</label>
|
</label>
|
||||||
|
<label class="checkbox">
|
||||||
|
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.throttled"> {{ _('System got throttled/unthrottled (currently only detected on RPis)') }}
|
||||||
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -9,8 +9,8 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div class="row-fluid">
|
<div class="row-fluid">
|
||||||
<a href="javascript:void(0)" class="btn span6" data-bind="click: function() { if(!setup()){disableTracking()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Anonymous Usage Tracking') }}</a>
|
<a href="javascript:void(0)" class="btn span6" data-bind="click: function() { if(!setup()){disableUsage()}}, enable: !setup(), css: {disabled: setup()}"><i class="fa fa-spinner fa-spin" style="display: none" data-bind="visible: active() && decision() === false"></i> {{ _('Disable Anonymous Usage Tracking') }}</a>
|
||||||
<a href="javascript:void(0)" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableTracking()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Anonymous Usage Tracking') }}</a>
|
<a href="javascript:void(0)" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableUsage()}}, enable: !setup(), css: {disabled: setup()}"><i class="fa fa-spinner fa-spin" style="display: none" data-bind="visible: active() && decision() === true"></i> {{ _('Enable Anonymous Usage Tracking') }}</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tracking_decision" style="display: none" data-bind="visible: setup()">
|
<div class="tracking_decision" style="display: none" data-bind="visible: setup()">
|
||||||
|
|||||||
@@ -231,12 +231,14 @@ class PrinterInterface(object):
|
|||||||
"""
|
"""
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
def extrude(self, amount, tags=None, *args, **kwargs):
|
def extrude(self, amount, speed=None, tags=None, *args, **kwargs):
|
||||||
"""
|
"""
|
||||||
Extrude ``amount`` millimeters of material from the tool.
|
Extrude ``amount`` millimeters of material from the tool.
|
||||||
|
|
||||||
Arguments:
|
Arguments:
|
||||||
amount (int, float): The amount of material to extrude in mm
|
amount (int, float): The amount of material to extrude in mm
|
||||||
|
speed (int, None): Speed at which to extrude (F parameter). If set to ``None`` (or left out)
|
||||||
|
the maximum speed of E axis from the printer profile will be used.
|
||||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||||
"""
|
"""
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|||||||
@@ -361,12 +361,22 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
|||||||
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"],
|
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"],
|
||||||
tags=kwargs.get("tags", set) | {"trigger:printer.home"})
|
tags=kwargs.get("tags", set) | {"trigger:printer.home"})
|
||||||
|
|
||||||
def extrude(self, amount, *args, **kwargs):
|
def extrude(self, amount, speed=None, *args, **kwargs):
|
||||||
if not isinstance(amount, (int, long, float)):
|
if not isinstance(amount, (int, long, float)):
|
||||||
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
||||||
|
|
||||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||||
extrusion_speed = printer_profile["axes"]["e"]["speed"]
|
|
||||||
|
# Use specified speed (if any)
|
||||||
|
max_e_speed = printer_profile["axes"]["e"]["speed"]
|
||||||
|
|
||||||
|
if speed is None:
|
||||||
|
# No speed was specified so default to value configured in printer profile
|
||||||
|
extrusion_speed = max_e_speed
|
||||||
|
else:
|
||||||
|
# Make sure that specified value is not greater than maximum as defined in printer profile
|
||||||
|
extrusion_speed = min([speed, max_e_speed])
|
||||||
|
|
||||||
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"],
|
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"],
|
||||||
tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"})
|
tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"})
|
||||||
|
|
||||||
@@ -963,6 +973,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
|||||||
payload = self._payload_for_print_job_event()
|
payload = self._payload_for_print_job_event()
|
||||||
if payload:
|
if payload:
|
||||||
payload["time"] = self._comm.getPrintTime()
|
payload["time"] = self._comm.getPrintTime()
|
||||||
|
payload["reason"] = "error"
|
||||||
|
|
||||||
def finalize():
|
def finalize():
|
||||||
self._fileManager.log_print(payload["origin"],
|
self._fileManager.log_print(payload["origin"],
|
||||||
@@ -1093,8 +1104,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
|||||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||||
|
|
||||||
|
|
||||||
def on_comm_print_job_failed(self):
|
def on_comm_print_job_failed(self, reason=None):
|
||||||
payload = self._payload_for_print_job_event()
|
payload = self._payload_for_print_job_event()
|
||||||
|
|
||||||
|
if reason:
|
||||||
|
payload["reason"] = reason
|
||||||
|
else:
|
||||||
|
payload["reason"] = "unknown"
|
||||||
|
|
||||||
if payload:
|
if payload:
|
||||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||||
|
|
||||||
@@ -1112,6 +1129,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
|||||||
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
|
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
|
||||||
if payload:
|
if payload:
|
||||||
payload["time"] = self._comm.getPrintTime()
|
payload["time"] = self._comm.getPrintTime()
|
||||||
|
payload["reason"] = "cancelled"
|
||||||
|
|
||||||
eventManager().fire(Events.PRINT_CANCELLED, payload)
|
eventManager().fire(Events.PRINT_CANCELLED, payload)
|
||||||
if not suppress_script:
|
if not suppress_script:
|
||||||
|
|||||||
@@ -242,7 +242,6 @@ class Server(object):
|
|||||||
|
|
||||||
# monkey patch a bunch of stuff
|
# monkey patch a bunch of stuff
|
||||||
util.tornado.fix_json_encode()
|
util.tornado.fix_json_encode()
|
||||||
util.flask.fix_flask_jsonify()
|
|
||||||
util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")])
|
util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")])
|
||||||
|
|
||||||
# setup app
|
# setup app
|
||||||
|
|||||||
@@ -129,9 +129,10 @@ def printerToolCommand():
|
|||||||
return make_response("Printer is currently printing", 409)
|
return make_response("Printer is currently printing", 409)
|
||||||
|
|
||||||
amount = data["amount"]
|
amount = data["amount"]
|
||||||
|
speed = data.get("speed", None)
|
||||||
if not isinstance(amount, (int, long, float)):
|
if not isinstance(amount, (int, long, float)):
|
||||||
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
||||||
printer.extrude(amount, tags=tags)
|
printer.extrude(amount, speed=speed, tags=tags)
|
||||||
|
|
||||||
elif command == "flowrate":
|
elif command == "flowrate":
|
||||||
factor = data["factor"]
|
factor = data["factor"]
|
||||||
|
|||||||
@@ -251,32 +251,6 @@ def fix_flask_login_remote_address():
|
|||||||
|
|
||||||
flask_login._get_remote_addr = fixed_get_remote_addr
|
flask_login._get_remote_addr = fixed_get_remote_addr
|
||||||
|
|
||||||
def fix_flask_jsonify():
|
|
||||||
def fixed_jsonify(*args, **kwargs):
|
|
||||||
"""Backported from https://github.com/pallets/flask/blob/7e714bd28b6e96d82b2848b48cf8ff48b517b09b/flask/json/__init__.py#L257"""
|
|
||||||
from flask.json import current_app, dumps
|
|
||||||
|
|
||||||
indent = None
|
|
||||||
separators = (',', ':')
|
|
||||||
|
|
||||||
if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:
|
|
||||||
indent = 2
|
|
||||||
separators = (', ', ': ')
|
|
||||||
|
|
||||||
if args and kwargs:
|
|
||||||
raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
|
|
||||||
elif len(args) == 1: # single args are passed directly to dumps()
|
|
||||||
data = args[0]
|
|
||||||
else:
|
|
||||||
data = args or kwargs
|
|
||||||
|
|
||||||
return current_app.response_class(
|
|
||||||
dumps(data, indent=indent, separators=separators) + '\n',
|
|
||||||
mimetype='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
flask.jsonify = fixed_jsonify
|
|
||||||
|
|
||||||
#~~ WSGI environment wrapper for reverse proxying
|
#~~ WSGI environment wrapper for reverse proxying
|
||||||
|
|
||||||
class ReverseProxiedEnvironment(object):
|
class ReverseProxiedEnvironment(object):
|
||||||
@@ -1132,10 +1106,13 @@ def get_flask_user_from_request(request):
|
|||||||
import flask_login
|
import flask_login
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
|
|
||||||
|
user = None
|
||||||
|
|
||||||
apikey = octoprint.server.util.get_api_key(request)
|
apikey = octoprint.server.util.get_api_key(request)
|
||||||
if settings().getBoolean(["api", "enabled"]) and apikey is not None:
|
if settings().getBoolean(["api", "enabled"]) and apikey is not None:
|
||||||
user = octoprint.server.util.get_user_for_apikey(apikey)
|
user = octoprint.server.util.get_user_for_apikey(apikey)
|
||||||
else:
|
|
||||||
|
if user is None:
|
||||||
user = flask_login.current_user
|
user = flask_login.current_user
|
||||||
|
|
||||||
return user
|
return user
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import octoprint.timelapse
|
|||||||
import octoprint.server
|
import octoprint.server
|
||||||
import octoprint.events
|
import octoprint.events
|
||||||
import octoprint.plugin
|
import octoprint.plugin
|
||||||
|
import octoprint.users
|
||||||
|
|
||||||
from octoprint.events import Events
|
from octoprint.events import Events
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
@@ -87,6 +88,8 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
self._eventManager = eventManager
|
self._eventManager = eventManager
|
||||||
self._pluginManager = pluginManager
|
self._pluginManager = pluginManager
|
||||||
|
|
||||||
|
self._userManager.register_callback(self._user_manager_callback)
|
||||||
|
|
||||||
self._remoteAddress = None
|
self._remoteAddress = None
|
||||||
self._user = None
|
self._user = None
|
||||||
|
|
||||||
@@ -95,6 +98,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
self._baseRateLimit = 0.5
|
self._baseRateLimit = 0.5
|
||||||
|
|
||||||
self._register_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.register")
|
self._register_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.register")
|
||||||
|
self._authed_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.authed")
|
||||||
self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit")
|
self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit")
|
||||||
|
|
||||||
self._registered = False
|
self._registered = False
|
||||||
@@ -112,6 +116,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
return "Unconnected {!r}".format(self)
|
return "Unconnected {!r}".format(self)
|
||||||
|
|
||||||
def on_open(self, info):
|
def on_open(self, info):
|
||||||
|
self._pluginManager.register_message_receiver(self.on_plugin_message)
|
||||||
self._remoteAddress = self._getRemoteAddress(info)
|
self._remoteAddress = self._getRemoteAddress(info)
|
||||||
self._logger.info("New connection from client: %s" % self._remoteAddress)
|
self._logger.info("New connection from client: %s" % self._remoteAddress)
|
||||||
|
|
||||||
@@ -145,8 +150,9 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
|
|
||||||
self._logger.info("Client connection closed: %s" % self._remoteAddress)
|
self._logger.info("Client connection closed: %s" % self._remoteAddress)
|
||||||
|
|
||||||
self._user = None
|
self._on_logout()
|
||||||
self._remoteAddress = None
|
self._remoteAddress = None
|
||||||
|
self._pluginManager.unregister_message_receiver(self.on_plugin_message)
|
||||||
|
|
||||||
def on_message(self, message):
|
def on_message(self, message):
|
||||||
try:
|
try:
|
||||||
@@ -169,12 +175,10 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
user = self._userManager.findUser(userid=user_id, session=user_session)
|
user = self._userManager.findUser(userid=user_id, session=user_session)
|
||||||
|
|
||||||
if user is not None:
|
if user is not None:
|
||||||
self._user = user
|
self._on_login(user)
|
||||||
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(),
|
|
||||||
self._remoteAddress))
|
|
||||||
else:
|
else:
|
||||||
self._user = None
|
|
||||||
self._logger.warn("Unknown user/session combo: {}:{}".format(user_id, user_session))
|
self._logger.warn("Unknown user/session combo: {}:{}".format(user_id, user_session))
|
||||||
|
self._on_logout()
|
||||||
|
|
||||||
self._register()
|
self._register()
|
||||||
|
|
||||||
@@ -270,6 +274,9 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
if not proceed:
|
if not proceed:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
self._do_emit(type, payload)
|
||||||
|
|
||||||
|
def _do_emit(self, type, payload):
|
||||||
try:
|
try:
|
||||||
self.send({type: payload})
|
self.send({type: payload})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -295,7 +302,6 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
self._printer.register_callback(self)
|
self._printer.register_callback(self)
|
||||||
self._fileManager.register_slicingprogress_callback(self)
|
self._fileManager.register_slicingprogress_callback(self)
|
||||||
octoprint.timelapse.register_callback(self)
|
octoprint.timelapse.register_callback(self)
|
||||||
self._pluginManager.register_message_receiver(self.on_plugin_message)
|
|
||||||
|
|
||||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
||||||
for event in octoprint.events.all_events():
|
for event in octoprint.events.all_events():
|
||||||
@@ -320,7 +326,6 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
self._printer.unregister_callback(self)
|
self._printer.unregister_callback(self)
|
||||||
self._fileManager.unregister_slicingprogress_callback(self)
|
self._fileManager.unregister_slicingprogress_callback(self)
|
||||||
octoprint.timelapse.unregister_callback(self)
|
octoprint.timelapse.unregister_callback(self)
|
||||||
self._pluginManager.unregister_message_receiver(self.on_plugin_message)
|
|
||||||
|
|
||||||
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
|
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
|
||||||
for event in octoprint.events.all_events():
|
for event in octoprint.events.all_events():
|
||||||
@@ -328,3 +333,40 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
|||||||
|
|
||||||
self._registered = False
|
self._registered = False
|
||||||
|
|
||||||
|
def _user_manager_callback(self, action, session_user):
|
||||||
|
if action != "logout":
|
||||||
|
# we are only interested in logouts
|
||||||
|
return
|
||||||
|
|
||||||
|
if not self._user or not session_user:
|
||||||
|
# we need both users set
|
||||||
|
return
|
||||||
|
|
||||||
|
if not isinstance(self._user, octoprint.users.SessionUser) or not isinstance(session_user, octoprint.users.SessionUser):
|
||||||
|
# and we need both users to be session users
|
||||||
|
return
|
||||||
|
|
||||||
|
if self._user.get_id() == session_user.get_id() and self._user.session == session_user.session:
|
||||||
|
# our user just logged out
|
||||||
|
self._on_logout()
|
||||||
|
|
||||||
|
def _on_login(self, user):
|
||||||
|
self._user = user
|
||||||
|
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(),
|
||||||
|
self._remoteAddress))
|
||||||
|
|
||||||
|
for name, hook in self._authed_hooks.items():
|
||||||
|
try:
|
||||||
|
hook(self, self._user)
|
||||||
|
except:
|
||||||
|
self._logger.exception("Error processing authed hook handler for plugin {}".format(name))
|
||||||
|
|
||||||
|
def _on_logout(self):
|
||||||
|
self._user = None
|
||||||
|
|
||||||
|
for name, hook in self._authed_hooks.items():
|
||||||
|
try:
|
||||||
|
hook(self, self._user)
|
||||||
|
except:
|
||||||
|
self._logger.exception("Error processing authed hook handler for plugin {}".format(name))
|
||||||
|
|
||||||
@@ -294,9 +294,9 @@ default_settings = {
|
|||||||
"tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"],
|
"tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"],
|
||||||
"settings": [
|
"settings": [
|
||||||
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
||||||
"section_features", "features", "webcam", "accesscontrol", "gcodevisualizer", "api",
|
"section_features", "features", "webcam", "accesscontrol", "gcodevisualizer", "api", "plugin_appkeys",
|
||||||
"section_octoprint", "server", "folders", "appearance", "plugin_logging", "plugin_pluginmanager",
|
"section_octoprint", "server", "folders", "appearance", "plugin_logging", "plugin_pluginmanager",
|
||||||
"plugin_softwareupdate", "plugin_announcements", "plugin_backup"
|
"plugin_softwareupdate", "plugin_announcements", "plugin_backup", "plugin_tracking", "plugin_pi_support"
|
||||||
],
|
],
|
||||||
"usersettings": ["access", "interface"],
|
"usersettings": ["access", "interface"],
|
||||||
"wizard": ["access"],
|
"wizard": ["access"],
|
||||||
@@ -355,7 +355,7 @@ default_settings = {
|
|||||||
"gcode": {
|
"gcode": {
|
||||||
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
|
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
|
||||||
"snippets": {
|
"snippets": {
|
||||||
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}",
|
"disable_hotends": "{% if printer_profile.extruder.sharedNozzle %}M104 T0 S0\n{% else %}{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}{% endif %}",
|
||||||
"disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}"
|
"disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<!-- Generator: Adobe Illustrator 21.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
<!-- Generator: Adobe Illustrator 21.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||||
<svg version="1.1" id="svg8868" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
<svg version="1.1" id="svg8868" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||||
viewBox="0 0 107.1 107.1" style="enable-background:new 0 0 107.1 107.1;" xml:space="preserve">
|
viewBox="0 0 107.1 107.1" width="256" height="256" style="enable-background:new 0 0 107.1 107.1;" xml:space="preserve">
|
||||||
<style type="text/css">
|
<style type="text/css">
|
||||||
.st0{fill:#13C100;}
|
.st0{fill:#13C100;}
|
||||||
.st1{fill:#169300;}
|
.st1{fill:#169300;}
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.0 KiB |
@@ -1,16 +1,26 @@
|
|||||||
ko.bindingHandlers.popover = {
|
ko.bindingHandlers.popover = {
|
||||||
|
keys: ["title", "animation", "placement", "trigger", "delay", "content", "html"],
|
||||||
|
|
||||||
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
|
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
|
||||||
var val = ko.utils.unwrapObservable(valueAccessor());
|
var val = ko.utils.unwrapObservable(valueAccessor());
|
||||||
|
|
||||||
var options = {
|
var keys = ko.bindingHandlers.popover.keys;
|
||||||
title: val.title,
|
var options = {};
|
||||||
animation: val.animation,
|
_.each(keys, function(key) {
|
||||||
placement: val.placement,
|
options[key] = ko.utils.unwrapObservable(val[key]);
|
||||||
trigger: val.trigger,
|
});
|
||||||
delay: val.delay,
|
|
||||||
content: val.content,
|
|
||||||
html: val.html
|
|
||||||
};
|
|
||||||
$(element).popover(options);
|
$(element).popover(options);
|
||||||
|
},
|
||||||
|
|
||||||
|
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
|
||||||
|
var val = ko.utils.unwrapObservable(valueAccessor());
|
||||||
|
|
||||||
|
var keys = ko.bindingHandlers.popover.keys;
|
||||||
|
var value;
|
||||||
|
_.each(keys, function(key) {
|
||||||
|
value = ko.utils.unwrapObservable(val[key]);
|
||||||
|
$(element).data("popover").options[key] = value;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -31,6 +31,8 @@ class UserManager(object):
|
|||||||
self._sessionids_by_userid = dict()
|
self._sessionids_by_userid = dict()
|
||||||
self._enabled = True
|
self._enabled = True
|
||||||
|
|
||||||
|
self._callbacks = []
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def enabled(self):
|
def enabled(self):
|
||||||
return self._enabled
|
return self._enabled
|
||||||
@@ -45,6 +47,16 @@ class UserManager(object):
|
|||||||
def disable(self):
|
def disable(self):
|
||||||
self._enabled = False
|
self._enabled = False
|
||||||
|
|
||||||
|
def register_callback(self, callback):
|
||||||
|
self._callbacks.append(callback)
|
||||||
|
|
||||||
|
def unregister_callback(self, callback):
|
||||||
|
try:
|
||||||
|
self._callbacks.remove(callback)
|
||||||
|
except ValueError:
|
||||||
|
# just wasn't registered
|
||||||
|
pass
|
||||||
|
|
||||||
def login_user(self, user):
|
def login_user(self, user):
|
||||||
self._cleanup_sessions()
|
self._cleanup_sessions()
|
||||||
|
|
||||||
@@ -70,6 +82,12 @@ class UserManager(object):
|
|||||||
|
|
||||||
self._logger.debug("Logged in user: %r" % user)
|
self._logger.debug("Logged in user: %r" % user)
|
||||||
|
|
||||||
|
for callback in self._callbacks:
|
||||||
|
try:
|
||||||
|
callback("login", user)
|
||||||
|
except:
|
||||||
|
self._logger.exception("Error while calling login callback {!r}".format(callback))
|
||||||
|
|
||||||
return user
|
return user
|
||||||
|
|
||||||
def logout_user(self, user):
|
def logout_user(self, user):
|
||||||
@@ -96,6 +114,12 @@ class UserManager(object):
|
|||||||
|
|
||||||
self._logger.debug("Logged out user: %r" % user)
|
self._logger.debug("Logged out user: %r" % user)
|
||||||
|
|
||||||
|
for callback in self._callbacks:
|
||||||
|
try:
|
||||||
|
callback("logout", user)
|
||||||
|
except:
|
||||||
|
self._logger.exception("Error while calling logout callback {!r}".format(callback))
|
||||||
|
|
||||||
def _cleanup_sessions(self):
|
def _cleanup_sessions(self):
|
||||||
import time
|
import time
|
||||||
for session, user in self._session_users_by_session.items():
|
for session, user in self._session_users_by_session.items():
|
||||||
|
|||||||
@@ -1299,6 +1299,9 @@ class CountedEvent(object):
|
|||||||
else:
|
else:
|
||||||
self._internal_set(self._counter - 1)
|
self._internal_set(self._counter - 1)
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.clear(completely=True)
|
||||||
|
|
||||||
def wait(self, timeout=None):
|
def wait(self, timeout=None):
|
||||||
self._event.wait(timeout)
|
self._event.wait(timeout)
|
||||||
|
|
||||||
|
|||||||
@@ -2322,7 +2322,7 @@ class MachineCom(object):
|
|||||||
def _on_external_reset(self):
|
def _on_external_reset(self):
|
||||||
# hold queue processing, clear queues and acknowledgements, reset line number and last lines
|
# hold queue processing, clear queues and acknowledgements, reset line number and last lines
|
||||||
with self._send_queue.blocked():
|
with self._send_queue.blocked():
|
||||||
self._clear_to_send.clear(completely=True)
|
self._clear_to_send.reset()
|
||||||
with self._command_queue.blocked():
|
with self._command_queue.blocked():
|
||||||
self._command_queue.clear()
|
self._command_queue.clear()
|
||||||
self._send_queue.clear()
|
self._send_queue.clear()
|
||||||
@@ -2493,7 +2493,7 @@ class MachineCom(object):
|
|||||||
# first hook to succeed wins, but any can pass on to the next
|
# first hook to succeed wins, but any can pass on to the next
|
||||||
self._changeState(self.STATE_OPEN_SERIAL)
|
self._changeState(self.STATE_OPEN_SERIAL)
|
||||||
self._serial = serial_obj
|
self._serial = serial_obj
|
||||||
self._clear_to_send.clear()
|
self._clear_to_send.reset()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return False
|
return False
|
||||||
@@ -3600,7 +3600,7 @@ class MachineComPrintCallback(object):
|
|||||||
def on_comm_print_job_started(self, suppress_script=False):
|
def on_comm_print_job_started(self, suppress_script=False):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def on_comm_print_job_failed(self):
|
def on_comm_print_job_failed(self, reason=None):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def on_comm_print_job_done(self, suppress_script=False):
|
def on_comm_print_job_done(self, suppress_script=False):
|
||||||
|
|||||||
@@ -47,6 +47,14 @@ def clean_ansi(line):
|
|||||||
|
|
||||||
|
|
||||||
class CommandlineError(Exception):
|
class CommandlineError(Exception):
|
||||||
|
"""
|
||||||
|
Raised by :py:func:`~octoprint.util.commandline.CommandLineCaller.checked_call` on non zero return codes
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
returncode (int): the return code of the command
|
||||||
|
stdout (str): the stdout output produced by the command
|
||||||
|
stderr (str): the stderr output produced by the command
|
||||||
|
"""
|
||||||
def __init__(self, returncode, stdout, stderr):
|
def __init__(self, returncode, stdout, stderr):
|
||||||
self.returncode = returncode
|
self.returncode = returncode
|
||||||
self.stdout = stdout
|
self.stdout = stdout
|
||||||
@@ -54,15 +62,78 @@ class CommandlineError(Exception):
|
|||||||
|
|
||||||
|
|
||||||
class CommandlineCaller(object):
|
class CommandlineCaller(object):
|
||||||
|
"""
|
||||||
|
The CommandlineCaller is a utility class that allows running command line commands while logging there stdout
|
||||||
|
and stderr via configurable callback functions.
|
||||||
|
|
||||||
|
Callbacks are expected to have a signature matching
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
def callback(*lines):
|
||||||
|
do_something_with_the_passed_lines()
|
||||||
|
|
||||||
|
The class utilizes sarge underneath.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
from octoprint.util.commandline import CommandLineCaller, CommandLineError
|
||||||
|
|
||||||
|
def log(prefix, *lines):
|
||||||
|
for line in lines:
|
||||||
|
print(u"{} {}".format(prefix, line))
|
||||||
|
|
||||||
|
def log_stdout(*lines):
|
||||||
|
log(u">>>", *lines)
|
||||||
|
|
||||||
|
def log_stderr(*lines):
|
||||||
|
log(u"!!!", *lines)
|
||||||
|
|
||||||
|
def log_call(*lines)
|
||||||
|
log(u"---", *lines)
|
||||||
|
|
||||||
|
caller = CommandLineCaller()
|
||||||
|
caller.on_log_call = log_call
|
||||||
|
caller.on_log_stdout = log_stdout
|
||||||
|
caller.on_log_stderr = log_stderr
|
||||||
|
|
||||||
|
try:
|
||||||
|
caller.checked_call(["some", "command", "with", "parameters"])
|
||||||
|
except CommandLineError as err:
|
||||||
|
print(u"Command returned {}".format(err.returncode))
|
||||||
|
else:
|
||||||
|
print(u"Command finished successfully")
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
self.on_log_call = lambda *args, **kwargs: None
|
self.on_log_call = lambda *args, **kwargs: None
|
||||||
|
"""Callback for the called command line"""
|
||||||
|
|
||||||
self.on_log_stdout = lambda *args, **kwargs: None
|
self.on_log_stdout = lambda *args, **kwargs: None
|
||||||
|
"""Callback for stdout output"""
|
||||||
|
|
||||||
self.on_log_stderr = lambda *args, **kwargs: None
|
self.on_log_stderr = lambda *args, **kwargs: None
|
||||||
|
"""Callback for stderr output"""
|
||||||
|
|
||||||
def checked_call(self, command, **kwargs):
|
def checked_call(self, command, **kwargs):
|
||||||
|
"""
|
||||||
|
Calls a command and raises an error if it doesn't return with return code 0
|
||||||
|
|
||||||
|
Args:
|
||||||
|
command (list, tuple or str): command to call
|
||||||
|
kwargs (dict): additional keyword arguments to pass to the sarge ``run`` call (note that ``_async``,
|
||||||
|
``stdout`` and ``stderr`` will be overwritten)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(tuple) a 3-tuple of return code, full stdout and full stderr output
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
CommandlineError
|
||||||
|
"""
|
||||||
returncode, stdout, stderr = self.call(command, **kwargs)
|
returncode, stdout, stderr = self.call(command, **kwargs)
|
||||||
|
|
||||||
if returncode != 0:
|
if returncode != 0:
|
||||||
@@ -71,6 +142,18 @@ class CommandlineCaller(object):
|
|||||||
return returncode, stdout, stderr
|
return returncode, stdout, stderr
|
||||||
|
|
||||||
def call(self, command, **kwargs):
|
def call(self, command, **kwargs):
|
||||||
|
"""
|
||||||
|
Calls a command
|
||||||
|
|
||||||
|
Args:
|
||||||
|
command (list, tuple or str): command to call
|
||||||
|
kwargs (dict): additional keyword arguments to pass to the sarge ``run`` call (note that ``_async``,
|
||||||
|
``stdout`` and ``stderr`` will be overwritten)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(tuple) a 3-tuple of return code, full stdout and full stderr output
|
||||||
|
"""
|
||||||
|
|
||||||
if isinstance(command, (list, tuple)):
|
if isinstance(command, (list, tuple)):
|
||||||
joined_command = " ".join(command)
|
joined_command = " ".join(command)
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
"""
|
||||||
|
This module contains a functions that monkey patch third party dependencies in the one or other way.
|
||||||
|
"""
|
||||||
|
from __future__ import absolute_import, division, print_function
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
import functools
|
||||||
|
import warnings
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def patch_sarge_async_on_py2():
|
||||||
|
if sys.version_info[0] >= 3:
|
||||||
|
return
|
||||||
|
|
||||||
|
def move_async(f):
|
||||||
|
@functools.wraps(f)
|
||||||
|
def decorated_function(*args, **kwargs):
|
||||||
|
if "async" in kwargs:
|
||||||
|
warnings.warn("sarge's \"async\" parameter is deprecated. Use \"_async\" instead.",
|
||||||
|
DeprecationWarning,
|
||||||
|
stacklevel=2)
|
||||||
|
kwargs["async_"] = kwargs.pop("async")
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
return decorated_function
|
||||||
|
|
||||||
|
import sarge
|
||||||
|
|
||||||
|
# wrap helper
|
||||||
|
sarge.run = move_async(sarge.run)
|
||||||
|
|
||||||
|
# wrap Command
|
||||||
|
sarge.Command.run = move_async(sarge.Command.run)
|
||||||
|
|
||||||
|
# wrap Pipeline
|
||||||
|
sarge.Pipeline.run = move_async(sarge.Pipeline.run)
|
||||||
|
sarge.Pipeline.run_command_node = move_async(sarge.Pipeline.run_command_node)
|
||||||
|
sarge.Pipeline.run_list_node = move_async(sarge.Pipeline.run_list_node)
|
||||||
|
sarge.Pipeline.run_logical_node = move_async(sarge.Pipeline.run_logical_node)
|
||||||
|
sarge.Pipeline.run_node = move_async(sarge.Pipeline.run_node)
|
||||||
|
sarge.Pipeline.run_node_in_thread = move_async(sarge.Pipeline.run_node_in_thread)
|
||||||
|
sarge.Pipeline.run_pipeline_node = move_async(sarge.Pipeline.run_pipeline_node)
|
||||||
+62
-30
@@ -8,8 +8,28 @@ import socket
|
|||||||
import sys
|
import sys
|
||||||
import netaddr
|
import netaddr
|
||||||
import netifaces
|
import netifaces
|
||||||
|
import logging
|
||||||
|
|
||||||
HAS_V6 = socket.has_ipv6
|
_cached_check_v6 = None
|
||||||
|
def check_v6():
|
||||||
|
global _cached_check_v6
|
||||||
|
|
||||||
|
def f():
|
||||||
|
if not socket.has_ipv6:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
||||||
|
except:
|
||||||
|
# "[Errno 97] Address family not supported by protocol" or anything else really...
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
if _cached_check_v6 is None:
|
||||||
|
_cached_check_v6 = f()
|
||||||
|
return _cached_check_v6
|
||||||
|
|
||||||
|
HAS_V6 = check_v6()
|
||||||
|
|
||||||
if hasattr(socket, "IPPROTO_IPV6") and hasattr(socket, "IPV6_V6ONLY"):
|
if hasattr(socket, "IPPROTO_IPV6") and hasattr(socket, "IPV6_V6ONLY"):
|
||||||
# Dual stack support, hooray!
|
# Dual stack support, hooray!
|
||||||
@@ -21,30 +41,31 @@ else:
|
|||||||
IPPROTO_IPV6 = 41
|
IPPROTO_IPV6 = 41
|
||||||
IPV6_V6ONLY = 27
|
IPV6_V6ONLY = 27
|
||||||
else:
|
else:
|
||||||
# Whatever we are running on here, it we don't want to use V6 on here due to lack of dual stack support
|
# Whatever we are running on here, we don't want to use V6 on here due to lack of dual stack support
|
||||||
HAS_V6 = False
|
HAS_V6 = False
|
||||||
|
|
||||||
def is_lan_address(address, additional_private=None):
|
def is_lan_address(address, additional_private=None):
|
||||||
if address.lower().startswith("::ffff:") and "." in address:
|
try:
|
||||||
# ipv6 mapped ipv4 address, unmap
|
if address.lower().startswith("::ffff:") and "." in address:
|
||||||
address = address[len("::ffff:"):]
|
# ipv6 mapped ipv4 address, unmap
|
||||||
|
address = address[len("::ffff:"):]
|
||||||
|
|
||||||
ip = netaddr.IPAddress(address)
|
ip = netaddr.IPAddress(address)
|
||||||
if ip.is_private() or ip.is_loopback():
|
if ip.is_private() or ip.is_loopback():
|
||||||
return True
|
return True
|
||||||
|
|
||||||
if additional_private is None or not isinstance(additional_private, (list, tuple)):
|
if additional_private is None or not isinstance(additional_private, (list, tuple)):
|
||||||
additional_private = []
|
additional_private = []
|
||||||
|
|
||||||
subnets = netaddr.IPSet()
|
subnets = netaddr.IPSet()
|
||||||
for additional in additional_private:
|
for additional in additional_private:
|
||||||
try:
|
try:
|
||||||
subnets.add(netaddr.IPNetwork(additional))
|
subnets.add(netaddr.IPNetwork(additional))
|
||||||
except:
|
except:
|
||||||
pass
|
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
|
||||||
|
logging.getLogger(__name__).exception("Error while trying to add additional private network to local subnets: {}".format(additional))
|
||||||
|
|
||||||
def to_ipnetwork(address):
|
def to_ipnetwork(address):
|
||||||
try:
|
|
||||||
prefix = address["netmask"]
|
prefix = address["netmask"]
|
||||||
if "/" in prefix:
|
if "/" in prefix:
|
||||||
# v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
|
# v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
|
||||||
@@ -55,19 +76,30 @@ def is_lan_address(address, additional_private=None):
|
|||||||
# interface comment in netifaces output, e.g. "fe80::457f:bbee:d579:1063%wlan0"
|
# interface comment in netifaces output, e.g. "fe80::457f:bbee:d579:1063%wlan0"
|
||||||
addr = addr[:addr.find("%")]
|
addr = addr[:addr.find("%")]
|
||||||
return netaddr.IPNetwork("{}/{}".format(addr, prefix))
|
return netaddr.IPNetwork("{}/{}".format(addr, prefix))
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
for interface in netifaces.interfaces():
|
for interface in netifaces.interfaces():
|
||||||
addrs = netifaces.ifaddresses(interface)
|
addrs = netifaces.ifaddresses(interface)
|
||||||
for v4 in addrs.get(socket.AF_INET, ()):
|
for v4 in addrs.get(socket.AF_INET, ()):
|
||||||
subnets.add(to_ipnetwork(v4))
|
try:
|
||||||
|
subnets.add(to_ipnetwork(v4))
|
||||||
|
except:
|
||||||
|
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
|
||||||
|
logging.getLogger(__name__).exception("Error while trying to add v4 network to local subnets: {!r}".format(v4))
|
||||||
|
|
||||||
if HAS_V6:
|
if HAS_V6:
|
||||||
for v6 in addrs.get(socket.AF_INET6, ()):
|
for v6 in addrs.get(socket.AF_INET6, ()):
|
||||||
subnets.add(to_ipnetwork(v6))
|
try:
|
||||||
|
subnets.add(to_ipnetwork(v6))
|
||||||
|
except:
|
||||||
|
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
|
||||||
|
logging.getLogger(__name__).exception("Error while trying to add v6 network to local subnets: {!r}".format(v6))
|
||||||
|
|
||||||
if ip in subnets:
|
if ip in subnets:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
except:
|
||||||
|
# we are extra careful here since an unhandled exception in this method will effectively nuke the whole UI
|
||||||
|
logging.getLogger(__name__).exception("Error while trying to determine whether {} is a local address".format(address))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return False
|
|
||||||
@@ -150,4 +150,5 @@ class ThrottleStateTestCase(unittest.TestCase):
|
|||||||
current_overheat=False,
|
current_overheat=False,
|
||||||
past_overheat=True,
|
past_overheat=True,
|
||||||
current_issue=True,
|
current_issue=True,
|
||||||
past_issue=True))
|
past_issue=True,
|
||||||
|
raw_value=-1))
|
||||||
Binary file not shown.
+1620
-2156
File diff suppressed because it is too large.
Load diff
+1081
-415
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user