Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a012c41dad | ||
|
|
e5e8581f9a | ||
|
|
95a9f84b39 | ||
|
|
371f1a818f | ||
|
|
4ed5f7ed28 | ||
|
|
4eb81aae9d | ||
|
|
dafa4c97ad | ||
|
|
0268cafa90 | ||
|
|
a5caac8d38 | ||
|
|
7ca9d56327 | ||
|
|
d9323b7172 | ||
|
|
8f6d67195d | ||
|
|
342d526a51 | ||
|
|
d7c5f57c98 | ||
|
|
d89ca38ee8 | ||
|
|
cb969be403 | ||
|
|
7cb649c303 | ||
|
|
6d7d365b27 | ||
|
|
8ad720e554 | ||
|
|
37190da2d6 | ||
|
|
2746139fa6 | ||
|
|
c9f10ae723 | ||
|
|
202006149c | ||
|
|
671973062e | ||
|
|
1d15c2a176 | ||
|
|
5e490ec7fd | ||
|
|
1889a40241 | ||
|
|
6d2be1743a | ||
|
|
e9e4adf09b | ||
|
|
535ad6eae6 | ||
|
|
c4167a82c5 | ||
|
|
087a9ece2c | ||
|
|
b77380a8ac | ||
|
|
169275b052 | ||
|
|
757dfcf5c7 | ||
|
|
8e39eac207 | ||
|
|
9e48b8ab65 | ||
|
|
36b07b2337 | ||
|
|
e57c46fb67 | ||
|
|
df8226b8c5 | ||
|
|
e0943527d6 | ||
|
|
025986794f | ||
|
|
ac2354907a | ||
|
|
7b5d2e3e0c | ||
|
|
efa556a812 | ||
|
|
7f9764c386 | ||
|
|
e95e546c08 | ||
|
|
b0e7df47a6 | ||
|
|
257fc0d1cd | ||
|
|
3fe2b611bc | ||
|
|
d6c63a5cb9 | ||
|
|
ad8205c386 | ||
|
|
6efd4dfd08 | ||
|
|
469bf844ee | ||
|
|
4f58c64881 | ||
|
|
b428faacc8 | ||
|
|
4e3adcc3f3 | ||
|
|
f88147003c | ||
|
|
bbbe85f737 | ||
|
|
fc97d0b424 | ||
|
|
b054ec47ad | ||
|
|
87e7a19fdd | ||
|
|
fed257b5d8 | ||
|
|
e53ae8cd56 | ||
|
|
a9f76dd1a3 | ||
|
|
6bc5b8a7a9 | ||
|
|
cb9bedb6a0 | ||
|
|
5ff790048d | ||
|
|
f32ea65b2c | ||
|
|
1f957e1ee2 | ||
|
|
32be5ca87c | ||
|
|
8876ab0ce5 | ||
|
|
ad8910354c | ||
|
|
e8d6a9b221 | ||
|
|
f3cfe2ba48 | ||
|
|
d2ecb0a28f | ||
|
|
134ee77e4a | ||
|
|
10f3f72b9c | ||
|
|
78b6d3a5e2 | ||
|
|
a920c4fe21 | ||
|
|
52468e7e1c | ||
|
|
9112a800c8 | ||
|
|
177d235b29 | ||
|
|
2de2dc7c31 | ||
|
|
8074a06d33 | ||
|
|
75c801d63f | ||
|
|
ed07764f09 | ||
|
|
a929100889 | ||
|
|
286376321c | ||
|
|
4a36a3eed2 | ||
|
|
8bf9b8650d | ||
|
|
d6da819cd6 | ||
|
|
2fbc81604a | ||
|
|
2ca63febee | ||
|
|
224674f27e | ||
|
|
2f1d71a98c | ||
|
|
7366110f07 | ||
|
|
e5eb72cbfb | ||
|
|
b0028cd3fb | ||
|
|
2343caea30 | ||
|
|
61d037f188 | ||
|
|
2a79d9183a | ||
|
|
5dbc88b6f2 | ||
|
|
83876806db | ||
|
|
5a5785be4a | ||
|
|
25cd4f8201 | ||
|
|
2d72a52338 | ||
|
|
b5a161594d | ||
|
|
a24363c4b0 | ||
|
|
524562527e | ||
|
|
26856d052f | ||
|
|
17f8817b78 | ||
|
|
4eb1d2bf80 | ||
|
|
62120affae | ||
|
|
66b501cfaa | ||
|
|
140bf9aa5a | ||
|
|
711ca457f2 | ||
|
|
07ae4ffe14 | ||
|
|
3800b21e69 | ||
|
|
196b152ec4 | ||
|
|
970810dc92 | ||
|
|
4fec14197b | ||
|
|
b354334a2e | ||
|
|
a934750504 | ||
|
|
9dc29689f4 | ||
|
|
8518b40b5f | ||
|
|
aabd624f88 | ||
|
|
6ae88ab8c6 | ||
|
|
6251031d6e | ||
|
|
249b3f442b | ||
|
|
ff6012bb00 | ||
|
|
a137946e3a | ||
|
|
909dd551d6 | ||
|
|
687b449207 | ||
|
|
efe552264c | ||
|
|
b7e788ec1b | ||
|
|
e964d2410c | ||
|
|
09284cd9b9 | ||
|
|
4963a4b849 | ||
|
|
46e425de88 | ||
|
|
376d38e0cf | ||
|
|
2e8f543aa3 | ||
|
|
d2dfd22a2c | ||
|
|
b51cb31b46 | ||
|
|
eea1050a18 | ||
|
|
a37165d7d9 | ||
|
|
b06f804e9e | ||
|
|
d64ca79f05 | ||
|
|
490ade5e17 | ||
|
|
573503e84d | ||
|
|
9e0e4bf7b6 | ||
|
|
452645d950 | ||
|
|
d2bb731bd7 | ||
|
|
40b5c272c4 | ||
|
|
31e4df44f9 | ||
|
|
cd3c8ebbe6 | ||
|
|
59a435a787 | ||
|
|
71cc312ccc | ||
|
|
8d1ae438e5 | ||
|
|
7ebcb47955 | ||
|
|
71e60183c5 | ||
|
|
9c055137eb | ||
|
|
eaa8933782 | ||
|
|
0d330e3c5a | ||
|
|
18ed113122 | ||
|
|
48e454856c | ||
|
|
917b86655f | ||
|
|
7a2225b332 | ||
|
|
20237a73ac | ||
|
|
4a3f894064 | ||
|
|
0c9098f7bf | ||
|
|
53a2e04501 | ||
|
|
c6f5f1a0f7 | ||
|
|
1cff2581db | ||
|
|
5cf02ac9ee | ||
|
|
9559f09ec7 | ||
|
|
542edbc3e6 | ||
|
|
f82d50b0f6 | ||
|
|
e224b0ac71 | ||
|
|
68f4ecefb0 | ||
|
|
d73d930e5f | ||
|
|
8c1262dd3f | ||
|
|
792fe328ef | ||
|
|
111a37e97e | ||
|
|
c2bb234c20 | ||
|
|
2dda3a0e32 | ||
|
|
e2394446b0 | ||
|
|
1befd0ecc1 | ||
|
|
7587f34c94 | ||
|
|
6b54a15ed9 | ||
|
|
d391f0c12b | ||
|
|
8460a4173d | ||
|
|
fe7149c715 | ||
|
|
443647e78e | ||
|
|
50bb0bcfd4 | ||
|
|
14661339ef | ||
|
|
8ca188e509 | ||
|
|
3da4877d50 | ||
|
|
382f10557e | ||
|
|
d9c6cca370 | ||
|
|
abf4f90f0e | ||
|
|
13ab34a5c8 | ||
|
|
2a67772f46 | ||
|
|
f69718b060 | ||
|
|
08c384ac68 | ||
|
|
00354f4a1e | ||
|
|
1a9b6c01a6 | ||
|
|
c4dc7d0f55 | ||
|
|
5a60af9d13 | ||
|
|
cb8ce62ec4 |
No files matched your search
@@ -11,6 +11,7 @@ trim_trailing_whitespace = true
|
||||
|
||||
[**.py]
|
||||
indent_style = tab
|
||||
indent_size = 4
|
||||
|
||||
[src/octoprint/static/js/app/**.js]
|
||||
indent_style = space
|
||||
|
||||
@@ -20,14 +20,14 @@ HEAD
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.9
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.9rc4
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.9rc5
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
|
||||
regressionfix/.* 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
|
||||
staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
|
||||
regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -91,6 +91,7 @@ date of first contribution):
|
||||
* [Ganey](https://github.com/ganey)
|
||||
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
||||
* [Andy Castille](https://github.com/klikini)
|
||||
* [Brad Fisher](https://github.com/bradcfisher)
|
||||
|
||||
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
|
||||
|
||||
@@ -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.
|
||||
@@ -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``
|
||||
-
|
||||
|
||||
@@ -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,511 @@
|
||||
.. _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 sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
|
||||
authorization process.
|
||||
3. 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`.
|
||||
4. 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.
|
||||
5. 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.
|
||||
6. 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
|
||||
|
||||
User->>App: enters URL of instance to connect to
|
||||
|
||||
alt Limit to specific user
|
||||
User->>App: enters user_id
|
||||
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
|
||||
else
|
||||
App->>Server: POST /plugin/appkeys/request, (app_name)
|
||||
end
|
||||
|
||||
note over User, Server: Step 3
|
||||
|
||||
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 4
|
||||
|
||||
loop
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 202
|
||||
end
|
||||
|
||||
note over User, Server: Step 5 & 6
|
||||
|
||||
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
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api:
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
.. _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.
|
||||
|
||||
.. note::
|
||||
|
||||
If this endpoint produces an HTTP :http:statuscode:`404` and the instance URL is correct, the bundled
|
||||
Application Keys Plugin has in all likelihood been disabled by the user. Fall back on manual API key copy-pasting
|
||||
by the user.
|
||||
|
||||
:json app: application identifier to use for the request, case insensitive
|
||||
:json 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.
|
||||
|
||||
: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.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 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.
|
||||
|
||||
**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
|
||||
|
||||
@@ -1165,7 +1165,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
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
|
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -402,6 +402,13 @@ octoprint.comm.firmware.info
|
||||
|
||||
``firmware_name`` will be ``Some Firmware Name`` in this case.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str firmware_name: The name of the parsed capability
|
||||
:param dict firmware_data: All data contained in the ``M115`` report
|
||||
@@ -421,6 +428,13 @@ octoprint.comm.firmware.capabilities
|
||||
|
||||
Note that hook handlers will be called once per received capability line.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str capability: The name of the parsed capability
|
||||
:param bool enabled: Whether the capability is reported as enabled or disabled
|
||||
@@ -440,6 +454,13 @@ octoprint.comm.protocol.action
|
||||
|
||||
No returned value is expected.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware.
|
||||
@@ -477,6 +498,13 @@ This describes actually two hooks:
|
||||
trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to
|
||||
:ref:`the action command hook <sec-plugins-hook-comm-protocol-action>`.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
|
||||
you will effectively block the send/receive loops, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a
|
||||
@@ -623,6 +651,13 @@ This describes actually four hooks:
|
||||
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
|
||||
to one already in the queue will give an error.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the send loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
The following hook handler replaces all ``M107`` ("Fan Off", deprecated) with an ``M106 S0`` ("Fan On" with speed
|
||||
@@ -658,6 +693,13 @@ octoprint.comm.protocol.gcode.received
|
||||
empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
|
||||
``return`` statement is used or just nothing is returned explicitly from the handler.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Looks for the response of an ``M115``, which contains information about the ``MACHINE_TYPE``, among other things.
|
||||
@@ -687,6 +729,13 @@ octoprint.comm.protocol.gcode.error
|
||||
Plugins might utilize this hook to handle errors generated by the printer that are recoverable in one way or
|
||||
the other and should not trigger the normal handling that assumes the worst.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example:**
|
||||
|
||||
Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the
|
||||
@@ -762,6 +811,13 @@ octoprint.comm.protocol.temperatures.received
|
||||
additional sanity checking to be applied and invalid values to be filtered out. If a handler returns an empty
|
||||
dictionary or ``None``, no further processing will take place.
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
|
||||
you will effectively block the receive loop, causing the communication with the printer to stall.
|
||||
|
||||
This includes I/O of any kind.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C.
|
||||
@@ -1033,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
|
||||
@@ -1134,6 +1238,71 @@ octoprint.server.http.routes
|
||||
:return: a list of 3-tuples with additional routes as defined above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-register:
|
||||
|
||||
octoprint.server.sockjs.register
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
|
||||
|
||||
Allows plugins to prevent a new :ref:`push socket client <sec-api-push>` to be registered to the system.
|
||||
|
||||
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
|
||||
signals to not register the client.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:return: whether to proceed with registration (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-emit:
|
||||
|
||||
octoprint.server.sockjs.emit
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
|
||||
|
||||
Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection <sec-api-push>`.
|
||||
|
||||
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object on which a message is about to be emitted
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:param string message: the message type about to be emitted
|
||||
:param dict payload: the payload of the message about to be emitted (may be None)
|
||||
:return: whether to proceed with sending the message (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-timelapse-extensions:
|
||||
|
||||
octoprint.timelapse.extensions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: timelapse_extension_hook(*args, **kwargs)
|
||||
|
||||
Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of
|
||||
additional file extensions.
|
||||
|
||||
**Example**
|
||||
|
||||
Allow the management of timelapse GIFs with extension ``gif``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_timelapse_extensions(*args, **kwargs):
|
||||
return ["gif"]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.timelapse.extensions": get_timelapse_extensions
|
||||
}
|
||||
|
||||
:return: a list of additional file extensions
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-ui-web-templatetypes:
|
||||
|
||||
octoprint.ui.web.templatetypes
|
||||
|
||||
@@ -12,46 +12,52 @@ import octoprint_setuptools
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Supported python versions
|
||||
PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
"flask>=0.10.1,<0.11",
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"werkzeug>=0.8.3,<0.9",
|
||||
"tornado==4.5.3",
|
||||
#"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a
|
||||
# vendored one
|
||||
"PyYAML>=3.10,<3.11",
|
||||
"Flask-Login>=0.2.11,<0.3",
|
||||
"Flask-Principal>=0.3.5,<0.4",
|
||||
"Flask-Babel>=0.9,<0.10",
|
||||
"Flask-Assets>=0.10,<0.11",
|
||||
"markdown>=2.6.9,<2.7",
|
||||
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
|
||||
# changes that might affect plugins, or due to other observed problems
|
||||
|
||||
"flask>=0.10.1,<0.11", # newer versions require newer Jinja versions
|
||||
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
|
||||
"Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3
|
||||
|
||||
# anything below this should be checked on releases for new versions
|
||||
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"werkzeug>=0.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",
|
||||
"sarge==0.1.4", # 0.1.5 introduced a breaking change with regards to the async keyword. Pinning
|
||||
# to 0.1.4 for now to work around this.
|
||||
"netifaces>=0.10.6,<0.11",
|
||||
"pylru>=1.0.9,<1.1",
|
||||
"rsa>=3.2.3,<3.3",
|
||||
"watchdog>=0.9.0,<0.10",
|
||||
"sarge==0.1.5post0",
|
||||
"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.4.2,<2.5",
|
||||
"psutil>=5.4.6,<5.5",
|
||||
"Click>=6.2,<6.3",
|
||||
"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",
|
||||
"futures>=3.2,<3.3",
|
||||
"emoji>=0.5.1,<0.6",
|
||||
"monotonic>=1.5,<1.6",
|
||||
"frozendict>=1.2,<1.3"
|
||||
]
|
||||
|
||||
@@ -64,11 +70,11 @@ 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
|
||||
"sphinx>=1.6,<1.7",
|
||||
"sphinx>=1.8.1,<1.9",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid>=0.3",
|
||||
"sphinx_rtd_theme",
|
||||
@@ -76,13 +82,10 @@ EXTRA_REQUIRES = dict(
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
plugins=[
|
||||
"cookiecutter>=1.4,<1.7"
|
||||
"cookiecutter>=1.6,<1.7"
|
||||
]
|
||||
)
|
||||
|
||||
# Additional requirements for setup
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
@@ -155,10 +158,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",
|
||||
|
||||
@@ -71,3 +71,6 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
click.echo("DONE:{}s".format(time.time() - start_time))
|
||||
click.echo("RESULTS:")
|
||||
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
|
||||
|
||||
if __name__ == "__main__":
|
||||
gcode_command()
|
||||
@@ -82,7 +82,6 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
after_safe_mode=log_startup,
|
||||
after_environment_detector=log_register_rollover)
|
||||
|
||||
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
|
||||
|
||||
except FatalStartupError as e:
|
||||
|
||||
@@ -256,7 +256,7 @@ class FileManager(object):
|
||||
file_name = storage_manager.split_path(path)
|
||||
|
||||
# we'll use the default printer profile for the backlog since we don't know better
|
||||
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
|
||||
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None)
|
||||
if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority):
|
||||
counter += 1
|
||||
|
||||
@@ -476,12 +476,9 @@ class FileManager(object):
|
||||
|
||||
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
|
||||
|
||||
if analysis is None:
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
else:
|
||||
self._add_analysis_result(destination, path, analysis)
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
@@ -700,7 +697,7 @@ class FileManager(object):
|
||||
def _on_analysis_finished(self, entry, result):
|
||||
self._add_analysis_result(entry.location, entry.path, result)
|
||||
|
||||
def _analysis_queue_entry(self, destination, path, printer_profile=None):
|
||||
def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
@@ -709,6 +706,6 @@ class FileManager(object):
|
||||
file_type = get_file_type(absolute_path)
|
||||
|
||||
if file_type:
|
||||
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile)
|
||||
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis)
|
||||
else:
|
||||
return None
|
||||
@@ -20,7 +20,7 @@ from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
|
||||
"""
|
||||
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
|
||||
for processing.
|
||||
@@ -33,6 +33,7 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio
|
||||
location (str): Location the file is located on.
|
||||
absolute_path (str): Absolute path on disk through which to access the file.
|
||||
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
|
||||
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
|
||||
"""
|
||||
|
||||
def __str__(self):
|
||||
@@ -298,7 +299,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
- * **Key**
|
||||
* **Description**
|
||||
- * ``estimatedPrintTime``
|
||||
* Estimated time the file take to print, in minutes
|
||||
* Estimated time the file take to print, in seconds
|
||||
- * ``filament``
|
||||
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
|
||||
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
|
||||
@@ -341,6 +342,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
import sys
|
||||
import yaml
|
||||
|
||||
if self._current.analysis:
|
||||
return self._current.analysis
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
|
||||
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
@@ -364,7 +367,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
|
||||
|
||||
self._aborted = False
|
||||
p = sarge.run(command, async=True, stdout=sarge.Capture())
|
||||
p = sarge.run(command, async_=True, stdout=sarge.Capture())
|
||||
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
|
||||
@@ -94,7 +94,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
"octoprint.printer.factory"]
|
||||
"octoprint.printer.factory",
|
||||
"octoprint.timelapse.extensions"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
|
||||
|
||||
@@ -861,7 +861,7 @@ class PluginManager(object):
|
||||
if plugin.check():
|
||||
return plugin
|
||||
else:
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
|
||||
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
def _is_plugin_disabled(self, key):
|
||||
|
||||
@@ -225,6 +225,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 +241,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']
|
||||
)
|
||||
@@ -1984,7 +1987,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information
|
||||
about the slicing job under the following keys:
|
||||
|
||||
_analysis
|
||||
analysis
|
||||
Analysis result of the generated machine code as returned by the slicer itself. This should match the
|
||||
data structure described for the analysis queue of the matching machine code format, e.g.
|
||||
:class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files.
|
||||
|
||||
@@ -49,7 +49,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
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -372,15 +372,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
result = []
|
||||
if "entries" in feed:
|
||||
for entry in feed["entries"]:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
try:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
except:
|
||||
self._logger.exception("Error while converting entry from feed, skipping it")
|
||||
return result
|
||||
|
||||
def _to_internal_entry(self, entry, read_until=None):
|
||||
"""Convert feed entries to internal data structure."""
|
||||
|
||||
published = calendar.timegm(entry["published_parsed"])
|
||||
timestamp = entry.get("published_parsed",
|
||||
entry.get("updated_parsed",
|
||||
None))
|
||||
if timestamp is None:
|
||||
return None
|
||||
|
||||
published = calendar.timegm(timestamp)
|
||||
|
||||
read = True
|
||||
if read_until is not None:
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
# 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
|
||||
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
|
||||
|
||||
class AppAlreadyExists(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PendingDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id, user_token):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
self.user_token = user_token
|
||||
self.created = monotonic_time()
|
||||
|
||||
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("/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 = 202
|
||||
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):
|
||||
if self._is_pending(app_token):
|
||||
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)
|
||||
|
||||
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(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))
|
||||
|
||||
return app_token, user_token
|
||||
|
||||
def _is_pending(self, app_token):
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.app_token == app_token:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _get_pending(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 _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,87 @@
|
||||
(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.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.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();
|
||||
});
|
||||
|
||||
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,866 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.plugin.core import FolderOrigin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
try:
|
||||
import zlib # check if zlib is available
|
||||
except ImportError:
|
||||
zlib = None
|
||||
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import codecs
|
||||
import flask
|
||||
import logging
|
||||
import os
|
||||
import requests
|
||||
import sarge
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
import json
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
|
||||
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
|
||||
|
||||
|
||||
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()
|
||||
|
||||
##~~ 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"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_state(self):
|
||||
backups = self._get_backups()
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(backups=backups,
|
||||
backup_in_progress=len(self._in_progress) > 0,
|
||||
unknown_plugins=unknown_plugins)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_unknown_plugins(self):
|
||||
# TODO add caching
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(unknown_plugins=unknown_plugins)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def delete_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
pass
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def get_backups(self):
|
||||
backups = self._get_backups()
|
||||
return flask.jsonify(backups=backups)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def create_backup(self):
|
||||
backup_file = "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.")
|
||||
|
||||
|
||||
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))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
response = flask.jsonify(started=True,
|
||||
name=backup_file)
|
||||
response.status_code = 201
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def delete_backup(self, filename):
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
full_path = os.path.realpath(os.path.join(backup_folder, filename))
|
||||
if full_path.startswith(backup_folder) \
|
||||
and os.path.exists(full_path) \
|
||||
and not is_hidden_path(full_path):
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except:
|
||||
self._logger.exception(u"Could not delete {}".format(filename))
|
||||
raise
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
|
||||
@admin_permission.require(403)
|
||||
@restricted_access
|
||||
def perform_restore(self):
|
||||
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 = plugin["compatibility"]["octoprint"]
|
||||
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")
|
||||
|
||||
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_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 = plugin["compatibility"]["octoprint"]
|
||||
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):
|
||||
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):
|
||||
total = 0
|
||||
for entry in scandir(path):
|
||||
if entry.is_dir():
|
||||
total += cls._get_disk_size(entry.path)
|
||||
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):
|
||||
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)
|
||||
|
||||
size = cls._get_disk_size(basedir)
|
||||
if not cls._free_space(os.path.dirname(temporary_path), size):
|
||||
raise InsufficientSpace()
|
||||
|
||||
own_folder = datafolder
|
||||
defaults = [os.path.join(basedir, "config.yaml"),] + \
|
||||
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
|
||||
|
||||
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, "w", compression) 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:
|
||||
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)
|
||||
|
||||
@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):
|
||||
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")
|
||||
return False
|
||||
|
||||
metadata_bytes = zip.read(metadata_zipinfo)
|
||||
metadata = json.loads(metadata_bytes)
|
||||
|
||||
backup_version = get_comparable_version(metadata["version"])
|
||||
if backup_version > get_octoprint_version():
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
|
||||
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")
|
||||
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")
|
||||
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:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while running restore", exc_info=sys.exc_info())
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
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...")
|
||||
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
|
||||
|
||||
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
|
||||
}
|
||||
@@ -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,263 @@
|
||||
$(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.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.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) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.performRestoreFromUpload = function() {
|
||||
if (self.backupUploadData === undefined) return;
|
||||
|
||||
var perform = function() {
|
||||
self.backupUploadData.submit();
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
||||
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);
|
||||
} else if (data.type === "backup_started") {
|
||||
self.backupInProgress(true);
|
||||
} else if (data.type === "restore_started") {
|
||||
self.restoreInProgress(true);
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
} 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,129 @@
|
||||
<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> | <a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></td>
|
||||
</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>
|
||||
|
||||
<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 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">
|
||||
|
||||
@@ -312,7 +312,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
working_dir))
|
||||
|
||||
import sarge
|
||||
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p = sarge.run(args, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p.wait_events()
|
||||
self._slicing_commands[machinecode_path] = p.commands[0]
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -685,9 +687,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
|
||||
@@ -749,17 +751,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:
|
||||
@@ -773,12 +774,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):
|
||||
"""
|
||||
@@ -601,8 +613,14 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
alive message
|
||||
"""
|
||||
|
||||
from BaseHTTPServer import BaseHTTPRequestHandler
|
||||
from StringIO import StringIO
|
||||
try:
|
||||
# noinspection PyCompatibility
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
except ImportError:
|
||||
# noinspection PyCompatibility
|
||||
from BaseHTTPServer import BaseHTTPRequestHandler
|
||||
|
||||
from io import BytesIO
|
||||
import socket
|
||||
|
||||
socket.setdefaulttimeout(timeout)
|
||||
@@ -617,8 +635,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
class Request(BaseHTTPRequestHandler):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self, request_text):
|
||||
self.rfile = StringIO(request_text)
|
||||
self.rfile = BytesIO(request_text)
|
||||
self.raw_requestline = self.rfile.readline()
|
||||
self.error_code = self.error_message = None
|
||||
self.parse_request()
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# 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
|
||||
|
||||
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
|
||||
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.hasBeenCustomized():
|
||||
# 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:
|
||||
# passive login successful, no need to handle that
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def on_ui_render(self, now, request, render_kwargs):
|
||||
from flask import render_template, make_response
|
||||
|
||||
"""
|
||||
Support theming of the login dialog, just in case the core UI is themed as well.
|
||||
|
||||
Example usage by a plugin:
|
||||
|
||||
def forcelogin_theming():
|
||||
from flask import url_for
|
||||
return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.forcelogin.theming": forcelogin_theming
|
||||
}
|
||||
|
||||
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
|
||||
url_for like in the example above to be prepared for any configured prefix URLs.
|
||||
"""
|
||||
additional_assets = []
|
||||
for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
|
||||
try:
|
||||
assets = hook()
|
||||
if isinstance(assets, (tuple, list)):
|
||||
additional_assets += assets
|
||||
except:
|
||||
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name))
|
||||
|
||||
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.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
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.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
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.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
|
||||
return user is not None and not user.is_anonymous() and user.is_active()
|
||||
|
||||
def socket_emit_validator(self, socket, user, message, payload):
|
||||
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
|
||||
if message in ("connected", "reauthRequired"):
|
||||
return True
|
||||
|
||||
return user is not None and not user.is_anonymous() and user.is_active()
|
||||
|
||||
|
||||
__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.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>
|
||||
@@ -195,6 +195,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;
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import flask
|
||||
import os
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
|
||||
_CPUINFO_PATH = "/proc/cpuinfo"
|
||||
|
||||
# based on https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F
|
||||
_RPI_REVISION_MAP = {
|
||||
"Beta": "1B (Beta)",
|
||||
"0002": "1B",
|
||||
"0003": "1B",
|
||||
"0004": "1B",
|
||||
"0005": "1B",
|
||||
"0006": "1B",
|
||||
"0007": "1A",
|
||||
"0008": "1A",
|
||||
"0009": "1A",
|
||||
"000d": "1B",
|
||||
"000e": "1B",
|
||||
"000f": "1B",
|
||||
"0010": "B+",
|
||||
"0011": "CM1",
|
||||
"0012": "A+",
|
||||
"0013": "B+",
|
||||
"0014": "CM1",
|
||||
"0015": "A+",
|
||||
"a01040": "2B",
|
||||
"a01041": "2B",
|
||||
"a21041": "2B",
|
||||
"a22042": "2B",
|
||||
"900021": "A+",
|
||||
"900032": "B+",
|
||||
"900092": "Zero",
|
||||
"900093": "Zero",
|
||||
"920093": "Zero",
|
||||
"9000c1": "Zero W",
|
||||
"a02082": "3B",
|
||||
"a020a0": "CM3",
|
||||
"a22082": "3B",
|
||||
"a32082": "3B",
|
||||
}
|
||||
|
||||
|
||||
def get_octopi_version():
|
||||
with open(_OCTOPI_VERSION_PATH, "r") as f:
|
||||
version_line = f.readline()
|
||||
return version_line.strip()
|
||||
|
||||
|
||||
def get_pi_cpuinfo():
|
||||
fields = dict(revision="Revision",
|
||||
hardware="Hardware",
|
||||
serial="Serial")
|
||||
|
||||
result = dict()
|
||||
with open(_CPUINFO_PATH) as f:
|
||||
for line in f:
|
||||
if not line:
|
||||
continue
|
||||
|
||||
for key, prefix in fields.items():
|
||||
if line.startswith(prefix):
|
||||
result[key] = line[line.index(":") + 1:].strip()
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_pi_model(hardware, revision):
|
||||
if hardware not in ("BCM2835",):
|
||||
return "unknown"
|
||||
|
||||
if revision.startswith("1000"):
|
||||
# strip flag for over-volted (https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F)
|
||||
revision = revision[4:]
|
||||
|
||||
return _RPI_REVISION_MAP.get(revision.lower(), "unknown")
|
||||
|
||||
|
||||
class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._version = None
|
||||
self._cpuinfo = None
|
||||
self._model = None
|
||||
|
||||
#~~ EnvironmentDetectionPlugin
|
||||
|
||||
def get_additional_environment(self):
|
||||
return dict(version=self._get_version(),
|
||||
revision=self._get_cpuinfo().get("revision", "unknown"),
|
||||
model=self._get_model())
|
||||
|
||||
#~~ SimpleApiPlugin
|
||||
|
||||
def on_api_get(self, request):
|
||||
return flask.jsonify(version=self._get_version())
|
||||
|
||||
#~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/octopi_support.js"],
|
||||
css=["css/octopi_support.css"]
|
||||
)
|
||||
|
||||
#~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="about", name="About OctoPi", template="octopi_support_about.jinja2")
|
||||
]
|
||||
|
||||
def get_template_vars(self):
|
||||
return dict(version=self._get_version())
|
||||
|
||||
#~~ Helpers
|
||||
|
||||
def _get_version(self):
|
||||
if self._version is None:
|
||||
try:
|
||||
self._version = get_octopi_version()
|
||||
except:
|
||||
self._logger.exception("Error while reading OctoPi version from file {}".format(_OCTOPI_VERSION_PATH))
|
||||
self._version = "unknown"
|
||||
return self._version
|
||||
|
||||
def _get_model(self):
|
||||
if self._model is None:
|
||||
try:
|
||||
cpuinfo = self._get_cpuinfo()
|
||||
self._model = get_pi_model(cpuinfo.get("hardware", "unknown"),
|
||||
cpuinfo.get("revision", "unknown"))
|
||||
except:
|
||||
self._logger.exception("Error while detecting RPi model")
|
||||
self._model = "unknown"
|
||||
return self._model
|
||||
|
||||
def _get_cpuinfo(self):
|
||||
if self._cpuinfo is None:
|
||||
try:
|
||||
self._cpuinfo = get_pi_cpuinfo()
|
||||
except:
|
||||
self._logger.exception("Error while fetching cpu info")
|
||||
self._cpuinfo = dict()
|
||||
return self._cpuinfo
|
||||
|
||||
__plugin_name__ = "OctoPi Support Plugin"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Provides additional information about your OctoPi instance in the UI."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"provide additional information about your OctoPi instance,"
|
||||
"which will make it more tricky to help you if you need support.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
def __plugin_check__():
|
||||
from octoprint.util.platform import get_os
|
||||
return get_os() == "linux" and os.path.exists(_OCTOPI_VERSION_PATH)
|
||||
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = OctoPiSupportPlugin()
|
||||
@@ -1,3 +0,0 @@
|
||||
#octopi_support_footer {
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintOctoPiSupportClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintOctoPiSupportClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("octopi_support"));
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("octopi_support", OctoPrintOctoPiSupportClient);
|
||||
return OctoPrintOctoPiSupportClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
|
||||
function OctoPiSupportViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.octopi_support.get()
|
||||
.done(function(response) {
|
||||
$("#octopi_support_footer").remove();
|
||||
if (!response.version) return;
|
||||
|
||||
var octoPrintVersion = $(".footer span.version");
|
||||
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
|
||||
+ " <span class='octopi_version'>" + response.version + "</span></span>")
|
||||
$(octoPiVersion).insertAfter(octoPrintVersion);
|
||||
})
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onServerReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: OctoPiSupportViewModel
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,303 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import flask
|
||||
import os
|
||||
import sarge
|
||||
|
||||
from flask_babel import gettext
|
||||
from octoprint.util import RepeatedTimer
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
_PROC_DT_MODEL_PATH = "/proc/device-tree/model"
|
||||
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
|
||||
_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled"
|
||||
|
||||
### uncomment for local debugging
|
||||
#import sys
|
||||
#base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
|
||||
#_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
|
||||
#_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
|
||||
#_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
|
||||
#import itertools
|
||||
#_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70000"))
|
||||
|
||||
|
||||
# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790
|
||||
_FLAG_UNDERVOLTAGE = 1 << 0
|
||||
_FLAG_FREQ_CAPPED = 1 << 1
|
||||
_FLAG_THROTTLED = 1 << 2
|
||||
_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):
|
||||
if value == 0:
|
||||
return ThrottleState()
|
||||
|
||||
kwargs = dict(undervoltage=_FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
|
||||
freq_capped=_FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
|
||||
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)
|
||||
return ThrottleState(**kwargs)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self._undervoltage = False
|
||||
self._freq_capped = False
|
||||
self._throttled = False
|
||||
self._past_undervoltage = False
|
||||
self._past_freq_capped = False
|
||||
self._past_throttled = False
|
||||
|
||||
for key, value in kwargs.items():
|
||||
local_key = "_{}".format(key)
|
||||
if hasattr(self, local_key) and isinstance(value, bool):
|
||||
setattr(self, local_key, value)
|
||||
|
||||
@property
|
||||
def undervoltage(self):
|
||||
return self.current_undervoltage or self.past_undervoltage
|
||||
|
||||
@property
|
||||
def current_undervoltage(self):
|
||||
return self._undervoltage
|
||||
|
||||
@property
|
||||
def past_undervoltage(self):
|
||||
return self._past_undervoltage
|
||||
|
||||
@property
|
||||
def overheat(self):
|
||||
return self.current_overheat or self.past_overheat
|
||||
|
||||
@property
|
||||
def current_overheat(self):
|
||||
return self._freq_capped
|
||||
|
||||
@property
|
||||
def past_overheat(self):
|
||||
return self._past_freq_capped
|
||||
|
||||
@property
|
||||
def issue(self):
|
||||
return self.current_issue or self.past_issue
|
||||
|
||||
@property
|
||||
def current_issue(self):
|
||||
return self._undervoltage or self._freq_capped or self._throttled
|
||||
|
||||
@property
|
||||
def past_issue(self):
|
||||
return self._past_undervoltage or self._past_freq_capped or self._past_throttled
|
||||
|
||||
def __eq__(self, other):
|
||||
if not isinstance(other, ThrottleState):
|
||||
return False
|
||||
|
||||
return self._undervoltage == other._undervoltage \
|
||||
and self._freq_capped == other._freq_capped \
|
||||
and self._throttled == other._throttled \
|
||||
and self._past_undervoltage == other._past_undervoltage \
|
||||
and self._past_freq_capped == other._past_freq_capped \
|
||||
and self._past_throttled == other._past_throttled
|
||||
|
||||
def as_dict(self):
|
||||
return dict(current_undervoltage=self.current_undervoltage,
|
||||
past_undervoltage=self.past_undervoltage,
|
||||
current_overheat=self.current_overheat,
|
||||
past_overheat=self.past_overheat,
|
||||
current_issue=self.current_issue,
|
||||
past_issue=self.past_issue)
|
||||
|
||||
|
||||
_proc_dt_model = None
|
||||
def get_proc_dt_model():
|
||||
global _proc_dt_model
|
||||
|
||||
if _proc_dt_model is None:
|
||||
with open(_PROC_DT_MODEL_PATH, "r") as f:
|
||||
_proc_dt_model = f.readline().strip(" \t\r\n\0")
|
||||
|
||||
return _proc_dt_model
|
||||
|
||||
|
||||
def get_vcgencmd_throttled_state(command):
|
||||
output = sarge.get_stdout(command)
|
||||
#output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging
|
||||
if not "throttled=0x" in output:
|
||||
raise ValueError("cannot parse \"{}\" output: {}".format(command, output))
|
||||
|
||||
value = output[len("throttled="):].strip(" \t\r\n\0")
|
||||
value = int(value, 0)
|
||||
return ThrottleState.from_value(value)
|
||||
|
||||
|
||||
def is_octopi():
|
||||
return os.path.exists(_OCTOPI_VERSION_PATH)
|
||||
|
||||
|
||||
_octopi_version = None
|
||||
def get_octopi_version():
|
||||
global _octopi_version
|
||||
|
||||
if _octopi_version is None:
|
||||
with open(_OCTOPI_VERSION_PATH, "r") as f:
|
||||
_octopi_version = f.readline().strip(" \t\r\n\0")
|
||||
|
||||
return _octopi_version
|
||||
|
||||
|
||||
class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.SettingsPlugin):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._throttle_state = ThrottleState()
|
||||
self._throttle_check = None
|
||||
self._throttle_undervoltage = False
|
||||
self._throttle_overheat = False
|
||||
self._throttle_functional = True
|
||||
|
||||
#~~ EnvironmentDetectionPlugin
|
||||
|
||||
def get_additional_environment(self):
|
||||
result = dict(model=get_proc_dt_model())
|
||||
|
||||
if is_octopi():
|
||||
result.update(dict(octopi_version=get_octopi_version()))
|
||||
|
||||
return result
|
||||
|
||||
#~~ SimpleApiPlugin
|
||||
|
||||
def on_api_get(self, request):
|
||||
result = dict(throttle_state=self._throttle_state.as_dict())
|
||||
result.update(self.get_additional_environment())
|
||||
return flask.jsonify(**result)
|
||||
|
||||
#~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/pi_support.js"],
|
||||
clientjs=["clientjs/pi_support.js"],
|
||||
css=["css/pi_support.css"]
|
||||
)
|
||||
|
||||
#~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
configs = [dict(type="settings", name=gettext("Pi Support"), template="pi_support_settings.jinja2", custom_bindings=False)]
|
||||
|
||||
if is_octopi():
|
||||
configs.append(dict(type="about", name="About OctoPi", template="pi_support_about_octopi.jinja2"))
|
||||
|
||||
return configs
|
||||
|
||||
def get_template_vars(self):
|
||||
return self.get_additional_environment()
|
||||
|
||||
#~~ StartupPlugin
|
||||
|
||||
def on_startup(self, *args, **kwargs):
|
||||
if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]):
|
||||
self._check_throttled_state()
|
||||
self._throttle_check = RepeatedTimer(self._check_throttled_state_interval,
|
||||
self._check_throttled_state,
|
||||
condition=self._check_throttled_state_condition)
|
||||
self._throttle_check.start()
|
||||
|
||||
#~~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(vcgencmd_throttle_check_enabled=True,
|
||||
vcgencmd_throttle_check_command=_VCGENCMD_THROTTLE)
|
||||
|
||||
def get_settings_restricted_paths(self):
|
||||
return dict(admin=[["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]])
|
||||
|
||||
#~~ Helpers
|
||||
|
||||
def _check_throttled_state_interval(self):
|
||||
if self._throttle_state.current_issue:
|
||||
# check state every 30s if something's currently amiss
|
||||
return 30
|
||||
else:
|
||||
# check state every 5min if nothing's currently amiss
|
||||
return 300
|
||||
|
||||
def _check_throttled_state_condition(self):
|
||||
return self._throttle_functional
|
||||
|
||||
def _check_throttled_state(self):
|
||||
command = self._settings.get(["vcgencmd_throttle_check_command"])
|
||||
|
||||
self._logger.debug("Retrieving throttle state via \"{}\"".format(command))
|
||||
try:
|
||||
state = get_vcgencmd_throttled_state(command)
|
||||
except:
|
||||
self._logger.exception("Got an error while trying to fetch the current throttle state via \"{}\"".format(command))
|
||||
self._throttle_functional = False
|
||||
return
|
||||
|
||||
if self._throttle_state == state:
|
||||
# no change
|
||||
return
|
||||
|
||||
self._throttle_state = state
|
||||
|
||||
if (not self._throttle_undervoltage and self._throttle_state.undervoltage) \
|
||||
or (not self._throttle_overheat and self._throttle_state.overheat):
|
||||
message = "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " \
|
||||
"by overheating or insufficient power."
|
||||
|
||||
if self._throttle_state.undervoltage:
|
||||
self._throttle_undervoltage = True
|
||||
message += "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " \
|
||||
"capable of supplying enough voltage and current to your Pi."
|
||||
|
||||
if self._throttle_state.overheat:
|
||||
self._throttle_overheat = True
|
||||
message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \
|
||||
"CPU and GPU."
|
||||
|
||||
self._logger.warn(message)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
|
||||
state=self._throttle_state.as_dict()))
|
||||
|
||||
|
||||
__plugin_name__ = "Pi Support Plugin"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Provides additional information about your Pi in the UI."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"provide additional information about your Pi,"
|
||||
"which will make it more tricky to help you if you need support.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
def __plugin_check__():
|
||||
try:
|
||||
proc_dt_model = get_proc_dt_model()
|
||||
if proc_dt_model is None:
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
||||
return "raspberry pi" in proc_dt_model.lower()
|
||||
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = PiSupportPlugin()
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
#octopi_support_footer {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pi_support_state_pulsate {
|
||||
animation: pulsate 1s ease-out;
|
||||
animation-iteration-count: infinite;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
$(function() {
|
||||
|
||||
function PiSupportViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.model = ko.observable();
|
||||
|
||||
self.currentUndervoltage = ko.observable(false);
|
||||
self.currentOverheat = ko.observable(false);
|
||||
self.pastUndervoltage = ko.observable(false);
|
||||
self.pastOverheat = ko.observable(false);
|
||||
self.currentIssue = ko.observable(false);
|
||||
self.pastIssue = ko.observable(false);
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.pi_support.get()
|
||||
.done(function(response) {
|
||||
// Raspberry Pi model
|
||||
self.model(response.model);
|
||||
|
||||
// Throttle state
|
||||
self.fromThrottleState(response.throttle_state);
|
||||
|
||||
// OctoPi version
|
||||
$("#octopi_support_footer").remove();
|
||||
if (!response.octopi_version) return;
|
||||
|
||||
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>")
|
||||
$(octoPiVersion).insertAfter(octoPrintVersion);
|
||||
})
|
||||
};
|
||||
|
||||
self.fromThrottleState = function(state) {
|
||||
self.currentUndervoltage(state.current_undervoltage);
|
||||
self.pastUndervoltage(state.past_undervoltage);
|
||||
self.currentOverheat(state.current_overheat);
|
||||
self.pastOverheat(state.past_overheat);
|
||||
self.currentIssue(state.current_issue);
|
||||
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.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onServerReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "pi_support") return;
|
||||
if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return;
|
||||
if (data.type !== "throttle_state") return;
|
||||
|
||||
self.fromThrottleState(data.state);
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PiSupportViewModel,
|
||||
elements: ["#navbar_plugin_pi_support"]
|
||||
});
|
||||
});
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
<h4>The ready-to-go Raspberry Pi image with OctoPrint</h4>
|
||||
|
||||
<p>Version <span class="plugin_octopi_support_version">{{ plugin_octopi_support_version }}</span></p>
|
||||
<p>Version <span class="plugin_pi_support_octopi_version">{{ plugin_pi_support_octopi_version }}</span>, running on <span class="plugin_pi_support_model">{{ plugin_pi_support_model }}</span></p>
|
||||
|
||||
<ul>
|
||||
<li>Website: <a href="https://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a> & <a href="https://octopi.octoprint.org" target="_blank" rel="noreferrer noopener">octopi.octoprint.org</a></li>
|
||||
<li>Website: <a href="https://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a></li>
|
||||
<li>Source Code: <a href="https://github.com/guysoft/OctoPi" target="_blank" rel="noreferrer noopener">github.com/guysoft/OctoPi</a></li>
|
||||
</ul>
|
||||
|
||||
@@ -0,0 +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">
|
||||
<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>
|
||||
@@ -0,0 +1,31 @@
|
||||
<h3>{{ _('Pi Support') }}</h3>
|
||||
|
||||
<p>{{ _('Please restart OctoPrint after changing any of this plugin\'s settings.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.pi_support.vcgencmd_throttle_check_enabled"> {{ _('Enable under voltage and overheat detection via <code>vcgencmd get_throttled</code>') }}
|
||||
</label>
|
||||
<span class="help-block">{{ _('This will regularly check with the Pi if something is amiss either with power regulation or CPU/GPU temperature.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Command for under voltage/overheat detection') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.pi_support.vcgencmd_throttle_check_command">
|
||||
<span class="help-block">{{ _('Defaults to <code>/usr/bin/vcgencmd get_throttled</code>. You usually shouldn\'t have to change this.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ from octoprint.server.util.flask import restricted_access, with_revalidation_che
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import get_os
|
||||
from octoprint.util.platform import get_os, is_os_compatible
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask_babel import gettext
|
||||
@@ -33,6 +33,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,
|
||||
@@ -111,7 +140,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._console_logger.propagate = False
|
||||
|
||||
# decouple repository fetching from server startup
|
||||
self._fetch_all_data(async=True)
|
||||
self._fetch_all_data(do_async=True)
|
||||
|
||||
##~~ SettingsPlugin
|
||||
|
||||
@@ -139,6 +168,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"]
|
||||
)
|
||||
@@ -208,7 +238,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
self._fetch_all_data(async=True)
|
||||
self._fetch_all_data(do_async=True)
|
||||
|
||||
##~~ SimpleApiPlugin
|
||||
|
||||
@@ -340,10 +370,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)
|
||||
|
||||
@@ -459,6 +485,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._plugin_manager.log_all_plugins()
|
||||
|
||||
self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version))
|
||||
self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key,
|
||||
version=new_plugin.version,
|
||||
source=source,
|
||||
source_type=source_type))
|
||||
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
@@ -549,6 +580,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
self._plugin_manager.reload_plugins()
|
||||
|
||||
self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key,
|
||||
version=plugin.version))
|
||||
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
@@ -667,7 +701,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if strip:
|
||||
lines = map(lambda x: x.strip(), lines)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines]))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines",
|
||||
loglines=[dict(line=line, stream=stream) for line in lines]))
|
||||
for line in lines:
|
||||
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
|
||||
|
||||
@@ -688,6 +723,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
elif not plugin.enabled and plugin.key not in self._pending_enable:
|
||||
self._pending_enable.add(plugin.key)
|
||||
|
||||
self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key,
|
||||
version=plugin.version))
|
||||
|
||||
def _mark_plugin_disabled(self, plugin, needs_restart=False):
|
||||
disabled_list = list(self._settings.global_get(["plugins", "_disabled"],
|
||||
validator=lambda x: isinstance(x, list),
|
||||
@@ -705,12 +743,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable:
|
||||
self._pending_disable.add(plugin.key)
|
||||
|
||||
def _fetch_all_data(self, async=False):
|
||||
self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key,
|
||||
version=plugin.version))
|
||||
|
||||
def _fetch_all_data(self, do_async=False):
|
||||
def run():
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
|
||||
if async:
|
||||
if do_async:
|
||||
thread = threading.Thread(target=run)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
@@ -764,30 +805,6 @@ 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 = map(map_repository_entry, repo_data)
|
||||
return True
|
||||
|
||||
@@ -859,30 +876,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;
|
||||
|
||||
@@ -90,6 +90,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",))
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import copy
|
||||
import flask
|
||||
import os
|
||||
import threading
|
||||
@@ -26,9 +27,16 @@ from flask_babel import gettext
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
|
||||
from octoprint.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
|
||||
|
||||
|
||||
@@ -42,7 +50,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):
|
||||
@@ -61,6 +69,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = None
|
||||
|
||||
self._environment_supported = False
|
||||
self._environment_versions = dict()
|
||||
self._environment_ready = threading.Event()
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
def initialize(self):
|
||||
@@ -91,6 +103,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# the server startup
|
||||
def fetch_data():
|
||||
self.get_current_versions()
|
||||
self._check_environment()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
@@ -164,6 +177,24 @@ 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
|
||||
@@ -482,11 +513,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()
|
||||
|
||||
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)
|
||||
|
||||
@@ -513,6 +550,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))
|
||||
@@ -535,6 +574,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# 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)
|
||||
|
||||
@@ -559,6 +601,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
return dict(
|
||||
css=["css/softwareupdate.css"],
|
||||
js=["js/softwareupdate.js"],
|
||||
clientjs=["clientjs/softwareupdate.js"],
|
||||
less=["less/softwareupdate.less"]
|
||||
)
|
||||
|
||||
@@ -645,6 +688,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="?",
|
||||
@@ -778,6 +822,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()
|
||||
@@ -897,6 +945,20 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# determine the target version to update to
|
||||
target_version = information["remote"]["value"]
|
||||
target_error = False
|
||||
target_result = None
|
||||
|
||||
def trigger_event(success, **additional_payload):
|
||||
if success:
|
||||
event = "update_succeeded"
|
||||
else:
|
||||
event = "update_failed"
|
||||
|
||||
payload = copy.copy(additional_payload)
|
||||
payload.update(dict(target=target,
|
||||
from_version=information["local"]["value"],
|
||||
to_version=target_version))
|
||||
|
||||
self._event_bus.fire("plugin_softwareupdate_{}".format(event), payload=payload)
|
||||
|
||||
### The actual update procedure starts here...
|
||||
|
||||
@@ -911,6 +973,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online)
|
||||
target_result = ("success", update_result)
|
||||
self._logger.info("Update of %s to %s successful!" % (target, target_version))
|
||||
trigger_event(True)
|
||||
|
||||
except exceptions.UnknownUpdateType:
|
||||
self._logger.warn("Update of %s can not be performed, unknown update type" % target)
|
||||
@@ -923,6 +986,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
except Exception as e:
|
||||
self._logger.exception("Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this" % target)
|
||||
trigger_event(False)
|
||||
|
||||
if not "ignorable" in populated_check or not populated_check["ignorable"]:
|
||||
target_error = True
|
||||
|
||||
@@ -960,7 +1025,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._logger.info("Restarting...")
|
||||
try:
|
||||
util.execute(restart_command, evaluate_returncode=False, async=True)
|
||||
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))
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -59,7 +59,9 @@ def _execute(command, **kwargs):
|
||||
joined_command = command
|
||||
_log_call(joined_command)
|
||||
|
||||
kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
|
||||
kwargs.update(dict(async_=True,
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture()))
|
||||
|
||||
try:
|
||||
p = sarge.run(command, **kwargs)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintSoftwareUpdateClient = function(base) {
|
||||
this.base = base;
|
||||
|
||||
var url = this.base.getBlueprintUrl("softwareupdate");
|
||||
this.checkUrl = url + "check";
|
||||
this.updateUrl = url + "update";
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
|
||||
if (arguments.length == 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
entries = params.entries;
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
}
|
||||
|
||||
entries = entries || [];
|
||||
if (typeof entries == "string") {
|
||||
entries = [entries];
|
||||
}
|
||||
|
||||
var data = {};
|
||||
if (!!force) {
|
||||
data.force = true;
|
||||
}
|
||||
if (entries && entries.length) {
|
||||
data.check = entries.join(",");
|
||||
}
|
||||
return this.base.getWithQuery(this.checkUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
}
|
||||
|
||||
return this.checkEntries({entries: [], force: force, opts: opts});
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
targets = params.targets;
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
}
|
||||
|
||||
targets = targets || [];
|
||||
if (typeof targets === "string") {
|
||||
targets = [targets];
|
||||
}
|
||||
|
||||
var data = {
|
||||
targets: targets,
|
||||
force: !!force
|
||||
};
|
||||
return this.base.postJson(this.updateUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
}
|
||||
|
||||
var data = {
|
||||
force: !!force
|
||||
};
|
||||
return this.base.postJson(this.updateUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient);
|
||||
return OctoPrintSoftwareUpdateClient;
|
||||
});
|
||||
@@ -1,88 +1,3 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintSoftwareUpdateClient = function(base) {
|
||||
this.base = base;
|
||||
|
||||
var url = this.base.getBlueprintUrl("softwareupdate");
|
||||
this.checkUrl = url + "check";
|
||||
this.updateUrl = url + "update";
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
|
||||
if (arguments.length == 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
entries = params.entries;
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
}
|
||||
|
||||
entries = entries || [];
|
||||
if (typeof entries == "string") {
|
||||
entries = [entries];
|
||||
}
|
||||
|
||||
var data = {};
|
||||
if (!!force) {
|
||||
data.force = true;
|
||||
}
|
||||
if (entries && entries.length) {
|
||||
data.check = entries.join(",");
|
||||
}
|
||||
return this.base.getWithQuery(this.checkUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
}
|
||||
|
||||
return this.checkEntries({entries: [], force: force, opts: opts});
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
targets = params.targets;
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
}
|
||||
|
||||
targets = targets || [];
|
||||
if (typeof targets === "string") {
|
||||
targets = [targets];
|
||||
}
|
||||
|
||||
var data = {
|
||||
targets: targets,
|
||||
force: !!force
|
||||
};
|
||||
return this.base.postJson(this.updateUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
}
|
||||
|
||||
var data = {
|
||||
force: !!force
|
||||
};
|
||||
return this.base.postJson(this.updateUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient);
|
||||
return OctoPrintSoftwareUpdateClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function SoftwareUpdateViewModel(parameters) {
|
||||
var self = this;
|
||||
@@ -116,6 +31,9 @@ $(function() {
|
||||
&& !self.octoprintReleasedVersion();
|
||||
});
|
||||
|
||||
self.environmentSupported = ko.observable(true);
|
||||
self.environmentVersions = ko.observableArray([]);
|
||||
|
||||
self.cacheTimestamp = ko.observable();
|
||||
self.cacheTimestampText = ko.pureComputed(function() {
|
||||
return formatDate(self.cacheTimestamp());
|
||||
@@ -132,6 +50,10 @@ $(function() {
|
||||
&& (!self.config_checkoutFolder() || self.config_checkoutFolder().trim() === '');
|
||||
});
|
||||
|
||||
self.enableUpdate = ko.pureComputed(function() {
|
||||
return !self.updateInProgress && self.environmentSupported();
|
||||
});
|
||||
|
||||
self.enable_configSave = ko.pureComputed(function() {
|
||||
return self.config_checkType() === "github_release"
|
||||
|| (self.config_checkType() === "git_commit" && !self.error_checkoutFolder());
|
||||
@@ -300,6 +222,9 @@ $(function() {
|
||||
var octoprint = data.information["octoprint"];
|
||||
self.octoprintReleasedVersion(!octoprint || octoprint.released_version);
|
||||
|
||||
self.environmentSupported(data.environment.supported);
|
||||
self.environmentVersions(data.environment.versions);
|
||||
|
||||
if (data.status === "inProgress") {
|
||||
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
|
||||
return;
|
||||
@@ -314,7 +239,7 @@ $(function() {
|
||||
_.each(self.versions.items(), function(update_info) {
|
||||
if (update_info.updateAvailable) {
|
||||
text += "<li>"
|
||||
+ "<i class='fa fa-li " + (update_info.updatePossible ? "fa-check" : "fa-remove")+ "'></i>"
|
||||
+ "<i class='fa fa-li " + (update_info.updatePossible && self.environmentSupported() ? "fa-check" : "fa-remove")+ "'></i>"
|
||||
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
|
||||
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
|
||||
+ "</li>";
|
||||
@@ -322,7 +247,11 @@ $(function() {
|
||||
});
|
||||
text += "</ul>";
|
||||
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
|
||||
if (!self.environmentSupported()) {
|
||||
text += "<p><small>" + gettext("This version of the Python environment is not supported for direct updates.") + "</small></p>";
|
||||
} else {
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
|
||||
}
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
text += "<p><small>" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "</small></p>";
|
||||
|
||||
@@ -15,6 +15,23 @@
|
||||
<a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||
</p>
|
||||
{% endtrans %}</div>
|
||||
<div class="alert" data-bind="visible: !environmentSupported()">{% trans %}
|
||||
<p>
|
||||
<strong>This version of the Python environment is not supported for direct updates.</strong>
|
||||
</p>
|
||||
<p>
|
||||
To reduce the likelihood of running into update problems in outdated environments, the following minimal
|
||||
versions are required to use this updater to update OctoPrint or any installed plugins:
|
||||
</p>
|
||||
{% endtrans %}
|
||||
<ul data-bind="foreach: environmentVersions">
|
||||
<li><span data-bind="text: name"></span>: <span data-bind="text: minimum"></span> ({{ _('you have') }}: <span data-bind="text: current"></span>)</li>
|
||||
</ul>
|
||||
{% trans %}
|
||||
<p>
|
||||
Please take a look at <a href="https://faq.octoprint.org/unsupported-python-environment" target="_blank">this FAQ entry on how to proceed</a>.
|
||||
</p>
|
||||
{% endtrans %}</div>
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
|
||||
@@ -29,7 +46,7 @@
|
||||
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: updateAvailable" class="btn btn-primary pull-right">{{ _('Update') }}</a>
|
||||
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
|
||||
<small class="muted">
|
||||
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
|
||||
@@ -59,7 +76,7 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.update(); }, enable: !updateInProgress, css: {disabled: updateInProgress}"><i class="fa fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.update(); }, enable: enableUpdate, css: {disabled: !enableUpdate}"><i class="fa fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
|
||||
|
||||
<div>
|
||||
|
||||
@@ -10,6 +10,7 @@ import logging
|
||||
import pkg_resources
|
||||
|
||||
from octoprint.util.pip import PipCaller, UnknownPip
|
||||
from octoprint.util.version import get_comparable_version
|
||||
from .. import exceptions
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||
@@ -23,8 +24,13 @@ _pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
def can_perform_update(target, check, online=True):
|
||||
from .. import MINIMUM_PIP
|
||||
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
|
||||
return "pip" in check and pip_caller is not None and pip_caller.available and (online or check.get("offline", False))
|
||||
return "pip" in check \
|
||||
and pip_caller is not None \
|
||||
and pip_caller.available \
|
||||
and pip_caller.version >= get_comparable_version(MINIMUM_PIP) \
|
||||
and (online or check.get("offline", False))
|
||||
|
||||
def _get_pip_caller(command=None):
|
||||
key = command
|
||||
|
||||
@@ -9,12 +9,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from .exceptions import ScriptError
|
||||
|
||||
|
||||
def execute(command, cwd=None, evaluate_returncode=True, async=False):
|
||||
def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
|
||||
do_async = kwargs.get("do_async", kwargs.get("async", False))
|
||||
|
||||
import sarge
|
||||
p = None
|
||||
|
||||
try:
|
||||
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async=async)
|
||||
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=do_async)
|
||||
except:
|
||||
returncode = p.returncode if p is not None else None
|
||||
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
# 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
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import requests
|
||||
import hashlib
|
||||
import logging
|
||||
|
||||
try:
|
||||
# noinspection PyCompatibility
|
||||
from urllib.parse import urlencode
|
||||
except ImportError:
|
||||
from urllib import urlencode
|
||||
|
||||
# noinspection PyCompatibility
|
||||
import concurrent.futures
|
||||
|
||||
from octoprint.util import RepeatedTimer
|
||||
from octoprint.util.version import get_octoprint_version_string
|
||||
from octoprint.events import Events
|
||||
|
||||
TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/"
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.ShutdownPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.WizardPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._environment = None
|
||||
self._printer_connection_parameters = None
|
||||
self._url = None
|
||||
self._ping_worker = None
|
||||
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
self._record_next_firmware_info = False
|
||||
|
||||
def initialize(self):
|
||||
self._init_tracking()
|
||||
|
||||
##~~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(enabled=None,
|
||||
unique_id=None,
|
||||
server=TRACKING_URL,
|
||||
ping=15*60,
|
||||
events=dict(startup=True,
|
||||
printjob=True,
|
||||
plugin=True,
|
||||
update=True,
|
||||
printer=True))
|
||||
|
||||
def get_settings_restricted_paths(self):
|
||||
return dict(admin=[["enabled"], ["unique_id"], ["events"]],
|
||||
never=[["server"], ["ping"]])
|
||||
|
||||
def on_settings_save(self, data):
|
||||
enabled = self._settings.get([b"enabled"])
|
||||
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
|
||||
if enabled is None and self._settings.get([b"enabled"]):
|
||||
# tracking was just enabled, let's init it and send a startup event
|
||||
self._init_tracking()
|
||||
self._track_startup()
|
||||
|
||||
##~~ EnvironmentDetectionPlugin
|
||||
|
||||
def on_environment_detected(self, environment, *args, **kwargs):
|
||||
self._environment = environment
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
self._track_startup()
|
||||
|
||||
ping = self._settings.get_int(["ping"])
|
||||
if ping:
|
||||
self._ping_worker = RepeatedTimer(ping, self._track_ping)
|
||||
self._ping_worker.start()
|
||||
|
||||
##~~ ShutdownPlugin
|
||||
|
||||
def on_shutdown(self):
|
||||
self._track_shutdown()
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
if event.startswith("plugin_pluginmanager_"):
|
||||
self._track_plugin_event(event, payload)
|
||||
if event.startswith("plugin_softwareupdate_"):
|
||||
self._track_update_event(event, payload)
|
||||
elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
|
||||
self._track_printjob_event(event, payload)
|
||||
elif event in (Events.CONNECTED,):
|
||||
self._printer_connection_parameters = dict(port=payload["port"],
|
||||
baudrate=payload["baudrate"])
|
||||
self._record_next_firmware_info = True
|
||||
elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info:
|
||||
self._record_next_firmware_info = False
|
||||
self._track_printer_event(event, payload)
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings", name=gettext("Anonymous Usage Tracking"), template="tracking_settings.jinja2", custom_bindings=False),
|
||||
dict(type="wizard", name=gettext("Anonymous Usage Tracking"), template="tracking_wizard.jinja2", custom_bindings=True, mandatory=True)
|
||||
]
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/tracking.js"])
|
||||
|
||||
##~~ WizardPlugin
|
||||
|
||||
def is_wizard_required(self):
|
||||
return self._settings.get([b"enabled"]) is None
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def _init_tracking(self):
|
||||
if not self._settings.get_boolean([b"enabled"]):
|
||||
return
|
||||
self._init_id()
|
||||
self._logger.info("Initialized anonymous tracking")
|
||||
|
||||
def _init_id(self):
|
||||
if self._settings.get_boolean([b"enabled"]) and not self._settings.get([b"unique_id"]):
|
||||
import uuid
|
||||
self._settings.set([b"unique_id"], str(uuid.uuid4()))
|
||||
self._settings.save()
|
||||
|
||||
def _track_ping(self):
|
||||
self._track("ping")
|
||||
|
||||
def _track_startup(self):
|
||||
if not self._settings.get_boolean(["events", "startup"]):
|
||||
return
|
||||
|
||||
payload = dict(version=get_octoprint_version_string(),
|
||||
os=self._environment[b"os"][b"id"],
|
||||
python=self._environment[b"python"][b"version"],
|
||||
pip=self._environment[b"python"][b"pip"],
|
||||
cores=self._environment[b"hardware"][b"cores"],
|
||||
freq=self._environment[b"hardware"][b"freq"],
|
||||
ram=self._environment[b"hardware"][b"ram"])
|
||||
|
||||
if b"plugins" in self._environment and b"pi_support" in self._environment[b"plugins"]:
|
||||
payload[b"pi_model"] = self._environment[b"plugins"][b"pi_support"][b"model"]
|
||||
if b"octopi_version" in self._environment[b"plugins"][b"pi_support"]:
|
||||
payload[b"octopi_version"] = self._environment[b"plugins"][b"pi_support"][b"octopi_version"]
|
||||
|
||||
self._track("startup", **payload)
|
||||
|
||||
def _track_shutdown(self):
|
||||
if not self._settings.get_boolean(["events", "startup"]):
|
||||
return
|
||||
|
||||
self._track("shutdown")
|
||||
|
||||
def _track_plugin_event(self, event, payload):
|
||||
if not self._settings.get_boolean(["events", "plugin"]):
|
||||
return
|
||||
|
||||
if event.endswith("_installplugin"):
|
||||
self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
|
||||
elif event.endswith("_uninstallplugin"):
|
||||
self._track("uninstall_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
|
||||
elif event.endswith("_enableplugin"):
|
||||
self._track("enable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
|
||||
elif event.endswith("_disableplugin"):
|
||||
self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
|
||||
|
||||
def _track_update_event(self, event, payload):
|
||||
if not self._settings.get_boolean(["events", "update"]):
|
||||
return
|
||||
|
||||
if event.endswith("_update_succeeded"):
|
||||
self._track("update_successful", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
|
||||
elif event.endswith("_update_failed"):
|
||||
self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
|
||||
|
||||
def _track_printjob_event(self, event, payload):
|
||||
if not self._settings.get_boolean(["events", "printjob"]):
|
||||
return
|
||||
|
||||
sha = hashlib.sha1()
|
||||
sha.update(payload.get("name"))
|
||||
sha.update(self._settings.get([b"unique_id"]))
|
||||
|
||||
track_event = None
|
||||
args = dict(origin=payload.get(b"origin"), file=sha.hexdigest())
|
||||
|
||||
if event == Events.PRINT_STARTED:
|
||||
track_event = "print_started"
|
||||
elif event == Events.PRINT_DONE:
|
||||
try:
|
||||
elapsed = int(payload.get(b"time"))
|
||||
except ValueError:
|
||||
elapsed = "unknown"
|
||||
args[b"elapsed"] = elapsed
|
||||
track_event = "print_done"
|
||||
elif event == Events.PRINT_FAILED:
|
||||
track_event = "print_failed"
|
||||
elif event == Events.PRINT_CANCELLED:
|
||||
track_event = "print_cancelled"
|
||||
|
||||
if track_event is not None:
|
||||
self._track(track_event, **args)
|
||||
|
||||
def _track_printer_event(self, event, payload):
|
||||
if not self._settings.get_boolean(["events", "printer"]):
|
||||
return
|
||||
|
||||
if event in (Events.FIRMWARE_DATA,):
|
||||
args = dict(firmware_name=payload["name"])
|
||||
if self._printer_connection_parameters:
|
||||
args["printer_port"] = self._printer_connection_parameters["port"]
|
||||
args["printer_baudrate"] = self._printer_connection_parameters["baudrate"]
|
||||
self._track("printer_connected", **args)
|
||||
|
||||
def _track(self, event, **kwargs):
|
||||
if not self._settings.get_boolean([b"enabled"]):
|
||||
return
|
||||
|
||||
self._executor.submit(self._do_track, event, **kwargs)
|
||||
|
||||
def _do_track(self, event, **kwargs):
|
||||
if not self._connectivity_checker.online:
|
||||
return
|
||||
|
||||
server = self._settings.get([b"server"])
|
||||
url = server.format(id=self._settings.get([b"unique_id"]), event=event)
|
||||
|
||||
headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())}
|
||||
try:
|
||||
params = urlencode(kwargs, doseq=True).replace("+", "%20")
|
||||
requests.get(url,
|
||||
params=params,
|
||||
timeout=3.1,
|
||||
headers=headers)
|
||||
self._logger.debug("Sent tracking event to {}".format(url))
|
||||
except:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Error while sending event to anonymous usage tracking".format(url))
|
||||
else:
|
||||
pass
|
||||
|
||||
__plugin_name__ = "Anonymous Usage Tracking"
|
||||
__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked"
|
||||
__plugin_homepage__ = "https://tracking.octoprint.org"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
|
||||
__plugin_implementation__ = TrackingPlugin()
|
||||
@@ -0,0 +1,85 @@
|
||||
$(function() {
|
||||
function TrackingViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
|
||||
self.setup = ko.observable(false);
|
||||
|
||||
self.decision = ko.observable();
|
||||
self.required = false;
|
||||
self.active = false;
|
||||
|
||||
self.enableTracking = function() {
|
||||
self.settingsViewModel.settings.plugins.tracking.enabled(true);
|
||||
self.decision(true);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.disableTracking = function() {
|
||||
self.settingsViewModel.settings.plugins.tracking.enabled(false);
|
||||
self.decision(false);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_tracking") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function() {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.tracking && response.tracking.required;
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function() {
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up anonymous usage tracking"),
|
||||
message: gettext("You haven't yet decided on whether to enable or disable anonymous usage tracking. You need to either enable or disable it before continuing.")
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function() {
|
||||
var data = {
|
||||
plugins: {
|
||||
tracking: {
|
||||
enabled: self.settingsViewModel.settings.plugins.tracking.enabled()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.active = true;
|
||||
self.settingsViewModel.saveData(data)
|
||||
.done(function() {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TrackingViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_tracking"
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
{% trans %}
|
||||
<p>
|
||||
Anonymous usage tracking provides valuable insights into how many instances running what versions of OctoPrint are out there,
|
||||
whether they are successfully completing print jobs and various other metrics.
|
||||
</p>
|
||||
<p>
|
||||
By enabling it you help to identify problems with new releases and release candidates early on, and to better
|
||||
tailor OctoPrint's future development to actual use.
|
||||
</p>
|
||||
{% endtrans %}
|
||||
@@ -0,0 +1,4 @@
|
||||
<p>{% trans %}
|
||||
For details on what gets tracked, please refer to <a href="https://tracking.octoprint.org" target="_blank" rel="noopener noreferrer">tracking.octoprint.org</a>
|
||||
and also the <a href="https://tracking.octoprint.org/privacy" target="_blank" rel="noopener noreferrer">Privacy Policy at tracking.octoprint.org</a>.
|
||||
{% endtrans %}</p>
|
||||
@@ -0,0 +1,44 @@
|
||||
<h3>{{ _('Anonymous Usage Tracking') }}</h3>
|
||||
|
||||
{% include "snippets/plugins/tracking/trackingDescription.jinja2" %}
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.tracking.enabled"> {{ _('Enable anonymous usage tracking') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" title="{{ _('Random unique instance ID') }}">{{ _('Instance ID') }}</label>
|
||||
<div class="controls">
|
||||
<span style="padding-top: 5px; margin-bottom: 5px; display: inline-block" data-bind="text: settings.plugins.tracking.unique_id() || 'N/A'"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" title="{{ _('Events to track. The ping is mandatory.') }}">{{ _('Tracked events') }}</label>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" checked="checked" disabled="disabled"> {{ _('Regular ping') }}
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.startup"> {{ _('Server startup & shutdown') }}
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.printer"> {{ _('Connected to printer') }}
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.printjob"> {{ _('Print started/cancelled/finished') }}
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.plugin"> {{ _('Plugin installed/uninstalled/enabled/disabled') }}
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.update"> {{ _('OctoPrint or a plugin updated successfully or unsuccessfully') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{% include "snippets/plugins/tracking/trackingDetails.jinja2" %}
|
||||
@@ -0,0 +1,23 @@
|
||||
<h3>{{ _('Configure Anonymous Usage Tracking') }}</h3>
|
||||
|
||||
{% include "snippets/plugins/tracking/trackingDescription.jinja2" %}
|
||||
|
||||
{% include "snippets/plugins/tracking/trackingDetails.jinja2" %}
|
||||
|
||||
<p>
|
||||
{{ _('<strong>Note:</strong> You can always change your decision and also access more granular controls via Settings > Anonymous Usage Tracking.') }}
|
||||
</p>
|
||||
|
||||
<div class="row-fluid">
|
||||
<a href="javascript:void(0)" class="btn span6" data-bind="click: function() { if(!setup()){disableTracking()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Anonymous Usage Tracking') }}</a>
|
||||
<a href="javascript:void(0)" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableTracking()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Anonymous Usage Tracking') }}</a>
|
||||
</div>
|
||||
|
||||
<div class="tracking_decision" style="display: none" data-bind="visible: setup()">
|
||||
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
|
||||
Anonymous Usage Tracking is <strong class="text-success">enabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
|
||||
Anonymous Usage Tracking is <strong class="text-danger">disabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
</div>
|
||||
@@ -647,6 +647,19 @@ class VirtualPrinter(object):
|
||||
else:
|
||||
time.sleep(_timeout)
|
||||
|
||||
def _gcode_G33(self, data):
|
||||
self._send("G33 Auto Calibrate")
|
||||
self._send("Will take ~60s")
|
||||
timeout = 60
|
||||
|
||||
if self._sendBusy and self._busyInterval > 0:
|
||||
until = time.time() + timeout
|
||||
while time.time() < until:
|
||||
time.sleep(self._busyInterval)
|
||||
self._send("busy:processing")
|
||||
else:
|
||||
time.sleep(timeout)
|
||||
|
||||
##~~ further helpers
|
||||
|
||||
def _calculate_checksum(self, line):
|
||||
@@ -719,6 +732,10 @@ class VirtualPrinter(object):
|
||||
| Triggers a resend error with a missing checksum
|
||||
trigger_missing_lineno
|
||||
| Triggers a "no line number with checksum" error w/o resend request
|
||||
trigger_fatal_error_marlin
|
||||
| Triggers a fatal error/simulated heater fail, Marlin style
|
||||
trigger_fatal_error_repetier
|
||||
| Triggers a fatal error/simulated heater fail, Repetier style
|
||||
drop_connection
|
||||
| Drops the serial connection
|
||||
prepare_ok <broken ok>
|
||||
@@ -769,6 +786,11 @@ class VirtualPrinter(object):
|
||||
self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, checksum=False))
|
||||
elif data == "trigger_missing_lineno":
|
||||
self._prepared_errors.append(lambda cur, last, line: self._send(self._error("lineno_missing", last)))
|
||||
elif data == "trigger_fatal_error_marlin":
|
||||
self._send("Error:Thermal Runaway, system stopped! Heater_ID: bed")
|
||||
self._send("Error:Printer halted. kill() called!")
|
||||
elif data == "trigger_fatal_error_repetier":
|
||||
self._send("fatal: Heater/sensor error - Printer stopped and heaters disabled due to this error. Fix error and restart with M999.")
|
||||
elif data == "drop_connection":
|
||||
self._debug_drop_connection = True
|
||||
elif data == "reset":
|
||||
|
||||
@@ -242,6 +242,7 @@ class Server(object):
|
||||
|
||||
# monkey patch a bunch of stuff
|
||||
util.tornado.fix_json_encode()
|
||||
util.flask.fix_flask_jsonify()
|
||||
util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")])
|
||||
|
||||
# setup app
|
||||
@@ -473,6 +474,7 @@ class Server(object):
|
||||
self._setup_assets()
|
||||
|
||||
# configure timelapse
|
||||
octoprint.timelapse.valid_timelapse("test")
|
||||
octoprint.timelapse.configure_timelapse()
|
||||
|
||||
# setup command triggers
|
||||
@@ -512,11 +514,24 @@ class Server(object):
|
||||
|
||||
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
|
||||
|
||||
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))
|
||||
user_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
|
||||
access_validators_from_plugins = []
|
||||
for plugin, hook in pluginManager.get_hooks("octoprint.server.http.access_validator").items():
|
||||
try:
|
||||
access_validators_from_plugins.append(util.tornado.access_validation_factory(app, hook))
|
||||
except:
|
||||
self._logger.exception("Error while adding tornado access validator from plugin {}".format(plugin))
|
||||
|
||||
admin_validators = [util.tornado.access_validation_factory(app, util.flask.admin_validator),] + access_validators_from_plugins
|
||||
user_validators = [util.tornado.access_validation_factory(app, util.flask.user_validator),] + access_validators_from_plugins
|
||||
|
||||
admin_validator = dict(access_validation=util.tornado.validation_chain(*admin_validators))
|
||||
user_validator = dict(access_validation=util.tornado.validation_chain(*user_validators))
|
||||
access_validator = dict(access_validation=util.tornado.validation_chain(*access_validators_from_plugins))
|
||||
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path),
|
||||
status_code=404))
|
||||
timelapse_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path) and octoprint.timelapse.valid_timelapse(path),
|
||||
status_code=404))
|
||||
|
||||
def joined_dict(*dicts):
|
||||
if not len(dicts):
|
||||
@@ -532,15 +547,17 @@ class Server(object):
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
# .mpg and .mp4 timelapses:
|
||||
(r"/downloads/timelapse/([^/]*\.m(.*))", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator)),
|
||||
(r"/downloads/timelapse/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
|
||||
download_handler_kwargs,
|
||||
timelapse_validator,
|
||||
access_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads"),
|
||||
as_attachment=True,
|
||||
name_generator=download_name_generator),
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator,
|
||||
additional_mime_types)),
|
||||
additional_mime_types,
|
||||
access_validator)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("logs"),
|
||||
mime_type_guesser=lambda *args, **kwargs: "text/plain"),
|
||||
download_handler_kwargs,
|
||||
@@ -1076,16 +1093,25 @@ class Server(object):
|
||||
def _setup_blueprints(self):
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.apps import apps, clear_registered_app
|
||||
import octoprint.server.views
|
||||
|
||||
app.register_blueprint(api, url_prefix="/api")
|
||||
app.register_blueprint(apps, url_prefix="/apps")
|
||||
import octoprint.server.views # do not remove or the index view won't be found
|
||||
|
||||
blueprints = OrderedDict()
|
||||
blueprints["/api"] = api
|
||||
blueprints["/apps"] = apps
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
self._register_blueprint_plugins()
|
||||
blueprints.update(self._prepare_blueprint_plugins())
|
||||
|
||||
# and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves
|
||||
self._register_asset_plugins()
|
||||
blueprints.update(self._prepare_asset_plugins())
|
||||
|
||||
# make sure all before/after_request hook results are attached as well
|
||||
self._add_plugin_request_handlers_to_blueprints(*blueprints.values())
|
||||
|
||||
# register everything with the system
|
||||
for url_prefix, blueprint in blueprints.items():
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
|
||||
global pluginLifecycleManager
|
||||
def clear_apps(name, plugin):
|
||||
@@ -1093,27 +1119,37 @@ class Server(object):
|
||||
pluginLifecycleManager.add_callback("enabled", clear_apps)
|
||||
pluginLifecycleManager.add_callback("disabled", clear_apps)
|
||||
|
||||
def _register_blueprint_plugins(self):
|
||||
def _prepare_blueprint_plugins(self):
|
||||
blueprints = OrderedDict()
|
||||
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin)
|
||||
for plugin in blueprint_plugins:
|
||||
try:
|
||||
self._register_blueprint_plugin(plugin)
|
||||
blueprint, prefix = self._prepare_blueprint_plugin(plugin)
|
||||
blueprints[prefix] = blueprint
|
||||
except:
|
||||
self._logger.exception("Error while registering blueprint of plugin {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
|
||||
def _register_asset_plugins(self):
|
||||
return blueprints
|
||||
|
||||
def _prepare_asset_plugins(self):
|
||||
blueprints = OrderedDict()
|
||||
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for plugin in asset_plugins:
|
||||
if isinstance(plugin, octoprint.plugin.BlueprintPlugin):
|
||||
continue
|
||||
try:
|
||||
self._register_asset_plugin(plugin)
|
||||
blueprint, prefix = self._prepare_asset_plugin(plugin)
|
||||
blueprints[prefix] = blueprint
|
||||
except:
|
||||
self._logger.exception("Error while registering assets of plugin {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
|
||||
def _register_blueprint_plugin(self, plugin):
|
||||
return blueprints
|
||||
|
||||
def _prepare_blueprint_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
blueprint = plugin.get_blueprint()
|
||||
if blueprint is None:
|
||||
@@ -1135,7 +1171,9 @@ class Server(object):
|
||||
if self._logger:
|
||||
self._logger.debug("Registered API of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix))
|
||||
|
||||
def _register_asset_plugin(self, plugin):
|
||||
return blueprint, url_prefix
|
||||
|
||||
def _prepare_asset_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
|
||||
url_prefix = "/plugin/{name}".format(name=name)
|
||||
@@ -1145,6 +1183,32 @@ class Server(object):
|
||||
if self._logger:
|
||||
self._logger.debug("Registered assets of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix))
|
||||
|
||||
return blueprint, url_prefix
|
||||
|
||||
def _add_plugin_request_handlers_to_blueprints(self, *blueprints):
|
||||
before_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.before_request")
|
||||
after_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.after_request")
|
||||
|
||||
for plugin, hook in before_hooks.items():
|
||||
for blueprint in blueprints:
|
||||
try:
|
||||
result = hook()
|
||||
if isinstance(result, (list, tuple)):
|
||||
for h in result:
|
||||
blueprint.before_request(h)
|
||||
except:
|
||||
self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin))
|
||||
|
||||
for plugin, hook in after_hooks.items():
|
||||
for blueprint in blueprints:
|
||||
try:
|
||||
result = hook()
|
||||
if isinstance(result, (list, tuple)):
|
||||
for h in result:
|
||||
blueprint.after_request(h)
|
||||
except:
|
||||
self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin))
|
||||
|
||||
def _setup_assets(self):
|
||||
global app
|
||||
global assets
|
||||
@@ -1285,25 +1349,6 @@ class Server(object):
|
||||
"js/lib/loglevel.min.js",
|
||||
"js/lib/sockjs.js"
|
||||
]
|
||||
js_client = [
|
||||
"js/app/client/base.js",
|
||||
"js/app/client/socket.js",
|
||||
"js/app/client/browser.js",
|
||||
"js/app/client/connection.js",
|
||||
"js/app/client/control.js",
|
||||
"js/app/client/files.js",
|
||||
"js/app/client/job.js",
|
||||
"js/app/client/languages.js",
|
||||
"js/app/client/printer.js",
|
||||
"js/app/client/printerprofiles.js",
|
||||
"js/app/client/settings.js",
|
||||
"js/app/client/slicing.js",
|
||||
"js/app/client/system.js",
|
||||
"js/app/client/timelapse.js",
|
||||
"js/app/client/users.js",
|
||||
"js/app/client/util.js",
|
||||
"js/app/client/wizard.js"
|
||||
]
|
||||
|
||||
css_libs = [
|
||||
"css/bootstrap.min.css",
|
||||
@@ -1356,13 +1401,15 @@ class Server(object):
|
||||
js_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["js"],
|
||||
filters="js_delimiter_bundler")
|
||||
|
||||
clientjs_core = dynamic_core_assets["clientjs"] + \
|
||||
all_assets_for_plugins(dynamic_plugin_assets["bundled"]["clientjs"])
|
||||
clientjs_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["clientjs"],
|
||||
filters="js_delimiter_bundler")
|
||||
|
||||
js_libs_bundle = Bundle(*js_libs,
|
||||
output="webassets/packed_libs.js",
|
||||
filters=",".join(js_filters))
|
||||
|
||||
js_client_bundle = Bundle(*js_client,
|
||||
output="webassets/packed_client.js",
|
||||
filters=",".join(js_filters))
|
||||
js_core_bundle = Bundle(*js_core,
|
||||
output="webassets/packed_core.js",
|
||||
filters=",".join(js_filters))
|
||||
@@ -1378,6 +1425,21 @@ class Server(object):
|
||||
output="webassets/packed_app.js",
|
||||
filters=",".join(js_filters))
|
||||
|
||||
js_client_core_bundle = Bundle(*clientjs_core,
|
||||
output="webassets/packed_client_core.js",
|
||||
filters=",".join(js_filters))
|
||||
|
||||
if len(clientjs_plugins) == 0:
|
||||
js_client_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
js_client_plugins_bundle = Bundle(*clientjs_plugins.values(),
|
||||
output="webassets/packed_client_plugins.js",
|
||||
filters=",".join(js_plugin_filters))
|
||||
|
||||
js_client_bundle = Bundle(js_client_core_bundle, js_client_plugins_bundle,
|
||||
output="webassets/packed_client.js",
|
||||
filters=",".join(js_filters))
|
||||
|
||||
# -- CSS -------------------------------------------------------------------------------------------------------
|
||||
|
||||
css_filters = ["cssrewrite"]
|
||||
@@ -1437,6 +1499,11 @@ class Server(object):
|
||||
# -- asset registration ----------------------------------------------------------------------------------------
|
||||
|
||||
assets.register("js_libs", js_libs_bundle)
|
||||
assets.register("js_client_core", js_client_core_bundle)
|
||||
for plugin, bundle in clientjs_plugins.items():
|
||||
# register our collected clientjs plugin bundles so that they are bound to the environment
|
||||
assets.register("js_client_plugin_{}".format(plugin), bundle)
|
||||
assets.register("js_client_plugins", js_client_plugins_bundle)
|
||||
assets.register("js_client", js_client_bundle)
|
||||
assets.register("js_core", js_core_bundle)
|
||||
for plugin, bundle in js_plugins.items():
|
||||
|
||||
@@ -7,20 +7,20 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
import netaddr
|
||||
import sarge
|
||||
|
||||
from flask import Blueprint, request, jsonify, abort, current_app, session, make_response, g
|
||||
from flask_login import login_user, logout_user, current_user
|
||||
from flask_principal import Identity, identity_changed, AnonymousIdentity
|
||||
|
||||
import octoprint.util as util
|
||||
import octoprint.util.net as util_net
|
||||
import octoprint.users
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login, get_remote_address
|
||||
|
||||
|
||||
#~~ init api blueprint, including sub modules
|
||||
@@ -214,7 +214,16 @@ def login():
|
||||
g.user = user
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
|
||||
remote_addr = get_remote_address(request)
|
||||
logging.getLogger(__name__).info("Actively logging in user {} from {}".format(user.get_id(), remote_addr))
|
||||
|
||||
response = user.asDict()
|
||||
response["_is_external_client"] = s().getBoolean(["server", "ipCheck", "enabled"]) \
|
||||
and not util_net.is_lan_address(remote_addr,
|
||||
additional_private=s().get(["server", "ipCheck", "trustedSubnets"]))
|
||||
return jsonify(response)
|
||||
|
||||
return make_response(("User unknown or password incorrect", 401, []))
|
||||
|
||||
elif "passive" in data:
|
||||
|
||||