Merge commit 'c623e90ebc59b90b4f4cf582ab8185b2872acff4'; commit 'f416e96414f33fb31afdf4dfbf3c863e3db35543'; commit '9ecf39febe31a44e5f5db28249ebbf006ac1580c'; commit '582b03f21fe3d808bf4e11bbba90af54b6651b34'; commit 'f5c8b04958170f19f1806b1722bf5e857ded3dce'; commit '36818057a3b4769a77731f3be8bc661437db7132'; commit 'd987cb23c119132b287f70f1c979aac8c9fff7d2' into py23
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.
|
||||
@@ -31,9 +31,12 @@ OctoPrint.egg-info
|
||||
*.codekit
|
||||
|
||||
venv
|
||||
venv2
|
||||
venv3
|
||||
venv26
|
||||
venv27
|
||||
venv33
|
||||
venv34
|
||||
venv35
|
||||
venv36
|
||||
venv37
|
||||
@@ -18,16 +18,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.9
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.11
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
|
||||
fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
|
||||
improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 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/...
|
||||
staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
|
||||
regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
|
||||
staging/maintenance 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
|
||||
regressionfix/.* 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -69,7 +69,7 @@ date of first contribution):
|
||||
* [Philipp Baum](https://github.com/philphilphil)
|
||||
* [Kyle Evans](https://github.com/kevans91)
|
||||
* [Javier Martínez Arrieta](https://github.com/Javierma)
|
||||
* ["MirceaDan"](https://github.com/ByReaL)
|
||||
* [Mircea Dan Gheorghe](https://github.com/ByReaL)
|
||||
* [Ovidiu Hossu](https://github.com/MoonshineSG)
|
||||
* [Eyck Jentzsch](https://github.com/eyck)
|
||||
* [Mathias Rangel Wulff](https://github.com/mathiasrw)
|
||||
@@ -93,7 +93,9 @@ date of first contribution):
|
||||
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
||||
* [Andy Castille](https://github.com/klikini)
|
||||
* [Zachary Nofzinger](https://github.com/ZachNo)
|
||||
* [Gaston Dombiak](https://github.com/gdombiak)
|
||||
* [Brad Fisher](https://github.com/bradcfisher)
|
||||
* [Aldo Hoeben](https://github.com/fieldofview)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
@@ -27,7 +27,7 @@ to **address problems in a timely manner** but also keep it possible for them
|
||||
to **fix bugs, add new and improve on existing functionality** instead of doing
|
||||
nothing but ticket management.
|
||||
|
||||

|
||||

|
||||
|
||||
- **[Read the FAQ](https://faq.octoprint.org)**
|
||||
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
|
||||
@@ -39,11 +39,11 @@ nothing but ticket management.
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
|
||||
such support issues.
|
||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
||||
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
|
||||
`[Brainstorming] New plugin hook for doing some cool stuff`).
|
||||
changes to the plugin system, please get in touch on the
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
|
||||
- If you need **support**, have a **question** or some **other reason** that
|
||||
doesn't fit any of the above categories, the issue tracker is not the right place.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
|
||||
|
||||
No matter what kind of ticket you create, never mix two or more "ticket reasons"
|
||||
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
@@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
> A bot is in place that monitors new tickets, automatically
|
||||
> categorizes them and checks new bug reports for usage of the provided template.
|
||||
> That bot will only bother you if you open a ticket that appears to be a bug (no
|
||||
> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
|
||||
> `[Request]` in the title) without the complete template, and it
|
||||
> will do that only to ensure that all information needed to solve the issue is
|
||||
> available for the maintainers to directly start tackling that problem.
|
||||
|
||||
@@ -301,7 +301,8 @@ the documentation.
|
||||
the discussion going on how best to solve *this* in OctoPrint's plugin
|
||||
system - maybe that's the actual PR you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large or otherwise disruptive changes to the
|
||||
code or appearance, please open a "Brainstorming" ticket first** so
|
||||
code or appearance, please get in touch on the
|
||||
[forums](https://discourse.octoprint.org/c/development)** first so
|
||||
that we can determine if it's a good time for your specific pull
|
||||
request. It might be that we're currently in the process of making
|
||||
heavy changes to the code locations you'd target as well, or your
|
||||
@@ -311,7 +312,8 @@ the documentation.
|
||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
||||
`dev/myNewFeature`)[1].
|
||||
4. Create your pull request **only against the `maintenance` or `devel` branch**:
|
||||
* if it's a bug fix for a bug in the current stable version: `maintenance` branch
|
||||
* if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
|
||||
*small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
|
||||
* otherwise: `devel` branch
|
||||
5. Create **one pull request per feature/bug fix**.
|
||||
6. Make sure there are **only relevant changes** included in your PR. No
|
||||
@@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 2017-11-22: Added note on how to run the unit tests
|
||||
* 2018-03-15: Link to new community forum and some clarifications re bug
|
||||
reporting
|
||||
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
|
||||
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
|
||||
* 2018-10-18: Allow PRs against `maintenance` branch for improvements and small
|
||||
new features, suggest getting in touch on the forum for larger changes
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
@@ -6,25 +6,23 @@ thanks to everyone who contributed!
|
||||
|
||||
## Patreon Patrons
|
||||
|
||||
* Andre Bubel
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brian E. Tyler
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* COLLE+McVOY
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* E3D BigBox
|
||||
* Eric Betts
|
||||
* Eric Slape
|
||||
* Ernesto Martinez
|
||||
* F. Kunsmann
|
||||
* Frank Sander
|
||||
* George Robles
|
||||
* günter weber
|
||||
* Hydra Research LLC
|
||||
* James Seigel
|
||||
* Jeff Moe
|
||||
* Jared Go
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
@@ -35,29 +33,25 @@ thanks to everyone who contributed!
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kodama Inc.
|
||||
* LA 3D Printer Repair
|
||||
* Lewis Newby
|
||||
* LulzBot®
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Martin Beattie
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* mitchell hirsch
|
||||
* Noe Ruiz
|
||||
* Mosaic Manufacturing
|
||||
* Patrick McGinnis
|
||||
* Prof Yuh Wen Chen
|
||||
* Randy C. Will
|
||||
* Robert Gusek
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Rudolff Vang
|
||||
* Samer Najia
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Sven Mueller
|
||||
* Symbiotic Devices
|
||||
* Thomas Hatley
|
||||
* Timothy D Hoogland
|
||||
* 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)!
|
||||
@@ -12,8 +12,11 @@ Authorization
|
||||
=============
|
||||
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one, a user specific one if "Access Control" is enabled or an :ref:`App Session Key <sec-api-apps-sessionkey>`.
|
||||
Users are able to generate and revoke their custom API key via the "Change password" dialog.
|
||||
configured one, a user specific one if "Access Control" is enabled or an app and user specific one as generated
|
||||
by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
|
||||
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
|
||||
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
|
||||
|
||||
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
|
||||
@@ -23,7 +26,7 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`.
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`.
|
||||
|
||||
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||
|
||||
@@ -120,3 +123,94 @@ If CORS is not enabled you will get errors like the following::
|
||||
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
|
||||
header is present on the requested resource.
|
||||
|
||||
.. _sec-api-general-login:
|
||||
|
||||
Login
|
||||
=====
|
||||
|
||||
.. http:post:: /api/login
|
||||
|
||||
Creates a login session or retrieves information about the currently existing session ("passive login").
|
||||
|
||||
Can be used in one of two ways: to login a user via username and password and create a persistent session (usually
|
||||
from a UI in the browser), or to retrieve information about the active user (from an existing session or an API key)
|
||||
via the ``passive`` flag.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
|
||||
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
|
||||
|
||||
:json passive: If present, performs a passive login only, returning information about the current user that's
|
||||
active either through an existing session or the used API key
|
||||
:json user: (active login only) Username
|
||||
:json pass: (active login only) Password
|
||||
:json remember: (active login only) Whether to set a "remember me" cookie on the session
|
||||
:status 200: Successful login
|
||||
:status 401: Username/password mismatch or unknown user
|
||||
:status 403: Deactivated account
|
||||
|
||||
.. _sec-api-general-logout:
|
||||
|
||||
Logout
|
||||
======
|
||||
|
||||
.. http:post:: /api/logout
|
||||
|
||||
Ends the current login session of the current user.
|
||||
|
||||
Only makes sense in the context of browser based workflows.
|
||||
|
||||
Will return a :http:statuscode:`204`.
|
||||
|
||||
:status 204: No error
|
||||
|
||||
.. _sec-api-general-datamodel:
|
||||
|
||||
Data model
|
||||
==========
|
||||
|
||||
.. _sec-api-general-datamodel-login:
|
||||
|
||||
Login response
|
||||
--------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- the user's name/id
|
||||
* - ``active``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user's account is active or not
|
||||
* - ``admin``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has admin rights or not
|
||||
* - ``user``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has user rights or not (always ``true``)
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- string or None
|
||||
- The user's API key, if set
|
||||
* - ``settings``
|
||||
- 1
|
||||
- dict
|
||||
- The user's settings, if any
|
||||
* - ``session``
|
||||
- 1
|
||||
- string
|
||||
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
|
||||
* - ``_is_external_client``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the client that made the request got detected as external from the local network or not.
|
||||
@@ -219,7 +219,7 @@ Issue a print head command
|
||||
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
|
||||
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
|
||||
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
|
||||
interpreted as an integer signifying the speed in mm/s, to append to the command.
|
||||
interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
home
|
||||
Homes the print head in all of the given axes. Additional parameters are:
|
||||
@@ -362,6 +362,8 @@ Issue a tool command
|
||||
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
|
||||
|
||||
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
|
||||
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
|
||||
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
flowrate
|
||||
Changes the flow rate factor to apply to extrusion of the tool.
|
||||
|
||||
@@ -47,23 +47,41 @@ Clients must ignore any unknown messages.
|
||||
|
||||
The data model of the attached payloads is described further below.
|
||||
|
||||
OctoPrint's SockJS socket also accepts one command from the client to the server,
|
||||
the ``throttle`` command. Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
OctoPrint's SockJS socket also accepts two commands from the client to the server.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
|
||||
existing user session with the socket. That is of special importance to receive
|
||||
any kind of messages if the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` is enabled
|
||||
(as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated
|
||||
clients.
|
||||
|
||||
.. sourcecode:: javascript
|
||||
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
|
||||
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
Example for a ``auth`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"auth": "someuser:LGZ0trf8By"
|
||||
}
|
||||
|
||||
* ``throttle``: Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
|
||||
.. _sec-api-push-datamodel:
|
||||
|
||||
|
||||
@@ -396,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
-
|
||||
* - ``feature.sdSupport``
|
||||
-
|
||||
* - ``feature.sdReleativePath``
|
||||
* - ``feature.sdRelativePath``
|
||||
-
|
||||
* - ``feature.sdAlwaysAvailable``
|
||||
-
|
||||
|
||||
@@ -7,7 +7,8 @@ Version information
|
||||
.. http:get:: /api/version
|
||||
|
||||
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
|
||||
the API version, ``server`` containing the server version.
|
||||
the API version, ``server`` containing the server version, ``text`` containing the server version including
|
||||
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
|
||||
|
||||
**Example Request**
|
||||
|
||||
@@ -26,7 +27,8 @@ Version information
|
||||
|
||||
{
|
||||
"api": "0.1",
|
||||
"server": "1.1.0"
|
||||
"server": "1.3.10",
|
||||
"text": "OctoPrint 1.3.10"
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
@@ -0,0 +1,67 @@
|
||||
.. _sec-bundledplugins-announcements:
|
||||
|
||||
Announcement Plugin
|
||||
===================
|
||||
|
||||
The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11).
|
||||
|
||||
It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new
|
||||
plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels
|
||||
via RSS or Atom feed URLs.
|
||||
|
||||
.. _fig-bundledplugins-announcements-example1:
|
||||
.. figure:: ../images/bundledplugins-announcements-example1.png
|
||||
:align: center
|
||||
:alt: Example notification
|
||||
|
||||
An example notification from the Announcement Plugin.
|
||||
|
||||
.. _fig-bundledplugins-announcements-example2:
|
||||
.. figure:: ../images/bundledplugins-announcements-example2.png
|
||||
:align: center
|
||||
:alt: Announcement reader
|
||||
|
||||
The Announcement Plugin's reader dialog.
|
||||
|
||||
.. _fig-bundledplugins-announcements-settings:
|
||||
.. figure:: ../images/bundledplugins-announcements-settings.png
|
||||
:align: center
|
||||
:alt: Announcement settings
|
||||
|
||||
The Announcement Plugin's settings dialog.
|
||||
|
||||
.. _sec-bundledplugins-announcements-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog.
|
||||
|
||||
On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the
|
||||
configuration of the existing channels through ``config.yaml``.
|
||||
|
||||
The available configuration keys are:
|
||||
|
||||
* ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure
|
||||
that follows this format:
|
||||
|
||||
* ``name``: Name of the channel, used e.g. in the title of the displayed notifications.
|
||||
* ``description``: Description of the channel.
|
||||
* ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification).
|
||||
* ``type``: Currently unused.
|
||||
* ``url``: URL for the feed acting as notification source, must be RSS or Atom format.
|
||||
|
||||
* ``enabled_channels``: List of identifiers of enabled channels.
|
||||
* ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly).
|
||||
* ``channel_order``: List of channel identifiers in the order they should appear in the UI.
|
||||
* ``ttl``: Time to live of the channel cache in minutes (default: 6 hours).
|
||||
* ``display_limit``: Limit of items to display per channel (default: 3).
|
||||
* ``summary_limit``: Limit of characters to display from each channel entry (default: 300).
|
||||
|
||||
.. _sec-bundledplugins-announcements-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Announcement plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/announcements``.
|
||||
@@ -0,0 +1,543 @@
|
||||
.. _sec-bundledplugins-appkeys:
|
||||
|
||||
Application Keys Plugin
|
||||
=======================
|
||||
|
||||
The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10).
|
||||
|
||||
It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it
|
||||
on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed
|
||||
on a per-user base as well as globally by administrators.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-confirmation:
|
||||
.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png
|
||||
:align: center
|
||||
:alt: Confirmation
|
||||
|
||||
The plugin's confirmation generated for a new application key request.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-user_settings:
|
||||
.. figure:: ../images/bundledplugins-appkeys-user_settings.png
|
||||
:align: center
|
||||
:alt: Key management via user settings
|
||||
|
||||
Users can manage the application specific API keys registered to their account via their user settings.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-settings:
|
||||
.. figure:: ../images/bundledplugins-appkeys-settings.png
|
||||
:align: center
|
||||
:alt: Global key management via settings
|
||||
|
||||
Administrators can manage all application specific API keys registered to any user.
|
||||
|
||||
.. _sec-bundledplugins-appkeys-workflow:
|
||||
|
||||
Workflow
|
||||
--------
|
||||
|
||||
The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist
|
||||
of the following steps:
|
||||
|
||||
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
|
||||
enters their username which is also their user ID into the App.
|
||||
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
|
||||
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
|
||||
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
|
||||
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
|
||||
authorization process.
|
||||
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
|
||||
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
|
||||
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
|
||||
signals that no decision has been made yet.
|
||||
6. The User either accepts or denies the access request which makes the Webinterface send a
|
||||
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
|
||||
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
|
||||
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
|
||||
an HTTP :http:statuscode:`404`.
|
||||
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant App
|
||||
participant Webinterface
|
||||
participant Server
|
||||
|
||||
note over User, Server: Step 1, 2 & 3
|
||||
|
||||
User->>App: enters URL of instance to connect to and optional user_id
|
||||
|
||||
App->>Server: GET /plugin/appkeys/probe
|
||||
|
||||
alt Workflow unsupported
|
||||
|
||||
Server->>App: 404
|
||||
App->>User: alternative workflow, copy-paste key manually
|
||||
|
||||
else Workflow supported
|
||||
|
||||
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
|
||||
|
||||
note over User, Server: Step 4
|
||||
|
||||
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
|
||||
Webinterface-->>User: Display confirmation dialog
|
||||
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
|
||||
|
||||
note over User, Server: Step 5
|
||||
|
||||
loop Poll for decision
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 202
|
||||
end
|
||||
|
||||
note over User, Server: Step 6 & 7
|
||||
|
||||
alt User accepts
|
||||
|
||||
User-->>Webinterface: Allow access
|
||||
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (True)
|
||||
Server->>Webinterface: 204
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 200, api_key
|
||||
|
||||
else User denies
|
||||
|
||||
User-->>Webinterface: Deny access
|
||||
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (False)
|
||||
Server->>Webinterface: 204
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 404
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api:
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-probe:
|
||||
|
||||
Probe for workflow support
|
||||
..........................
|
||||
|
||||
.. http:get:: /plugin/appkeys/probe
|
||||
|
||||
Probes for support of the workflow.
|
||||
|
||||
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
|
||||
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
|
||||
|
||||
:status 204: the workflow is supported
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-startauthprocess:
|
||||
|
||||
Start authorization process
|
||||
...........................
|
||||
|
||||
.. http:post:: /plugin/appkeys/request
|
||||
|
||||
Starts the authorization process.
|
||||
|
||||
Expects a :ref:`Key request <sec-bundledplugins-appkey-datamodel-keyrequest>` as request body.
|
||||
|
||||
The ``app`` parameter should be a human readable identifier to use
|
||||
for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively,
|
||||
so ``My App`` and ``my APP`` are considered the same application identifiers.
|
||||
|
||||
The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter
|
||||
is left unset, any user will be able to complete the authorization process and grant access to the app with their
|
||||
account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use
|
||||
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
|
||||
is logged in on.
|
||||
|
||||
:json app: application identifier to use for the request, case insensitive
|
||||
:json user: optional user id to restrict the decision to the specified user
|
||||
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-polldecision:
|
||||
|
||||
Poll for decision on existing request
|
||||
.....................................
|
||||
|
||||
.. http:get:: /plugin/appkeys/request/<str:app_token>
|
||||
|
||||
Endpoint generated per authorization request to poll for the result.
|
||||
|
||||
Returns an HTTP :http:statuscode:`202` while no decision has been made yet, an HTTP :http:statuscode:`200` and
|
||||
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
|
||||
HTTP :http:statuscode:`404` if the request has been denied or timed out.
|
||||
|
||||
.. note::
|
||||
|
||||
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
|
||||
for more than 5s.
|
||||
|
||||
:status 200: access granted, API key in response body
|
||||
:status 202: no decision has been made yet, continue polling
|
||||
:status 404: access denied or request timed out
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-decide:
|
||||
|
||||
Decide on existing request
|
||||
..........................
|
||||
|
||||
.. http:post:: /plugin/appkeys/decision/<str:user_token>
|
||||
|
||||
Endpoint to decide on the authorization request.
|
||||
|
||||
Expects a :ref:`Decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` as request body.
|
||||
|
||||
Returns an HTTP :http:statuscode:`204` on success.
|
||||
|
||||
:json decision: boolean value to indicate whether to confirm (``True``) or deny (``False``) access
|
||||
:status 204: success
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-fetchlist:
|
||||
|
||||
Fetch list of existing application keys
|
||||
.......................................
|
||||
|
||||
.. http:get:: /api/plugin/appkeys
|
||||
|
||||
Fetches a list of existing application keys and pending requests registered in the system for the current user.
|
||||
|
||||
If the additional optional parameter ``all`` is provided and the user has administrator rights, fetches a list
|
||||
of *all** application keys and pending requests registered in the system for any user.
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`List response <sec-bundledplugins-appkey-datamodel-listreponse>` in the
|
||||
body upon success.
|
||||
|
||||
:query all: Fetch all application keys and pending requests from all users. Requires administrator rights.
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-issuecommand:
|
||||
|
||||
Issue an application key command
|
||||
................................
|
||||
|
||||
.. http:post:: /api/plugin/appkeys
|
||||
|
||||
Application key commands allow revoking existing application keys and manually generating new ones. The available
|
||||
commands are:
|
||||
|
||||
revoke
|
||||
Revokes an existing application key. Must belong to the user issuing the command, unless the user has admin rights
|
||||
in which case they make revoke any application key in the system. Expects the key in question as parameter ``key``.
|
||||
|
||||
generate
|
||||
Generates a new application key for the user, using the application identifier provided as parameter ``app``.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires user rights.
|
||||
|
||||
**Example revoke request**
|
||||
|
||||
Revokes the (fictional) key ``aabbccddeeff112233445566``.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/plugin/appkeys HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "revoke",
|
||||
"key": "aabbccddeeff112233445566"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example generate request**
|
||||
|
||||
Generates a new key for application identifier "My awesome application 1.0".
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/plugin/appkeys HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "generate",
|
||||
"key": "My awesome application 1.0"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``revoke`` or ``generate``
|
||||
:json string key: ``revoke`` command: The key to revoke
|
||||
:json string app: ``generate`` command: Application identifier for which to generate a key
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: Invalid or missing parameter
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel:
|
||||
|
||||
Data model
|
||||
----------
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keyrequest:
|
||||
|
||||
Key request
|
||||
...........
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``app``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier to use for the request
|
||||
* - ``user``
|
||||
- 0..1
|
||||
- str
|
||||
- User identifier/name to restrict the request to
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keyresponse:
|
||||
|
||||
Key response
|
||||
............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- str
|
||||
- the API key generated for the application
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-decisionrequest:
|
||||
|
||||
Decision request
|
||||
................
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``decision``
|
||||
- 1
|
||||
- boolean
|
||||
- ``True`` if the access request it to be granted, ``False`` otherwise
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-listreponse:
|
||||
|
||||
List response
|
||||
.............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``keys``
|
||||
- 1
|
||||
- list of :ref:`key list entries <sec-bundledplugins-appkey-datamodel-keylistentry>`
|
||||
- Keys registered in the system
|
||||
* - ``pending``
|
||||
- 1
|
||||
- list of :ref:`pending list entries <sec-bundledplugins-appkey-datamodel-pendinglistentry>`
|
||||
- Currently pending authorization requests
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keylistentry:
|
||||
|
||||
Key list entry
|
||||
..............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``api_key``
|
||||
- 1
|
||||
- str
|
||||
- API key
|
||||
* - ``app_id``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier
|
||||
* - ``user_id``
|
||||
- 1
|
||||
- str
|
||||
- User ID of the key's owner
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-pendinglistentry:
|
||||
|
||||
Pending list entry
|
||||
..................
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``app_id``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier
|
||||
* - ``user_id``
|
||||
- 0..1
|
||||
- str
|
||||
- optional: User ID of user who can grant or deny request
|
||||
* - ``user_token``
|
||||
- 1
|
||||
- str
|
||||
- Token to grant or deny request
|
||||
|
||||
.. _sec-bundledplugins-appkeys-jsclientlib:
|
||||
|
||||
JavaScript Client Library
|
||||
-------------------------
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.getKeys(opts)
|
||||
|
||||
Retrieves registered keys and pending requests for the current user.
|
||||
|
||||
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.getAllKeys(opts)
|
||||
|
||||
Retrieves registered keys and pending requests for all users.
|
||||
|
||||
Needs administrator rights.
|
||||
|
||||
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.generateKey(app, opts)
|
||||
|
||||
Generates a key for the given ``app`` and the current user.
|
||||
|
||||
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
|
||||
|
||||
:param string app: Application identifier
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.revokeKey(key, opts)
|
||||
|
||||
Revokes the given ``key``. The key must belong to the current user, or the current user must have administrator
|
||||
rights.
|
||||
|
||||
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
|
||||
|
||||
:param string key: Key to revoke
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.decide(token, decision, opts)
|
||||
|
||||
Decides on an existing authorization request.
|
||||
|
||||
See :ref:`Decide on existing request <sec-bundledplugins-appkeys-api-decide>` for more details.
|
||||
|
||||
:param string token: User token for which to make the decision, as pushed to the client via the socket.
|
||||
:param boolean decision: Whether to grant access (``true``) or not (``false``).
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
|
||||
|
||||
Probes for workflow support.
|
||||
|
||||
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` identifier.
|
||||
|
||||
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.requestForUser(app, user, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` and ``user`` identifiers.
|
||||
|
||||
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.checkDecision(token, opts)
|
||||
|
||||
Polls for a decision on an existing authorization request identified by ``token``.
|
||||
|
||||
See :ref:`Poll for decision on existing request <sec-bundledplugins-appkeys-api-polldecision>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
|
||||
|
||||
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
|
||||
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
|
||||
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
|
||||
for the workflow, the promise is rejected.
|
||||
|
||||
**Example usage**
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
OctoPrint.plugins.appkeys.authenticate("My App", "some_user")
|
||||
.done(function(api_key) {
|
||||
console.log("Got our API key:", api_key);
|
||||
})
|
||||
.fail(function() {
|
||||
console.log("No API key for us");
|
||||
})
|
||||
|
||||
:param string app: Application identifier
|
||||
:param string user: Optional user identifier
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. _sec-bundledplugins-appkeys-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Application Keys plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/appkeys``.
|
||||
@@ -0,0 +1,70 @@
|
||||
.. _sec-bundledplugins-backup:
|
||||
|
||||
Backup Plugin
|
||||
=============
|
||||
|
||||
The OctoPrint Backup Plugin comes bundled with OctoPrint (starting with 1.3.10).
|
||||
|
||||
It allows the creation and restoration of backups of OctoPrint's settings, data and installed plugins [#]_.
|
||||
|
||||
This allows easy migration
|
||||
to newly setup instances as well as making regular backups to prevent data loss.
|
||||
|
||||
.. _fig-bundledplugins-backup-settings:
|
||||
.. figure:: ../images/bundledplugins-backup-settings.png
|
||||
:align: center
|
||||
:alt: OctoPrint Backup Plugin
|
||||
|
||||
The plugin's settings panel with existing backups, the backup creation and restore sections.
|
||||
|
||||
As long as plugins adhere to the standard of storing their data and settings in OctoPrint's plugin data folders, their
|
||||
data will be part of the backup. Note that the backups made by the Backup Plugin will *not* be part of any backups -
|
||||
you'll need to persist the resulting zip files yourself!
|
||||
|
||||
.. _sec-bundledplugins-backup-cli:
|
||||
|
||||
Command line usage
|
||||
------------------
|
||||
|
||||
The Backup Plugin implements a command line interface that allows creation and restoration of backups.
|
||||
It adds two new commands, ``backup:backup`` and ``backup_restore``.
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
$ octoprint plugins backup:backup --help
|
||||
Initializing settings & plugin subsystem...
|
||||
Usage: octoprint plugins backup:backup [OPTIONS]
|
||||
|
||||
Creates a new backup.
|
||||
|
||||
Options:
|
||||
--exclude TEXT Identifiers of data folders to exclude, e.g. 'uploads' to
|
||||
exclude uploads or 'timelapse' to exclude timelapses.
|
||||
--help Show this message and exit.
|
||||
|
||||
$ octoprint plugins backup:restore --help
|
||||
Initializing settings & plugin subsystem...
|
||||
Usage: octoprint plugins backup:restore [OPTIONS] PATH
|
||||
|
||||
Restores an existing backup from the backup zip provided as argument.
|
||||
|
||||
OctoPrint does not need to run for this to proceed.
|
||||
|
||||
Options:
|
||||
--help Show this message and exit.
|
||||
|
||||
.. note::
|
||||
|
||||
The ``backup:backup`` command can be useful in combination with a cronjob to create backups in regular intervals.
|
||||
|
||||
.. _sec-bundledplugins-backup-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Backup plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/backup``.
|
||||
|
||||
.. [#] Note that only those plugins that are available on `OctoPrint's official plugin repository <https://plugins.octoprint.org>`_
|
||||
can be automatically restored. If you have plugins installed that are not available on there you'll get their
|
||||
names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them.
|
||||
@@ -0,0 +1,35 @@
|
||||
.. _sec-bundledplugins-forcelogin:
|
||||
|
||||
ForceLogin Plugin
|
||||
=================
|
||||
|
||||
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
|
||||
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
|
||||
instead forces users to log in if they want to get any kind of information from OctoPrint.
|
||||
|
||||
.. _fig-bundledplugins-forcelogin:
|
||||
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
|
||||
:align: center
|
||||
:alt: Forced login dialog
|
||||
|
||||
OctoPrint's new forced login dialog.
|
||||
|
||||
.. warning::
|
||||
|
||||
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
|
||||
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
|
||||
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
|
||||
is not OctoPrint itself.
|
||||
|
||||
.. note::
|
||||
|
||||
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
|
||||
the ForceLogin Plugin in OctoPrint's plugin manager.
|
||||
|
||||
.. _sec-bundledplugins-forcelogin-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/forcelogin``.
|
||||
@@ -8,8 +8,12 @@ Bundled Plugins
|
||||
:maxdepth: 2
|
||||
|
||||
action_command_prompt.rst
|
||||
announcements.rst
|
||||
appkeys.rst
|
||||
backup.rst
|
||||
cura.rst
|
||||
discovery.rst
|
||||
forcelogin.rst
|
||||
logging.rst
|
||||
pluginmanager.rst
|
||||
printer_safety_check.rst
|
||||
|
||||
@@ -16,17 +16,12 @@ such identification.
|
||||
|
||||
An example of a warning generated by the Printer Safety Check
|
||||
|
||||
Currently the following firmwares produce this warning:
|
||||
|
||||
* Anet A8 stock firmware
|
||||
Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
for a list of currently identified printers.
|
||||
|
||||
If you know of further printers/printer firmwares that need to be added here, please
|
||||
`get in touch on the forum and provide their response to an M115 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
|
||||
.. note::
|
||||
|
||||
Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
|
||||
|
||||
@@ -562,6 +562,9 @@ Use the following settings to enable or disable OctoPrint features:
|
||||
- M117
|
||||
- M118
|
||||
|
||||
# whether G90/G91 also influence absolute/relative mode of extruders
|
||||
g90InfluencesExtruder: false
|
||||
|
||||
.. _sec-configuration-config_yaml-folder:
|
||||
|
||||
Folder
|
||||
@@ -1058,6 +1061,15 @@ Use the following settings to configure the server:
|
||||
# How many days to leave unused entries in the preemptive cache config
|
||||
until: 7
|
||||
|
||||
# Configuration of the client IP check to warn about connections from external networks
|
||||
ipCheck:
|
||||
|
||||
# whether to enable the check, defaults to true
|
||||
enabled: true
|
||||
|
||||
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
|
||||
trustedSubnets: []
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -1165,7 +1177,7 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
|
||||
# A list of filters to display in the terminal tab. Defaults to the filters shown below
|
||||
terminalFilters:
|
||||
- name: Suppress temperature messages
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv: ok T:)'
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)'
|
||||
- name: Suppress SD status messages
|
||||
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
|
||||
- name: Suppress wait responses
|
||||
|
||||
@@ -14,18 +14,28 @@ below.
|
||||
* Prerequisites:
|
||||
|
||||
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Git <https://git-scm.com>`_
|
||||
|
||||
* Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
|
||||
* Checkout the OctoPrint sources from their Git repository:
|
||||
* ``git clone https://github.com/foosel/OctoPrint.git``
|
||||
* ``git clone -b <your dev branch> https://github.com/foosel/OctoPrint.git``
|
||||
* Enter the checked out source folder: ``cd OctoPrint``
|
||||
* Create a virtual environment in the checked out source folder to use for installing and running OctoPrint and its
|
||||
dependencies (this avoids potential versioning issues for the dependencies with system wide installed
|
||||
instances): ``virtualenv venv``
|
||||
* Activate the virtual environment: ``source venv/bin/activate`` (Linux, MacOS) or
|
||||
``source venv/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
* Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
|
||||
instances):
|
||||
* PY2: ``virtualenv --python=python2 venv2``
|
||||
* PY3: ``virtualenv --python=python3 venv3``
|
||||
* Activate the virtual environment:
|
||||
* PY2 : ``source venv2/bin/activate`` (Linux, MacOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
* PY3 : ``source venv3/bin/activate`` (Linux, MacOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
* Update ``pip`` in the virtual environment:
|
||||
* PY2: ``pip2 install --upgrade pip``
|
||||
* PY3: ``pip3 install --upgrade pip``
|
||||
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
|
||||
including its regular *and* development and plugin development dependencies: ``pip install -e .[develop,plugins]``
|
||||
including its regular *and* development and plugin development dependencies:
|
||||
* PY2: ``pip2 install -e .[develop,plugins]``
|
||||
* PY3: ``pip3 install -e .[develop,plugins]``
|
||||
|
||||
When the virtual environment is activated you can then:
|
||||
|
||||
|
||||
@@ -141,7 +141,8 @@ Disconnected
|
||||
The server has disconnected from the printer
|
||||
|
||||
Error
|
||||
An error has occurred in the printer communication.
|
||||
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
|
||||
on the connection.
|
||||
|
||||
Payload:
|
||||
|
||||
@@ -338,6 +339,8 @@ PrintFailed
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``time``: the elapsed time of the print when it failed, in seconds (float)
|
||||
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
|
||||
@@ -31,7 +31,13 @@ Internet!).
|
||||
.. hint::
|
||||
|
||||
If you plan to have your OctoPrint instance accessible over the internet,
|
||||
**always enable Access Control**.
|
||||
**always enable Access Control** and ideally **don't make it accessible to
|
||||
everyone over the internet but instead use a VPN** or at the very least
|
||||
HTTP basic authentication on a layer above OctoPrint.
|
||||
|
||||
A physical device that includes heaters and stepper motors really should not be
|
||||
publicly reachable by everyone with an internet connection, even with access
|
||||
control enabled.
|
||||
|
||||
.. _sec-features-access_control-rerunning_wizard:
|
||||
|
||||
|
||||
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
|
||||
.. code-block:: jinja
|
||||
:caption: Default ``disable_hotends`` snippet
|
||||
|
||||
{% if printer_profile.extruder.sharedNozzle %}
|
||||
M104 T0 S0
|
||||
{% else %}
|
||||
{% for tool in range(printer_profile.extruder.count) %}
|
||||
M104 T{{ tool }} S0
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
The ``disable_bed`` snippet is defined as follows:
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
@@ -80,9 +80,13 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s
|
||||
|
||||
.. seealso::
|
||||
|
||||
`OctoPrint-ForceLogin <https://github.com/OctoPrint/OctoPrint-ForceLogin>`_
|
||||
A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the
|
||||
client library's :ref:`browser component <sec-jsclientlib-browser>` to login the user.
|
||||
:ref:`Application Key Plugin <sec-bundledplugins-appkeys>`
|
||||
A bundled plugin that implements an authorization workflow for third party clients. It adds various additional
|
||||
methods to the JS Client Library.
|
||||
:ref:`ForceLogin Plugin <sec-bundledplugins-forcelogin>`
|
||||
A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and
|
||||
various hooks. Utilizes the client library's :ref:`browser component <sec-jsclientlib-browser>` to login the
|
||||
user.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
|
||||
@@ -6,4 +6,10 @@ octoprint.util
|
||||
.. automodule:: octoprint.util
|
||||
:members:
|
||||
|
||||
.. _sec-modules-util-commandline:
|
||||
|
||||
octoprint.util.commandline
|
||||
--------------------------
|
||||
|
||||
.. automodule:: octoprint.util.commandline
|
||||
:members:
|
||||
@@ -3,7 +3,7 @@
|
||||
Helpers
|
||||
=======
|
||||
|
||||
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
|
||||
Helpers are methods that plugins can expose to other plugins in order to make common functionality available on the
|
||||
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
|
||||
|
||||
An example for providing some helper functions to the system can be found in the
|
||||
|
||||
@@ -1089,6 +1089,54 @@ octoprint.printer.estimation.factory
|
||||
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
|
||||
:rtype: class or function
|
||||
|
||||
.. _sec-plugins-hook-server-http-after_request:
|
||||
|
||||
octoprint.server.api.after_request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: after_request_handlers_hook(*args, **kwargs)
|
||||
|
||||
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
|
||||
|
||||
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-before_request:
|
||||
|
||||
octoprint.server.api.before_request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: after_request_handlers_hook(*args, **kwargs)
|
||||
|
||||
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
|
||||
|
||||
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-access_validator:
|
||||
|
||||
octoprint.server.http.access_validator
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: access_validator_hook(request, *args, **kwargs)
|
||||
|
||||
Allows adding additional access validators to the default tornado routers.
|
||||
|
||||
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled
|
||||
"Force Login" plugin for a usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-bodysize:
|
||||
|
||||
octoprint.server.http.bodysize
|
||||
@@ -1190,6 +1238,59 @@ octoprint.server.http.routes
|
||||
:return: a list of 3-tuples with additional routes as defined above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-authed:
|
||||
|
||||
octoprint.server.sockjs.authed
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
|
||||
|
||||
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-register:
|
||||
|
||||
octoprint.server.sockjs.register
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
|
||||
|
||||
Allows plugins to prevent a new :ref:`push socket client <sec-api-push>` to be registered to the system.
|
||||
|
||||
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
|
||||
signals to not register the client.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:return: whether to proceed with registration (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-emit:
|
||||
|
||||
octoprint.server.sockjs.emit
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
|
||||
|
||||
Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection <sec-api-push>`.
|
||||
|
||||
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object on which a message is about to be emitted
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:param string message: the message type about to be emitted
|
||||
:param dict payload: the payload of the message about to be emitted (may be None)
|
||||
:return: whether to proceed with sending the message (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-timelapse-extensions:
|
||||
|
||||
octoprint.timelapse.extensions
|
||||
|
||||
@@ -12,46 +12,55 @@ import octoprint_setuptools
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Supported python versions
|
||||
PYTHON_REQUIRES = ">=2.7.9" # py 3 marked as supported so that we can migrate... NOT officially supported though!
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
"flask>=0.12,<0.13",
|
||||
"werkzeug>=0.11.1,<0.12",
|
||||
"tornado==4.5.3",
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
#"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a
|
||||
# vendored one
|
||||
"PyYAML>=3.12,<3.13",
|
||||
"Flask-Login>=0.4,<0.5",
|
||||
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
|
||||
# changes that might affect plugins, or due to other observed problems
|
||||
|
||||
"flask>=0.12,<0.13", # newer versions require newer Jinja versions
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
|
||||
"Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
|
||||
# anything below this should be checked on releases for new versions
|
||||
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Babel>=0.11,<0.12",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"markdown>=2.6.4,<2.7",
|
||||
"werkzeug>=0.14.1,<0.15",
|
||||
"PyYAML>=3.13,<4",
|
||||
"markdown>=3.0,<3.1",
|
||||
"pyserial>=3.4,<3.5",
|
||||
"netaddr>=0.7.19,<0.8",
|
||||
"watchdog>=0.8.3,<0.9",
|
||||
"watchdog>=0.9.0,<0.10",
|
||||
"sarge==0.1.5post0",
|
||||
"netifaces>=0.10.6,<0.11",
|
||||
"pylru>=1.0.9,<1.1",
|
||||
"rsa>=3.4,<3.5",
|
||||
"netifaces>=0.10.7,<0.11",
|
||||
"pylru>=1.1,<1.2",
|
||||
"rsa>=4.0,<5",
|
||||
"pkginfo>=1.4.2,<1.5",
|
||||
"requests>=2.18.4,<3",
|
||||
"semantic_version>=2.6.0,<2.7",
|
||||
"psutil>=5.4.6,<5.5",
|
||||
"Click>=6.7,<6.8",
|
||||
"requests>=2.20.0,<3",
|
||||
"semantic_version>=2.6,<2.7",
|
||||
"psutil>=5.4.8,<5.5",
|
||||
"Click>=7,<8",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
"chainmap>=1.0.2,<1.1",
|
||||
"future>=0.15.2,<0.16",
|
||||
"scandir>=1.3,<1.4",
|
||||
"websocket-client>=0.40.0,<0.41",
|
||||
"python-dateutil>=2.6.1,<2.7",
|
||||
"future>=0.17,<0.18",
|
||||
"scandir>=1.9,<1.10",
|
||||
"websocket-client>=0.53,<0.54",
|
||||
"python-dateutil>=2.7.5,<2.8",
|
||||
"wrapt>=1.10.11,<1.11",
|
||||
"futures>=3.1.1,<3.2",
|
||||
"emoji>=0.4.5,<0.5",
|
||||
"monotonic>=1.3,<1.4",
|
||||
"frozendict>=1.2,<1.3"
|
||||
"frozendict>=1.2,<1.3",
|
||||
"six>=1.11.0"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
@@ -63,7 +72,7 @@ EXTRA_REQUIRES = dict(
|
||||
develop=[
|
||||
# Testing dependencies
|
||||
"mock>=2.0.0,<3",
|
||||
"nose>=1.3.0,<1.4",
|
||||
"nose>=1.3.7,<1.4",
|
||||
"ddt",
|
||||
|
||||
# Documentation dependencies
|
||||
@@ -75,13 +84,10 @@ EXTRA_REQUIRES = dict(
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
plugins=[
|
||||
"cookiecutter>=1.5,<1.7"
|
||||
"cookiecutter>=1.6,<1.7"
|
||||
]
|
||||
)
|
||||
|
||||
# Additional requirements for setup
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
@@ -154,10 +160,10 @@ def params():
|
||||
long_description = read_file_contents(os.path.join(here, "README.md"))
|
||||
long_description_content_type = "text/markdown"
|
||||
|
||||
python_requires = PYTHON_REQUIRES
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
setup_requires = SETUP_REQUIRES
|
||||
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
import io
|
||||
import sys
|
||||
import logging as log
|
||||
|
||||
@@ -103,8 +104,9 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
if callable(after_logging):
|
||||
after_logging(**kwargs)
|
||||
|
||||
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
|
||||
safe_mode = safe_mode or settings_safe_mode
|
||||
settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None
|
||||
settings_incomplete_startup_safemode = "incomplete_startup" if settings.getBoolean(["server", "incompleteStartup"]) else None
|
||||
safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode
|
||||
kwargs["safe_mode"] = safe_mode
|
||||
if callable(after_safe_mode):
|
||||
after_safe_mode(**kwargs)
|
||||
@@ -293,7 +295,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
with open(logging_file, "r") as f:
|
||||
with io.open(logging_file, 'rt', encoding='utf-8') as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
|
||||
# we merge that with the default config
|
||||
@@ -595,6 +597,9 @@ def main():
|
||||
# cut off stuff from the beginning
|
||||
args = args[-1 * sys_args_length:] if sys_args_length else []
|
||||
|
||||
from octoprint.util.fixes import patch_sarge_async_on_py2
|
||||
patch_sarge_async_on_py2()
|
||||
|
||||
from octoprint.cli import octo
|
||||
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
#import sys
|
||||
#if sys.version_info[0] >= 3:
|
||||
# raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import octoprint
|
||||
octoprint.main()
|
||||
@@ -12,6 +12,7 @@
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
import errno
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
@@ -130,7 +131,7 @@ def git_get_keywords(versionfile_abs):
|
||||
# _version.py.
|
||||
keywords = {}
|
||||
try:
|
||||
f = open(versionfile_abs, "r")
|
||||
f = io.open(versionfile_abs, 'rt', encoding='utf-8')
|
||||
for line in f.readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
@@ -306,7 +307,7 @@ def git_parse_lookup_file(path):
|
||||
return []
|
||||
|
||||
lookup = []
|
||||
with open(path, "r") as f:
|
||||
with io.open(path, 'rt', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
if '#' in line:
|
||||
line = line[:line.rindex("#")]
|
||||
|
||||
@@ -5,6 +5,7 @@ __author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from functools import partial
|
||||
@@ -183,7 +184,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
def _load(self):
|
||||
if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
|
||||
try:
|
||||
with open(self._groupfile, "r") as f:
|
||||
with io.open(self._groupfile, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
if not "groups" in data:
|
||||
|
||||
@@ -5,6 +5,7 @@ __author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import six
|
||||
|
||||
from flask import g, abort
|
||||
from flask_babel import gettext
|
||||
@@ -249,8 +250,8 @@ class PermissionsMetaClass(type):
|
||||
return None
|
||||
|
||||
|
||||
@six.add_metaclass(PermissionsMetaClass)
|
||||
class Permissions(object):
|
||||
__metaclass__ = PermissionsMetaClass
|
||||
|
||||
# Special permission
|
||||
ADMIN = OctoPrintPermission("Admin",
|
||||
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from flask_login import UserMixin, AnonymousUserMixin
|
||||
from werkzeug.local import LocalProxy
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import yaml
|
||||
import uuid
|
||||
@@ -432,7 +433,7 @@ class FilebasedUserManager(UserManager):
|
||||
def _load(self):
|
||||
if os.path.exists(self._userfile) and os.path.isfile(self._userfile):
|
||||
self._customized = True
|
||||
with open(self._userfile, "r") as f:
|
||||
with io.open(self._userfile, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
for name in data.keys():
|
||||
attributes = data[name]
|
||||
|
||||
@@ -5,6 +5,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import click
|
||||
import io
|
||||
import json
|
||||
|
||||
import octoprint_client
|
||||
@@ -12,6 +13,10 @@ import octoprint_client
|
||||
from octoprint.cli import get_ctx_obj_option, bulk_options
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
|
||||
try:
|
||||
unicode
|
||||
except:
|
||||
unicode =str
|
||||
|
||||
class JsonStringParamType(click.ParamType):
|
||||
name = "json"
|
||||
@@ -143,16 +148,16 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
||||
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
|
||||
if json_flag or yaml_flag:
|
||||
if json_flag:
|
||||
with open(file_path, "rb") as fp:
|
||||
with io.open(file_path, 'rb') as fp:
|
||||
data = json.load(fp)
|
||||
else:
|
||||
import yaml
|
||||
with open(file_path, "rb") as fp:
|
||||
with io.open(file_path, 'rb') as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
else:
|
||||
with open(file_path, "rb") as fp:
|
||||
with io.open(file_path, 'rb') as fp:
|
||||
data = fp.read()
|
||||
|
||||
r = ctx.obj.client.post(path, data, timeout=timeout)
|
||||
|
||||
@@ -88,7 +88,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
commands = hook(self, pass_octoprint_ctx)
|
||||
for command in commands:
|
||||
if not isinstance(command, click.Command):
|
||||
self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
|
||||
self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
|
||||
continue
|
||||
result[name + self.sep + command.name] = command
|
||||
except:
|
||||
|
||||
@@ -26,6 +26,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
logger.info("Starting OctoPrint {}".format(__display_version__))
|
||||
if safe_mode:
|
||||
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
|
||||
if safe_mode == "flag":
|
||||
reason = "command line flag"
|
||||
elif safe_mode == "settings":
|
||||
reason = "setting in config.yaml"
|
||||
elif safe_mode == "incomplete_startup":
|
||||
reason = "problem during last startup"
|
||||
else:
|
||||
reason = "unknown"
|
||||
logger.info("Reason for safe mode: {}".format(reason))
|
||||
|
||||
if recorder and len(recorder):
|
||||
logger.info(get_divider_line("-", "Logged during platform initialization:"))
|
||||
@@ -179,7 +188,7 @@ def serve_command(ctx, **kwargs):
|
||||
basedir = get_value("basedir")
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = get_value("safe_mode")
|
||||
safe_mode = "flag" if get_value("safe_mode") else None
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
run_server(basedir, configfile, host, port, debug,
|
||||
@@ -217,7 +226,7 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
basedir = get_value("basedir")
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = get_value("safe_mode")
|
||||
safe_mode = "flag" if get_value("safe_mode") else None
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
if pid is None:
|
||||
|
||||
@@ -6,6 +6,7 @@ Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
import io
|
||||
import sys, os, time, signal
|
||||
|
||||
class Daemon:
|
||||
@@ -60,9 +61,9 @@ class Daemon:
|
||||
# redirect standard file descriptors
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
si = open(os.devnull, 'r')
|
||||
so = open(os.devnull, 'a+')
|
||||
se = open(os.devnull, 'a+')
|
||||
si = io.open(os.devnull, 'rt', encoding='utf-8')
|
||||
so = io.open(os.devnull, 'at+', encoding='utf-8')
|
||||
se = io.open(os.devnull, 'at+', encoding='utf-8')
|
||||
|
||||
os.dup2(si.fileno(), sys.stdin.fileno())
|
||||
os.dup2(so.fileno(), sys.stdout.fileno())
|
||||
@@ -142,7 +143,7 @@ class Daemon:
|
||||
def get_pid(self):
|
||||
"""Get the pid from the pidfile."""
|
||||
try:
|
||||
with open(self.pidfile,'r') as pf:
|
||||
with io.open(self.pidfile,'rt', encoding='utf-8') as pf:
|
||||
pid = int(pf.read().strip())
|
||||
except (IOError, ValueError):
|
||||
pid = None
|
||||
@@ -150,7 +151,7 @@ class Daemon:
|
||||
|
||||
def set_pid(self, pid):
|
||||
"""Write the pid to the pidfile."""
|
||||
with open(self.pidfile,'w+') as f:
|
||||
with io.open(self.pidfile,'wt+', encoding='utf-8') as f:
|
||||
f.write(str(pid) + '\n')
|
||||
|
||||
def remove_pidfile(self):
|
||||
|
||||
@@ -360,7 +360,7 @@ class CommandTrigger(GenericEventListener):
|
||||
processedCommand = self._processCommand(command, payload)
|
||||
self.executeCommand(processedCommand, commandType, debug=debug)
|
||||
except KeyError as e:
|
||||
self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command)
|
||||
self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command)
|
||||
|
||||
def executeCommand(self, command, commandType, debug=False):
|
||||
if commandType == "system":
|
||||
@@ -388,9 +388,9 @@ class CommandTrigger(GenericEventListener):
|
||||
commandExecutioner(command)
|
||||
except subprocess.CalledProcessError as e:
|
||||
if debug:
|
||||
self._logger.warn("Command failed with return code {}: {}".format(e.returncode, str(e)))
|
||||
self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e)))
|
||||
else:
|
||||
self._logger.warn("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
|
||||
self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
|
||||
except:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import io
|
||||
import os
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -338,7 +339,7 @@ class FileManager(object):
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = StreamWrapper(os.path.basename(dest_path),
|
||||
io.BytesIO(u";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")),
|
||||
io.FileIO(tmp_path, "rb"))
|
||||
io.FileIO(tmp_path, 'rb'))
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
self.add_file(dest_location, dest_path, file_obj,
|
||||
@@ -447,7 +448,7 @@ class FileManager(object):
|
||||
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
|
||||
if not destinations:
|
||||
destinations = self._storage_managers.keys()
|
||||
if isinstance(destinations, (str, unicode, basestring)):
|
||||
if isinstance(destinations, basestring):
|
||||
destinations = [destinations]
|
||||
|
||||
result = dict()
|
||||
@@ -642,7 +643,7 @@ class FileManager(object):
|
||||
|
||||
import yaml
|
||||
try:
|
||||
with open(self._recovery_file) as f:
|
||||
with io.open(self._recovery_file, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
return data
|
||||
except:
|
||||
|
||||
@@ -5,7 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import pylru
|
||||
@@ -500,7 +500,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if os.path.exists(old_metadata_path):
|
||||
# load the old metadata file
|
||||
try:
|
||||
with open(old_metadata_path) as f:
|
||||
with io.open(old_metadata_path, 'rt', encoding='utf-8') as f:
|
||||
import yaml
|
||||
self._old_metadata = yaml.safe_load(f)
|
||||
except:
|
||||
@@ -1033,7 +1033,7 @@ class LocalFileStorage(StorageInterface):
|
||||
def path_in_storage(self, path):
|
||||
if isinstance(path, (tuple, list)):
|
||||
path = self.join_path(*path)
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
if isinstance(path, basestring):
|
||||
path = to_unicode(path)
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
@@ -1115,7 +1115,7 @@ class LocalFileStorage(StorageInterface):
|
||||
try:
|
||||
print_time = float(print_time)
|
||||
except:
|
||||
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
|
||||
self._logger.warning("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
|
||||
continue
|
||||
|
||||
if not printer_profile in former_print_times:
|
||||
@@ -1462,7 +1462,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
blocksize = 65536
|
||||
hash = hashlib.sha1()
|
||||
with open(path, "rb") as f:
|
||||
with io.open(path, 'rb') as f:
|
||||
buffer = f.read(blocksize)
|
||||
while len(buffer) > 0:
|
||||
hash.update(buffer)
|
||||
@@ -1522,7 +1522,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
metadata_path = os.path.join(path, ".metadata.json")
|
||||
if os.path.exists(metadata_path):
|
||||
with open(metadata_path) as f:
|
||||
with io.open(metadata_path, 'rt', encoding='utf-8') as f:
|
||||
try:
|
||||
import json
|
||||
metadata = json.load(f)
|
||||
@@ -1577,7 +1577,7 @@ class LocalFileStorage(StorageInterface):
|
||||
# TODO 1.3.10 Remove ".metadata.yaml" files
|
||||
return
|
||||
|
||||
with open(metadata_path_yaml) as f:
|
||||
with io.open(metadata_path_yaml, 'rt', encoding='utf-8') as f:
|
||||
try:
|
||||
metadata = yaml.safe_load(f)
|
||||
except:
|
||||
|
||||
@@ -64,7 +64,7 @@ class DiskFileWrapper(AbstractFileWrapper):
|
||||
shutil.copy2(self.path, path)
|
||||
|
||||
def stream(self):
|
||||
return io.open(self.path, "rb")
|
||||
return io.open(self.path, 'rb')
|
||||
|
||||
class StreamWrapper(AbstractFileWrapper):
|
||||
"""
|
||||
@@ -87,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper):
|
||||
"""
|
||||
import shutil
|
||||
|
||||
with atomic_write(path, "wb") as dest:
|
||||
with atomic_write(path, 'wb') as dest:
|
||||
with self.stream() as source:
|
||||
shutil.copyfileobj(source, dest)
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.logging import handlers
|
||||
|
||||
def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args):
|
||||
@@ -120,7 +122,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
formatted divider line
|
||||
"""
|
||||
|
||||
assert isinstance(c, (str, unicode, bytes)), "c is not text"
|
||||
assert isinstance(c, basestring), "c is not text"
|
||||
assert len(c) == 1, "c is not a single character"
|
||||
assert isinstance(length, int), "length is not an int"
|
||||
assert isinstance(indent, int), "indent is not an int"
|
||||
@@ -128,7 +130,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
if message is None:
|
||||
return c * length
|
||||
|
||||
assert isinstance(message, (str, unicode, bytes)), "message is not text"
|
||||
assert isinstance(message, basestring), "message is not text"
|
||||
|
||||
space = length - 2 * (indent + 1)
|
||||
if space >= len(message):
|
||||
|
||||
@@ -21,6 +21,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import os
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
@@ -169,7 +170,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
||||
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None,
|
||||
initialized=True):
|
||||
"""
|
||||
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
|
||||
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||
@@ -207,7 +209,6 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
|
||||
is determined be presence of injected ``_identifier`` property.
|
||||
|
||||
"""
|
||||
|
||||
if not isinstance(types, (list, tuple)):
|
||||
@@ -217,18 +218,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||
for plugin in plugins:
|
||||
if initialized and not hasattr(plugin, "_identifier"):
|
||||
continue
|
||||
|
||||
if hasattr(plugin, method):
|
||||
logger.debug("Calling {} on {}".format(method, plugin._identifier))
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(plugin._identifier, plugin, result)
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
|
||||
logger.exception("Error while calling plugin %s" % plugin._identifier)
|
||||
if error_callback:
|
||||
error_callback(plugin._identifier, plugin, exc)
|
||||
|
||||
@@ -498,7 +502,7 @@ class PluginSettings(object):
|
||||
self.settings.remove(self._prefix_path())
|
||||
|
||||
def __getattr__(self, item):
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
all_access_methods = list(self.access_methods.keys()) + list(self.deprecated_access_methods.keys())
|
||||
if item in all_access_methods:
|
||||
decorator = None
|
||||
if item in self.deprecated_access_methods:
|
||||
|
||||
@@ -28,6 +28,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import os
|
||||
import io
|
||||
import imp
|
||||
from collections import defaultdict, namedtuple, OrderedDict
|
||||
import logging
|
||||
@@ -512,7 +513,7 @@ class PluginInfo(object):
|
||||
try:
|
||||
import ast
|
||||
|
||||
with open(path, "rb") as f:
|
||||
with io.open(path, 'rb') as f:
|
||||
root = ast.parse(f.read())
|
||||
|
||||
assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets,
|
||||
@@ -682,7 +683,7 @@ class PluginManager(object):
|
||||
actual_readonly = not os.access(folder, os.W_OK)
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
self.logger.warning("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
for entry in scandir(folder):
|
||||
@@ -818,7 +819,7 @@ class PluginManager(object):
|
||||
else:
|
||||
return None
|
||||
except:
|
||||
self.logger.warn("Could not locate plugin {key}".format(key=key))
|
||||
self.logger.warning("Could not locate plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
# Create a simple dummy entry first ...
|
||||
@@ -831,7 +832,7 @@ class PluginManager(object):
|
||||
plugin.forced_disabled = True
|
||||
|
||||
if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)):
|
||||
self.logger.warn("Plugin {} is blacklisted.".format(plugin))
|
||||
self.logger.warning("Plugin {} is blacklisted.".format(plugin))
|
||||
plugin.blacklisted = True
|
||||
|
||||
if not plugin.validate("before_import", additional_validators=self.plugin_validators):
|
||||
@@ -892,7 +893,7 @@ class PluginManager(object):
|
||||
incl_all_found=True)
|
||||
|
||||
# let's clean everything we DIDN'T find first
|
||||
removed = [key for key in self.enabled_plugins.keys() + self.disabled_plugins.keys() if key not in found]
|
||||
removed = [key for key in list(self.enabled_plugins.keys()) + list(self.disabled_plugins.keys()) if key not in found]
|
||||
for key in removed:
|
||||
try:
|
||||
del self.enabled_plugins[key]
|
||||
@@ -925,7 +926,7 @@ class PluginManager(object):
|
||||
try:
|
||||
if plugin.loaded and not plugin.forced_disabled:
|
||||
if plugin.blacklisted:
|
||||
self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
continue
|
||||
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
|
||||
except PluginNeedsRestart:
|
||||
@@ -967,7 +968,7 @@ class PluginManager(object):
|
||||
|
||||
def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True):
|
||||
if not name in self.plugins:
|
||||
self.logger.warn("Trying to load an unknown plugin {name}".format(**locals()))
|
||||
self.logger.warning("Trying to load an unknown plugin {name}".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -990,7 +991,7 @@ class PluginManager(object):
|
||||
|
||||
def unload_plugin(self, name):
|
||||
if not name in self.plugins:
|
||||
self.logger.warn("Trying to unload unknown plugin {name}".format(**locals()))
|
||||
self.logger.warning("Trying to unload unknown plugin {name}".format(**locals()))
|
||||
return
|
||||
|
||||
plugin = self.plugins[name]
|
||||
@@ -1024,7 +1025,7 @@ class PluginManager(object):
|
||||
|
||||
def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False):
|
||||
if not name in self.disabled_plugins:
|
||||
self.logger.warn("Tried to enable plugin {name}, however it is not disabled".format(**locals()))
|
||||
self.logger.warning("Tried to enable plugin {name}, however it is not disabled".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -1066,7 +1067,7 @@ class PluginManager(object):
|
||||
|
||||
def disable_plugin(self, name, plugin=None):
|
||||
if not name in self.enabled_plugins:
|
||||
self.logger.warn("Tried to disable plugin {name}, however it is not enabled".format(**locals()))
|
||||
self.logger.warning("Tried to disable plugin {name}, however it is not enabled".format(**locals()))
|
||||
return
|
||||
|
||||
if plugin is None:
|
||||
@@ -1105,7 +1106,7 @@ class PluginManager(object):
|
||||
try:
|
||||
callback, order = self._get_callback_and_order(definition)
|
||||
except ValueError as e:
|
||||
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
continue
|
||||
|
||||
self._plugin_hooks[hook].append((order, name, callback))
|
||||
@@ -1124,7 +1125,7 @@ class PluginManager(object):
|
||||
try:
|
||||
callback, order = self._get_callback_and_order(definition)
|
||||
except ValueError as e:
|
||||
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
continue
|
||||
|
||||
try:
|
||||
@@ -1480,7 +1481,7 @@ class PluginManager(object):
|
||||
try:
|
||||
int(sorting_value)
|
||||
except ValueError:
|
||||
self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
|
||||
self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
|
||||
sorting_value = None
|
||||
|
||||
return sorting_value is None, sorting_value, impl[0]
|
||||
@@ -1619,7 +1620,7 @@ def is_editable_install(install_dir, package, module, location):
|
||||
if os.path.isfile(package_link):
|
||||
expected_target = os.path.normcase(os.path.realpath(location))
|
||||
try:
|
||||
with open(package_link) as f:
|
||||
with io.open(package_link, 'rt', encoding='utf-8') as f:
|
||||
contents = f.readlines()
|
||||
for line in contents:
|
||||
target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module)))
|
||||
|
||||
@@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
class OctoPrintPlugin(Plugin):
|
||||
"""
|
||||
The parent class of all OctoPrint plugin mixins.
|
||||
@@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
|
||||
externally reachable, use :func:`on_after_startup` instead or additionally.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``StartupPlugin.on_startup``.
|
||||
|
||||
:param string host: the host the server will listen on, may be ``0.0.0.0``
|
||||
@@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
Called just after launch of the server, so when the listen loop is actually running already.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``StartupPlugin.on_after_startup``.
|
||||
"""
|
||||
|
||||
@@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
Called upon the imminent shutdown of OctoPrint.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
The relevant sorting context is ``ShutdownPlugin.on_shutdown``.
|
||||
"""
|
||||
pass
|
||||
@@ -225,6 +234,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
js
|
||||
JavaScript files, such as additional view models
|
||||
jsclient
|
||||
JavaScript files containing additional parts for the JS Client Library (since 1.3.10)
|
||||
css
|
||||
CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode.
|
||||
less
|
||||
@@ -239,6 +250,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=['js/my_file.js', 'js/my_other_file.js'],
|
||||
clientjs=['clientjs/my_file.js'],
|
||||
css=['css/my_styles.css'],
|
||||
less=['less/my_styles.less']
|
||||
)
|
||||
@@ -1801,6 +1813,10 @@ class EventHandlerPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
Called by OctoPrint upon processing of a fired event on the platform.
|
||||
|
||||
.. warning::
|
||||
|
||||
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
|
||||
|
||||
Arguments:
|
||||
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
|
||||
for possible values
|
||||
|
||||
@@ -62,7 +62,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/action_command_prompt.js"])
|
||||
return dict(js=["js/action_command_prompt.js"],
|
||||
clientjs=["clientjs/action_command_prompt.js"])
|
||||
|
||||
#~ SettingsPlugin
|
||||
|
||||
@@ -124,7 +125,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
if action == b"prompt_begin":
|
||||
if self._prompt is not None and self._prompt.active:
|
||||
self._logger.warn("Prompt is already defined")
|
||||
self._logger.warning("Prompt is already defined")
|
||||
return
|
||||
self._prompt = Prompt(parameter.strip())
|
||||
|
||||
@@ -132,7 +133,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
if self._prompt is None:
|
||||
return
|
||||
if self._prompt.active:
|
||||
self._logger.warn("Prompt is already active")
|
||||
self._logger.warning("Prompt is already active")
|
||||
return
|
||||
self._prompt.add_choice(parameter.strip())
|
||||
|
||||
@@ -140,7 +141,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
if self._prompt is None:
|
||||
return
|
||||
if self._prompt.active:
|
||||
self._logger.warn("Prompt is already active")
|
||||
self._logger.warning("Prompt is already active")
|
||||
return
|
||||
self._show_prompt()
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
|
||||
var data = {
|
||||
choice: choice
|
||||
};
|
||||
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
|
||||
return OctoPrintActionCommandPromptClient;
|
||||
});
|
||||
@@ -1,29 +1,3 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
|
||||
var data = {
|
||||
choice: choice
|
||||
};
|
||||
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
|
||||
return OctoPrintActionCommandPromptClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function ActionCommandPromptViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -21,7 +21,7 @@ import flask
|
||||
from collections import OrderedDict
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify
|
||||
from flask_babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
@@ -150,7 +150,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
# Blueprint Plugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
|
||||
def get_channel_data(self):
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
@@ -211,7 +211,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
unless=lambda: force)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
|
||||
def channel_command(self, channel):
|
||||
from octoprint.server.util.flask import get_json_command_from_request
|
||||
@@ -391,15 +391,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
result = []
|
||||
if "entries" in feed:
|
||||
for entry in feed["entries"]:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
try:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
except:
|
||||
self._logger.exception("Error while converting entry from feed, skipping it")
|
||||
return result
|
||||
|
||||
def _to_internal_entry(self, entry, read_until=None):
|
||||
"""Convert feed entries to internal data structure."""
|
||||
|
||||
published = calendar.timegm(entry["published_parsed"])
|
||||
timestamp = entry.get("published_parsed",
|
||||
entry.get("updated_parsed",
|
||||
None))
|
||||
if timestamp is None:
|
||||
return None
|
||||
|
||||
published = calendar.timegm(timestamp)
|
||||
|
||||
read = True
|
||||
if read_until is not None:
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import flask
|
||||
import threading
|
||||
import os
|
||||
import yaml
|
||||
import codecs
|
||||
import time
|
||||
from binascii import hexlify
|
||||
from collections import defaultdict
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
||||
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
|
||||
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
|
||||
class AppAlreadyExists(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PendingDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
self.user_token = user_token
|
||||
self.created = monotonic_time()
|
||||
|
||||
if callable(timeout_callback):
|
||||
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
|
||||
self.poll_timeout.start()
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
user_id=self.user_id,
|
||||
user_token=self.user_token)
|
||||
|
||||
|
||||
class ReadyDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
|
||||
@classmethod
|
||||
def for_pending(cls, pending, user_id):
|
||||
return cls(pending.app_id, pending.app_token, user_id)
|
||||
|
||||
|
||||
class ActiveKey(object):
|
||||
def __init__(self, app_id, api_key, user_id):
|
||||
self.app_id = app_id
|
||||
self.api_key = api_key
|
||||
self.user_id = user_id
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key,
|
||||
user_id=self.user_id)
|
||||
|
||||
def internal(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key)
|
||||
|
||||
@classmethod
|
||||
def for_internal(cls, internal, user_id):
|
||||
return cls(internal["app_id"], internal["api_key"], user_id)
|
||||
|
||||
|
||||
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._pending_decisions = []
|
||||
self._pending_lock = threading.RLock()
|
||||
|
||||
self._ready_decisions = []
|
||||
self._ready_lock = threading.RLock()
|
||||
|
||||
self._keys = defaultdict(list)
|
||||
self._keys_lock = threading.RLock()
|
||||
|
||||
self._key_path = None
|
||||
|
||||
def initialize(self):
|
||||
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
|
||||
self._load_keys()
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="usersettings", name=gettext("Application Keys")),
|
||||
dict(type="settings", name=gettext("Application Keys"))]
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/appkeys.js"],
|
||||
clientjs=["clientjs/appkeys.js"],
|
||||
less=["less/appkeys.less"],
|
||||
css=["css/appkeys.css"])
|
||||
|
||||
##~~ BlueprintPlugin mixin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def handle_probe(self):
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
def handle_request(self):
|
||||
data = flask.request.json
|
||||
if not "app" in data:
|
||||
return flask.make_response("No app name provided", 400)
|
||||
|
||||
app_name = data["app"]
|
||||
user_id = None
|
||||
if "user" in data:
|
||||
user_id = data["user"]
|
||||
|
||||
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
|
||||
app_name=app_name,
|
||||
user_token=user_token,
|
||||
user_id=user_id))
|
||||
response = flask.jsonify(app_token=app_token)
|
||||
response.status_code = 201
|
||||
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
||||
@no_firstrun_access
|
||||
def handle_decision_poll(self, app_token):
|
||||
result = self._get_pending_by_app_token(app_token)
|
||||
if result:
|
||||
for pending_decision in result:
|
||||
pending_decision.poll_timeout.reset()
|
||||
|
||||
response = flask.jsonify(message="Awaiting decision")
|
||||
response.status_code = 202
|
||||
return response
|
||||
|
||||
result = self._get_decision(app_token)
|
||||
if result:
|
||||
return flask.jsonify(api_key=result)
|
||||
|
||||
return flask.abort(404)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
|
||||
@restricted_access
|
||||
def handle_decision(self, user_token):
|
||||
data = flask.request.json
|
||||
if not "decision" in data:
|
||||
return flask.make_response("No decision provided", 400)
|
||||
decision = data["decision"] in valid_boolean_trues
|
||||
user_id = current_user.get_name()
|
||||
|
||||
result = self._set_decision(user_token, decision, user_id)
|
||||
if not result:
|
||||
return flask.abort(404)
|
||||
|
||||
# Close access_request dialog for this request on all open OctoPrint connections
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
return False # No API key required to request API access
|
||||
|
||||
##~~ SimpleApiPlugin mixin
|
||||
|
||||
def get_api_commands(self):
|
||||
return dict(generate=["app"],
|
||||
revoke=["key"])
|
||||
|
||||
def on_api_get(self, request):
|
||||
user_id = current_user.get_name()
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
|
||||
keys = self._all_api_keys()
|
||||
else:
|
||||
keys = self._api_keys_for_user(user_id)
|
||||
|
||||
return flask.jsonify(keys=map(lambda x: x.external(), keys),
|
||||
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
user_id = current_user.get_name()
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if command == "revoke":
|
||||
api_key = data.get("key")
|
||||
if not api_key:
|
||||
return flask.abort(400)
|
||||
|
||||
if not admin_permission.can():
|
||||
user_for_key = self._user_for_api_key(api_key)
|
||||
if user_for_key is None or user_for_key.user_id != user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
self._delete_api_key(api_key)
|
||||
|
||||
elif command == "generate":
|
||||
# manual generateKey
|
||||
app_name = data.get("app")
|
||||
if not app_name:
|
||||
return flask.abort(400)
|
||||
|
||||
self._add_api_key(user_id, app_name.strip())
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
##~~ key validator hook
|
||||
|
||||
def validate_api_key(self, api_key, *args, **kwargs):
|
||||
return self._user_for_api_key(api_key)
|
||||
|
||||
##~~ Helpers
|
||||
|
||||
def _add_pending_decision(self, app_name, user_id=None):
|
||||
app_token = self._generate_key()
|
||||
user_token = self._generate_key()
|
||||
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
|
||||
timeout_callback=self._expire_pending))
|
||||
|
||||
return app_token, user_token
|
||||
|
||||
def _get_pending_by_app_token(self, app_token):
|
||||
result = []
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.app_token == app_token:
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _get_pending_by_user_id(self, user_id):
|
||||
result = []
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.user_id == user_id or data.user_id is None:
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _expire_pending(self, user_token):
|
||||
with self._pending_lock:
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
len_after = len(self._pending_decisions)
|
||||
|
||||
if len_after < len_before:
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
|
||||
def _remove_stale_pending(self):
|
||||
with self._pending_lock:
|
||||
cutoff = monotonic_time() - CUTOFF_TIME
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.created >= cutoff,
|
||||
self._pending_decisions)
|
||||
len_after = len(self._pending_decisions)
|
||||
if len_after < len_before:
|
||||
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
|
||||
|
||||
def _set_decision(self, user_token, decision, user_id):
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
|
||||
pending = data
|
||||
break
|
||||
else:
|
||||
return False # not found
|
||||
|
||||
if decision:
|
||||
with self._ready_lock:
|
||||
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
|
||||
|
||||
with self._pending_lock:
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
|
||||
return True
|
||||
|
||||
def _get_decision(self, app_token):
|
||||
self._remove_stale_pending()
|
||||
|
||||
with self._ready_lock:
|
||||
for data in self._ready_decisions:
|
||||
if data.app_token == app_token:
|
||||
decision = data
|
||||
break
|
||||
else:
|
||||
return False # not found
|
||||
|
||||
api_key = self._add_api_key(decision.user_id, decision.app_id)
|
||||
|
||||
with self._ready_lock:
|
||||
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
|
||||
|
||||
return api_key
|
||||
|
||||
def _add_api_key(self, user_id, app_name):
|
||||
with self._keys_lock:
|
||||
for key in self._keys[user_id]:
|
||||
if key.app_id.lower() == app_name.lower():
|
||||
return key.api_key
|
||||
|
||||
key = ActiveKey(app_name, self._generate_key(), user_id)
|
||||
self._keys[user_id].append(key)
|
||||
self._save_keys()
|
||||
return key.api_key
|
||||
|
||||
def _delete_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
self._keys[user_id] = filter(lambda x: x.api_key != api_key, data)
|
||||
self._save_keys()
|
||||
|
||||
def _user_for_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
if filter(lambda x: x.api_key == api_key, data):
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
return None
|
||||
|
||||
def _api_keys_for_user(self, user_id):
|
||||
with self._keys_lock:
|
||||
return self._keys[user_id]
|
||||
|
||||
def _all_api_keys(self):
|
||||
with self._keys_lock:
|
||||
result = []
|
||||
for user_id, keys in self._keys.items():
|
||||
result += keys
|
||||
return result
|
||||
|
||||
def _generate_key(self):
|
||||
return hexlify(os.urandom(16))
|
||||
|
||||
def _load_keys(self):
|
||||
with self._keys_lock:
|
||||
if not os.path.exists(self._key_path):
|
||||
return
|
||||
|
||||
try:
|
||||
with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
|
||||
persisted = yaml.safe_load(f)
|
||||
except:
|
||||
self._logger.exception("Could not load application keys from {}".format(self._key_path))
|
||||
return
|
||||
|
||||
if not isinstance(persisted, dict):
|
||||
return
|
||||
|
||||
keys = defaultdict(list)
|
||||
for user_id, persisted_keys in persisted.items():
|
||||
keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
|
||||
self._keys = keys
|
||||
|
||||
def _save_keys(self):
|
||||
with self._keys_lock:
|
||||
to_persist = dict()
|
||||
for user_id, keys in self._keys.items():
|
||||
to_persist[user_id] = [x.internal() for x in keys]
|
||||
|
||||
try:
|
||||
with atomic_write(self._key_path) as f:
|
||||
yaml.safe_dump(to_persist, f)
|
||||
except:
|
||||
self._logger.exception("Could not write application keys to {}".format(self._key_path))
|
||||
|
||||
__plugin_name__ = u"Application Keys Plugin"
|
||||
__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys"
|
||||
__plugin_author__ = u"Gina Häußge, Aldo Hoeben"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to "
|
||||
u"obtain an API key without you manually copy-pasting it.")
|
||||
__plugin_implementation__ = AppKeysPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintAppKeysClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
|
||||
return this.base.simpleApiGet("appkeys", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
|
||||
return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.probe = function(opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
|
||||
return this.requestForUser(app, undefined, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
|
||||
var deferred = $.Deferred();
|
||||
var client = this;
|
||||
|
||||
client.probe()
|
||||
.done(function() {
|
||||
client.requestForUser(app, user)
|
||||
.done(function(response) {
|
||||
var token = response.app_token;
|
||||
if (!token) {
|
||||
// no token received, something went wrong
|
||||
deferred.reject();
|
||||
return;
|
||||
}
|
||||
|
||||
var interval = 1000;
|
||||
var poll = function() {
|
||||
client.checkDecision(token)
|
||||
.done(function(response) {
|
||||
if (response.api_key) {
|
||||
// got a decision, resolve the promise
|
||||
deferred.resolve(response.api_key);
|
||||
} else {
|
||||
// no decision yet, poll a bit more
|
||||
deferred.notify();
|
||||
window.setTimeout(poll, interval);
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
};
|
||||
window.setTimeout(poll, interval);
|
||||
})
|
||||
.fail(function() {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
})
|
||||
.fail(function() {
|
||||
// workflow unsupported
|
||||
deferred.reject();
|
||||
});
|
||||
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient);
|
||||
return OctoPrintAppKeysClient;
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}
|
||||
@@ -0,0 +1,308 @@
|
||||
$(function() {
|
||||
function UserAppKeysViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.userkeys",
|
||||
{
|
||||
"app": function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
|
||||
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"app",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
);
|
||||
self.pending = {};
|
||||
self.openRequests = {};
|
||||
|
||||
self.editorApp = ko.observable();
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getKeys()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
self.pending = response.pending;
|
||||
_.each(self.pending, function(data, token) {
|
||||
self.openRequests[token] = self.promptForAccess(data.app_id, token);
|
||||
})
|
||||
};
|
||||
|
||||
self.generateKey = function() {
|
||||
return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
|
||||
.done(self.requestData)
|
||||
.done(function() {
|
||||
self.editorApp("");
|
||||
});
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.allowApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, true)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.denyApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, false)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.promptForAccess = function(app, token) {
|
||||
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
|
||||
message = _.sprintf(message, {app: app});
|
||||
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
|
||||
return new PNotify({
|
||||
title: gettext("Access Request"),
|
||||
text: message,
|
||||
hide: false,
|
||||
icon: "fa fa-key",
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Allow"),
|
||||
click: function(notice) {
|
||||
self.allowApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}, {
|
||||
text: gettext("Deny"),
|
||||
click: function(notice) {
|
||||
self.denyApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
},
|
||||
buttons: {
|
||||
sticker: false,
|
||||
closer: false
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onUserSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "appkeys") {
|
||||
return;
|
||||
}
|
||||
|
||||
var app, token, user;
|
||||
|
||||
if (data.type === "request_access" && self.loginState.isUser()) {
|
||||
app = data.app_name;
|
||||
token = data.user_token;
|
||||
user = data.user_id;
|
||||
|
||||
if (user && user !== self.loginState.username()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.pending[token] !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.openRequests[token] = self.promptForAccess(app, token);
|
||||
|
||||
} else if (data.type === "end_request") {
|
||||
token = data.user_token;
|
||||
|
||||
if (self.openRequests[token] !== undefined) {
|
||||
// another instance responded to the access request before the current user did
|
||||
if (self.openRequests[token].state !== "closed") {
|
||||
self.openRequests[token].remove();
|
||||
}
|
||||
delete self.openRequests[token]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function AllAppKeysViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.allkeys",
|
||||
{
|
||||
"user_app": function (a, b) {
|
||||
// sorts ascending, first by user, then by app
|
||||
if (a["user_id"] > b["user_id"]) return 1;
|
||||
if (a["user_id"] < b["user_id"]) return -1;
|
||||
|
||||
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
|
||||
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"user_app",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
self.users = ko.observableArray([]);
|
||||
self.apps = ko.observableArray([]);
|
||||
|
||||
self.markedForDeletion = ko.observableArray([]);
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getAllKeys()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
|
||||
var users = [];
|
||||
var apps = [];
|
||||
_.each(response.keys, function(key) {
|
||||
users.push(key.user_id);
|
||||
apps.push(key.app_id.toLowerCase());
|
||||
});
|
||||
|
||||
users = _.uniq(users);
|
||||
users.sort();
|
||||
self.users(users);
|
||||
|
||||
apps = _.uniq(apps);
|
||||
apps.sort();
|
||||
self.apps(apps);
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.revokeMarked = function() {
|
||||
var perform = function() {
|
||||
self._bulkRevoke(self.markedForDeletion())
|
||||
.done(function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markAllOnPageForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
|
||||
};
|
||||
|
||||
self.markAllForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
|
||||
};
|
||||
|
||||
self.markAllByUserForDeletion = function(user) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
|
||||
};
|
||||
|
||||
self.markAllByAppForDeletion = function(app) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); })
|
||||
};
|
||||
|
||||
self.markAllByFilterForDeletion = function(filter) {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))));
|
||||
};
|
||||
|
||||
self.clearMarked = function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
};
|
||||
|
||||
self._bulkRevoke = function(keys) {
|
||||
var title, message, handler;
|
||||
|
||||
title = gettext("Revoking application keys");
|
||||
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length});
|
||||
handler = function(key) {
|
||||
return OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: keys.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(keys, function(key) {
|
||||
var request = handler(key);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UserAppKeysViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#usersettings_plugin_appkeys"]
|
||||
]);
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AllAppKeysViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#settings_plugin_appkeys"]
|
||||
])
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
#settings_plugin_appkeys_userkeys_table,
|
||||
#settings_plugin_appkeys_allkeys_table {
|
||||
.settings_plugin_appkeys_app {
|
||||
}
|
||||
.settings_plugin_appkeys_actions {
|
||||
width: 75px;
|
||||
text-align: center;
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
}
|
||||
.settings_plugin_appkeys_user {
|
||||
width: 100px;
|
||||
}
|
||||
.settings_plugin_appkeys_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<div data-bind="visible: keys.allSize() <= 0">
|
||||
<p>{{ _('There are no application keys registered yet.') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: keys.allSize() > 0">
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllOnPageForDeletion">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllForDeletion">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li class="dropdown-submenu">
|
||||
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by user...') }}</a>
|
||||
<ul class="dropdown-menu" data-bind="foreach: users">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByUserForDeletion($data) }, text: $data"></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="dropdown-submenu">
|
||||
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by app...') }}</a>
|
||||
<ul class="dropdown-menu" data-bind="foreach: apps">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByAppForDeletion($data) }, text: $data"></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarked">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: revokeMarked, enable: markedForDeletion().length > 0">{{ _('Revoke selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_allkeys_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_appkeys_checkbox"></th>
|
||||
<th class="settings_plugin_appkeys_user">{{ _('User') }}</th>
|
||||
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
|
||||
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_checkbox"><input type="checkbox" data-bind="value: api_key, checked: $root.markedForDeletion"></td>
|
||||
<td class="settings_plugin_appkeys_user"><span data-bind="text: user_id"></span></td>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: keys.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,49 @@
|
||||
<legend>{{ _('Registered application keys') }}</legend>
|
||||
|
||||
<div data-bind="visible: keys.allSize() <= 0">
|
||||
<p>{{ _('There are no application keys registered yet.') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: keys.allSize() > 0">
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_userkeys_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
|
||||
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: keys.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('Manually generate an application key') }}</legend>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Application identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" data-bind="value: editorApp">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="click: generateKey">{{ _('Generate') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,954 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.plugin.core import FolderOrigin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server.util.flask import no_firstrun_access
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import is_os_compatible
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
try:
|
||||
import zlib # check if zlib is available
|
||||
except ImportError:
|
||||
zlib = None
|
||||
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import codecs
|
||||
import flask
|
||||
import logging
|
||||
import os
|
||||
import requests
|
||||
import sarge
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
import json
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
|
||||
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
|
||||
|
||||
|
||||
class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin):
|
||||
|
||||
_pip_caller = None
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._in_progress = []
|
||||
self._in_progress_lock = threading.RLock()
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="ACCESS",
|
||||
name="Backup access",
|
||||
description=gettext("Allows access to backups and restores"),
|
||||
roles=["access"],
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
]
|
||||
|
||||
##~~ StarupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
self._clean_dir_backup(self._settings._basedir,
|
||||
on_log_progress=self._logger.info)
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/backup.js"],
|
||||
clientjs=["clientjs/backup.js"],
|
||||
css=["css/backup.css"],
|
||||
less=["less/backup.less"])
|
||||
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_state(self):
|
||||
backups = self._get_backups()
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(backups=backups,
|
||||
backup_in_progress=len(self._in_progress) > 0,
|
||||
unknown_plugins=unknown_plugins,
|
||||
restore_supported=is_os_compatible(["!windows"]))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_unknown_plugins(self):
|
||||
# TODO add caching
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(unknown_plugins=unknown_plugins)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def delete_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
pass
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_backups(self):
|
||||
backups = self._get_backups()
|
||||
return flask.jsonify(backups=backups)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def create_backup(self):
|
||||
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
|
||||
|
||||
data = flask.request.json
|
||||
exclude = data.get("exclude", [])
|
||||
|
||||
def on_backup_start(name, temporary_path, exclude):
|
||||
self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path,
|
||||
u",".join(exclude) if len(exclude) else "-"))
|
||||
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.append(name)
|
||||
self._send_client_message("backup_started", payload=dict(name=name))
|
||||
|
||||
def on_backup_done(name, final_path, exclude):
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.remove(name)
|
||||
self._send_client_message("backup_done", payload=dict(name=name))
|
||||
|
||||
self._logger.info(u"... done creating backup zip.")
|
||||
|
||||
def on_backup_error(name, exc_info):
|
||||
with self._in_progress_lock:
|
||||
try:
|
||||
self._in_progress.remove(name)
|
||||
except ValueError:
|
||||
# we'll ignore that
|
||||
pass
|
||||
|
||||
self._send_client_message("backup_error", payload=dict(name=name,
|
||||
error=u"{}".format(exc_info[1])))
|
||||
self._logger.error(u"Error while creating backup zip", exc_info=exc_info)
|
||||
|
||||
thread = threading.Thread(target=self._create_backup,
|
||||
args=(backup_file,),
|
||||
kwargs=dict(exclude=exclude,
|
||||
settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_backup_start=on_backup_start,
|
||||
on_backup_done=on_backup_done,
|
||||
on_backup_error=on_backup_error))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
response = flask.jsonify(started=True,
|
||||
name=backup_file)
|
||||
response.status_code = 201
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def delete_backup(self, filename):
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
full_path = os.path.realpath(os.path.join(backup_folder, filename))
|
||||
if full_path.startswith(backup_folder) \
|
||||
and os.path.exists(full_path) \
|
||||
and not is_hidden_path(full_path):
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except:
|
||||
self._logger.exception(u"Could not delete {}".format(filename))
|
||||
raise
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def perform_restore(self):
|
||||
if not is_os_compatible(["!windows"]):
|
||||
return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400)
|
||||
|
||||
input_name = "file"
|
||||
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
||||
|
||||
if input_upload_path in flask.request.values:
|
||||
# file to restore was uploaded
|
||||
path = flask.request.values[input_upload_path]
|
||||
|
||||
elif flask.request.json and "path" in flask.request.json:
|
||||
# existing backup is supposed to be restored
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"]))
|
||||
if not path.startswith(backup_folder) \
|
||||
or not os.path.exists(path) \
|
||||
or is_hidden_path(path):
|
||||
return flask.abort(404)
|
||||
|
||||
else:
|
||||
return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400)
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def on_log(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", dict(line=line, type="stdout"))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
|
||||
octoprint_compatible=octoprint_compatible,
|
||||
os_compatible=os_compatible))
|
||||
continue
|
||||
|
||||
self._logger.info(u"Installing plugin {}".format(plugin["id"]))
|
||||
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=on_log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
self._send_client_message("unknown_plugins", payload=dict(plugins=plugins))
|
||||
|
||||
def on_log_progress(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stdout"))
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
self._logger.error(line, exc_info=exc_info)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stderr"))
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr"))
|
||||
|
||||
def on_restore_start(path):
|
||||
self._send_client_message("restore_started")
|
||||
|
||||
def on_restore_done(path):
|
||||
self._send_client_message("restore_done")
|
||||
|
||||
def on_restore_failed(path):
|
||||
self._send_client_message("restore_failed")
|
||||
|
||||
def on_invalid_backup(line):
|
||||
on_log_error(line)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
archive.close()
|
||||
shutil.copy(path, archive.name)
|
||||
path = archive.name
|
||||
|
||||
# noinspection PyTypeChecker
|
||||
thread = threading.Thread(target=self._restore_backup,
|
||||
args=(path,),
|
||||
kwargs=dict(settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_invalid_backup=on_invalid_backup,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_restore_start=on_restore_start,
|
||||
on_restore_done=on_restore_done,
|
||||
on_restore_failed=on_restore_failed))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return flask.jsonify(started=True)
|
||||
|
||||
##~~ tornado hook
|
||||
|
||||
def route_hook(self, *args, **kwargs):
|
||||
from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.server import app
|
||||
from octoprint.server.util.tornado import access_validation_factory
|
||||
from octoprint.server.util.flask import admin_validator
|
||||
|
||||
return [
|
||||
(r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(),
|
||||
as_attachment=True,
|
||||
path_validation=path_validation_factory(lambda path: not is_hidden_path(path),
|
||||
status_code=404),
|
||||
access_validation=access_validation_factory(app, admin_validator)))
|
||||
]
|
||||
|
||||
def bodysize_hook(self, current_max_body_sizes, *args, **kwargs):
|
||||
# max upload size of 1GB for the restore endpoint
|
||||
return [("POST", r"/restore", 1024 * 1024 * 1024)]
|
||||
|
||||
##~~ CLI hook
|
||||
|
||||
def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
import click
|
||||
|
||||
@click.command("backup")
|
||||
@click.option("--exclude", multiple=True,
|
||||
help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or "
|
||||
"'timelapse' to exclude timelapses.")
|
||||
def backup_command(exclude):
|
||||
"""
|
||||
Creates a new backup.
|
||||
"""
|
||||
|
||||
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
|
||||
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
|
||||
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
click.echo("Creating backup at {}, please wait...".format(backup_file))
|
||||
self._create_backup(backup_file,
|
||||
exclude=exclude,
|
||||
settings=settings,
|
||||
plugin_manager=cli_group.plugin_manager,
|
||||
datafolder=datafolder)
|
||||
click.echo("Done.")
|
||||
|
||||
@click.command("restore")
|
||||
@click.argument("path")
|
||||
def restore_command(path):
|
||||
"""
|
||||
Restores an existing backup from the backup zip provided as argument.
|
||||
|
||||
OctoPrint does not need to run for this to proceed.
|
||||
"""
|
||||
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
|
||||
plugin_manager = cli_group.plugin_manager
|
||||
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
# register plugin manager plugin setting overlays
|
||||
plugin_info = plugin_manager.get_plugin_info("pluginmanager")
|
||||
if plugin_info and plugin_info.implementation:
|
||||
default_settings_overlay = dict(plugins=dict())
|
||||
default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults()
|
||||
settings.add_overlay(default_settings_overlay, at_end=True)
|
||||
|
||||
if not os.path.isabs(path):
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
path = os.path.join(datafolder, path)
|
||||
|
||||
if not os.path.exists(path):
|
||||
click.echo(u"Backup {} does not exist".format(path), err=True)
|
||||
sys.exit(-1)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
archive.close()
|
||||
shutil.copy(path, archive.name)
|
||||
path = archive.name
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def log(line):
|
||||
click.echo(u"\t{}".format(line))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
continue
|
||||
|
||||
click.echo(u"Installing plugin {}".format(plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.")
|
||||
for plugin in plugins:
|
||||
click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
|
||||
|
||||
def on_log_progress(line):
|
||||
click.echo(line)
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
click.echo(line, err=True)
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
click.echo(line.rstrip(), err=True)
|
||||
|
||||
if self._restore_backup(path,
|
||||
settings=settings,
|
||||
plugin_manager=plugin_manager,
|
||||
datafolder=datafolder,
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_invalid_backup=on_log_error):
|
||||
click.echo(u"Restored from {}".format(path))
|
||||
else:
|
||||
click.echo(u"Restoring from {} failed".format(path), err=True)
|
||||
|
||||
return [backup_command, restore_command]
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def _get_backups(self):
|
||||
backups = []
|
||||
for entry in scandir(self.get_plugin_data_folder()):
|
||||
if is_hidden_path(entry.path):
|
||||
continue
|
||||
if not entry.is_file():
|
||||
continue
|
||||
if not entry.name.endswith(".zip"):
|
||||
continue
|
||||
|
||||
backups.append(dict(name=entry.name,
|
||||
date=entry.stat().st_mtime,
|
||||
size=entry.stat().st_size,
|
||||
url=flask.url_for("index") + "plugin/backup/download/" + entry.name))
|
||||
return backups
|
||||
|
||||
def _get_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
if os.path.exists(data_file):
|
||||
try:
|
||||
with codecs.open(data_file, mode="r", encoding="utf-8") as f:
|
||||
unknown_plugins = json.load(f)
|
||||
|
||||
assert isinstance(unknown_plugins, list)
|
||||
assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins))
|
||||
|
||||
installed_plugins = self._plugin_manager.plugins
|
||||
unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
|
||||
if not unknown_plugins:
|
||||
# no plugins left uninstalled, delete data file
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return unknown_plugins
|
||||
except:
|
||||
self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file))
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def _clean_dir_backup(cls, basedir,
|
||||
on_log_progress=None):
|
||||
basedir_backup = basedir + ".bck"
|
||||
|
||||
if os.path.exists(basedir_backup):
|
||||
def remove_bck():
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Found config folder backup from prior restore, deleting it...")
|
||||
shutil.rmtree(basedir_backup)
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"... deleted.")
|
||||
|
||||
thread = threading.Thread(target=remove_bck)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
@classmethod
|
||||
def _get_disk_size(cls, path, ignored=None):
|
||||
if ignored is None:
|
||||
ignored = []
|
||||
|
||||
if path in ignored:
|
||||
return 0
|
||||
|
||||
total = 0
|
||||
for entry in scandir(path):
|
||||
if entry.is_dir():
|
||||
total += cls._get_disk_size(entry.path, ignored=ignored)
|
||||
elif entry.is_file():
|
||||
total += entry.stat().st_size
|
||||
return total
|
||||
|
||||
@classmethod
|
||||
def _free_space(cls, path, size):
|
||||
from psutil import disk_usage
|
||||
return disk_usage(path).free > size
|
||||
|
||||
@classmethod
|
||||
def _get_plugin_repository_data(cls, url, logger=None):
|
||||
if logger is None:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
except:
|
||||
logger.exception(u"Error while fetching the plugin repository data from {}".format(url))
|
||||
return dict()
|
||||
|
||||
from octoprint.plugins.pluginmanager import map_repository_entry
|
||||
return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()))
|
||||
|
||||
@classmethod
|
||||
def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None):
|
||||
if pip_args is None:
|
||||
pip_args = []
|
||||
|
||||
if on_log is None:
|
||||
on_log = logging.getLogger(__name__).info
|
||||
|
||||
# prepare pip caller
|
||||
def log(prefix, *lines):
|
||||
for line in lines:
|
||||
on_log(u"{} {}".format(prefix, line.rstrip()))
|
||||
|
||||
def log_call(*lines):
|
||||
log(u">", *lines)
|
||||
|
||||
def log_stdout(*lines):
|
||||
log(u"<", *lines)
|
||||
|
||||
def log_stderr(*lines):
|
||||
log(u"!", *lines)
|
||||
|
||||
if cls._pip_caller is None:
|
||||
cls._pip_caller = LocalPipCaller(force_user=force_user)
|
||||
|
||||
cls._pip_caller.on_log_call = log_call
|
||||
cls._pip_caller.on_log_stdout = log_stdout
|
||||
cls._pip_caller.on_log_stderr = log_stderr
|
||||
|
||||
# install plugin
|
||||
pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir']
|
||||
|
||||
if plugin.get("follow_dependency_links"):
|
||||
pip.append("--process-dependency-links")
|
||||
|
||||
if force_user:
|
||||
pip.append("--user")
|
||||
|
||||
if pip_args:
|
||||
pip += pip_args
|
||||
|
||||
cls._pip_caller.execute(*pip)
|
||||
|
||||
@classmethod
|
||||
def _create_backup(cls, name,
|
||||
exclude=None,
|
||||
settings=None,
|
||||
plugin_manager=None,
|
||||
datafolder=None,
|
||||
on_backup_start=None,
|
||||
on_backup_done=None,
|
||||
on_backup_error=None):
|
||||
exclude_by_default = ("generated", "logs", "watched",)
|
||||
|
||||
try:
|
||||
if exclude is None:
|
||||
exclude = []
|
||||
|
||||
configfile = settings._configfile
|
||||
basedir = settings._basedir
|
||||
|
||||
temporary_path = os.path.join(datafolder, ".{}".format(name))
|
||||
final_path = os.path.join(datafolder, name)
|
||||
|
||||
own_folder = datafolder
|
||||
defaults = [os.path.join(basedir, "config.yaml"),] + \
|
||||
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
|
||||
|
||||
# check how much many bytes we are about to backup
|
||||
size = os.stat(configfile).st_size
|
||||
for folder in default_settings["folder"].keys():
|
||||
if folder in exclude or folder in exclude_by_default:
|
||||
continue
|
||||
size += cls._get_disk_size(settings.global_get_basefolder(folder),
|
||||
ignored=[own_folder,])
|
||||
size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,])
|
||||
|
||||
# since we can't know the compression ratio beforehand, we assume we need the same amount of space
|
||||
if not cls._free_space(os.path.dirname(temporary_path), size):
|
||||
raise InsufficientSpace()
|
||||
|
||||
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
|
||||
|
||||
if callable(on_backup_start):
|
||||
on_backup_start(name, temporary_path, exclude)
|
||||
|
||||
with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip:
|
||||
def add_to_zip(source, target, ignored=None):
|
||||
if ignored is None:
|
||||
ignored = []
|
||||
|
||||
if source in ignored:
|
||||
return
|
||||
|
||||
if os.path.isdir(source):
|
||||
for entry in scandir(source):
|
||||
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
|
||||
elif os.path.isfile(source):
|
||||
zip.write(source, arcname=target)
|
||||
|
||||
# add metadata
|
||||
metadata = dict(version=get_octoprint_version_string(),
|
||||
excludes=exclude)
|
||||
zip.writestr("metadata.json", json.dumps(metadata))
|
||||
|
||||
# backup current config file
|
||||
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
|
||||
|
||||
# backup configured folder paths
|
||||
for folder in default_settings["folder"].keys():
|
||||
if folder in exclude or folder in exclude_by_default:
|
||||
continue
|
||||
|
||||
add_to_zip(settings.global_get_basefolder(folder),
|
||||
"basedir/" + folder.replace("_", "/"),
|
||||
ignored=[own_folder,])
|
||||
|
||||
# backup anything else that might be lying around in our basedir
|
||||
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
|
||||
|
||||
# add list of installed plugins
|
||||
plugins = []
|
||||
plugin_folder = settings.global_get_basefolder("plugins")
|
||||
for key, plugin in plugin_manager.plugins.items():
|
||||
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
|
||||
# ignore anything bundled or from the plugins folder we already include in the backup
|
||||
continue
|
||||
|
||||
plugins.append(dict(key=plugin.key,
|
||||
name=plugin.name,
|
||||
url=plugin.url))
|
||||
|
||||
if len(plugins):
|
||||
zip.writestr("plugin_list.json", json.dumps(plugins))
|
||||
|
||||
os.rename(temporary_path, final_path)
|
||||
|
||||
if callable(on_backup_done):
|
||||
on_backup_done(name, final_path, exclude)
|
||||
except:
|
||||
if callable(on_backup_error):
|
||||
exc_info = sys.exc_info()
|
||||
try:
|
||||
on_backup_error(name, exc_info)
|
||||
finally:
|
||||
del exc_info
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def _restore_backup(cls, path,
|
||||
settings=None,
|
||||
plugin_manager=None,
|
||||
datafolder=None,
|
||||
on_install_plugins=None,
|
||||
on_report_unknown_plugins=None,
|
||||
on_invalid_backup=None,
|
||||
on_log_progress=None,
|
||||
on_log_error=None,
|
||||
on_restore_start=None,
|
||||
on_restore_done=None,
|
||||
on_restore_failed=None):
|
||||
if not is_os_compatible(["!windows"]):
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Restore is not supported on this operating system")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
basedir = settings._basedir
|
||||
cls._clean_dir_backup(basedir,
|
||||
on_log_progress=on_log_progress)
|
||||
|
||||
plugin_repo = dict()
|
||||
repo_url = settings.global_get(["plugins", "pluginmanager", "repository"])
|
||||
if repo_url:
|
||||
plugin_repo = cls._get_plugin_repository_data(repo_url)
|
||||
|
||||
if callable(on_restore_start):
|
||||
on_restore_start(path)
|
||||
|
||||
try:
|
||||
|
||||
with zipfile.ZipFile(path, "r") as zip:
|
||||
# read metadata
|
||||
try:
|
||||
metadata_zipinfo = zip.getinfo("metadata.json")
|
||||
except KeyError:
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
metadata_bytes = zip.read(metadata_zipinfo)
|
||||
metadata = json.loads(metadata_bytes)
|
||||
|
||||
backup_version = get_comparable_version(metadata["version"], base=True)
|
||||
if backup_version > get_octoprint_version(base=True):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
# unzip to temporary folder
|
||||
temp = tempfile.mkdtemp()
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacking backup to {}...".format(temp))
|
||||
abstemp = os.path.abspath(temp)
|
||||
for member in zip.infolist():
|
||||
abspath = os.path.abspath(os.path.join(temp, member.filename))
|
||||
if abspath.startswith(abstemp):
|
||||
zip.extract(member, temp)
|
||||
|
||||
# sanity check
|
||||
configfile = os.path.join(temp, "basedir", "config.yaml")
|
||||
if not os.path.exists(configfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks config.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
import yaml
|
||||
|
||||
with codecs.open(configfile) as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
|
||||
if configdata.get("accessControl", dict()).get("enabled", True):
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks users.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacked")
|
||||
|
||||
# install available plugins
|
||||
with codecs.open(os.path.join(temp, "plugin_list.json"), "r") as f:
|
||||
plugins = json.load(f)
|
||||
|
||||
known_plugins = []
|
||||
unknown_plugins = []
|
||||
if plugins:
|
||||
if plugin_repo:
|
||||
for plugin in plugins:
|
||||
if plugin["key"] in plugin_manager.plugins:
|
||||
# already installed
|
||||
continue
|
||||
|
||||
if plugin["key"] in plugin_repo:
|
||||
# not installed, can be installed from repository url
|
||||
known_plugins.append(plugin_repo[plugin["key"]])
|
||||
else:
|
||||
# not installed, not installable
|
||||
unknown_plugins.append(plugin)
|
||||
|
||||
else:
|
||||
# no repo, all plugins are not installable
|
||||
unknown_plugins = plugins
|
||||
|
||||
if callable(on_log_progress):
|
||||
if known_plugins:
|
||||
on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins))))
|
||||
if unknown_plugins:
|
||||
on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins))))
|
||||
|
||||
if callable(on_install_plugins):
|
||||
on_install_plugins(known_plugins)
|
||||
|
||||
if callable(on_report_unknown_plugins):
|
||||
on_report_unknown_plugins(unknown_plugins)
|
||||
|
||||
# move config data
|
||||
basedir_backup = basedir + ".bck"
|
||||
basedir_extracted = os.path.join(temp, "basedir")
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
|
||||
os.rename(basedir, basedir_backup)
|
||||
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
|
||||
os.rename(basedir_extracted, basedir)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
|
||||
on_log_error(u"Rolling back old config data")
|
||||
|
||||
os.rename(basedir_backup, basedir)
|
||||
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if unknown_plugins:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Writing info file about unknown plugins")
|
||||
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f:
|
||||
json.dump(unknown_plugins, f)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
|
||||
exc_info = sys.exc_info())
|
||||
|
||||
finally:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary unpacked folder")
|
||||
shutil.rmtree(temp)
|
||||
|
||||
except:
|
||||
exc_info = sys.exc_info()
|
||||
try:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while running restore", exc_info=exc_info)
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
finally:
|
||||
del exc_info
|
||||
return False
|
||||
|
||||
finally:
|
||||
# remove zip
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary zip")
|
||||
os.remove(path)
|
||||
|
||||
# restart server
|
||||
if restart_command:
|
||||
import sarge
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Restarting...")
|
||||
if callable(on_restore_done):
|
||||
on_restore_done(path)
|
||||
|
||||
try:
|
||||
sarge.run(restart_command, async_=True)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restarting via command {}".format(restart_command),
|
||||
exc_info=sys.exc_info())
|
||||
on_log_error(u"Please restart OctoPrint manually")
|
||||
return False
|
||||
|
||||
else:
|
||||
if callable(on_restore_done):
|
||||
on_restore_done(path)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _send_client_message(self, message, payload=None):
|
||||
if payload is None:
|
||||
payload = dict()
|
||||
payload["type"] = message
|
||||
self._plugin_manager.send_plugin_message(self._identifier, payload)
|
||||
|
||||
|
||||
|
||||
class InsufficientSpace(Exception):
|
||||
pass
|
||||
|
||||
__plugin_name__ = gettext(u"Backup & Restore")
|
||||
__plugin_author__ = u"Gina Häußge"
|
||||
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
|
||||
u"& restore your OctoPrint settings and data.")
|
||||
__plugin_license__ = u"AGPLv3"
|
||||
__plugin_implementation__ = BackupPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
|
||||
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
|
||||
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintBackupClient = function(base) {
|
||||
this.base = base;
|
||||
this.url = this.base.getBlueprintUrl("backup");
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.url, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
|
||||
exclude = exclude || [];
|
||||
|
||||
var data = {
|
||||
exclude: exclude
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url + "backup", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
|
||||
return this.base.delete(this.url + "backup/" + backup, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
|
||||
var data = {
|
||||
path: backup
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url + "restore", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) {
|
||||
data = data || {};
|
||||
|
||||
var filename = data.filename || undefined;
|
||||
return this.base.upload(this.url + "restore", file, filename, data);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) {
|
||||
return this.base.delete(this.url + "unknown_plugins", opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient);
|
||||
return OctoPrintBackupClient;
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
|
||||
@@ -0,0 +1,289 @@
|
||||
$(function() {
|
||||
function BackupViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
self.backups = new ItemListHelper(
|
||||
"plugin.backup.backups",
|
||||
{
|
||||
"date": function (a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"date",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
|
||||
self.markedForBackupDeletion = ko.observableArray([]);
|
||||
|
||||
self.excludeFromBackup = ko.observableArray([]);
|
||||
self.backupInProgress = ko.observable(false);
|
||||
self.restoreSupported = ko.observable(true);
|
||||
|
||||
self.backupUploadButton = $("#settings-backup-upload");
|
||||
self.backupUploadData = undefined;
|
||||
self.backupUploadButton.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
if (data.files.length === 0) {
|
||||
// no files? ignore
|
||||
return false;
|
||||
}
|
||||
|
||||
self.backupUploadName(data.files[0].name);
|
||||
self.backupUploadData = data;
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.backupUploadName(undefined);
|
||||
self.backupUploadData = undefined;
|
||||
}
|
||||
});
|
||||
self.backupUploadName = ko.observable();
|
||||
self.restoreInProgress = ko.observable(false);
|
||||
self.restoreTitle = ko.observable();
|
||||
self.restoreDialog = undefined;
|
||||
self.restoreOutput = undefined;
|
||||
self.unknownPlugins = ko.observableArray([]);
|
||||
|
||||
self.loglines = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.backup.get()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.backups.updateItems(response.backups);
|
||||
self.unknownPlugins(response.unknown_plugins);
|
||||
self.restoreSupported(response.restore_supported);
|
||||
};
|
||||
|
||||
self.createBackup = function() {
|
||||
var excluded = self.excludeFromBackup();
|
||||
OctoPrint.plugins.backup.createBackup(excluded)
|
||||
.done(function() {
|
||||
self.excludeFromBackup([]);
|
||||
})
|
||||
};
|
||||
|
||||
self.removeBackup = function(backup) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteBackup(backup)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.restoreBackup = function(backup) {
|
||||
if (!self.restoreSupported()) return;
|
||||
|
||||
var perform = function() {
|
||||
self.restoreInProgress(true);
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: "Preparing to restore...", stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.performRestoreFromUpload = function() {
|
||||
if (self.backupUploadData === undefined) return;
|
||||
|
||||
var perform = function() {
|
||||
self.restoreInProgress(true);
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
|
||||
self.backupUploadData.submit();
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.deleteUnknownPluginRecord = function() {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteUnknownPlugins()
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markFilesOnPage = function() {
|
||||
self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
|
||||
};
|
||||
|
||||
self.markAllFiles = function() {
|
||||
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedFiles = function() {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.removeMarkedFiles = function() {
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForBackupDeletion())
|
||||
.done(function() {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
|
||||
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "backup") return;
|
||||
|
||||
if (data.type === "backup_done") {
|
||||
self.requestData();
|
||||
self.backupInProgress(false);
|
||||
new PNotify({
|
||||
title: gettext("Backup created successfully"),
|
||||
type: "success"
|
||||
});
|
||||
} else if (data.type === "backup_started") {
|
||||
self.backupInProgress(true);
|
||||
} else if (data.type === "backup_error") {
|
||||
self.requestData();
|
||||
self.backupInProgress(false);
|
||||
new PNotify({
|
||||
title: gettext("Creating the backup failed"),
|
||||
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
} else if (data.type === "restore_started") {
|
||||
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
} else if (data.type === "restore_failed") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "restore_done") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "install_plugin") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}),
|
||||
stream: "message"
|
||||
});
|
||||
} else if (data.type === "plugin_incompatible") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}),
|
||||
stream: "stderr"
|
||||
});
|
||||
} else if (data.type === "unknown_plugins") {
|
||||
if (data.plugins.length > 0) {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"});
|
||||
_.each(data.plugins, function(plugin) {
|
||||
self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"});
|
||||
});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.unknownPlugins(data.plugins);
|
||||
}
|
||||
} else if (data.type === "logline") {
|
||||
self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream}));
|
||||
self._scrollRestoreOutputToEnd();
|
||||
}
|
||||
};
|
||||
|
||||
self._scrollRestoreOutputToEnd = function() {
|
||||
self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height());
|
||||
};
|
||||
|
||||
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
};
|
||||
|
||||
self._bulkRemove = function(files) {
|
||||
var title, message, handler;
|
||||
|
||||
title = gettext("Deleting backups");
|
||||
message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
|
||||
handler = function(filename) {
|
||||
return OctoPrint.plugins.backup.deleteBackup(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: files.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function(filename) {
|
||||
var request = handler(filename);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: BackupViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#settings_plugin_backup"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
#settings_plugin_backup_backup_table {
|
||||
.settings_plugin_backup_name {
|
||||
}
|
||||
.settings_plugin_backup_actions {
|
||||
width: 75px;
|
||||
text-align: center;
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
}
|
||||
.settings_plugin_backup_date {
|
||||
width: 200px;
|
||||
text-align: right;
|
||||
}
|
||||
.settings_plugin_backup_size {
|
||||
width: 100px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.settings_plugin_backup_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_backup_restoredialog_output {
|
||||
.message {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.error {
|
||||
font-weight: bold;
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.stdout {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.stderr {
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.call {
|
||||
color: #000099;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
<div class="alert" data-bind="visible: unknownPlugins().length > 0">
|
||||
{% trans %}
|
||||
Some plugins during the last restore could not be identified and hence not automatically installed.
|
||||
Please install them manually, they are listed below including their stated homepages:
|
||||
{% endtrans %}
|
||||
<ul data-bind="foreach: unknownPlugins">
|
||||
<li><span data-bind="text: name"></span>: <a data-bind="text: url, attr: {href: url}" target="_blank" rel="noreferrer noopener"></a></li>
|
||||
</ul>
|
||||
<small><a href="javascript:void(0)" data-bind="click: deleteUnknownPluginRecord">{{ _('Delete record of unknown plugins') }}</a></small>
|
||||
</div>
|
||||
|
||||
|
||||
<h3>{{ _('Existing backups') }}</h3>
|
||||
|
||||
<div data-bind="visible: backups.allSize() <= 0">
|
||||
<p>{{ _('There are no backups. Maybe create one below?') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: backups.allSize() > 0">
|
||||
<p>{{ _('These are the backups of your settings and files that already exist on this OctoPrint instance. You may delete, download or restore them.') }}</p>
|
||||
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForBackupDeletion().length > 0">{{ _('Delete selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_backup_backup_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_backup_checkbox"></th>
|
||||
<th class="settings_plugin_backup_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_backup_date">{{ _('Date') }}</th>
|
||||
<th class="settings_plugin_backup_size">{{ _('Size') }}</th>
|
||||
<th class="settings_plugin_backup_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: backups.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_backup_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForBackupDeletion"></td>
|
||||
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
|
||||
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
|
||||
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a> | <a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()"> | <a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: backups.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: backups.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: backups.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.backups.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.backups.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: backups.currentPage() === backups.lastPage()}"><a href="javascript:void(0)" data-bind="click: backups.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Create backup') }}</h3>
|
||||
|
||||
<p>{{ _('Create a new backup of the current state.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: 'timelapse', checked: excludeFromBackup"> {{ _('Exclude timelapses from backup') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: createBackup"><i class="fa fa-spinner fa-spin" data-bind="visible: backupInProgress"></i> {{ _('Create backup now') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div data-bind="visible: restoreSupported()">
|
||||
<h3>{{ _('Restore from uploaded backup') }}</h3>
|
||||
|
||||
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Backup file') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="btn fileinput-button">
|
||||
<span>{{ _('Browse...') }}</span>
|
||||
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
|
||||
</span>
|
||||
<span class="add-on" data-bind="text: backupUploadName"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div data-bind="visible: !restoreSupported()">
|
||||
{{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to <a href="%(url)s" target="_blank" rel="noopener noreferrer">restore your backups manually for now</a>.', url='https://faq.octoprint.org/manual-restore') }}
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_backup_restoredialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<h3>{{ _('Restoring from backup...') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_backup_restoredialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.restoreInProgress()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,14 +1,22 @@
|
||||
<h3>{{ _('Access Control') }}</h3>
|
||||
|
||||
{% trans %}<p>
|
||||
{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}<p>
|
||||
<strong>Please read the following, it is very important for your printer's health!</strong>
|
||||
</p>
|
||||
<p>
|
||||
OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
|
||||
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
|
||||
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
|
||||
malicious intent - to gain access to your printer</strong> via an untrustworthy network
|
||||
and using it in such a way that it is damaged or worse (i.e. causes a fire).
|
||||
</p>
|
||||
<p>
|
||||
If you plan on accessing OctoPrint remotely over the internet, <strong>you should not only rely on the built-in
|
||||
Access Control mechanisms</strong> however -
|
||||
<a href="{{ safe_remote_url }}" target="_blank" rel="noopener noreferrer">take additional precautions</a>.
|
||||
Your OctoPrint enabled printer is a critical home appliance you really should not give anyone who happens to be
|
||||
connected to the internet access to - even read-only! <strong>An instance available publicly on the internet
|
||||
will be found, and people will try to break it open.</strong>
|
||||
</p>
|
||||
<p>
|
||||
It looks like you haven't configured access control yet. Please <strong>set up a username and password</strong> for the
|
||||
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
|
||||
@@ -36,12 +44,12 @@
|
||||
</div>
|
||||
</form>
|
||||
{% trans %}<p>
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy local network and you don't
|
||||
need Access Control for other reasons, you may alternatively disable Access Control. You should only
|
||||
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
|
||||
<strong>Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!</strong>
|
||||
</p>{% endtrans %}
|
||||
|
||||
<div class="row-fluid">
|
||||
|
||||
@@ -5,6 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
@@ -105,11 +106,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
return flask.make_response(u"Something went wrong while converting imported profile: {message}".format(message=str(e)), 500)
|
||||
|
||||
else:
|
||||
self._logger.warn(u"No profile file included for importing, aborting")
|
||||
self._logger.warning(u"No profile file included for importing, aborting")
|
||||
return flask.make_response(u"No file included", 400)
|
||||
|
||||
if profile_dict is None:
|
||||
self._logger.warn(u"Could not convert profile, aborting")
|
||||
self._logger.warning(u"Could not convert profile, aborting")
|
||||
return flask.make_response(u"Could not convert Cura profile", 400)
|
||||
|
||||
name, _ = os.path.splitext(filename)
|
||||
@@ -142,14 +143,14 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
display_name=profile_display_name,
|
||||
description=profile_description)
|
||||
except octoprint.slicing.ProfileAlreadyExists:
|
||||
self._logger.warn(u"Profile {profile_name} already exists, aborting".format(**locals()))
|
||||
self._logger.warning(u"Profile {profile_name} already exists, aborting".format(**locals()))
|
||||
return flask.make_response(u"A profile named {profile_name} already exists for slicer cura".format(**locals()), 409)
|
||||
|
||||
if profile_make_default:
|
||||
try:
|
||||
self._slicing_manager.set_default_profile("cura", profile_name)
|
||||
except octoprint.slicing.UnknownProfile:
|
||||
self._logger.warn(u"Profile {profile_name} could not be set as default, aborting".format(**locals()))
|
||||
self._logger.warning(u"Profile {profile_name} could not be set as default, aborting".format(**locals()))
|
||||
return flask.make_response(u"The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500)
|
||||
|
||||
result = dict(
|
||||
@@ -428,7 +429,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
if p.returncode == 0:
|
||||
return True, dict(analysis=analysis)
|
||||
else:
|
||||
self._logger.warn(u"Could not slice via Cura, got return code %r" % p.returncode)
|
||||
self._logger.warning(u"Could not slice via Cura, got return code %r" % p.returncode)
|
||||
return False, "Got returncode %r" % p.returncode
|
||||
|
||||
except octoprint.slicing.SlicingCancelled as e:
|
||||
@@ -459,7 +460,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
def _load_profile(self, path):
|
||||
import yaml
|
||||
profile_dict = dict()
|
||||
with open(path, "r") as f:
|
||||
with io.open(path, 'rt', encoding='utf-8') as f:
|
||||
try:
|
||||
profile_dict = yaml.safe_load(f)
|
||||
except:
|
||||
@@ -473,7 +474,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||
import yaml
|
||||
with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f:
|
||||
with octoprint.util.atomic_write(path, 'wb', max_permissions=0o666) as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=2, allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, pos_x=None, pos_y=None, used_extruders=1):
|
||||
|
||||
@@ -359,6 +359,8 @@ class Profile(object):
|
||||
regex_print_temperature = re.compile("print_temperature(\d?)")
|
||||
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
|
||||
|
||||
regex_broken_replacements = re.compile("\?([a-zA-Z0-9_]*)\?")
|
||||
|
||||
@classmethod
|
||||
def from_cura_ini(cls, path):
|
||||
import logging
|
||||
@@ -366,7 +368,7 @@ class Profile(object):
|
||||
|
||||
import os
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
logger.warn("Path {path} does not exist or is not a file, cannot import".format(**locals()))
|
||||
logger.warning("Path {path} does not exist or is not a file, cannot import".format(**locals()))
|
||||
return None
|
||||
|
||||
try:
|
||||
@@ -688,9 +690,9 @@ class Profile(object):
|
||||
gcode = defaults[key]
|
||||
|
||||
if key in ("start_gcode", "end_gcode"):
|
||||
return gcode[extruder_count-1]
|
||||
return self.regex_broken_replacements.sub("{\\1}", gcode[extruder_count-1])
|
||||
else:
|
||||
return gcode
|
||||
return self.regex_broken_replacements.sub("{\\1}", gcode)
|
||||
|
||||
def get_profile_string(self):
|
||||
import base64
|
||||
@@ -752,17 +754,16 @@ class Profile(object):
|
||||
|
||||
if key == "start_gcode":
|
||||
contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count)
|
||||
prefix += self.get_start_gcode_prefix(contents)
|
||||
prefix += self.get_start_gcode_prefix(contents, extruder_count=extruder_count)
|
||||
|
||||
else:
|
||||
contents = self.get_gcode_template(key, extruder_count=extruder_count)
|
||||
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
|
||||
|
||||
def get_start_gcode_prefix(self, contents):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
def get_start_gcode_prefix(self, contents, extruder_count=1):
|
||||
prefix = ""
|
||||
without_comments = Profile.regex_strip_comments.sub("", contents)
|
||||
|
||||
gcode_parameter_key = "S"
|
||||
if self.get("gcode_flavor") == GcodeFlavors.MACH3:
|
||||
@@ -776,12 +777,12 @@ class Profile(object):
|
||||
bed_temp = 0
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
bed_temp = self.get_float("print_bed_temperature")
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in without_comments
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M140 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp)
|
||||
|
||||
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
|
||||
if temp > 0 and not "{print_temperature}" in without_comments:
|
||||
if extruder_count > 0:
|
||||
def temp_line(temp, extruder, param, template):
|
||||
t = temp
|
||||
|
||||
@@ -181,6 +181,15 @@ $(function() {
|
||||
self.uploadDialog.modal("hide");
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
self.uploadBusy(false);
|
||||
new PNotify({
|
||||
title: gettext("Profile import failed"),
|
||||
text: gettext("Could not import the provided profile, it might be invalid. Check <code>octoprint.log</code> for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -194,8 +194,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
params["txtRecord"] = pybonjour.TXTRecord(txt_record)
|
||||
|
||||
key = (reg_type, port)
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
|
||||
|
||||
counter = 1
|
||||
while True:
|
||||
try:
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self._logger.info(u"Registered '{name}' for {regtype}".format(**params))
|
||||
return True
|
||||
except pybonjour.BonjourError as be:
|
||||
if be.errorCode == pybonjour.kDNSServiceErr_NameConflict:
|
||||
# Name already registered by different service, let's try a counter postfix. See #2852
|
||||
counter += 1
|
||||
params["name"] = u"{} ({})".format(name, counter)
|
||||
else:
|
||||
raise
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
@@ -653,7 +665,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
|
||||
interface_address = octoprint.util.address_for_client(*address)
|
||||
if not interface_address:
|
||||
self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
self._logger.warning("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
continue
|
||||
message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
sock.sendto(message, address)
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import flask
|
||||
import flask_login
|
||||
from flask_babel import gettext
|
||||
|
||||
from collections import defaultdict
|
||||
import threading
|
||||
import json
|
||||
|
||||
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
MAX_BACKLOG_LEN = 100
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._message_backlog = defaultdict(list)
|
||||
self._message_backlog_mutex = threading.RLock()
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/viewmodel.js"]
|
||||
)
|
||||
|
||||
def will_handle_ui(self, request):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return False
|
||||
|
||||
from octoprint.server.util.flask import passive_login
|
||||
|
||||
result = passive_login()
|
||||
if hasattr(result, "status_code") and result.status_code == 200:
|
||||
try:
|
||||
data = json.loads(result.data)
|
||||
if "name" in data:
|
||||
# passive login successful, no need to handle that
|
||||
return False
|
||||
except:
|
||||
self._logger.exception("Error while trying to decode passive login response")
|
||||
|
||||
return True
|
||||
|
||||
def on_ui_render(self, now, request, render_kwargs):
|
||||
from flask import render_template, make_response
|
||||
|
||||
"""
|
||||
Support theming of the login dialog, just in case the core UI is themed as well.
|
||||
|
||||
Example usage by a plugin:
|
||||
|
||||
def forcelogin_theming():
|
||||
from flask import url_for
|
||||
return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.forcelogin.theming": forcelogin_theming
|
||||
}
|
||||
|
||||
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
|
||||
url_for like in the example above to be prepared for any configured prefix URLs.
|
||||
"""
|
||||
additional_assets = []
|
||||
for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
|
||||
try:
|
||||
assets = hook()
|
||||
if isinstance(assets, (tuple, list)):
|
||||
additional_assets += assets
|
||||
except:
|
||||
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name))
|
||||
|
||||
render_kwargs.update(dict(forcelogin_theming=additional_assets))
|
||||
return make_response(render_template("forcelogin_index.jinja2", **render_kwargs))
|
||||
|
||||
def get_ui_custom_tracked_files(self):
|
||||
from os.path import join as opj
|
||||
|
||||
paths = [opj("static", "css", "forcelogin.css"),
|
||||
opj("static", "js", "main.js"),
|
||||
opj("static", "js", "viewmodel.js"),
|
||||
opj("static", "less", "forcelogin.less"),
|
||||
opj("templates", "parts", "forcelogin_css.jinja2"),
|
||||
opj("templates", "parts", "forcelogin_javascripts.jinja2"),
|
||||
opj("templates", "forcelogin_index.jinja2")]
|
||||
|
||||
return [opj(self._basefolder, path) for path in paths]
|
||||
|
||||
def get_ui_preemptive_caching_enabled(self):
|
||||
return False
|
||||
|
||||
def get_before_request_handlers(self):
|
||||
def check_login_required():
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return
|
||||
|
||||
if flask.request.endpoint in ("api.login",):
|
||||
return
|
||||
|
||||
user = flask_login.current_user
|
||||
if user is None or user.is_anonymous or not user.is_active:
|
||||
return flask.make_response("Forbidden", 403)
|
||||
|
||||
return [check_login_required]
|
||||
|
||||
def access_validator(self, request):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return
|
||||
|
||||
import tornado.web
|
||||
from octoprint.server.util.flask import get_flask_user_from_request
|
||||
|
||||
user = get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated():
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
def socket_register_validator(self, socket, user):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return True
|
||||
|
||||
return user is not None and not user.is_anonymous and user.is_active
|
||||
|
||||
def socket_authed(self, socket, user):
|
||||
with self._message_backlog_mutex:
|
||||
backlog = self._message_backlog.pop(socket, [])
|
||||
|
||||
if len(backlog):
|
||||
for message, payload in backlog:
|
||||
socket._do_emit(message, payload)
|
||||
self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog)))
|
||||
|
||||
def socket_emit_validator(self, socket, user, message, payload):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return True
|
||||
|
||||
if message in ("connected", "reauthRequired"):
|
||||
return True
|
||||
|
||||
if user is not None and not user.is_anonymous and user.is_active:
|
||||
return True
|
||||
|
||||
with self._message_backlog_mutex:
|
||||
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
|
||||
self._message_backlog[socket].append((message, payload))
|
||||
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
|
||||
else:
|
||||
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
|
||||
|
||||
return False
|
||||
|
||||
|
||||
__plugin_name__ = "Force Login"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Forces users to login, disables read-only mode."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your "
|
||||
"OctoPrint instance. Only disable this if you are comfortable with this, your "
|
||||
"OctoPrint instance is not publicly reachable on the internet and you fully "
|
||||
"trust everyone who has access to your local network!")
|
||||
|
||||
__plugin_implementation__ = ForceLoginPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
|
||||
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
|
||||
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
|
||||
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
|
||||
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Will get included into the login dialog, NOT into the regular OctoPrint
|
||||
* web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
var overlayElement = $("#login-overlay");
|
||||
var errorElement = $("#login-error");
|
||||
var offlineElement = $("#login-offline");
|
||||
var buttonElement = $("#login-button");
|
||||
var reconnectElement = $("#login-reconnect");
|
||||
|
||||
buttonElement.click(function() {
|
||||
var usernameElement = $("#login-user");
|
||||
var passwordElement = $("#login-password");
|
||||
var rememberElement = $("#login-remember");
|
||||
|
||||
var username = usernameElement.val();
|
||||
var password = passwordElement.val();
|
||||
var remember = rememberElement.checked;
|
||||
|
||||
overlayElement.addClass("in");
|
||||
errorElement.removeClass("in");
|
||||
|
||||
OctoPrint.browser.login(username, password, remember)
|
||||
.done(function() {
|
||||
location.reload();
|
||||
})
|
||||
.fail(function() {
|
||||
usernameElement.val("");
|
||||
passwordElement.val("");
|
||||
|
||||
overlayElement.removeClass("in");
|
||||
errorElement.addClass("in");
|
||||
});
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
var OctoPrint = window.OctoPrint;
|
||||
|
||||
OctoPrint.options.baseurl = BASE_URL;
|
||||
|
||||
OctoPrint.socket.onMessage("connected", function(data) {
|
||||
var payload = data.data;
|
||||
OctoPrint.options.apikey = payload.apikey;
|
||||
|
||||
// update the API key directly in jquery's ajax options too,
|
||||
// to ensure the fileupload plugin and any plugins still using
|
||||
// $.ajax directly still work fine too
|
||||
UI_API_KEY = payload["apikey"];
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
});
|
||||
|
||||
OctoPrint.socket.onConnected = function() {
|
||||
buttonElement.prop("disabled", false);
|
||||
offlineElement.removeClass("in");
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function() {
|
||||
buttonElement.prop("disabled", true);
|
||||
offlineElement.addClass("in");
|
||||
};
|
||||
|
||||
reconnectElement.click(function() {
|
||||
OctoPrint.socket.reconnect();
|
||||
});
|
||||
|
||||
OctoPrint.socket.connect();
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* View model that takes care to redirect to / on logout in the regular
|
||||
* OctoPrint web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
function ForceLoginViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([ForceLoginViewModel, [], []]);
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
body {
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.form-signin {
|
||||
max-width: 300px;
|
||||
padding: 19px 29px 29px;
|
||||
margin: 0 auto 20px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #e5e5e5;
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
|
||||
.form-signin-heading, .checkbox {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
input[type="text"], input[type="password"] {
|
||||
font-size: 16px;
|
||||
height: auto;
|
||||
margin-bottom: 15px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
}
|
||||
|
||||
#login-error,
|
||||
#login-offline {
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
#login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.background {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #000000;
|
||||
filter:alpha(opacity=50);
|
||||
-moz-opacity:0.5;
|
||||
-khtml-opacity: 0.5;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
|
||||
.outer {
|
||||
display: table;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.inner {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
|
||||
.content {
|
||||
text-align: center;
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>OctoPrint Login</title>
|
||||
|
||||
{% include "parts/forcelogin_css.jinja2" %}
|
||||
|
||||
{% include "parts/forcelogin_javascripts.jinja2" %}
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin">
|
||||
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
|
||||
|
||||
<div id="login-error" class="alert alert-error">{{ _('Incorrect username or password.') }}</div>
|
||||
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
|
||||
|
||||
<input type="text" id="login-user" class="input-block-level" placeholder="{{ _('Username') }}">
|
||||
<input type="password" id="login-password" class="input-block-level" placeholder="{{ _('Password') }}">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="login-remember"> {{ _('Remember me') }}
|
||||
</label>
|
||||
<button class="btn btn-block btn-large btn-primary" id="login-button" type="submit">{{ _('Log in') }}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="login-overlay">
|
||||
<div class="background"></div>
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<i class="fa fa-spinner fa-spin fa-4x"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,10 @@
|
||||
<!-- le CSS -->
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("plugin.forcelogin.static", filename="css/forcelogin.css") }}">
|
||||
|
||||
{% for url in forcelogin_theming %}
|
||||
<link rel="stylesheet" href="{{ url }}">
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,15 @@
|
||||
<!-- le javascript -->
|
||||
|
||||
<script>
|
||||
var BASE_URL = "{{ url_for('index') }}";
|
||||
</script>
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
{% assets "js_client" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
<script src="{{ url_for("plugin.forcelogin.static", filename="js/main.js") }}"></script>
|
||||
@@ -8,7 +8,7 @@ import octoprint.plugin
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import redirect_to_tornado, require_firstrun
|
||||
from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
@@ -18,6 +18,7 @@ from werkzeug.utils import secure_filename
|
||||
from werkzeug.exceptions import BadRequest
|
||||
import yaml
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
try:
|
||||
@@ -41,7 +42,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
]
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_all(self):
|
||||
files = self._getLogFiles()
|
||||
@@ -52,7 +53,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
setup=dict(loggers=loggers, levels=levels))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_log_files(self):
|
||||
files = self._getLogFiles()
|
||||
@@ -60,13 +61,13 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return jsonify(files=files, free=free, total=total)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def download_log(self, filename):
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def delete_log(self, filename):
|
||||
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
|
||||
@@ -78,7 +79,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_logging_setup(self):
|
||||
loggers = self._get_available_loggers()
|
||||
@@ -86,13 +87,13 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return jsonify(loggers=loggers, levels=levels)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_logging_levels_api(self):
|
||||
return jsonify(self._get_logging_levels())
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def set_logging_levels_api(self):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
@@ -145,7 +146,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
with open(logging_file, "r") as f:
|
||||
with io.open(logging_file, 'rt', encoding='utf-8') as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
return config_from_file
|
||||
|
||||
@@ -208,6 +209,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/logging.js"],
|
||||
clientjs=["clientjs/logging.js"],
|
||||
less=["less/logging.less"],
|
||||
css=["css/logging.css"])
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
|
||||
var OctoPrintLoggingClient = function(base) {
|
||||
this.base = base;
|
||||
|
||||
this.baseUrl = this.base.getBlueprintUrl("logging");
|
||||
this.logsUrl = this.baseUrl + "logs";
|
||||
this.setupUrl = this.baseUrl + "setup";
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.baseUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.listLogs = function(opts) {
|
||||
return this.base.get(this.logsUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) {
|
||||
var fileUrl = this.logsUrl + "/" + file;
|
||||
return this.base.delete(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) {
|
||||
var fileUrl = this.logsUrl + "/" + file;
|
||||
return this.base.download(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) {
|
||||
return this.base.putJson(this.setupUrl + "/levels", config, opts);
|
||||
};
|
||||
|
||||
//~~ wrapper for backwards compatibility
|
||||
|
||||
var DeprecatedOctoPrintLogsClient = function(base) {
|
||||
this.base = base;
|
||||
this.wrapped = this.base.plugins.logging;
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.list = function(opts) {
|
||||
log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead");
|
||||
return this.wrapped.listLogs(opts);
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) {
|
||||
log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead");
|
||||
return this.wrapped.deleteLog(file, opts);
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) {
|
||||
log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead");
|
||||
return this.wrapped.downloadLog(file, opts);
|
||||
};
|
||||
|
||||
// register plugin component
|
||||
OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient);
|
||||
|
||||
// also register deprecated client under old endpoint
|
||||
OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient);
|
||||
|
||||
return OctoPrintLoggingClient;
|
||||
});
|
||||
@@ -1,72 +1,3 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
|
||||
var OctoPrintLoggingClient = function(base) {
|
||||
this.base = base;
|
||||
|
||||
this.baseUrl = this.base.getBlueprintUrl("logging");
|
||||
this.logsUrl = this.baseUrl + "logs";
|
||||
this.setupUrl = this.baseUrl + "setup";
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.baseUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.listLogs = function(opts) {
|
||||
return this.base.get(this.logsUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) {
|
||||
var fileUrl = this.logsUrl + "/" + file;
|
||||
return this.base.delete(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) {
|
||||
var fileUrl = this.logsUrl + "/" + file;
|
||||
return this.base.download(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) {
|
||||
return this.base.putJson(this.setupUrl + "/levels", config, opts);
|
||||
};
|
||||
|
||||
//~~ wrapper for backwards compatibility
|
||||
|
||||
var DeprecatedOctoPrintLogsClient = function(base) {
|
||||
this.base = base;
|
||||
this.wrapped = this.base.plugins.logging;
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.list = function(opts) {
|
||||
log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead");
|
||||
return this.wrapped.listLogs(opts);
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) {
|
||||
log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead");
|
||||
return this.wrapped.deleteLog(file, opts);
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) {
|
||||
log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead");
|
||||
return this.wrapped.downloadLog(file, opts);
|
||||
};
|
||||
|
||||
// register plugin component
|
||||
OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient);
|
||||
|
||||
// also register deprecated client under old endpoint
|
||||
OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient);
|
||||
|
||||
return OctoPrintLoggingClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function LoggingViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -5,6 +5,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import flask
|
||||
import io
|
||||
import os
|
||||
import sarge
|
||||
|
||||
@@ -35,10 +36,9 @@ _FLAG_PAST_UNDERVOLTAGE = 1 << 16
|
||||
_FLAG_PAST_FREQ_CAPPED = 1 << 17
|
||||
_FLAG_PAST_THROTTLED = 1 << 18
|
||||
|
||||
|
||||
class ThrottleState(object):
|
||||
@classmethod
|
||||
def from_value(cls, value):
|
||||
def from_value(cls, value=0):
|
||||
if value == 0:
|
||||
return ThrottleState()
|
||||
|
||||
@@ -47,10 +47,12 @@ class ThrottleState(object):
|
||||
throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED,
|
||||
past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
|
||||
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)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self._raw_value = kwargs.get('raw_value', -1)
|
||||
self._undervoltage = False
|
||||
self._freq_capped = False
|
||||
self._throttled = False
|
||||
@@ -111,7 +113,8 @@ class ThrottleState(object):
|
||||
and self._past_throttled == other._past_throttled
|
||||
|
||||
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,
|
||||
current_overheat=self.current_overheat,
|
||||
past_overheat=self.past_overheat,
|
||||
@@ -124,7 +127,7 @@ def get_proc_dt_model():
|
||||
global _proc_dt_model
|
||||
|
||||
if _proc_dt_model is None:
|
||||
with open(_PROC_DT_MODEL_PATH, "r") as f:
|
||||
with io.open(_PROC_DT_MODEL_PATH, 'rt', encoding='utf-8') as f:
|
||||
_proc_dt_model = f.readline().strip(" \t\r\n\0")
|
||||
|
||||
return _proc_dt_model
|
||||
@@ -150,7 +153,7 @@ def get_octopi_version():
|
||||
global _octopi_version
|
||||
|
||||
if _octopi_version is None:
|
||||
with open(_OCTOPI_VERSION_PATH, "r") as f:
|
||||
with io.open(_OCTOPI_VERSION_PATH, 'rt', encoding='utf-8') as f:
|
||||
_octopi_version = f.readline().strip(" \t\r\n\0")
|
||||
|
||||
return _octopi_version
|
||||
@@ -193,6 +196,7 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/pi_support.js"],
|
||||
clientjs=["clientjs/pi_support.js"],
|
||||
css=["css/pi_support.css"]
|
||||
)
|
||||
|
||||
@@ -241,6 +245,16 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
def _check_throttled_state_condition(self):
|
||||
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):
|
||||
command = self._settings.get(["vcgencmd_throttle_check_command"])
|
||||
|
||||
@@ -273,10 +287,11 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \
|
||||
"CPU and GPU."
|
||||
|
||||
self._logger.warn(message)
|
||||
self._logger.warning(message)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
|
||||
state=self._throttle_state.as_dict()))
|
||||
self._event_bus.fire("plugin_pi_support_throttle_state", self._throttle_state.as_dict())
|
||||
|
||||
|
||||
__plugin_name__ = "Pi Support Plugin"
|
||||
@@ -298,5 +313,9 @@ def __plugin_check__():
|
||||
return "raspberry pi" in proc_dt_model.lower()
|
||||
|
||||
def __plugin_load__():
|
||||
plugin = PiSupportPlugin()
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = PiSupportPlugin()
|
||||
__plugin_implementation__ = plugin
|
||||
|
||||
global __plugin_helpers__
|
||||
__plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state)
|
||||
@@ -0,0 +1,19 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPiSupportClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPiSupportClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
|
||||
return OctoPrintPiSupportClient;
|
||||
});
|
||||
|
||||
@@ -1,22 +1,3 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPiSupportClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPiSupportClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
|
||||
return OctoPrintPiSupportClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
|
||||
function PiSupportViewModel(parameters) {
|
||||
@@ -46,7 +27,7 @@ $(function() {
|
||||
|
||||
var octoPrintVersion = $(".footer span.version");
|
||||
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);
|
||||
})
|
||||
};
|
||||
@@ -60,11 +41,34 @@ $(function() {
|
||||
self.pastIssue(state.past_issue);
|
||||
};
|
||||
|
||||
self.issuePopoverContent = 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>"
|
||||
+ "<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>"
|
||||
+ "<p>" + gettext("A blinking icon indicates an acute issue!") + "</p>"
|
||||
};
|
||||
self.popoverContent = ko.pureComputed(function() {
|
||||
var undervoltageParagraphClasses = "muted";
|
||||
var undervoltageSymbolClasses = "";
|
||||
|
||||
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.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: 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>
|
||||
@@ -11,15 +11,16 @@ import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import get_os
|
||||
from octoprint.util.platform import get_os, is_os_compatible
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask_babel import gettext
|
||||
|
||||
import io
|
||||
import logging
|
||||
import sarge
|
||||
import sys
|
||||
@@ -33,6 +34,35 @@ import threading
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = copy.deepcopy(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True
|
||||
)
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(
|
||||
entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
|
||||
result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"])
|
||||
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(
|
||||
entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"])
|
||||
|
||||
return result
|
||||
|
||||
|
||||
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
|
||||
success_string = "Successfully installed"
|
||||
failure_string = "Could not install"
|
||||
|
||||
|
||||
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
@@ -155,6 +185,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/pluginmanager.js"],
|
||||
clientjs=["clientjs/pluginmanager.js"],
|
||||
css=["css/pluginmanager.css"],
|
||||
less=["less/pluginmanager.less"]
|
||||
)
|
||||
@@ -183,7 +214,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403)
|
||||
def upload_archive(self):
|
||||
import flask
|
||||
@@ -216,7 +247,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
try:
|
||||
os.remove(archive.name)
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
|
||||
self._logger.warning("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
@@ -358,10 +389,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing=dict())
|
||||
|
||||
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
|
||||
success_string = "Successfully installed"
|
||||
failure_string = "Could not install"
|
||||
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
|
||||
@@ -448,7 +475,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after)
|
||||
if new_plugin is None:
|
||||
self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to "
|
||||
self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to "
|
||||
"initialize properly during runtime. Please restart OctoPrint.")
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
@@ -504,7 +531,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return make_response("Bundled plugins cannot be uninstalled", 403)
|
||||
|
||||
if plugin.origin is None:
|
||||
self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals()))
|
||||
self._logger.warning(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals()))
|
||||
return make_response("Could not uninstall plugin, its origin is unknown")
|
||||
|
||||
if plugin.origin.type == "entry_point":
|
||||
@@ -539,7 +566,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
os.remove(pyc_file)
|
||||
|
||||
else:
|
||||
self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals()))
|
||||
self._logger.warning(u"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals()))
|
||||
return make_response("Could not uninstall plugin, its origin is unknown")
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
@@ -758,7 +785,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if mtime + self._repository_cache_ttl >= time.time() > mtime:
|
||||
try:
|
||||
import json
|
||||
with open(self._repository_cache_path) as f:
|
||||
with io.open(self._repository_cache_path, 'rt', encoding='utf-8') as f:
|
||||
repo_data = json.load(f)
|
||||
self._logger.info("Loaded plugin repository data from disk, was still valid")
|
||||
except:
|
||||
@@ -784,7 +811,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
try:
|
||||
import json
|
||||
with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f:
|
||||
with octoprint.util.atomic_write(self._repository_cache_path, 'wb') as f:
|
||||
json.dump(repo_data, f)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
|
||||
@@ -797,31 +824,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if repo_data is None:
|
||||
return False
|
||||
|
||||
current_os = get_os()
|
||||
octoprint_version = get_octoprint_version(base=True)
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = copy.deepcopy(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True
|
||||
)
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
|
||||
result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"],
|
||||
octoprint_version=octoprint_version)
|
||||
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
|
||||
|
||||
return result
|
||||
|
||||
self._repository_plugins = list(map(map_repository_entry, repo_data))
|
||||
self._repository_plugins = map(map_repository_entry, repo_data)
|
||||
return True
|
||||
|
||||
def _fetch_notices_from_disk(self):
|
||||
@@ -832,7 +835,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if mtime + self._notices_cache_ttl >= time.time() > mtime:
|
||||
try:
|
||||
import json
|
||||
with open(self._notices_cache_path) as f:
|
||||
with io.open(self._notices_cache_path, 'rt', encoding='utf-8') as f:
|
||||
notice_data = json.load(f)
|
||||
self._logger.info("Loaded notice data from disk, was still valid")
|
||||
except:
|
||||
@@ -881,7 +884,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
parsed_date = dateutil.parser.parse(notice["date"])
|
||||
notice["timestamp"] = parsed_date.timetuple()
|
||||
except Exception as e:
|
||||
self._logger.warn("Error while parsing date {!r} for plugin notice "
|
||||
self._logger.warning("Error while parsing date {!r} for plugin notice "
|
||||
"of plugin {}, ignoring notice: {}".format(notice["date"], key, str(e)))
|
||||
continue
|
||||
|
||||
@@ -892,30 +895,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._notices = notices
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _is_os_compatible(current_os, compatibility_entries):
|
||||
"""
|
||||
Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries``
|
||||
"""
|
||||
if len(compatibility_entries) == 0:
|
||||
# shortcut - no compatibility info means we are compatible
|
||||
return True
|
||||
|
||||
negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries))
|
||||
positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries)
|
||||
|
||||
negative_match = False
|
||||
if negative_entries:
|
||||
# check if we are blacklisted
|
||||
negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries))
|
||||
|
||||
positive_match = True
|
||||
if positive_entries:
|
||||
# check if we are whitelisted
|
||||
positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries))
|
||||
|
||||
return positive_match and not negative_match
|
||||
|
||||
@property
|
||||
def _reconnect_hooks(self):
|
||||
reconnect_hooks = self.__class__.RECONNECT_HOOKS
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPluginManagerClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
|
||||
var refresh_repo, refresh_notices;
|
||||
if (_.isPlainObject(refresh)) {
|
||||
refresh_repo = refresh.repo || false;
|
||||
refresh_notices = refresh.notices || false;
|
||||
} else {
|
||||
refresh_repo = refresh;
|
||||
refresh_notices = false;
|
||||
}
|
||||
|
||||
var query = [];
|
||||
if (refresh_repo) query.push("refresh_repository=true");
|
||||
if (refresh_notices) query.push("refresh_notices=true");
|
||||
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
|
||||
return this.get(true, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) {
|
||||
return this.get(false, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) {
|
||||
var data = {
|
||||
url: pluginUrl,
|
||||
dependency_links: !!dependencyLinks
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
|
||||
var data = {
|
||||
url: pluginUrl,
|
||||
dependency_links: !!dependencyLinks,
|
||||
reinstall: plugin,
|
||||
force: true
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.upload = function(file) {
|
||||
return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
|
||||
return OctoPrintPluginManagerClient;
|
||||
});
|
||||
@@ -1,86 +1,3 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPluginManagerClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
|
||||
var refresh_repo, refresh_notices;
|
||||
if (_.isPlainObject(refresh)) {
|
||||
refresh_repo = refresh.repo || false;
|
||||
refresh_notices = refresh.notices || false;
|
||||
} else {
|
||||
refresh_repo = refresh;
|
||||
refresh_notices = false;
|
||||
}
|
||||
|
||||
var query = [];
|
||||
if (refresh_repo) query.push("refresh_repository=true");
|
||||
if (refresh_notices) query.push("refresh_notices=true");
|
||||
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
|
||||
return this.get(true, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) {
|
||||
return this.get(false, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) {
|
||||
var data = {
|
||||
url: pluginUrl,
|
||||
dependency_links: !!dependencyLinks
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
|
||||
var data = {
|
||||
url: pluginUrl,
|
||||
dependency_links: !!dependencyLinks,
|
||||
reinstall: plugin,
|
||||
force: true
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.upload = function(file) {
|
||||
return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
|
||||
return OctoPrintPluginManagerClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function PluginManagerViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -26,32 +26,43 @@ Learn more at https://faq.octoprint.org/warning-{warning_type}
|
||||
"""
|
||||
|
||||
# Anet A8
|
||||
ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_")
|
||||
ANETA8_M115_TEST = ("aneta8", lambda name, data: name and name.lower().startswith("anet_a8_"))
|
||||
|
||||
# Anycubic MEGA
|
||||
ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower()
|
||||
ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower()
|
||||
ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower())
|
||||
ANYCUBIC_RECEIVED_TEST = ("anycubic", lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower()))
|
||||
|
||||
# Creality CR-10s
|
||||
CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower()
|
||||
CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower()
|
||||
CR10S_RECEIVED_TEST = ("cr10s", lambda line: line and CR10S_AUTHOR in line.lower())
|
||||
|
||||
# Malyan M200 aka Monoprice Select Mini
|
||||
MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200"
|
||||
# Creality Ender 3
|
||||
ENDER3_AUTHOR = " | Author: (Ender3)".lower()
|
||||
ENDER3_RECEIVED_TEST = ("ender3", lambda line: line and ENDER3_AUTHOR in line.lower())
|
||||
|
||||
# iMe on Micro3D
|
||||
IME_M115_TEST = ("ime", lambda name, data: name and name.lower().startswith("ime"))
|
||||
|
||||
# Malyan M200 aka Monoprice Select Mini, versions less than 4.0
|
||||
MALYANM200_M115_TEST = ("malyan_m200", lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" and get_comparable_version(data.get("VER", "0")) < get_comparable_version("4.0"))
|
||||
|
||||
# Stock Micro3D
|
||||
MICRO3D_M115_TEST = ("micro3d", lambda name, data: name and name.lower().startswith("micro3d"))
|
||||
|
||||
# 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 = ("repetier_before_092", 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"))
|
||||
|
||||
# THERMAL_PROTECTION capability reported as disabled
|
||||
THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled
|
||||
THERMAL_PROTECTION_CAP_TEST = ("capability", lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled)
|
||||
|
||||
SAFETY_CHECKS = {
|
||||
"firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST, REPETIER_BEFORE_092_M115_TEST),
|
||||
received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST),
|
||||
"firmware-unsafe": dict(m115=(ANETA8_M115_TEST, IME_M115_TEST, MALYANM200_M115_TEST, MICRO3D_M115_TEST,
|
||||
REPETIER_BEFORE_092_M115_TEST),
|
||||
received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST, ENDER3_RECEIVED_TEST),
|
||||
cap=(THERMAL_PROTECTION_CAP_TEST,),
|
||||
message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \
|
||||
u"thermal runaway protection). This is a fire risk.")
|
||||
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."))
|
||||
}
|
||||
|
||||
def extract_repetier_version(name):
|
||||
@@ -91,6 +102,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=("js/printer_safety_check.js",),
|
||||
clientjs=("clientjs/printer_safety_check.js",),
|
||||
css=("css/printer_safety_check.css",),
|
||||
less=("less/printer_safety_check.less",))
|
||||
|
||||
@@ -147,9 +159,14 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
|
||||
if not checks or not message:
|
||||
continue
|
||||
|
||||
if any(x(*args, **kwargs) for x in checks):
|
||||
self._register_warning(warning_type, message)
|
||||
changes = True
|
||||
for check_name, check in checks:
|
||||
if check(*args, **kwargs):
|
||||
self._register_warning(warning_type, message)
|
||||
self._event_bus.fire("plugin_printer_safety_check_warning", dict(check_type=check_type,
|
||||
check_name=check_name,
|
||||
warning_type=warning_type))
|
||||
changes = True
|
||||
break
|
||||
|
||||
if changes:
|
||||
self._ping_clients()
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPrinterSafetyCheckClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient);
|
||||
return OctoPrintPrinterSafetyCheckClient;
|
||||
});
|
||||
@@ -1,22 +1,3 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPrinterSafetyCheckClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient);
|
||||
return OctoPrintPrinterSafetyCheckClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function PrinterSafetyCheckViewModel(parameters) {
|
||||
var self = this;
|
||||
@@ -43,7 +24,7 @@ $(function() {
|
||||
self.fromResponse = function(data) {
|
||||
var warnings = [];
|
||||
_.each(data, function(message, warning_type) {
|
||||
warnings.push({type: warning_type, message: message});
|
||||
warnings.push({type: warning_type, message: gettext(message)});
|
||||
});
|
||||
self.warnings(warnings);
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import io
|
||||
import copy
|
||||
import flask
|
||||
import os
|
||||
@@ -24,13 +25,21 @@ from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import VERSION, REVISION, BRANCH
|
||||
from octoprint.access import USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util import dict_merge, to_unicode
|
||||
from octoprint.util.version import get_comparable_version
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
import octoprint.settings
|
||||
|
||||
|
||||
MINIMUM_PYTHON = "2.7.9"
|
||||
MINIMUM_SETUPTOOLS = "5.5.1"
|
||||
MINIMUM_PIP = "9.0.1"
|
||||
|
||||
|
||||
##~~ Plugin
|
||||
|
||||
class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
@@ -43,7 +52,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
|
||||
DATA_FORMAT_VERSION = "v3"
|
||||
DATA_FORMAT_VERSION = "v4"
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
@@ -62,6 +71,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = None
|
||||
|
||||
self._environment_supported = True
|
||||
self._environment_versions = dict()
|
||||
self._environment_ready = threading.Event()
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
def initialize(self):
|
||||
@@ -104,14 +117,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._console_logger.propagate = False
|
||||
|
||||
def on_after_startup(self):
|
||||
# refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from
|
||||
# the server startup
|
||||
def fetch_data():
|
||||
self.get_current_versions()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
self._check_environment()
|
||||
self.get_current_versions()
|
||||
|
||||
def _get_configured_checks(self):
|
||||
with self._configured_checks_mutex:
|
||||
@@ -121,6 +128,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||
check_providers = self._settings.get(["check_providers"], merged=True)
|
||||
if not isinstance(check_providers, dict):
|
||||
check_providers = dict()
|
||||
|
||||
effective_configs = dict()
|
||||
|
||||
for name, hook in update_check_hooks.items():
|
||||
@@ -132,9 +142,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
for key, default_config in hook_checks.items():
|
||||
if key in effective_configs or key == "octoprint":
|
||||
if key == name:
|
||||
self._logger.warn("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook")))
|
||||
self._logger.warning("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook")))
|
||||
else:
|
||||
self._logger.warn("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key))
|
||||
self._logger.warning("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key))
|
||||
continue
|
||||
|
||||
check_providers[key] = name
|
||||
@@ -159,7 +169,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if effective_config:
|
||||
effective_configs[key] = effective_config
|
||||
else:
|
||||
self._logger.warn("Update for {} is empty or None, ignoring it".format(key))
|
||||
self._logger.warning("Update for {} is empty or None, ignoring it".format(key))
|
||||
|
||||
# finally set all our internal representations to our processed results
|
||||
for key, config in effective_configs.items():
|
||||
@@ -181,13 +191,31 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
return self._configured_checks
|
||||
|
||||
def _check_environment(self):
|
||||
from platform import python_version
|
||||
import pkg_resources
|
||||
|
||||
local_pip = LocalPipCaller()
|
||||
|
||||
# check python and setuptools version
|
||||
versions = dict(python=python_version(),
|
||||
setuptools=pkg_resources.get_distribution("setuptools").version,
|
||||
pip=local_pip.version_string)
|
||||
supported = get_comparable_version(versions["python"]) >= get_comparable_version(MINIMUM_PYTHON) \
|
||||
and get_comparable_version(versions["setuptools"]) >= get_comparable_version(MINIMUM_SETUPTOOLS) \
|
||||
and get_comparable_version(versions["pip"]) >= get_comparable_version(MINIMUM_PIP)
|
||||
|
||||
self._environment_supported = supported
|
||||
self._environment_versions = versions
|
||||
self._environment_ready.set()
|
||||
|
||||
def _load_version_cache(self):
|
||||
if not os.path.isfile(self._version_cache_path):
|
||||
return
|
||||
|
||||
import yaml
|
||||
try:
|
||||
with open(self._version_cache_path) as f:
|
||||
with io.open(self._version_cache_path, 'rt', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f)
|
||||
timestamp = os.stat(self._version_cache_path).st_mtime
|
||||
except:
|
||||
@@ -489,7 +517,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
#~~ BluePrint API
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403)
|
||||
def check_for_update(self):
|
||||
if "check" in flask.request.values:
|
||||
@@ -500,11 +528,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
force = flask.request.values.get("force", "false") in octoprint.settings.valid_boolean_trues
|
||||
|
||||
def view():
|
||||
self._environment_ready.wait(timeout=30.0)
|
||||
|
||||
try:
|
||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||
return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible and self._environment_supported else "updateAvailable" if update_available else "current",
|
||||
information=information,
|
||||
timestamp=self._version_cache_timestamp))
|
||||
timestamp=self._version_cache_timestamp,
|
||||
environment=dict(supported=self._environment_supported,
|
||||
versions=[dict(name=gettext("Python"), current=self._environment_versions.get("python", "unknown"), minimum=MINIMUM_PYTHON),
|
||||
dict(name=gettext("pip"), current=self._environment_versions.get("pip", "unknown"), minimum=MINIMUM_PIP),
|
||||
dict(name=gettext("setuptools"), current=self._environment_versions.get("setuptools", "unknown"), minimum=MINIMUM_SETUPTOOLS)])))
|
||||
except exceptions.ConfigurationInvalid as e:
|
||||
return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
|
||||
|
||||
@@ -531,6 +565,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(str(data.get("online", None)))
|
||||
|
||||
hash.update(",".join(targets))
|
||||
|
||||
hash.update(str(self._environment_supported))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
hash.update(str(self._connectivity_checker.online))
|
||||
hash.update(str(self._update_in_progress))
|
||||
@@ -546,13 +582,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
|
||||
def perform_update(self):
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
# do not update while a print job is running
|
||||
return flask.make_response("Printer is currently printing or paused", 409)
|
||||
|
||||
if not self._environment_supported:
|
||||
return flask.make_response("Direct updates are not supported in this Python environment", 409)
|
||||
|
||||
if not "application/json" in flask.request.headers["Content-Type"]:
|
||||
return flask.make_response("Expected content-type JSON", 400)
|
||||
|
||||
@@ -579,6 +618,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
return dict(
|
||||
css=["css/softwareupdate.css"],
|
||||
js=["js/softwareupdate.js"],
|
||||
clientjs=["clientjs/softwareupdate.js"],
|
||||
less=["less/softwareupdate.less"]
|
||||
)
|
||||
|
||||
@@ -648,7 +688,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
future = executor.submit(self._get_current_version, target, populated_check, force=force)
|
||||
futures_to_result[future] = (target, populated_check)
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target,
|
||||
self._logger.warning("Unknown update check type for target {}: {}".format(target,
|
||||
check.get("type",
|
||||
"<n/a>")))
|
||||
continue
|
||||
@@ -665,6 +705,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
continue
|
||||
|
||||
target_information, target_update_available, target_update_possible, target_online, target_error = future.result()
|
||||
target_update_possible = target_update_possible and self._environment_supported
|
||||
|
||||
target_information = dict_merge(dict(local=dict(name="?", value="?"),
|
||||
remote=dict(name="?", value="?",
|
||||
@@ -763,11 +804,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
update_possible = False
|
||||
information["needs_online"] = True
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown check type %s for %s" % (check["type"], target))
|
||||
self._logger.warning("Unknown check type %s for %s" % (check["type"], target))
|
||||
update_possible = False
|
||||
error = "unknown_check"
|
||||
except exceptions.NetworkError:
|
||||
self._logger.warn("Could not check %s for updates due to a network error" % target)
|
||||
self._logger.warning("Could not check %s for updates due to a network error" % target)
|
||||
update_possible = False
|
||||
error = "network"
|
||||
except:
|
||||
@@ -798,6 +839,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
:param targets: an iterable defining the targets to update, if not supplied defaults to all targets
|
||||
"""
|
||||
|
||||
if not self._environment_supported:
|
||||
self._logger.error("Direct updates are unsupported in this environment")
|
||||
return [], dict()
|
||||
|
||||
targets = kwargs.get("targets", kwargs.get("check_targets", None))
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
@@ -911,7 +956,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
return False, None
|
||||
|
||||
if not update_possible:
|
||||
self._logger.warn("Cannot perform update for %s, update type is not fully configured" % target)
|
||||
self._logger.warning("Cannot perform update for %s, update type is not fully configured" % target)
|
||||
return False, None
|
||||
|
||||
# determine the target version to update to
|
||||
@@ -948,12 +993,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
trigger_event(True)
|
||||
|
||||
except exceptions.UnknownUpdateType:
|
||||
self._logger.warn("Update of %s can not be performed, unknown update type" % target)
|
||||
self._logger.warning("Update of %s can not be performed, unknown update type" % target)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type"))
|
||||
return False, None
|
||||
|
||||
except exceptions.CannotUpdateOffline:
|
||||
self._logger.warn("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target)
|
||||
self._logger.warning("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection"))
|
||||
|
||||
except Exception as e:
|
||||
@@ -1000,8 +1045,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
util.execute(restart_command, evaluate_returncode=False, do_async=True)
|
||||
except exceptions.ScriptError as e:
|
||||
self._logger.exception("Error while restarting via command {}".format(restart_command))
|
||||
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
|
||||
self._logger.warn("Restart stderr:\n{}".format(e.stderr))
|
||||
self._logger.warning("Restart stdout:\n{}".format(e.stdout))
|
||||
self._logger.warning("Restart stderr:\n{}".format(e.stderr))
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
|
||||
@@ -124,7 +124,8 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
if targets:
|
||||
data["check"] = targets
|
||||
|
||||
client = create_client(apikey=apikey,
|
||||
client = create_client(settings=cli_group.settings,
|
||||
apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
@@ -149,7 +150,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
plugin_message_data = plugin_message["data"]
|
||||
|
||||
if plugin_message_type == "updating":
|
||||
click.echo("Updating {} to {}...".format(plugin_message_data["name"], plugin_message_data["target"]))
|
||||
click.echo("Updating {} to {}...".format(plugin_message_data.get("name", "unknown"), plugin_message_data.get("version", "n/a")))
|
||||
|
||||
elif plugin_message_type == "update_failed":
|
||||
click.echo("\t... failed :(")
|
||||
@@ -191,9 +192,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
flags["seen_close"] = True
|
||||
click.echo("Disconnected from server...")
|
||||
|
||||
socket = client.connect_socket(on_message=on_message,
|
||||
on_open=on_open,
|
||||
on_close=on_close)
|
||||
socket = client.create_socket(on_message=on_message,
|
||||
on_open=on_open,
|
||||
on_close=on_close)
|
||||
|
||||
r = client.post_json("plugin/softwareupdate/update", data=data)
|
||||
try:
|
||||
|
||||