Merge branch 'maintenance' into pr/2900

This commit is contained in:
Gina Häußge committed 2019-01-16 17:52:06 +01:00
commit 06a3baa588
133 files changed
+8893 -6692

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
---
name: Bug report
about: Create a report to help improve OctoPrint
---
<!--
READ THE FOLLOWING FIRST:
If not already done, please read the the Contribution Guidelines that
are linked to the right under "Helpful resources" > "Contributing".
Also read the FAQ: https://faq.octoprint.org
This is a bug and feature tracker, please only use it to report bugs
or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
discourse.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (if you don't know
where to find some information - it's all described in the Contribution
Guidelines linked up there in the big yellow box).
When reporting a bug do NOT delete ANY lines from the template.
Make sure any bug you want to report is still present with the CURRENT
OctoPrint version and that it does not vanish when you start OctoPrint
in safe mode - how to do that is also explained in the Contribution
Guidelines linked up there in the big yellow box.
Thank you!
-->
#### What were you doing?
<!--
Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
Ideally provide exact steps to follow in order to reproduce your problem:
-->
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
<!--
If you encountered a problem with specific files of any sorts, make sure
to also include a link to a file with which to reproduce the problem.
-->
#### What did you expect to happen?
#### What happened instead?
#### Did the same happen when running OctoPrint in safe mode?
<!--
Test if you can reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.
If you can't reproduce in safe mode, this is a bug with one of your
installed third party plugins. Don't open a ticket here!
If you can't test this in safe mode, state why.
-->
#### Version of OctoPrint
<!--
Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.
-->
#### Operating System running OctoPrint
<!--
OctoPi, Linux, Windows, MacOS, something else? With version please.
OctoPi's version can be found in /etc/octopi_version or in the lower left
corner of the web interface.
-->
#### Printer model & used firmware incl. version
<!--
If applicable, always include if unsure.
-->
#### Browser and version of browser, operating system running browser
<!--
If applicable, always include if unsure.
-->
#### Link to octoprint.log
<!--
On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
The Contribution Guidelines tell you where to find that.
-->
#### Link to contents of terminal tab or serial.log
<!--
On gist.github.com or pastebin.com. If applicable, always include if unsure or
reporting communication issues. Never truncate.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
terminal tab at the time of the bug occurrence, even if you do not have
a serial.log (which the Contribution Guidelines tell you where to find).
-->
#### Link to contents of Javascript console in the browser
<!--
On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
always include if unsure or reporting UI issues.
The Contribution Guidelines tell you where to find that.
-->
#### Screenshot(s)/video(s) showing the problem:
<!--
If applicable. Always include if unsure or reporting UI issues.
-->
I have read the FAQ.
+21
View File
@@ -0,0 +1,21 @@
---
name: Feature request
about: Suggest an idea for this project
---
<!--
Please make sure to add [Request] to your issue's title. Thank you!
-->
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+7 -7
View File
@@ -18,16 +18,16 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.9
# maintenance is currently the branch for preparation of maintenance release 1.3.11
# so are any fix/... and improve/... branches
maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.9rc5
# staging/maintenance is currently the branch for preparation of 1.3.10rc5
# so is regressionfix/...
staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
staging/maintenance 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
regressionfix/.* 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
+4
View File
@@ -91,7 +91,11 @@ date of first contribution):
* [Ganey](https://github.com/ganey)
* [Sven Lohrmann](https://github.com/malnvenshorn)
* [Andy Castille](https://github.com/klikini)
* [Gaston Dombiak](https://github.com/gdombiak)
* [Brad Fisher](https://github.com/bradcfisher)
* [Aldo Hoeben](https://github.com/fieldofview)
* [Henning Groß](https://github.com/hgross)
* [Jubaleth](https://github.com/jubaleth)
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
+139 -1017
View File
File diff suppressed because it is too large. Load diff
+12 -8
View File
@@ -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.
![Ticket flow chart](https://i.imgur.com/SmU7iCJ.png)
![Ticket flow chart](https://i.imgur.com/cw19qHX.png)
- **[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
+8 -14
View File
@@ -6,25 +6,23 @@ thanks to everyone who contributed!
## Patreon Patrons
* Andre Bubel
* Andrew Moorby
* Arnljot Arntsen
* Boris Hussein
* Brad Jackson
* Brian E. Tyler
* Christian Petropolis
* Christian Wolf
* COLLE+McVOY
* D Brian Kimmel
* DeltaMaker 3D Printers
* E3D BigBox
* Eric Betts
* Eric Slape
* Ernesto Martinez
* F. Kunsmann
* Frank Sander
* George Robles
* günter weber
* Hydra Research LLC
* James Seigel
* Jeff Moe
* Jared Go
* Jeff Renfer
* Jefferson Hunt
* Jeremiah Avery
@@ -35,29 +33,25 @@ thanks to everyone who contributed!
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kodama Inc.
* LA 3D Printer Repair
* Lewis Newby
* LulzBot®
* Makespace Madrid
* Mark Walker
* Martin Beattie
* Michael Aumock
* Miles Flavel
* mitchell hirsch
* Noe Ruiz
* Mosaic Manufacturing
* Patrick McGinnis
* Prof Yuh Wen Chen
* Randy C. Will
* Robert Gusek
* Roger Strolz
* Roy Cortes
* Rudolff Vang
* Samer Najia
* Simon Hallam
* Stefan Krister
* Sven Mueller
* Symbiotic Devices
* Thomas Hatley
* Timothy D Hoogland
* Trent Shumay
and 1351 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1446 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+4
View File
@@ -11,6 +11,10 @@ Apps
Session Keys
============
.. deprecated:: 1.3.11
This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` instead.
OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based
validity and are generated by OctoPrint for requesting apps.
+96 -2
View File
@@ -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.
@@ -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.
+3 -1
View File
@@ -219,7 +219,7 @@ Issue a print head command
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
interpreted as an integer signifying the speed in mm/s, to append to the command.
interpreted as an integer signifying the speed in mm/min, to append to the command.
home
Homes the print head in all of the given axes. Additional parameters are:
@@ -362,6 +362,8 @@ Issue a tool command
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command.
flowrate
Changes the flow rate factor to apply to extrusion of the tool.
+32 -14
View File
@@ -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:
+4 -2
View File
@@ -7,7 +7,8 @@ Version information
.. http:get:: /api/version
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
the API version, ``server`` containing the server version.
the API version, ``server`` containing the server version, ``text`` containing the server version including
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
**Example Request**
@@ -26,7 +27,8 @@ Version information
{
"api": "0.1",
"server": "1.1.0"
"server": "1.3.10",
"text": "OctoPrint 1.3.10"
}
:statuscode 200: No error
+543
View File
@@ -0,0 +1,543 @@
.. _sec-bundledplugins-appkeys:
Application Keys Plugin
=======================
The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10).
It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it
on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed
on a per-user base as well as globally by administrators.
.. _fig-bundledplugins-appkeys-confirmation:
.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png
:align: center
:alt: Confirmation
The plugin's confirmation generated for a new application key request.
.. _fig-bundledplugins-appkeys-user_settings:
.. figure:: ../images/bundledplugins-appkeys-user_settings.png
:align: center
:alt: Key management via user settings
Users can manage the application specific API keys registered to their account via their user settings.
.. _fig-bundledplugins-appkeys-settings:
.. figure:: ../images/bundledplugins-appkeys-settings.png
:align: center
:alt: Global key management via settings
Administrators can manage all application specific API keys registered to any user.
.. _sec-bundledplugins-appkeys-workflow:
Workflow
--------
The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist
of the following steps:
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
enters their username which is also their user ID into the App.
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
authorization process.
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
signals that no decision has been made yet.
6. The User either accepts or denies the access request which makes the Webinterface send a
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
an HTTP :http:statuscode:`404`.
.. mermaid::
sequenceDiagram
participant User
participant App
participant Webinterface
participant Server
note over User, Server: Step 1, 2 & 3
User->>App: enters URL of instance to connect to and optional user_id
App->>Server: GET /plugin/appkeys/probe
alt Workflow unsupported
Server->>App: 404
App->>User: alternative workflow, copy-paste key manually
else Workflow supported
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
note over User, Server: Step 4
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
Webinterface-->>User: Display confirmation dialog
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
note over User, Server: Step 5
loop Poll for decision
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 202
end
note over User, Server: Step 6 & 7
alt User accepts
User-->>Webinterface: Allow access
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (True)
Server->>Webinterface: 204
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 200, api_key
else User denies
User-->>Webinterface: Deny access
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (False)
Server->>Webinterface: 204
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 404
end
end
.. _sec-bundledplugins-appkeys-api:
API
---
.. _sec-bundledplugins-appkeys-api-probe:
Probe for workflow support
..........................
.. http:get:: /plugin/appkeys/probe
Probes for support of the workflow.
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
:status 204: the workflow is supported
.. _sec-bundledplugins-appkeys-api-startauthprocess:
Start authorization process
...........................
.. http:post:: /plugin/appkeys/request
Starts the authorization process.
Expects a :ref:`Key request <sec-bundledplugins-appkey-datamodel-keyrequest>` as request body.
The ``app`` parameter should be a human readable identifier to use
for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively,
so ``My App`` and ``my APP`` are considered the same application identifiers.
The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter
is left unset, any user will be able to complete the authorization process and grant access to the app with their
account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
is logged in on.
:json app: application identifier to use for the request, case insensitive
:json user: optional user id to restrict the decision to the specified user
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
.. _sec-bundledplugins-appkeys-api-polldecision:
Poll for decision on existing request
.....................................
.. http:get:: /plugin/appkeys/request/<str:app_token>
Endpoint generated per authorization request to poll for the result.
Returns an HTTP :http:statuscode:`202` while no decision has been made yet, an HTTP :http:statuscode:`200` and
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
HTTP :http:statuscode:`404` if the request has been denied or timed out.
.. note::
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
for more than 5s.
:status 200: access granted, API key in response body
:status 202: no decision has been made yet, continue polling
:status 404: access denied or request timed out
.. _sec-bundledplugins-appkeys-api-decide:
Decide on existing request
..........................
.. http:post:: /plugin/appkeys/decision/<str:user_token>
Endpoint to decide on the authorization request.
Expects a :ref:`Decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` as request body.
Returns an HTTP :http:statuscode:`204` on success.
:json decision: boolean value to indicate whether to confirm (``True``) or deny (``False``) access
:status 204: success
.. _sec-bundledplugins-appkeys-api-fetchlist:
Fetch list of existing application keys
.......................................
.. http:get:: /api/plugin/appkeys
Fetches a list of existing application keys and pending requests registered in the system for the current user.
If the additional optional parameter ``all`` is provided and the user has administrator rights, fetches a list
of *all** application keys and pending requests registered in the system for any user.
Returns a :http:statuscode:`200` with a :ref:`List response <sec-bundledplugins-appkey-datamodel-listreponse>` in the
body upon success.
:query all: Fetch all application keys and pending requests from all users. Requires administrator rights.
.. _sec-bundledplugins-appkeys-api-issuecommand:
Issue an application key command
................................
.. http:post:: /api/plugin/appkeys
Application key commands allow revoking existing application keys and manually generating new ones. The available
commands are:
revoke
Revokes an existing application key. Must belong to the user issuing the command, unless the user has admin rights
in which case they make revoke any application key in the system. Expects the key in question as parameter ``key``.
generate
Generates a new application key for the user, using the application identifier provided as parameter ``app``.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
**Example revoke request**
Revokes the (fictional) key ``aabbccddeeff112233445566``.
.. sourcecode:: http
POST /api/plugin/appkeys HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "revoke",
"key": "aabbccddeeff112233445566"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example generate request**
Generates a new key for application identifier "My awesome application 1.0".
.. sourcecode:: http
POST /api/plugin/appkeys HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "generate",
"key": "My awesome application 1.0"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``revoke`` or ``generate``
:json string key: ``revoke`` command: The key to revoke
:json string app: ``generate`` command: Application identifier for which to generate a key
:statuscode 204: No error
:statuscode 400: Invalid or missing parameter
.. _sec-bundledplugins-appkey-datamodel:
Data model
----------
.. _sec-bundledplugins-appkey-datamodel-keyrequest:
Key request
...........
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``app``
- 1
- str
- Application identifier to use for the request
* - ``user``
- 0..1
- str
- User identifier/name to restrict the request to
.. _sec-bundledplugins-appkey-datamodel-keyresponse:
Key response
............
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``apikey``
- 1
- str
- the API key generated for the application
.. _sec-bundledplugins-appkey-datamodel-decisionrequest:
Decision request
................
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``decision``
- 1
- boolean
- ``True`` if the access request it to be granted, ``False`` otherwise
.. _sec-bundledplugins-appkey-datamodel-listreponse:
List response
.............
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``keys``
- 1
- list of :ref:`key list entries <sec-bundledplugins-appkey-datamodel-keylistentry>`
- Keys registered in the system
* - ``pending``
- 1
- list of :ref:`pending list entries <sec-bundledplugins-appkey-datamodel-pendinglistentry>`
- Currently pending authorization requests
.. _sec-bundledplugins-appkey-datamodel-keylistentry:
Key list entry
..............
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``api_key``
- 1
- str
- API key
* - ``app_id``
- 1
- str
- Application identifier
* - ``user_id``
- 1
- str
- User ID of the key's owner
.. _sec-bundledplugins-appkey-datamodel-pendinglistentry:
Pending list entry
..................
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``app_id``
- 1
- str
- Application identifier
* - ``user_id``
- 0..1
- str
- optional: User ID of user who can grant or deny request
* - ``user_token``
- 1
- str
- Token to grant or deny request
.. _sec-bundledplugins-appkeys-jsclientlib:
JavaScript Client Library
-------------------------
.. js:function:: OctoPrintClient.plugins.appkeys.getKeys(opts)
Retrieves registered keys and pending requests for the current user.
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.getAllKeys(opts)
Retrieves registered keys and pending requests for all users.
Needs administrator rights.
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.generateKey(app, opts)
Generates a key for the given ``app`` and the current user.
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
:param string app: Application identifier
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.revokeKey(key, opts)
Revokes the given ``key``. The key must belong to the current user, or the current user must have administrator
rights.
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
:param string key: Key to revoke
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.decide(token, decision, opts)
Decides on an existing authorization request.
See :ref:`Decide on existing request <sec-bundledplugins-appkeys-api-decide>` for more details.
:param string token: User token for which to make the decision, as pushed to the client via the socket.
:param boolean decision: Whether to grant access (``true``) or not (``false``).
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
Probes for workflow support.
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
Starts a new authorization request for the provided ``app`` identifier.
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.requestForUser(app, user, opts)
Starts a new authorization request for the provided ``app`` and ``user`` identifiers.
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.checkDecision(token, opts)
Polls for a decision on an existing authorization request identified by ``token``.
See :ref:`Poll for decision on existing request <sec-bundledplugins-appkeys-api-polldecision>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
for the workflow, the promise is rejected.
**Example usage**
.. sourcecode:: javascript
OctoPrint.plugins.appkeys.authenticate("My App", "some_user")
.done(function(api_key) {
console.log("Got our API key:", api_key);
})
.fail(function() {
console.log("No API key for us");
})
:param string app: Application identifier
:param string user: Optional user identifier
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. _sec-bundledplugins-appkeys-sourcecode:
Source code
-----------
The source of the Application Keys plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/appkeys``.
+70
View File
@@ -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.
+35
View File
@@ -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``.
+3
View File
@@ -9,8 +9,11 @@ Bundled Plugins
action_command_prompt.rst
announcements.rst
appkeys.rst
backup.rst
cura.rst
discovery.rst
forcelogin.rst
logging.rst
pluginmanager.rst
printer_safety_check.rst
+39
View File
@@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
- hidden
- plugins
.. _sec-bundledplugins-pluginmanager-events:
Events
------
plugin_pluginmanager_install_plugin
A plugin was installed.
Payload:
* ``id``: the identifier of the installed plugin
* ``version``: the version of the installed plugin
* ``source``: source from which the plugin was installed, can be an URL or a path in the local file system
* ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path``
plugin_pluginmanager_uninstall_plugin
A plugin was uninstalled.
Payload:
* ``id``: the identifier of the uninstalled plugin
* ``version``: the version of the uninstalled plugin
plugin_pluginmanager_enable_plugin
A plugin was enabled.
Payload:
* ``id``: the identifier of the enabled plugin
* ``version``: the version of the enabled plugin
plugin_pluginmanager_disabled_plugin
A plugin was disabled.
Payload:
* ``id``: the identifier of the disabled plugin
* ``version``: the version of the disabled plugin
.. _sec-bundledplugins-pluginmanager-hooks:
Hooks
+16 -7
View File
@@ -16,17 +16,12 @@ such identification.
An example of a warning generated by the Printer Safety Check
Currently the following firmwares produce this warning:
* Anet A8 stock firmware
Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
for a list of currently identified printers.
If you know of further printers/printer firmwares that need to be added here, please
`get in touch on the forum and provide their response to an M115 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
.. seealso::
`Entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
.. note::
Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
@@ -34,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl
unexpectedly and with `catastrophic <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
.. _sec-bundledplugins-printer_safety_check-events:
Events
------
warning
A printer safety warning was triggered.
Payload:
* ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``)
* ``check_name``: name of check that was triggered (e.g. ``aneta8``)
* ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``)
.. _sec-bundledplugins-printer_safety_check-source:
Source Code
+23
View File
@@ -325,6 +325,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing
branch: devel
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
.. _sec-bundledplugins-softwareupdate-events:
Events
------
plugin_softwareupdate_update_succeeded
An update succeeded.
Payload:
* ``target``: update target
* ``from_version``: version from which was updated
* ``to_version``: version to which was updated
plugin_softwareupdate_update_failed
An update failed.
Payload:
* ``target``: update target
* ``from_version``: version from which was updated
* ``to_version``: version to which was updated
.. _sec-bundledplugins-softwareupdate-hooks:
Hooks
+14 -1
View File
@@ -81,7 +81,8 @@ Settings for the REST API:
# Whether to allow cross origin access to the API or not
allowCrossOrigin: false
# Additional app api keys, see REST API > Apps in the docs
# Additional app api keys, see REST API > Apps in the docs.
# Deprecated since 1.3.11, to be removed in 1.4.0!
apps:
"some.app.identifier:some_version":
pubkey: <RSA pubkey>
@@ -562,6 +563,9 @@ Use the following settings to enable or disable OctoPrint features:
- M117
- M118
# whether G90/G91 also influence absolute/relative mode of extruders
g90InfluencesExtruder: false
.. _sec-configuration-config_yaml-folder:
Folder
@@ -1058,6 +1062,15 @@ Use the following settings to configure the server:
# How many days to leave unused entries in the preemptive cache config
until: 7
# Configuration of the client IP check to warn about connections from external networks
ipCheck:
# whether to enable the check, defaults to true
enabled: true
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
trustedSubnets: []
.. note::
+29 -12
View File
@@ -6,15 +6,6 @@ Events
.. contents::
.. note::
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
to indicate what to do with the command contained.
.. _sec-events-configuration:
Configuration
@@ -85,6 +76,10 @@ and its origin via the placeholder ``{origin}``.
Available Events
================
.. note::
Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook <sec-plugins-hook-events-register_custom_events>`.
Server
------
@@ -141,7 +136,8 @@ Disconnected
The server has disconnected from the printer
Error
An error has occurred in the printer communication.
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
on the connection.
Payload:
@@ -322,6 +318,9 @@ PrintStarted
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who started the print job (if available)
.. deprecated:: 1.3.0
@@ -338,6 +337,10 @@ PrintFailed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the elapsed time of the print when it failed, in seconds (float)
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
.. deprecated:: 1.3.0
@@ -354,6 +357,8 @@ PrintDone
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the time needed for the print, in seconds (float)
.. deprecated:: 1.3.0
@@ -371,6 +376,9 @@ PrintCancelling
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who cancelled the print job (if available)
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
PrintCancelled
@@ -381,7 +389,10 @@ PrintCancelled
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of cancelling, if available
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who cancelled the print job (if available)
* ``position``: the print head position at the time of cancelling (if available)
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
@@ -408,7 +419,10 @@ PrintPaused
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of pausing, if available
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who paused the print job (if available)
* ``position``: the print head position at the time of pausing (if available)
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
@@ -435,6 +449,9 @@ PrintResumed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who resumed the print job (if available)
.. deprecated:: 1.3.0
+4
View File
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
.. code-block:: jinja
:caption: Default ``disable_hotends`` snippet
{% if printer_profile.extruder.sharedNozzle %}
M104 T0 S0
{% else %}
{% for tool in range(printer_profile.extruder.count) %}
M104 T{{ tool }} S0
{% endfor %}
{% endif %}
The ``disable_bed`` snippet is defined as follows:
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

+7 -3
View File
@@ -80,9 +80,13 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s
.. seealso::
`OctoPrint-ForceLogin <https://github.com/OctoPrint/OctoPrint-ForceLogin>`_
A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the
client library's :ref:`browser component <sec-jsclientlib-browser>` to login the user.
:ref:`Application Key Plugin <sec-bundledplugins-appkeys>`
A bundled plugin that implements an authorization workflow for third party clients. It adds various additional
methods to the JS Client Library.
:ref:`ForceLogin Plugin <sec-bundledplugins-forcelogin>`
A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and
various hooks. Utilizes the client library's :ref:`browser component <sec-jsclientlib-browser>` to login the
user.
.. toctree::
:maxdepth: 3
+6
View File
@@ -6,4 +6,10 @@ octoprint.util
.. automodule:: octoprint.util
:members:
.. _sec-modules-util-commandline:
octoprint.util.commandline
--------------------------
.. automodule:: octoprint.util.commandline
:members:
+85
View File
@@ -208,6 +208,10 @@ octoprint.accesscontrol.appkey
.. py:function:: acl_appkey_hook(*args, **kwargs)
.. deprecated:: 1.3.11
This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` instead.
By handling this hook plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
@@ -903,6 +907,34 @@ octoprint.comm.transport.serial.factory
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
optionally ``baudrate`` and ``timeout`` attributes as described above.
.. _sec-plugins-hook-events-register_custom_events:
octoprint.events.register_custom_events
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: register_custom_events_hook(*args, **kwargs)
Return a list of custom :ref:`events <sec-events>` to register in the system for your plugin.
Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object
will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_<IDENTIFIER>``. Their
value will be prefixed with ``plugin_<identifier>_``.
Example:
Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events
in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event``
and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``.
.. code-block:: python
:linenos:
def register_custom_events(*args, **kwargs):
return ["my_custom_event", "my_other_custom_event"]
:return: A list of custom events to register
:rtype: list
.. _sec-plugins-hook-filemanager-analysis-factory:
octoprint.filemanager.analysis.factory
@@ -1323,6 +1355,59 @@ octoprint.server.http.routes
:return: a list of 3-tuples with additional routes as defined above
:rtype: list
.. _sec-plugins-hook-server-sockjs-authed:
octoprint.server.sockjs.authed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
.. _sec-plugins-hook-server-sockjs-register:
octoprint.server.sockjs.register
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
Allows plugins to prevent a new :ref:`push socket client <sec-api-push>` to be registered to the system.
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
signals to not register the client.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user currently authenticated on the socket - might be None
:return: whether to proceed with registration (``True``) or not (``False``)
:rtype: boolean
.. _sec-plugins-hook-server-sockjs-emit:
octoprint.server.sockjs.emit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection <sec-api-push>`.
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object on which a message is about to be emitted
:param object user: the user currently authenticated on the socket - might be None
:param string message: the message type about to be emitted
:param dict payload: the payload of the message about to be emitted (may be None)
:return: whether to proceed with sending the message (``True``) or not (``False``)
:rtype: boolean
.. _sec-plugins-hook-timelapse-extensions:
octoprint.timelapse.extensions
+17
View File
@@ -0,0 +1,17 @@
# init/systemd files for OctoPrint.
Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different
setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly.
## init
```
octoprint.default => /etc/default/octoprint
octoprint.init => /etc/init.d/octoprint
```
## systemd
```
octoprint.service => /etc/systemd/service/octoprint.service
```
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=The snappy web interface for your 3D printer
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=pi
ExecStart=/home/pi/OctoPrint/venv/bin/octoprint
[Install]
WantedBy=multi-user.target
+40 -35
View File
@@ -12,45 +12,53 @@ import octoprint_setuptools
#-----------------------------------------------------------------------------------------------------------------------
# Supported python versions
PYTHON_REQUIRES = ">=2.7.9,<3"
# Requirements for our application
INSTALL_REQUIRES = [
"flask>=0.10.1,<0.11",
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
"werkzeug>=0.8.3,<0.9",
"tornado==4.5.3",
#"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a
# vendored one
"PyYAML>=3.10,<3.11",
"Flask-Login>=0.2.11,<0.3",
"Flask-Principal>=0.3.5,<0.4",
"Flask-Babel>=0.9,<0.10",
"Flask-Assets>=0.10,<0.11",
"markdown>=2.6.9,<2.7",
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
# changes that might affect plugins, or due to other observed problems
"flask>=0.10.1,<0.11", # newer versions require newer Jinja versions
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
"Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"Flask-Principal>=0.4,<0.5",
"Flask-Babel>=0.12,<0.13",
"Flask-Assets>=0.12,<0.13",
"werkzeug>=0.14.1,<0.15",
"PyYAML>=3.13,<4",
"markdown>=3.0,<3.1",
"pyserial>=3.4,<3.5",
"netaddr>=0.7.19,<0.8",
"watchdog>=0.8.3,<0.9",
"watchdog>=0.9.0,<0.10",
"sarge==0.1.5post0",
"netifaces>=0.10.6,<0.11",
"pylru>=1.0.9,<1.1",
"rsa>=3.2.3,<3.3",
"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"
]
@@ -63,7 +71,7 @@ EXTRA_REQUIRES = dict(
develop=[
# Testing dependencies
"mock>=2.0.0,<3",
"nose>=1.3.0,<1.4",
"nose>=1.3.7,<1.4",
"ddt",
# Documentation dependencies
@@ -75,13 +83,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 = []
@@ -154,10 +159,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",
+7 -3
View File
@@ -103,8 +103,9 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
if callable(after_logging):
after_logging(**kwargs)
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
safe_mode = safe_mode or settings_safe_mode
settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None
settings_incomplete_startup_safemode = "incomplete_startup" if settings.getBoolean(["server", "incompleteStartup"]) else None
safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode
kwargs["safe_mode"] = safe_mode
if callable(after_safe_mode):
after_safe_mode(**kwargs)
@@ -141,7 +142,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
ignore_blacklist=ignore_blacklist,
connectivity_checker=connectivity_checker)
except Exception as ex:
raise FatalStartupError("Could not initialize settings manager", cause=ex)
raise FatalStartupError("Could not initialize plugin manager", cause=ex)
kwargs["plugin_manager"] = plugin_manager
if callable(after_plugin_manager):
@@ -595,6 +596,9 @@ def main():
# cut off stuff from the beginning
args = args[-1 * sys_args_length:] if sys_args_length else []
from octoprint.util.fixes import patch_sarge_async_on_py2
patch_sarge_async_on_py2()
from octoprint.cli import octo
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
+4
View File
@@ -2,6 +2,10 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
import sys
if sys.version_info[0] >= 3:
raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
if __name__ == "__main__":
import octoprint
octoprint.main()
+11 -2
View File
@@ -26,6 +26,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if safe_mode == "flag":
reason = "command line flag"
elif safe_mode == "settings":
reason = "setting in config.yaml"
elif safe_mode == "incomplete_startup":
reason = "problem during last startup"
else:
reason = "unknown"
logger.info("Reason for safe mode: {}".format(reason))
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
@@ -179,7 +188,7 @@ def serve_command(ctx, **kwargs):
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
run_server(basedir, configfile, host, port, debug,
@@ -217,7 +226,7 @@ if sys.platform != "win32" and sys.platform != "darwin":
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
if pid is None:
+25 -6
View File
@@ -14,6 +14,7 @@ except ImportError:
import Queue as queue
import threading
import collections
import re
from octoprint.settings import settings
import octoprint.plugin
@@ -23,7 +24,7 @@ _instance = None
def all_events():
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)]
class Events(object):
@@ -119,6 +120,23 @@ class Events(object):
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
@classmethod
def register_event(cls, event, prefix=None):
name = cls._to_identifier(event)
if prefix:
event = prefix + event
name = cls._to_identifier(prefix) + name
setattr(cls, name, event)
return name, event
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
@classmethod
def _to_identifier(cls, name):
s1 = cls._first_cap_re.sub(r'\1_\2', name)
return cls._all_cap_re.sub(r'\1_\2', s1).upper()
def eventManager():
global _instance
@@ -135,6 +153,7 @@ class EventManager(object):
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
self._startup_signaled = False
self._shutdown_signaled = False
@@ -156,14 +175,14 @@ class EventManager(object):
self._shutdown_signaled = True
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
for listener in eventListeners:
self._logger.debug("Sending action to %r" % listener)
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except:
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
@@ -227,7 +246,7 @@ class EventManager(object):
return
self._registeredListeners[event].append(callback)
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
def unsubscribe (self, event, callback):
"""
@@ -239,7 +258,7 @@ class EventManager(object):
return
self._registeredListeners[event].remove(callback)
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
self._logger.debug("Unsubscribed listener {!r} for event {}".format(callback, event))
def join(self, timeout=None):
self._worker.join(timeout)
+7 -13
View File
@@ -21,6 +21,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import logging
import threading
from octoprint.settings import settings as s
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
@@ -32,16 +33,6 @@ from octoprint.util import deprecated
_instance = None
def _validate_plugin(phase, plugin_info):
if phase == "after_load":
if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin):
# transform app plugin into hook
import warnings
warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning)
hooks = plugin_info.hooks
if not "octoprint.accesscontrol.appkey" in hooks:
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
return True
def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None,
@@ -168,7 +159,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None,
initialized=True):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
@@ -206,7 +198,6 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
is determined be presence of injected ``_identifier`` property.
"""
if not isinstance(types, (list, tuple)):
@@ -216,18 +207,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
if kwargs is None:
kwargs = dict()
logger = logging.getLogger(__name__)
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if initialized and not hasattr(plugin, "_identifier"):
continue
if hasattr(plugin, method):
logger.debug("Calling {} on {}".format(method, plugin._identifier))
try:
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(plugin._identifier, plugin, result)
except Exception as exc:
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
logger.exception("Error while calling plugin %s" % plugin._identifier)
if error_callback:
error_callback(plugin._identifier, plugin, exc)
+6 -3
View File
@@ -839,12 +839,15 @@ class PluginManager(object):
# ... then create and return the real one
return self._import_plugin(key, *module,
name=name, version=version, summary=summary, author=author, url=url,
module_name=module_name, name=name, version=version, summary=summary, author=author, url=url,
license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata)
def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
def _import_plugin(self, key, f, filename, description, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
try:
instance = imp.load_module(key, f, filename, description)
if module_name:
instance = imp.load_module(module_name, f, filename, description)
else:
instance = imp.load_module(key, f, filename, description)
plugin = PluginInfo(key, filename, instance,
name=name,
version=version,
+19 -20
View File
@@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
# noinspection PyCompatibility
from past.builtins import basestring
class OctoPrintPlugin(Plugin):
"""
The parent class of all OctoPrint plugin mixins.
@@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
externally reachable, use :func:`on_after_startup` instead or additionally.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``StartupPlugin.on_startup``.
:param string host: the host the server will listen on, may be ``0.0.0.0``
@@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
"""
Called just after launch of the server, so when the listen loop is actually running already.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``StartupPlugin.on_after_startup``.
"""
@@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
"""
Called upon the imminent shutdown of OctoPrint.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``ShutdownPlugin.on_shutdown``.
"""
pass
@@ -225,6 +234,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
js
JavaScript files, such as additional view models
jsclient
JavaScript files containing additional parts for the JS Client Library (since 1.3.10)
css
CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode.
less
@@ -239,6 +250,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
def get_assets(self):
return dict(
js=['js/my_file.js', 'js/my_other_file.js'],
clientjs=['clientjs/my_file.js'],
css=['css/my_styles.css'],
less=['less/my_styles.less']
)
@@ -1799,6 +1811,10 @@ class EventHandlerPlugin(OctoPrintPlugin):
"""
Called by OctoPrint upon processing of a fired event on the platform.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
Arguments:
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
for possible values
@@ -2043,20 +2059,3 @@ class ProgressPlugin(OctoPrintPlugin):
:param int progress: Current progress as a value between 0 and 100
"""
pass
class AppPlugin(OctoPrintPlugin):
"""
Using the :class:`AppPlugin mixin` plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
.. deprecated:: 1.2.0
Refer to the :ref:`octoprint.accesscontrol.appkey hook <sec-plugins-hook-accesscontrol-appkey>` instead.
"""
# noinspection PyMethodMayBeStatic
def get_additional_apps(self):
return []
@@ -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;
+403
View File
@@ -0,0 +1,403 @@
# coding=utf-8
from __future__ import absolute_import
import flask
import threading
import os
import yaml
import codecs
import time
from binascii import hexlify
from collections import defaultdict
from flask_babel import gettext
import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, admin_permission
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
class AppAlreadyExists(Exception):
pass
class PendingDecision(object):
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = monotonic_time()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
self.poll_timeout.start()
def external(self):
return dict(app_id=self.app_id,
user_id=self.user_id,
user_token=self.user_token)
class ReadyDecision(object):
def __init__(self, app_id, app_token, user_id):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
@classmethod
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
class ActiveKey(object):
def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
self.user_id = user_id
def external(self):
return dict(app_id=self.app_id,
api_key=self.api_key,
user_id=self.user_id)
def internal(self):
return dict(app_id=self.app_id,
api_key=self.api_key)
@classmethod
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._pending_decisions = []
self._pending_lock = threading.RLock()
self._ready_decisions = []
self._ready_lock = threading.RLock()
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
self._key_path = None
def initialize(self):
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
##~~ TemplatePlugin
def get_template_configs(self):
return [dict(type="usersettings", name=gettext("Application Keys")),
dict(type="settings", name=gettext("Application Keys"))]
##~~ AssetPlugin
def get_assets(self):
return dict(js=["js/appkeys.js"],
clientjs=["clientjs/appkeys.js"],
less=["less/appkeys.less"],
css=["css/appkeys.css"])
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
@no_firstrun_access
def handle_probe(self):
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if not "app" in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
user_id = None
if "user" in data:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
app_name=app_name,
user_token=user_token,
user_id=user_id))
response = flask.jsonify(app_token=app_token)
response.status_code = 201
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
return response
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
@no_firstrun_access
def handle_decision_poll(self, app_token):
result = self._get_pending_by_app_token(app_token)
if result:
for pending_decision in result:
pending_decision.poll_timeout.reset()
response = flask.jsonify(message="Awaiting decision")
response.status_code = 202
return response
result = self._get_decision(app_token)
if result:
return flask.jsonify(api_key=result)
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if not "decision" in data:
return flask.make_response("No decision provided", 400)
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
result = self._set_decision(user_token, decision, user_id)
if not result:
return flask.abort(404)
# Close access_request dialog for this request on all open OctoPrint connections
self._plugin_manager.send_plugin_message(self._identifier, dict(
type="end_request",
user_token=user_token
))
return NO_CONTENT
def is_blueprint_protected(self):
return False # No API key required to request API access
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return dict(generate=["app"],
revoke=["key"])
def on_api_get(self, request):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
return flask.jsonify(keys=map(lambda x: x.external(), keys),
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
def on_api_command(self, command, data):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if command == "revoke":
api_key = data.get("key")
if not api_key:
return flask.abort(400)
if not admin_permission.can():
user_for_key = self._user_for_api_key(api_key)
if user_for_key is None or user_for_key.user_id != user_id:
return flask.abort(403)
self._delete_api_key(api_key)
elif command == "generate":
# manual generateKey
app_name = data.get("app")
if not app_name:
return flask.abort(400)
self._add_api_key(user_id, app_name.strip())
return NO_CONTENT
##~~ key validator hook
def validate_api_key(self, api_key, *args, **kwargs):
return self._user_for_api_key(api_key)
##~~ Helpers
def _add_pending_decision(self, app_name, user_id=None):
app_token = self._generate_key()
user_token = self._generate_key()
with self._pending_lock:
self._remove_stale_pending()
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
timeout_callback=self._expire_pending))
return app_token, user_token
def _get_pending_by_app_token(self, app_token):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.app_token == app_token:
result.append(data)
return result
def _get_pending_by_user_id(self, user_id):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_id == user_id or data.user_id is None:
result.append(data)
return result
def _expire_pending(self, user_token):
with self._pending_lock:
len_before = len(self._pending_decisions)
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._plugin_manager.send_plugin_message(self._identifier, dict(
type="end_request",
user_token=user_token
))
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = filter(lambda x: x.created >= cutoff,
self._pending_decisions)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
def _set_decision(self, user_token, decision, user_id):
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
pending = data
break
else:
return False # not found
if decision:
with self._ready_lock:
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
with self._pending_lock:
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
return True
def _get_decision(self, app_token):
self._remove_stale_pending()
with self._ready_lock:
for data in self._ready_decisions:
if data.app_token == app_token:
decision = data
break
else:
return False # not found
api_key = self._add_api_key(decision.user_id, decision.app_id)
with self._ready_lock:
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
return api_key
def _add_api_key(self, user_id, app_name):
with self._keys_lock:
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
return key.api_key
key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
self._save_keys()
return key.api_key
def _delete_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
self._keys[user_id] = filter(lambda x: x.api_key != api_key, data)
self._save_keys()
def _user_for_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
if filter(lambda x: x.api_key == api_key, data):
return self._user_manager.findUser(userid=user_id)
return None
def _api_keys_for_user(self, user_id):
with self._keys_lock:
return self._keys[user_id]
def _all_api_keys(self):
with self._keys_lock:
result = []
for user_id, keys in self._keys.items():
result += keys
return result
def _generate_key(self):
return hexlify(os.urandom(16))
def _load_keys(self):
with self._keys_lock:
if not os.path.exists(self._key_path):
return
try:
with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
persisted = yaml.safe_load(f)
except:
self._logger.exception("Could not load application keys from {}".format(self._key_path))
return
if not isinstance(persisted, dict):
return
keys = defaultdict(list)
for user_id, persisted_keys in persisted.items():
keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
self._keys = keys
def _save_keys(self):
with self._keys_lock:
to_persist = dict()
for user_id, keys in self._keys.items():
to_persist[user_id] = [x.internal() for x in keys]
try:
with atomic_write(self._key_path) as f:
yaml.safe_dump(to_persist, f)
except:
self._logger.exception("Could not write application keys to {}".format(self._key_path))
__plugin_name__ = u"Application Keys Plugin"
__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys"
__plugin_author__ = u"Gina Häußge, Aldo Hoeben"
__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to "
u"obtain an API key without you manually copy-pasting it.")
__plugin_implementation__ = AppKeysPlugin()
__plugin_hooks__ = {
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
}
@@ -0,0 +1,98 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintAppKeysClient = function(base) {
this.base = base;
};
OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
return this.base.simpleApiGet("appkeys", opts);
};
OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
};
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
};
OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
};
OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
};
OctoPrintAppKeysClient.prototype.probe = function(opts) {
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
};
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
return this.requestForUser(app, undefined, opts);
};
OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
};
OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
};
OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
var deferred = $.Deferred();
var client = this;
client.probe()
.done(function() {
client.requestForUser(app, user)
.done(function(response) {
var token = response.app_token;
if (!token) {
// no token received, something went wrong
deferred.reject();
return;
}
var interval = 1000;
var poll = function() {
client.checkDecision(token)
.done(function(response) {
if (response.api_key) {
// got a decision, resolve the promise
deferred.resolve(response.api_key);
} else {
// no decision yet, poll a bit more
deferred.notify();
window.setTimeout(poll, interval);
}
})
.fail(function() {
// something went wrong
deferred.reject();
});
};
window.setTimeout(poll, interval);
})
.fail(function() {
// something went wrong
deferred.reject();
});
})
.fail(function() {
// workflow unsupported
deferred.reject();
});
return deferred.promise();
};
OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient);
return OctoPrintAppKeysClient;
});
@@ -0,0 +1 @@
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}
@@ -0,0 +1,308 @@
$(function() {
function UserAppKeysViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.keys = new ItemListHelper(
"plugin.appkeys.userkeys",
{
"app": function (a, b) {
// sorts ascending
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
return 0;
}
},
{
},
"app",
[],
[],
5
);
self.pending = {};
self.openRequests = {};
self.editorApp = ko.observable();
self.requestData = function() {
OctoPrint.plugins.appkeys.getKeys()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
self.keys.updateItems(response.keys);
self.pending = response.pending;
_.each(self.pending, function(data, token) {
self.openRequests[token] = self.promptForAccess(data.app_id, token);
})
};
self.generateKey = function() {
return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
.done(self.requestData)
.done(function() {
self.editorApp("");
});
};
self.revokeKey = function(key) {
var perform = function() {
OctoPrint.plugins.appkeys.revokeKey(key)
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
perform);
};
self.allowApp = function(token) {
return OctoPrint.plugins.appkeys.decide(token, true)
.done(self.requestData);
};
self.denyApp = function(token) {
return OctoPrint.plugins.appkeys.decide(token, false)
.done(self.requestData);
};
self.promptForAccess = function(app, token) {
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
message = _.sprintf(message, {app: app});
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
return new PNotify({
title: gettext("Access Request"),
text: message,
hide: false,
icon: "fa fa-key",
confirm: {
confirm: true,
buttons: [{
text: gettext("Allow"),
click: function(notice) {
self.allowApp(token);
notice.remove();
}
}, {
text: gettext("Deny"),
click: function(notice) {
self.denyApp(token);
notice.remove();
}
}]
},
buttons: {
sticker: false,
closer: false
}
});
};
self.onUserSettingsShown = function() {
self.requestData();
};
self.onUserLoggedIn = function() {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin !== "appkeys") {
return;
}
var app, token, user;
if (data.type === "request_access" && self.loginState.isUser()) {
app = data.app_name;
token = data.user_token;
user = data.user_id;
if (user && user !== self.loginState.username()) {
return;
}
if (self.pending[token] !== undefined) {
return;
}
self.openRequests[token] = self.promptForAccess(app, token);
} else if (data.type === "end_request") {
token = data.user_token;
if (self.openRequests[token] !== undefined) {
// another instance responded to the access request before the current user did
if (self.openRequests[token].state !== "closed") {
self.openRequests[token].remove();
}
delete self.openRequests[token]
}
}
};
}
function AllAppKeysViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.keys = new ItemListHelper(
"plugin.appkeys.allkeys",
{
"user_app": function (a, b) {
// sorts ascending, first by user, then by app
if (a["user_id"] > b["user_id"]) return 1;
if (a["user_id"] < b["user_id"]) return -1;
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
return 0;
}
},
{
},
"user_app",
[],
[],
10
);
self.users = ko.observableArray([]);
self.apps = ko.observableArray([]);
self.markedForDeletion = ko.observableArray([]);
self.onSettingsShown = function() {
self.requestData();
};
self.onUserLoggedIn = function() {
self.requestData();
};
self.requestData = function() {
OctoPrint.plugins.appkeys.getAllKeys()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
self.keys.updateItems(response.keys);
var users = [];
var apps = [];
_.each(response.keys, function(key) {
users.push(key.user_id);
apps.push(key.app_id.toLowerCase());
});
users = _.uniq(users);
users.sort();
self.users(users);
apps = _.uniq(apps);
apps.sort();
self.apps(apps);
};
self.revokeKey = function(key) {
var perform = function() {
OctoPrint.plugins.appkeys.revokeKey(key)
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
perform);
};
self.revokeMarked = function() {
var perform = function() {
self._bulkRevoke(self.markedForDeletion())
.done(function() {
self.markedForDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
perform);
};
self.markAllOnPageForDeletion = function() {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
};
self.markAllForDeletion = function() {
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
};
self.markAllByUserForDeletion = function(user) {
self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
};
self.markAllByAppForDeletion = function(app) {
self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); })
};
self.markAllByFilterForDeletion = function(filter) {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))));
};
self.clearMarked = function() {
self.markedForDeletion.removeAll();
};
self._bulkRevoke = function(keys) {
var title, message, handler;
title = gettext("Revoking application keys");
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length});
handler = function(key) {
return OctoPrint.plugins.appkeys.revokeKey(key)
.done(function() {
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
};
var deferred = $.Deferred();
var promise = deferred.promise();
var options = {
title: title,
message: message,
max: keys.length,
output: true
};
showProgressModal(options, promise);
var requests = [];
_.each(keys, function(key) {
var request = handler(key);
requests.push(request)
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
}
OCTOPRINT_VIEWMODELS.push([
UserAppKeysViewModel,
["loginStateViewModel"],
["#usersettings_plugin_appkeys"]
]);
OCTOPRINT_VIEWMODELS.push([
AllAppKeysViewModel,
["loginStateViewModel"],
["#settings_plugin_appkeys"]
])
});
@@ -0,0 +1,24 @@
#settings_plugin_appkeys_userkeys_table,
#settings_plugin_appkeys_allkeys_table {
.settings_plugin_appkeys_app {
}
.settings_plugin_appkeys_actions {
width: 75px;
text-align: center;
a {
color: black;
}
}
.settings_plugin_appkeys_user {
width: 100px;
}
.settings_plugin_appkeys_checkbox {
text-align: center;
width: 10px;
input[type="checkbox"] {
margin-top: 0;
}
}
}
@@ -0,0 +1,59 @@
<div data-bind="visible: keys.allSize() <= 0">
<p>{{ _('There are no application keys registered yet.') }}</p>
</div>
<div data-bind="visible: keys.allSize() > 0">
<div class="pull-left">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: markAllOnPageForDeletion">{{ _('Select all on this page') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: markAllForDeletion">{{ _('Select all') }}</a></li>
<li class="divider"></li>
<li class="dropdown-submenu">
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by user...') }}</a>
<ul class="dropdown-menu" data-bind="foreach: users">
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByUserForDeletion($data) }, text: $data"></a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by app...') }}</a>
<ul class="dropdown-menu" data-bind="foreach: apps">
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByAppForDeletion($data) }, text: $data"></a></li>
</ul>
</li>
<li class="divider"></li>
<li><a href="javascript:void(0)" data-bind="click: clearMarked">{{ _('Clear selection') }}</a></li>
</ul>
</div>
<button class="btn btn-small" data-bind="click: revokeMarked, enable: markedForDeletion().length > 0">{{ _('Revoke selected') }}</button>
</div>
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_allkeys_table">
<thead>
<tr>
<th class="settings_plugin_appkeys_checkbox"></th>
<th class="settings_plugin_appkeys_user">{{ _('User') }}</th>
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: keys.paginatedItems">
<tr>
<td class="settings_plugin_appkeys_checkbox"><input type="checkbox" data-bind="value: api_key, checked: $root.markedForDeletion"></td>
<td class="settings_plugin_appkeys_user"><span data-bind="text: user_id"></span></td>
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: keys.pages">
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
</ul>
</div>
</div>
@@ -0,0 +1,49 @@
<legend>{{ _('Registered application keys') }}</legend>
<div data-bind="visible: keys.allSize() <= 0">
<p>{{ _('There are no application keys registered yet.') }}</p>
</div>
<div data-bind="visible: keys.allSize() > 0">
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_userkeys_table">
<thead>
<tr>
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: keys.paginatedItems">
<tr>
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: keys.pages">
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
</ul>
</div>
</div>
<legend>{{ _('Manually generate an application key') }}</legend>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Application identifier') }}</label>
<div class="controls">
<input type="text" data-bind="value: editorApp">
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="click: generateKey">{{ _('Generate') }}</button>
</div>
</div>
</form>
+171 -85
View File
@@ -11,7 +11,8 @@ 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.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
from octoprint.util.platform import is_os_compatible
from octoprint.util.pip import LocalPipCaller
try:
@@ -69,6 +70,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
def get_assets(self):
return dict(js=["js/backup.js"],
clientjs=["clientjs/backup.js"],
css=["css/backup.css"],
less=["less/backup.less"])
@@ -82,7 +84,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(backups=backups,
backup_in_progress=len(self._in_progress) > 0,
unknown_plugins=unknown_plugins)
unknown_plugins=unknown_plugins,
restore_supported=is_os_compatible(["!windows"]))
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
@admin_permission.require(403)
@@ -134,6 +137,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
self._logger.info(u"... done creating backup zip.")
def on_backup_error(name, exc_info):
with self._in_progress_lock:
try:
self._in_progress.remove(name)
except ValueError:
# we'll ignore that
pass
self._send_client_message("backup_error", payload=dict(name=name,
error=u"{}".format(exc_info[1])))
self._logger.error(u"Error while creating backup zip", exc_info=exc_info)
thread = threading.Thread(target=self._create_backup,
args=(backup_file,),
@@ -142,7 +156,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
plugin_manager=self._plugin_manager,
datafolder=self.get_plugin_data_folder(),
on_backup_start=on_backup_start,
on_backup_done=on_backup_done))
on_backup_done=on_backup_done,
on_backup_error=on_backup_error))
thread.daemon = True
thread.start()
@@ -171,6 +186,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
@admin_permission.require(403)
@restricted_access
def perform_restore(self):
if not is_os_compatible(["!windows"]):
return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400)
input_name = "file"
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
@@ -199,8 +217,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
self._send_client_message("logline", dict(line=line, type="stdout"))
for plugin in plugins:
octoprint_compatible = plugin["compatibility"]["octoprint"]
os_compatible = plugin["compatibility"]["os"]
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
@@ -250,6 +268,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
def on_restore_failed(path):
self._send_client_message("restore_failed")
def on_invalid_backup(line):
on_log_error(line)
archive = tempfile.NamedTemporaryFile(delete=False)
archive.close()
shutil.copy(path, archive.name)
@@ -263,6 +284,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
datafolder=self.get_plugin_data_folder(),
on_install_plugins=on_install_plugins,
on_report_unknown_plugins=on_report_unknown_plugins,
on_invalid_backup=on_invalid_backup,
on_log_progress=on_log_progress,
on_log_error=on_log_error,
on_restore_start=on_restore_start,
@@ -300,8 +322,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
import click
@click.command("backup")
@click.option("--exclude", multiple=True)
@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)
@@ -309,16 +337,22 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
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("Created {}".format(backup_file))
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
@@ -359,8 +393,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
click.echo(u"\t{}".format(line))
for plugin in plugins:
octoprint_compatible = plugin["compatibility"]["octoprint"]
os_compatible = plugin["compatibility"]["os"]
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
@@ -407,7 +441,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
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_log_error=on_log_error,
on_invalid_backup=on_log_error):
click.echo(u"Restored from {}".format(path))
else:
click.echo(u"Restoring from {} failed".format(path), err=True)
@@ -479,11 +514,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
thread.start()
@classmethod
def _get_disk_size(cls, path):
def _get_disk_size(cls, path, ignored=None):
if ignored is None:
ignored = []
if path in ignored:
return 0
total = 0
for entry in scandir(path):
if entry.is_dir():
total += cls._get_disk_size(entry.path)
total += cls._get_disk_size(entry.path, ignored=ignored)
elif entry.is_file():
total += entry.stat().st_size
return total
@@ -558,81 +599,103 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
plugin_manager=None,
datafolder=None,
on_backup_start=None,
on_backup_done=None):
if exclude is None:
exclude = []
on_backup_done=None,
on_backup_error=None):
exclude_by_default = ("generated", "logs", "watched",)
configfile = settings._configfile
basedir = settings._basedir
try:
if exclude is None:
exclude = []
temporary_path = os.path.join(datafolder, ".{}".format(name))
final_path = os.path.join(datafolder, name)
configfile = settings._configfile
basedir = settings._basedir
size = cls._get_disk_size(basedir)
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
temporary_path = os.path.join(datafolder, ".{}".format(name))
final_path = os.path.join(datafolder, name)
own_folder = datafolder
defaults = [os.path.join(basedir, "config.yaml"),] + \
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
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
# check how much many bytes we are about to backup
size = os.stat(configfile).st_size
for folder in default_settings["folder"].keys():
if folder in exclude:
if folder in exclude or folder in exclude_by_default:
continue
add_to_zip(settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[own_folder,])
size += cls._get_disk_size(settings.global_get_basefolder(folder),
ignored=[own_folder,])
size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,])
# backup anything else that might be lying around in our basedir
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
# since we can't know the compression ratio beforehand, we assume we need the same amount of space
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
# 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
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
plugins.append(dict(key=plugin.key,
name=plugin.name,
url=plugin.url))
if callable(on_backup_start):
on_backup_start(name, temporary_path, exclude)
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip:
def add_to_zip(source, target, ignored=None):
if ignored is None:
ignored = []
os.rename(temporary_path, final_path)
if source in ignored:
return
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
if os.path.isdir(source):
for entry in scandir(source):
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
elif os.path.isfile(source):
zip.write(source, arcname=target)
# add metadata
metadata = dict(version=get_octoprint_version_string(),
excludes=exclude)
zip.writestr("metadata.json", json.dumps(metadata))
# backup current config file
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
# backup configured folder paths
for folder in default_settings["folder"].keys():
if folder in exclude or folder in exclude_by_default:
continue
add_to_zip(settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[own_folder,])
# backup anything else that might be lying around in our basedir
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
# add list of installed plugins
plugins = []
plugin_folder = settings.global_get_basefolder("plugins")
for key, plugin in plugin_manager.plugins.items():
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
# ignore anything bundled or from the plugins folder we already include in the backup
continue
plugins.append(dict(key=plugin.key,
name=plugin.name,
url=plugin.url))
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
shutil.move(temporary_path, final_path)
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
except:
if callable(on_backup_error):
exc_info = sys.exc_info()
try:
on_backup_error(name, exc_info)
finally:
del exc_info
raise
@classmethod
def _restore_backup(cls, path,
@@ -647,6 +710,13 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
on_restore_start=None,
on_restore_done=None,
on_restore_failed=None):
if not is_os_compatible(["!windows"]):
if callable(on_log_error):
on_log_error(u"Restore is not supported on this operating system")
if callable(on_restore_failed):
on_restore_failed(path)
return False
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
basedir = settings._basedir
@@ -670,15 +740,19 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
except KeyError:
if callable(on_invalid_backup):
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
if callable(on_restore_failed):
on_restore_failed(path)
return False
metadata_bytes = zip.read(metadata_zipinfo)
metadata = json.loads(metadata_bytes)
backup_version = get_comparable_version(metadata["version"])
if backup_version > get_octoprint_version():
backup_version = get_comparable_version(metadata["version"], base=True)
if backup_version > get_octoprint_version(base=True):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
if callable(on_restore_failed):
on_restore_failed(path)
return False
# unzip to temporary folder
@@ -697,6 +771,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if not os.path.exists(configfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks config.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
import yaml
@@ -709,6 +785,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if not os.path.exists(userfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks users.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
if callable(on_log_progress):
@@ -756,18 +834,18 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if callable(on_log_progress):
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
os.rename(basedir, basedir_backup)
shutil.move(basedir, basedir_backup)
try:
if callable(on_log_progress):
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
os.rename(basedir_extracted, basedir)
shutil.move(basedir_extracted, basedir)
except:
if callable(on_log_error):
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
on_log_error(u"Rolling back old config data")
os.rename(basedir_backup, basedir)
shutil.move(basedir_backup, basedir)
if callable(on_restore_failed):
on_restore_failed(path)
@@ -795,10 +873,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
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)
exc_info = sys.exc_info()
try:
if callable(on_log_error):
on_log_error(u"Error while running restore", exc_info=exc_info)
if callable(on_restore_failed):
on_restore_failed(path)
finally:
del exc_info
return False
finally:
@@ -813,6 +895,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if callable(on_log_progress):
on_log_progress(u"Restarting...")
if callable(on_restore_done):
on_restore_done(path)
try:
sarge.run(restart_command, async_=True)
except:
@@ -822,8 +907,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
on_log_error(u"Please restart OctoPrint manually")
return False
if callable(on_restore_done):
on_restore_done(path)
else:
if callable(on_restore_done):
on_restore_done(path)
return True
@@ -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;
});
@@ -1,56 +1,3 @@
(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;
});
$(function() {
function BackupViewModel(parameters) {
var self = this;
@@ -80,6 +27,7 @@ $(function() {
self.excludeFromBackup = ko.observableArray([]);
self.backupInProgress = ko.observable(false);
self.restoreSupported = ko.observable(true);
self.backupUploadButton = $("#settings-backup-upload");
self.backupUploadData = undefined;
@@ -119,6 +67,7 @@ $(function() {
self.fromResponse = function(response) {
self.backups.updateItems(response.backups);
self.unknownPlugins(response.unknown_plugins);
self.restoreSupported(response.restore_supported);
};
self.createBackup = function() {
@@ -141,7 +90,15 @@ $(function() {
};
self.restoreBackup = function(backup) {
if (!self.restoreSupported()) return;
var perform = function() {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Preparing to restore...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
OctoPrint.plugins.backup.restoreBackup(backup);
};
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
@@ -152,6 +109,12 @@ $(function() {
if (self.backupUploadData === undefined) return;
var perform = function() {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
self.backupUploadData.submit();
};
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
@@ -208,14 +171,24 @@ $(function() {
if (data.type === "backup_done") {
self.requestData();
self.backupInProgress(false);
new PNotify({
title: gettext("Backup created successfully"),
type: "success"
});
} else if (data.type === "backup_started") {
self.backupInProgress(true);
} else if (data.type === "backup_error") {
self.requestData();
self.backupInProgress(false);
new PNotify({
title: gettext("Creating the backup failed"),
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
type: "error",
hide: false
});
} else if (data.type === "restore_started") {
self.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"});
@@ -46,7 +46,7 @@
<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>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></td>
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()">&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
</tr>
</tbody>
</table>
@@ -91,30 +91,36 @@
</div>
</form>
<h3>{{ _('Restore from uploaded backup') }}</h3>
<div data-bind="visible: restoreSupported()">
<h3>{{ _('Restore from uploaded backup') }}</h3>
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
<form class="form-horizontal">
<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>
<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>
<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 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>
</div>
</form>
</form>
</div>
<div data-bind="visible: !restoreSupported()">
{{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to <a href="%(url)s" target="_blank" rel="noopener noreferrer">restore your backups manually for now</a>.', url='https://faq.octoprint.org/manual-restore') }}
</div>
<div id="settings_plugin_backup_restoredialog" class="modal hide fade">
<div class="modal-header">
+9 -8
View File
@@ -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
+14 -2
View File
@@ -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):
"""
+42 -1
View File
@@ -10,9 +10,18 @@ import flask
import flask_login
from flask_babel import gettext
from collections import defaultdict
import threading
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin):
MAX_BACKLOG_LEN = 100
# noinspection PyMissingConstructor
def __init__(self):
self._message_backlog = defaultdict(list)
self._message_backlog_mutex = threading.RLock()
def get_assets(self):
return dict(
@@ -85,6 +94,9 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return
elif not self._user_manager.enabled:
# ACL isn't enabled
return
if flask.request.endpoint in ("api.login",):
return
@@ -99,6 +111,9 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return
elif not self._user_manager.enabled:
# ACL isn't enabled
return
import tornado.web
from octoprint.server.util.flask import get_flask_user_from_request
@@ -111,18 +126,43 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return True
elif not self._user_manager.enabled:
# ACL isn't enabled
return True
return user is not None and not user.is_anonymous() and user.is_active()
def socket_authed(self, socket, user):
with self._message_backlog_mutex:
backlog = self._message_backlog.pop(socket, [])
if len(backlog):
for message, payload in backlog:
socket._do_emit(message, payload)
self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog)))
def socket_emit_validator(self, socket, user, message, payload):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return True
elif not self._user_manager.enabled:
# ACL isn't enabled
return True
if message in ("connected", "reauthRequired"):
return True
return user is not None and not user.is_anonymous() and user.is_active()
if user is not None and not user.is_anonymous() and user.is_active():
return True
with self._message_backlog_mutex:
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
self._message_backlog[socket].append((message, payload))
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
else:
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
return False
__plugin_name__ = "Force Login"
@@ -138,5 +178,6 @@ __plugin_hooks__ = {
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
}
@@ -17,7 +17,7 @@ $(function() {
var username = usernameElement.val();
var password = passwordElement.val();
var remember = rememberElement.checked;
var remember = rememberElement.prop("checked");
overlayElement.addClass("in");
errorElement.removeClass("in");
@@ -1,5 +1,6 @@
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OctoPrint Login</title>
{% include "parts/forcelogin_css.jinja2" %}
@@ -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 +1 @@
table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
@@ -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;
@@ -78,6 +9,8 @@ $(function() {
self.configuredLoggers = ko.observableArray();
self.configuredLoggersChanged = false;
self.markedForDeletion = ko.observableArray([]);
self.availableLoggersSorted = ko.computed(function() {
return _.sortBy(self.availableLoggers());
});
@@ -183,8 +116,37 @@ $(function() {
};
self.removeFile = function(filename) {
OctoPrint.plugins.logging.deleteLog(filename)
.done(self.requestData);
var perform = function() {
OctoPrint.plugins.logging.deleteLog(filename)
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: filename}),
perform);
};
self.markFilesOnPage = function() {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.listHelper.paginatedItems(), "name"))));
};
self.markAllFiles = function() {
self.markedForDeletion(_.map(self.listHelper.allItems, "name"));
};
self.clearMarkedFiles = function() {
self.markedForDeletion.removeAll();
};
self.removeMarkedFiles = function() {
var perform = function() {
self._bulkRemove(self.markedForDeletion(), "files")
.done(function() {
self.markedForDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d log files."), {count: self.markedForDeletion().length}),
perform);
};
self.onSettingsShown = function() {
@@ -203,6 +165,47 @@ $(function() {
console.log("ConfiguredLoggers has not changed. Not saving.");
}
};
self._bulkRemove = function(files) {
var title = gettext("Deleting log files");
var message = _.sprintf(gettext("Deleting %(count)d log files..."), {count: files.length});
var handler = function(filename) {
return OctoPrint.plugins.logging.deleteLog(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({
@@ -1,5 +1,14 @@
table {
th, td {
&.settings_logs_checkbox {
text-align: center;
width: 10px;
input[type="checkbox"] {
margin-top: 0;
}
}
&.settings_logs_name {
text-overflow: ellipsis;
text-align: left;
@@ -1,13 +1,31 @@
<h3>{{ _('Logs') }}</h3>
<div class="pull-right">
<small>
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
</small>
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-wrench"></i> <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('name'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('modification'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'modification' ? 'visible' : 'hidden'}"></i> {{ _('Sort by modification date') }} ({{ _('descending') }})</a></li>
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('size'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
</ul>
</div>
</div>
<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: markedForDeletion().length > 0">{{ _('Delete selected') }}</button>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
<thead>
<tr>
<th class="settings_logs_checkbox"></th>
<th class="settings_logs_name">{{ _('Name') }}</th>
<th class="settings_logs_size">{{ _('Size') }}</th>
<th class="settings_logs_date">{{ _('Date') }}</th>
@@ -16,6 +34,7 @@
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_logs_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForDeletion"></td>
<td class="settings_logs_name" data-bind="text: name"></td>
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
+35 -5
View File
@@ -12,6 +12,7 @@ from flask_babel import gettext
from octoprint.util import RepeatedTimer
import octoprint.plugin
import octoprint.events
_PROC_DT_MODEL_PATH = "/proc/device-tree/model"
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
@@ -35,10 +36,9 @@ _FLAG_PAST_UNDERVOLTAGE = 1 << 16
_FLAG_PAST_FREQ_CAPPED = 1 << 17
_FLAG_PAST_THROTTLED = 1 << 18
class ThrottleState(object):
@classmethod
def from_value(cls, value):
def from_value(cls, value=0):
if value == 0:
return ThrottleState()
@@ -47,10 +47,12 @@ class ThrottleState(object):
throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED,
past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED)
past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
raw_value=value)
return ThrottleState(**kwargs)
def __init__(self, **kwargs):
self._raw_value = kwargs.get('raw_value', -1)
self._undervoltage = False
self._freq_capped = False
self._throttled = False
@@ -111,7 +113,8 @@ class ThrottleState(object):
and self._past_throttled == other._past_throttled
def as_dict(self):
return dict(current_undervoltage=self.current_undervoltage,
return dict(raw_value=self._raw_value,
current_undervoltage=self.current_undervoltage,
past_undervoltage=self.past_undervoltage,
current_overheat=self.current_overheat,
past_overheat=self.past_overheat,
@@ -193,6 +196,7 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
def get_assets(self):
return dict(
js=["js/pi_support.js"],
clientjs=["clientjs/pi_support.js"],
css=["css/pi_support.css"]
)
@@ -241,6 +245,16 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
def _check_throttled_state_condition(self):
return self._throttle_functional
def get_throttle_state(self, run_now=False):
"""Exposed as public helper."""
if run_now:
self._check_throttled_state()
if not self._throttle_functional:
return False
return self._throttle_state.as_dict()
def _check_throttled_state(self):
command = self._settings.get(["vcgencmd_throttle_check_command"])
@@ -278,6 +292,13 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
state=self._throttle_state.as_dict()))
# noinspection PyUnresolvedReferences
self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict())
def register_custom_events(*args, **kwargs):
return ["throttle_state",]
__plugin_name__ = "Pi Support Plugin"
__plugin_author__ = "Gina Häußge"
@@ -298,5 +319,14 @@ def __plugin_check__():
return "raspberry pi" in proc_dt_model.lower()
def __plugin_load__():
plugin = PiSupportPlugin()
global __plugin_implementation__
__plugin_implementation__ = PiSupportPlugin()
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events
}
global __plugin_helpers__
__plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state)
@@ -0,0 +1,19 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintPiSupportClient = function(base) {
this.base = base;
};
OctoPrintPiSupportClient.prototype.get = function(opts) {
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
};
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
return OctoPrintPiSupportClient;
});
@@ -1,22 +1,3 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintPiSupportClient = function(base) {
this.base = base;
};
OctoPrintPiSupportClient.prototype.get = function(opts) {
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
};
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
return OctoPrintPiSupportClient;
});
$(function() {
function PiSupportViewModel(parameters) {
@@ -46,7 +27,7 @@ $(function() {
var octoPrintVersion = $(".footer span.version");
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>")
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>");
$(octoPiVersion).insertAfter(octoPrintVersion);
})
};
@@ -60,11 +41,34 @@ $(function() {
self.pastIssue(state.past_issue);
};
self.issuePopoverContent = function() {
return "<p><strong><i class=\"fa fa-bolt\"></i><i class=\"fa fa-exclamation\"></i></strong></strong> - " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "</p>"
+ "<p><strong><i class=\"fa fa-thermometer-full\"></i><i class=\"fa fa-exclamation\"></i></strong> - " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "</p>"
+ "<p>" + gettext("A blinking icon indicates an acute issue!") + "</p>"
};
self.popoverContent = ko.pureComputed(function() {
var undervoltageParagraphClasses = "muted";
var undervoltageSymbolClasses = "";
var overheatParagraphClasses = "muted";
var overheatSymbolClasses = "";
if (self.currentUndervoltage()) {
undervoltageSymbolClasses = "text-error pi_support_state_pulsate";
undervoltageParagraphClasses = "";
} else if (self.pastUndervoltage()) {
undervoltageSymbolClasses = "text-error";
undervoltageParagraphClasses = "";
}
if (self.currentOverheat()) {
overheatSymbolClasses = "text-error pi_support_state_pulsate";
overheatParagraphClasses = "";
} else if (self.pastOverheat()) {
overheatSymbolClasses = "text-error";
overheatParagraphClasses = "";
}
return "<p class='" + undervoltageParagraphClasses + "'><strong class='" + undervoltageSymbolClasses + "'><i class=\"fa fa-bolt\"></i><i class=\"fa fa-exclamation\"></i></strong></strong> - " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "</p>"
+ "<p class='" + overheatParagraphClasses + "'><strong class='" + overheatSymbolClasses + "'><i class=\"fa fa-thermometer-full\"></i><i class=\"fa fa-exclamation\"></i></strong> - " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "</p>"
+ "<p>" + gettext("A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up.") + "</p>"
+ "<p><small>" + gettext("Click the symbol in the navbar for more information.") + "</small></p>";
});
self.onStartup = function() {
self.requestData();
@@ -1,4 +1,4 @@
<a href="javascript:void(0)" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('Issues reported by the Pi') }}', html: true, content: issuePopoverContent(), trigger: 'hover' }" style="display: none">
<a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('What do the symbols mean?') }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage') }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat') }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
</a>
+26 -13
View File
@@ -16,6 +16,7 @@ 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, is_os_compatible
from octoprint.events import Events
from flask import jsonify, make_response
from flask_babel import gettext
@@ -168,6 +169,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"]
)
@@ -362,7 +364,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
raise ValueError("Either URL or path must be provided")
self._logger.info("Installing plugin from {}".format(source))
pip_args = ["install", sarge.shell_quote(source), '--no-cache-dir']
pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(source), "--no-cache-dir"]
if dependency_links or self._settings.get_boolean(["dependency_links"]):
pip_args.append("--process-dependency-links")
@@ -484,10 +486,12 @@ 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))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key,
version=new_plugin.version,
source=source,
source_type=source_type))
result = dict(result=True,
source=source,
@@ -520,7 +524,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if origin is None:
origin = plugin.origin[2]
pip_args = ["uninstall", "--yes", origin]
pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin]
try:
self._call_pip(pip_args)
except:
@@ -579,8 +583,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))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, dict(id=plugin.key,
version=plugin.version))
result = dict(result=True,
needs_restart=needs_restart,
@@ -722,8 +727,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))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, 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"],
@@ -742,8 +748,9 @@ 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)
self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key,
version=plugin.version))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, dict(id=plugin.key,
version=plugin.version))
def _fetch_all_data(self, do_async=False):
def run():
@@ -960,6 +967,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
versions=notification.get("versions", []),
important=notification.get("important", False))
def _register_custom_events(*args, **kwargs):
return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"]
__plugin_name__ = "Plugin Manager"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
@@ -973,5 +985,6 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
"octoprint.events.register_custom_events": _register_custom_events
}
@@ -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;
@@ -25,32 +25,43 @@ Learn more at https://faq.octoprint.org/warning-{warning_type}
"""
# Anet A8
ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_")
ANETA8_M115_TEST = ("aneta8", lambda name, data: name and name.lower().startswith("anet_a8_"))
# Anycubic MEGA
ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower()
ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower()
ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower())
ANYCUBIC_RECEIVED_TEST = ("anycubic", lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower()))
# Creality CR-10s
CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower()
CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower()
CR10S_RECEIVED_TEST = ("cr10s", lambda line: line and CR10S_AUTHOR in line.lower())
# Malyan M200 aka Monoprice Select Mini
MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200"
# Creality Ender 3
ENDER3_AUTHOR = " | Author: (Ender3)".lower()
ENDER3_RECEIVED_TEST = ("ender3", lambda line: line and ENDER3_AUTHOR in line.lower())
# iMe on Micro3D
IME_M115_TEST = ("ime", lambda name, data: name and name.lower().startswith("ime"))
# Malyan M200 aka Monoprice Select Mini, versions less than 4.0
MALYANM200_M115_TEST = ("malyan_m200", lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" and get_comparable_version(data.get("VER", "0")) < get_comparable_version("4.0"))
# Stock Micro3D
MICRO3D_M115_TEST = ("micro3d", lambda name, data: name and name.lower().startswith("micro3d"))
# Any Repetier versions < 0.92
REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92")
REPETIER_BEFORE_092_M115_TEST = ("repetier_before_092", lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92"))
# THERMAL_PROTECTION capability reported as disabled
THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled
THERMAL_PROTECTION_CAP_TEST = ("capability", lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled)
SAFETY_CHECKS = {
"firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST, REPETIER_BEFORE_092_M115_TEST),
received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST),
"firmware-unsafe": dict(m115=(ANETA8_M115_TEST, IME_M115_TEST, MALYANM200_M115_TEST, MICRO3D_M115_TEST,
REPETIER_BEFORE_092_M115_TEST),
received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST, ENDER3_RECEIVED_TEST),
cap=(THERMAL_PROTECTION_CAP_TEST,),
message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \
u"thermal runaway protection). This is a fire risk.")
message=gettext(u"Your printer's firmware is known to lack mandatory safety features (e.g. "
u"thermal runaway protection). This is a fire risk."))
}
def extract_repetier_version(name):
@@ -90,6 +101,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",))
@@ -135,9 +147,17 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
if not checks or not message:
continue
if any(x(*args, **kwargs) for x in checks):
self._register_warning(warning_type, message)
changes = True
for check_name, check in checks:
if check(*args, **kwargs):
self._register_warning(warning_type, message)
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING, dict(check_type=check_type,
check_name=check_name,
warning_type=warning_type))
changes = True
break
if changes:
self._ping_clients()
@@ -159,6 +179,11 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
def _ping_clients(self):
self._plugin_manager.send_plugin_message(self._identifier, dict(type="update"))
def register_custom_events(*args, **kwargs):
return ["warning",]
__plugin_name__ = "Printer Safety Check"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html"
@@ -171,6 +196,7 @@ __plugin_implementation__ = PrinterSafetyCheckPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received,
"octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received,
"octoprint.events.register_custom_events": register_custom_events
}
@@ -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;
@@ -42,7 +23,7 @@ $(function() {
self.fromResponse = function(data) {
var warnings = [];
_.each(data, function(message, warning_type) {
warnings.push({type: warning_type, message: message});
warnings.push({type: warning_type, message: gettext(message)});
});
self.warnings(warnings);
};
@@ -27,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
@@ -43,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):
@@ -62,6 +69,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache_dirty = False
self._version_cache_timestamp = None
self._environment_supported = True
self._environment_versions = dict()
self._environment_ready = threading.Event()
self._console_logger = None
def initialize(self):
@@ -88,14 +99,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._console_logger.propagate = False
def on_after_startup(self):
# refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from
# the server startup
def fetch_data():
self.get_current_versions()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
self._check_environment()
self.get_current_versions()
def _get_configured_checks(self):
with self._configured_checks_mutex:
@@ -105,6 +110,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
check_providers = self._settings.get(["check_providers"], merged=True)
if not isinstance(check_providers, dict):
check_providers = dict()
effective_configs = dict()
for name, hook in update_check_hooks.items():
@@ -165,6 +173,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
@@ -483,11 +509,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
force = flask.request.values.get("force", "false") in octoprint.settings.valid_boolean_trues
def view():
self._environment_ready.wait(timeout=30.0)
try:
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible and self._environment_supported else "updateAvailable" if update_available else "current",
information=information,
timestamp=self._version_cache_timestamp))
timestamp=self._version_cache_timestamp,
environment=dict(supported=self._environment_supported,
versions=[dict(name=gettext("Python"), current=self._environment_versions.get("python", "unknown"), minimum=MINIMUM_PYTHON),
dict(name=gettext("pip"), current=self._environment_versions.get("pip", "unknown"), minimum=MINIMUM_PIP),
dict(name=gettext("setuptools"), current=self._environment_versions.get("setuptools", "unknown"), minimum=MINIMUM_SETUPTOOLS)])))
except exceptions.ConfigurationInvalid as e:
return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
@@ -514,6 +546,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))
@@ -536,6 +570,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)
@@ -560,6 +597,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
return dict(
css=["css/softwareupdate.css"],
js=["js/softwareupdate.js"],
clientjs=["clientjs/softwareupdate.js"],
less=["less/softwareupdate.less"]
)
@@ -646,6 +684,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="?",
@@ -779,6 +818,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()
@@ -901,17 +944,21 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
target_result = None
def trigger_event(success, **additional_payload):
from octoprint.events import Events
if success:
event = "update_succeeded"
# noinspection PyUnresolvedReferences
event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED
else:
event = "update_failed"
# noinspection PyUnresolvedReferences
event = Events.PLUGIN_SOFTWAREUPDATE_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)
self._event_bus.fire(event, payload=payload)
### The actual update procedure starts here...
@@ -1155,6 +1202,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
return None
def _register_custom_events(*args, **kwargs):
return ["update_succeeded", "update_failed"]
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
@@ -1177,7 +1228,8 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.cli.commands": cli.commands
"octoprint.cli.commands": cli.commands,
"octoprint.events.register_custom_events": _register_custom_events
}
@@ -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>
@@ -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
@@ -80,7 +86,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
install_arg = check["pip"].format(target_version=target_version, target=target_version)
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
pip_args = ["install", install_arg, "--no-cache-dir"]
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
pip_kwargs = dict()
if pip_working_directory is not None:
pip_kwargs.update(cwd=pip_working_directory)
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .exceptions import ScriptError
import logging
def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
do_async = kwargs.get("do_async", kwargs.get("async", False))
@@ -18,6 +20,7 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
try:
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=do_async)
except:
logging.getLogger(__name__).exception("Error while executing command: {}".format(command))
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 ""
stderr = p.stderr.text if p is not None and p.stderr is not None else ""
+159 -20
View File
@@ -6,7 +6,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import octoprint.plugin
from flask.ext.babel import gettext
from flask_babel import gettext
import requests
import hashlib
@@ -21,7 +21,7 @@ except ImportError:
# noinspection PyCompatibility
import concurrent.futures
from octoprint.util import RepeatedTimer
from octoprint.util import RepeatedTimer, monotonic_time
from octoprint.util.version import get_octoprint_version_string
from octoprint.events import Events
@@ -39,6 +39,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
def __init__(self):
self._environment = None
self._throttle_state = None
self._helpers_get_throttle_state = None
self._printer_connection_parameters = None
self._url = None
self._ping_worker = None
@@ -46,6 +48,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._record_next_firmware_info = False
self._startup_time = monotonic_time()
def initialize(self):
self._init_tracking()
@@ -58,9 +62,12 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
ping=15*60,
events=dict(startup=True,
printjob=True,
commerror=True,
plugin=True,
update=True,
printer=True))
printer=True,
printer_safety_check=True,
throttled=True))
def get_settings_restricted_paths(self):
return dict(admin=[["enabled"], ["unique_id"], ["events"]],
@@ -84,13 +91,19 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
##~~ 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 = RepeatedTimer(ping, self._track_ping, run_first=True)
self._ping_worker.start()
# cautiously look for the get_throttled helper from pi_support
pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if pi_helper and 'get_throttled' in pi_helper:
self._helpers_get_throttle_state = pi_helper['get_throttled']
# now that we have everything set up, phone home.
self._track_startup()
##~~ ShutdownPlugin
def on_shutdown(self):
@@ -98,21 +111,39 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
##~~ EventHandlerPlugin
# noinspection PyUnresolvedReferences
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):
if event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
self._track_printjob_event(event, payload)
elif event in (Events.ERROR,):
self._track_commerror_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)
elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and \
event in (Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN):
self._track_plugin_event(event, payload)
elif hasattr(Events, "PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED") and \
event in (Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED, Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED):
self._track_update_event(event, payload)
elif hasattr(Events, "PLUGIN_PI_SUPPORT_THROTTLE_STATE") and event in (Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,):
self._throttle_state = payload
self._track_throttle_event(event, payload)
elif hasattr(Events, "PLUGIN_PRINTER_SAFETY_CHECK_WARNING") and event in (Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING,):
self._track_printer_safety_event(event, payload)
##~~ TemplatePlugin
def get_template_configs(self):
@@ -124,7 +155,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
##~~ AssetPlugin
def get_assets(self):
return dict(js=["js/tracking.js"])
return dict(js=["js/usage.js"])
##~~ WizardPlugin
@@ -146,9 +177,16 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._settings.save()
def _track_ping(self):
self._track("ping")
if not self._settings.get_boolean([b"enabled"]):
return
uptime = int(monotonic_time() - self._startup_time)
self._track("ping", octoprint_uptime=uptime)
def _track_startup(self):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "startup"]):
return
@@ -162,31 +200,41 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
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([b"enabled"]):
return
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([b"enabled"]):
return
if not self._settings.get_boolean(["events", "plugin"]):
return
if event.endswith("_installplugin"):
if event.endswith("_install_plugin"):
self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_uninstallplugin"):
elif event.endswith("_uninstall_plugin"):
self._track("uninstall_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_enableplugin"):
elif event.endswith("_enable_plugin"):
self._track("enable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_disableplugin"):
elif event.endswith("_disable_plugin"):
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([b"enabled"]):
return
if not self._settings.get_boolean(["events", "update"]):
return
@@ -195,12 +243,65 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
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_throttle_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "throttled"]):
return
args = dict(throttled_now=payload[b"current_issue"],
throttled_past=payload[b"past_issue"],
throttled_mask=payload[b"raw_value"],
throttled_voltage_now=payload[b"current_undervoltage"],
throttled_voltage_past=payload[b"past_undervoltage"],
throttled_overheat_now=payload[b"current_overheat"],
throttled_overheat_past=payload[b"past_overheat"])
if payload[b"current_issue"]:
track_event = "system_throttled"
else:
track_event = "system_unthrottled"
if track_event is not None:
self._track(track_event, **args)
def _track_commerror_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "commerror"]):
return
if not b"reason" in payload or not b"error" in payload:
return
track_event = "commerror_{}".format(payload[b"reason"])
args = dict(commerror_text=payload[b"error"])
if callable(self._helpers_get_throttle_state):
try:
throttle_state = self._helpers_get_throttle_state(run_now=True)
if throttle_state and (throttle_state.get(b"current_issue", False) or throttle_state.get(b"past_issue", False)):
args[b"throttled_now"] = throttle_state[b"current_issue"]
args[b"throttled_past"] = throttle_state[b"past_issue"]
args[b"throttled_mask"] = throttle_state[b"raw_value"]
except:
# ignored
pass
self._track(track_event, **args)
def _track_printjob_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "printjob"]):
return
sha = hashlib.sha1()
sha.update(payload.get("name"))
sha.update(payload.get("path"))
sha.update(self._settings.get([b"unique_id"]))
track_event = None
args = dict(origin=payload.get(b"origin"), file=sha.hexdigest())
@@ -215,14 +316,38 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
args[b"elapsed"] = elapsed
track_event = "print_done"
elif event == Events.PRINT_FAILED:
try:
elapsed = int(payload.get(b"time"))
except ValueError:
elapsed = "unknown"
args[b"elapsed"] = elapsed
args[b"reason"] = payload.get(b"reason", "unknown")
if b"error" in payload and self._settings.get_boolean(["events", "commerror"]):
args[b"commerror_text"] = payload[b"error"]
track_event = "print_failed"
elif event == Events.PRINT_CANCELLED:
track_event = "print_cancelled"
if callable(self._helpers_get_throttle_state):
try:
throttle_state = self._helpers_get_throttle_state(run_now=True)
if throttle_state and (throttle_state.get(b"current_issue", False) or throttle_state.get(b"past_issue", False)):
args[b"throttled_now"] = throttle_state[b"current_issue"]
args[b"throttled_past"] = throttle_state[b"past_issue"]
args[b"throttled_mask"] = throttle_state[b"raw_value"]
except:
# ignored
pass
if track_event is not None:
self._track(track_event, **args)
def _track_printer_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "printer"]):
return
@@ -233,6 +358,17 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
args["printer_baudrate"] = self._printer_connection_parameters["baudrate"]
self._track("printer_connected", **args)
def _track_printer_safety_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "printer_safety_check"]):
return
self._track("printer_safety_warning",
printer_safety_warning_type=payload.get(b"warning_type", "unknown"),
printer_safety_check_name=payload.get(b"check_name", "unknown"))
def _track(self, event, **kwargs):
if not self._settings.get_boolean([b"enabled"]):
return
@@ -245,15 +381,18 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
server = self._settings.get([b"server"])
url = server.format(id=self._settings.get([b"unique_id"]), event=event)
# Don't print the URL or UUID! That would expose the UUID in forums/tickets
# if pasted. It's okay for the user to know their uuid, but it shouldn't be shared.
headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())}
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))
self._logger.info("Sent tracking event {}, payload: {!r}".format(event, kwargs))
except:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Error while sending event to anonymous usage tracking".format(url))
@@ -262,7 +401,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
__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_url__ = "https://tracking.octoprint.org"
__plugin_author__ = "Gina Häußge"
__plugin_implementation__ = TrackingPlugin()
@@ -1,5 +1,5 @@
$(function() {
function TrackingViewModel(parameters) {
function UsageViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
@@ -7,16 +7,16 @@ $(function() {
self.setup = ko.observable(false);
self.decision = ko.observable();
self.active = ko.observable();
self.required = false;
self.active = false;
self.enableTracking = function() {
self.enableUsage = function() {
self.settingsViewModel.settings.plugins.tracking.enabled(true);
self.decision(true);
self._sendData();
};
self.disableTracking = function() {
self.disableUsage = function() {
self.settingsViewModel.settings.plugins.tracking.enabled(false);
self.decision(false);
self._sendData();
@@ -45,7 +45,7 @@ $(function() {
};
self.onWizardPreventSettingsRefreshDialog = function() {
return self.active;
return self.active();
};
self.onWizardDetails = function(response) {
@@ -68,17 +68,33 @@ $(function() {
}
};
self.active = true;
self.active(true);
self.settingsViewModel.saveData(data)
.done(function() {
self.setup(true);
self.active = false;
self.active(false);
})
.fail(function() {
self.decision(false);
self.setup(true);
self.active(false);
var message = gettext("Please open a <a href='%(bugreport)s' target='_blank' rel='noopener noreferrer'>" +
"bug report</a> on this. Make sure to include all requested information, including your " +
"<a href='%(jsconsole)s' target='_blank' rel='noopener noreferrer'>JS console</a> and " +
"<code>octoprint.log</code>.");
new PNotify({
title: gettext("Something went wrong"),
text: _.sprintf(message, {bugreport: "https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#how-to-file-a-bug-report", jsconsole: "https://webmasters.stackexchange.com/a/77337"}),
type: "error",
hide: false
});
});
};
}
OCTOPRINT_VIEWMODELS.push([
TrackingViewModel,
UsageViewModel,
["settingsViewModel"],
"#wizard_plugin_tracking"
]);
@@ -28,15 +28,24 @@
<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.printer_safety_check"> {{ _('Printer Safety Check warnings') }}
</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.commerror"> {{ _('Errors in the communication with the printer and/or reported by the firmware') }}
</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>
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.throttled"> {{ _('System got throttled/unthrottled (currently only detected on RPis)') }}
</label>
</div>
</div>
</form>
@@ -9,8 +9,8 @@
</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>
<a href="javascript:void(0)" class="btn span6" data-bind="click: function() { if(!setup()){disableUsage()}}, enable: !setup(), css: {disabled: setup()}"><i class="fa fa-spinner fa-spin" style="display: none" data-bind="visible: active() && decision() === false"></i> {{ _('Disable Anonymous Usage Tracking') }}</a>
<a href="javascript:void(0)" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableUsage()}}, enable: !setup(), css: {disabled: setup()}"><i class="fa fa-spinner fa-spin" style="display: none" data-bind="visible: active() && decision() === true"></i> {{ _('Enable Anonymous Usage Tracking') }}</a>
</div>
<div class="tracking_decision" style="display: none" data-bind="visible: setup()">
+5 -3
View File
@@ -231,12 +231,14 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def extrude(self, amount, tags=None, *args, **kwargs):
def extrude(self, amount, speed=None, tags=None, *args, **kwargs):
"""
Extrude ``amount`` millimeters of material from the tool.
Arguments:
amount (int, float): The amount of material to extrude in mm
speed (int, None): Speed at which to extrude (F parameter). If set to ``None`` (or left out)
the maximum speed of E axis from the printer profile will be used.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
@@ -417,9 +419,9 @@ class PrinterInterface(object):
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
if self.is_printing():
self.pause_print(tags=tags)
self.pause_print(tags=tags, *args, **kwargs)
elif self.is_paused():
self.resume_print(tags=tags)
self.resume_print(tags=tags, *args, **kwargs)
def cancel_print(self, tags=None, *args, **kwargs):
"""
+95 -25
View File
@@ -41,6 +41,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
from collections import deque
self._logger = logging.getLogger(__name__)
self._logger_job = logging.getLogger("{}.job".format(__name__))
self._dict = frozendict if settings().getBoolean(["devel", "useFrozenDictForPrinterState"]) else dict
@@ -364,12 +365,22 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"],
tags=kwargs.get("tags", set) | {"trigger:printer.home"})
def extrude(self, amount, *args, **kwargs):
def extrude(self, amount, speed=None, *args, **kwargs):
if not isinstance(amount, (int, long, float)):
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
printer_profile = self._printerProfileManager.get_current_or_default()
extrusion_speed = printer_profile["axes"]["e"]["speed"]
# Use specified speed (if any)
max_e_speed = printer_profile["axes"]["e"]["speed"]
if speed is None:
# No speed was specified so default to value configured in printer profile
extrusion_speed = max_e_speed
else:
# Make sure that specified value is not greater than maximum as defined in printer profile
extrusion_speed = min([speed, max_e_speed])
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"],
tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"})
@@ -514,9 +525,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._updateProgressData()
self._setCurrentZ(None)
self._comm.startPrint(pos=pos,
user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"})
def pause_print(self, *args, **kwargs):
def pause_print(self, user=None, *args, **kwargs):
"""
Pause the current printjob.
"""
@@ -526,9 +538,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm.isPaused():
return
self._comm.setPause(True, tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"})
self._comm.setPause(True,
user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"})
def resume_print(self, *args, **kwargs):
def resume_print(self, user=None, *args, **kwargs):
"""
Resume the current printjob.
"""
@@ -538,9 +552,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not self._comm.isPaused():
return
self._comm.setPause(False, tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"})
self._comm.setPause(False,
user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"})
def cancel_print(self, *args, **kwargs):
def cancel_print(self, user=None, *args, **kwargs):
"""
Cancel the current printjob.
"""
@@ -549,7 +565,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# tell comm layer to cancel - will also trigger our cancelled handler
# for further processing
self._comm.cancelPrint(tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"})
self._comm.cancelPrint(user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"})
def log_lines(self, *lines):
serial_logger = logging.getLogger("SERIAL")
@@ -951,6 +968,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
filament=filament,
user=user))
def _updateJobUser(self, user):
with self._selectedFileMutex:
if self._selectedFile is not None and self._selectedFile.get("user", None) != user:
self._selectedFile["user"] = user
job_data = self.get_current_job()
self._stateMonitor.set_job_data(self._dict(file=job_data["file"],
estimatedPrintTime=job_data["estimatedPrintTime"],
averagePrintTime=job_data["averagePrintTime"],
lastPrintTIme=job_data["lastPrintTime"],
filament=job_data["filament"],
user=user))
def _sendInitialStateUpdate(self, callback):
try:
data = self._stateMonitor.get_current_data()
@@ -1010,6 +1040,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload = self._payload_for_print_job_event()
if payload:
payload["time"] = self._comm.getPrintTime()
payload["reason"] = "error"
payload["error"] = self._comm.getErrorString()
def finalize():
self._fileManager.log_print(payload["origin"],
@@ -1079,10 +1111,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def on_comm_file_selected(self, full_path, size, sd, user=None):
if full_path is not None:
payload = self._payload_for_print_job_event(location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
print_job_file=full_path)
print_job_file=full_path,
print_job_user=user,
action_user=user)
eventManager().fire(Events.FILE_SELECTED, payload)
self._logger_job.info("Print job selected - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
else:
eventManager().fire(Events.FILE_DESELECTED)
self._logger_job.info("Print job deselected - user: {}".format(user if user else "n/a"))
self._setJobData(full_path, size, sd, user=user)
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
@@ -1093,11 +1132,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = False
self.start_print(pos=self._posAfterSelect, user=user)
def on_comm_print_job_started(self, suppress_script=False):
def on_comm_print_job_started(self, suppress_script=False, user=None):
self._updateJobUser(user) # the final job owner should always be whoever _started_ the job
self._stateMonitor.trigger_progress_update()
payload = self._payload_for_print_job_event()
payload = self._payload_for_print_job_event(print_job_user=user,
action_user=user)
if payload:
eventManager().fire(Events.PRINT_STARTED, payload)
self._logger_job.info("Print job started - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
if not suppress_script:
self.script("beforePrintStarted",
context=dict(event=payload),
@@ -1117,6 +1163,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
eventManager().fire(Events.PRINT_DONE, payload)
self._logger_job.info("Print job done - origin: {}, path: {}, owner: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner")))
if not suppress_script:
self.script("afterPrintDone",
context=dict(event=payload),
@@ -1140,27 +1190,29 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
def on_comm_print_job_failed(self):
payload = self._payload_for_print_job_event()
if payload:
eventManager().fire(Events.PRINT_FAILED, payload)
def on_comm_print_job_cancelling(self, firmware_error=None):
payload = self._payload_for_print_job_event()
def on_comm_print_job_cancelling(self, firmware_error=None, user=None):
payload = self._payload_for_print_job_event(action_user=user)
if payload:
if firmware_error:
payload["firmwareError"] = firmware_error
eventManager().fire(Events.PRINT_CANCELLING, payload)
def on_comm_print_job_cancelled(self, suppress_script=False):
def on_comm_print_job_cancelled(self, suppress_script=False, user=None):
self._setCurrentZ(None)
self._updateProgressData()
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None,
action_user=user)
if payload:
payload["time"] = self._comm.getPrintTime()
payload["reason"] = "cancelled"
eventManager().fire(Events.PRINT_CANCELLED, payload)
self._logger_job.info("Print job cancelled - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
if not suppress_script:
self.script("afterPrintCancelled",
context=dict(event=payload),
@@ -1180,20 +1232,30 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
thread.daemon = True
thread.start()
def on_comm_print_job_paused(self, suppress_script=False):
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
def on_comm_print_job_paused(self, suppress_script=False, user=None):
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None,
action_user=user)
if payload:
eventManager().fire(Events.PRINT_PAUSED, payload)
self._logger_job.info("Print job paused - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
if not suppress_script:
self.script("afterPrintPaused",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
def on_comm_print_job_resumed(self, suppress_script=False):
payload = self._payload_for_print_job_event()
def on_comm_print_job_resumed(self, suppress_script=False, user=None):
payload = self._payload_for_print_job_event(action_user=user)
if payload:
eventManager().fire(Events.PRINT_RESUMED, payload)
self._logger_job.info("Print job resumed - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
if not suppress_script:
self.script("beforePrintResumed",
context=dict(event=payload),
@@ -1245,7 +1307,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
except:
self._logger.exception("Error while trying to persist print recovery data")
def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, position=None):
def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, print_job_user=None,
position=None, action_user=None):
if print_job_file is None:
with self._selectedFileMutex:
selected_file = self._selectedFile
@@ -1254,6 +1317,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
print_job_file = selected_file.get("filename", None)
print_job_size = selected_file.get("filesize", None)
print_job_user = selected_file.get("user", None)
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
if not print_job_file or not location:
@@ -1284,6 +1348,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if position is not None:
result["position"] = position
if print_job_user is not None:
result["owner"] = print_job_user
if action_user is not None:
result["user"] = action_user
return result
+61 -27
View File
@@ -21,6 +21,7 @@ from builtins import bytes, range
from past.builtins import basestring
import os
import sys
import logging
import logging.config
import atexit
@@ -190,6 +191,10 @@ class Server(object):
if self._settings is None:
self._settings = settings()
self._settings.setBoolean(["server", "incompleteStartup"], True)
self._settings.save()
if self._plugin_manager is None:
self._plugin_manager = octoprint.plugin.plugin_manager()
@@ -242,6 +247,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
@@ -440,6 +446,17 @@ class Server(object):
implementation.on_settings_initialized()
custom_events_hooks = pluginManager.get_hooks("octoprint.events.register_custom_events")
for name, hook in custom_events_hooks.items():
try:
result = hook()
if isinstance(result, (list, tuple)):
for event in result:
constant, value = octoprint.events.Events.register_event(event, prefix="plugin_{}_".format(name))
self._logger.debug("Registered event {} of plugin {} as Events.{} = \"{}\"".format(event, name, constant, value))
except:
self._logger.exception("Error while retrieving custom event list from plugin {}".format(name))
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory,
settings_plugin_inject_factory]
pluginManager.initialize_implementations()
@@ -650,11 +667,16 @@ class Server(object):
if not isinstance(trusted_downstream, list):
self._logger.warn("server.reverseProxy.trustedDownstream is not a list, skipping")
trusted_downstreams = []
self._server = util.tornado.CustomHTTPServer(self._tornado_app,
max_body_sizes=max_body_sizes,
default_max_body_size=self._settings.getInt(["server", "maxSize"]),
xheaders=True,
trusted_downstream=trusted_downstream)
server_kwargs = dict(max_body_sizes=max_body_sizes,
default_max_body_size=self._settings.getInt(["server", "maxSize"]),
xheaders=True,
trusted_downstream=trusted_downstream)
if sys.platform == "win32":
# set 10min idle timeout under windows to hopefully make #2916 less likely
server_kwargs.update(dict(idle_connection_timeout=600))
self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs)
self._server.listen(self._port, address=self._host if self._host != "::" else None) # special case - tornado
# only listens on v4 & v6
# if we use None as address
@@ -727,6 +749,14 @@ class Server(object):
implementation.on_after_startup()
pluginLifecycleManager.add_callback("enabled", call_on_after_startup)
# if there was a rogue plugin we wouldn't even have made it here, so remove startup triggered safe mode
# flag again...
self._settings.setBoolean(["server", "incompleteStartup"], False)
self._settings.save()
# make a backup of the current config
self._settings.backup(ext="backup")
# when we are through with that we also run our preemptive cache
if settings().getBoolean(["devel", "cache", "preemptive"]):
self._execute_preemptive_flask_caching(preemptiveCache)
@@ -1340,6 +1370,7 @@ class Server(object):
"js/lib/pnotify/pnotify.nonblock.min.js",
"js/lib/pnotify/pnotify.reference.min.js",
"js/lib/pnotify/pnotify.tooltip.min.js",
"js/lib/pnotify/pnotify.maxheight.js",
"js/lib/moment-with-locales.min.js",
"js/lib/pusher.color.min.js",
"js/lib/detectmobilebrowser.js",
@@ -1348,25 +1379,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",
@@ -1419,13 +1431,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))
@@ -1441,6 +1455,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"]
@@ -1500,6 +1529,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():
+6 -2
View File
@@ -177,7 +177,8 @@ def apiPrinterState():
def apiVersion():
return jsonify({
"server": octoprint.server.VERSION,
"api": VERSION
"api": VERSION,
"text": "OctoPrint {}".format(octoprint.server.DISPLAY_VERSION)
})
@@ -215,9 +216,12 @@ def login():
login_user(user, remember=remember)
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
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(get_remote_address(request),
and not util_net.is_lan_address(remote_addr,
additional_private=s().get(["server", "ipCheck", "trustedSubnets"]))
return jsonify(response)
+4 -4
View File
@@ -49,17 +49,17 @@ def controlJob():
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
action = data.get("action", "toggle")
if action == "toggle":
printer.toggle_pause_print(tags=tags)
printer.toggle_pause_print(tags=tags, user=user)
elif action == "pause":
printer.pause_print(tags=tags)
printer.pause_print(tags=tags, user=user)
elif action == "resume":
printer.resume_print(tags=tags)
printer.resume_print(tags=tags, user=user)
else:
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
elif command == "cancel":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
printer.cancel_print(tags=tags)
printer.cancel_print(tags=tags, user=user)
return NO_CONTENT
+2 -1
View File
@@ -129,9 +129,10 @@ def printerToolCommand():
return make_response("Printer is currently printing", 409)
amount = data["amount"]
speed = data.get("speed", None)
if not isinstance(amount, (int, long, float)):
return make_response("Not a number for extrusion amount: %r" % amount, 400)
printer.extrude(amount, tags=tags)
printer.extrude(amount, speed=speed, tags=tags)
elif command == "flowrate":
factor = data["factor"]
-6
View File
@@ -548,9 +548,3 @@ def _saveSettings(data):
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
s.save()
payload = dict(
config_hash=s.config_hash,
effective_hash=s.effective_hash
)
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
+10
View File
@@ -7,13 +7,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import rsa
from flask import Blueprint, request, make_response, jsonify
import logging
import octoprint.server
import octoprint.plugin
from octoprint.server.util import noCachingResponseHandler, corsResponseHandler
from octoprint.server.util.flask import get_remote_address
from octoprint.settings import settings as s
logger = logging.getLogger(__name__)
apps = Blueprint("apps", __name__)
apps.after_request(noCachingResponseHandler)
@@ -21,11 +25,16 @@ apps.after_request(corsResponseHandler)
@apps.route("/auth", methods=["GET"])
def getSessionKey():
logger.warn("Client {} accessed the apps API which has been deprecated since 1.3.11 and will be removed in "
"1.4.0. Clients should use the Application Keys Plugin workflow instead".format(get_remote_address(request)))
unverified_key, valid_until = octoprint.server.appSessionManager.create()
return jsonify(unverifiedKey=unverified_key, validUntil=valid_until)
@apps.route("/auth", methods=["POST"])
def verifySessionKey():
logger.warn("Client {} accessed the apps API which has been deprecated since 1.3.11 and will be removed in "
"1.4.0. Clients should use the Application Keys Plugin workflow instead".format(get_remote_address(request)))
if not "application/json" in request.headers["Content-Type"]:
return None, None, make_response("Expected content-type JSON", 400)
@@ -95,6 +104,7 @@ def _get_registered_apps():
for name, hook in hooks.items():
try:
additional_apps = hook()
logger.warn("Plugin {} is still implementing the appkey hook that is deprecated since 1.3.11 and will be removed in 1.4.0. Switch it over to the Application Keys Plugin workflow.".format(name))
except:
import logging
logging.getLogger(__name__).exception("Error while retrieving additional appkeys from plugin {name}".format(**locals()))
+112 -22
View File
@@ -251,6 +251,32 @@ def fix_flask_login_remote_address():
flask_login._get_remote_addr = fixed_get_remote_addr
def fix_flask_jsonify():
def fixed_jsonify(*args, **kwargs):
"""Backported from https://github.com/pallets/flask/blob/7e714bd28b6e96d82b2848b48cf8ff48b517b09b/flask/json/__init__.py#L257"""
from flask.json import current_app, dumps
indent = None
separators = (',', ':')
if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:
indent = 2
separators = (', ', ': ')
if args and kwargs:
raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
elif len(args) == 1: # single args are passed directly to dumps()
data = args[0]
else:
data = args or kwargs
return current_app.response_class(
dumps(data, indent=indent, separators=separators) + '\n',
mimetype='application/json'
)
flask.jsonify = fixed_jsonify
#~~ WSGI environment wrapper for reverse proxying
class ReverseProxiedEnvironment(object):
@@ -509,15 +535,38 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
#~~ passive login helper
_cached_local_networks = None
def _local_networks():
global _cached_local_networks
if _cached_local_networks is None:
logger = logging.getLogger(__name__)
local_networks = netaddr.IPSet([])
for entry in settings().get(["accessControl", "localNetworks"]):
network = netaddr.IPNetwork(entry)
local_networks.add(network)
logger.debug("Added network {} to localNetworks".format(network))
if network.version == 4:
network_v6 = network.ipv6()
local_networks.add(network_v6)
logger.debug("Also added v6 representation of v4 network {} = {} to localNetworks".format(network, network_v6))
_cached_local_networks = local_networks
return _cached_local_networks
def passive_login():
logger = logging.getLogger(__name__)
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.login_user(flask_login.current_user)
else:
user = flask_login.current_user
remoteAddr = get_remote_address(flask.request)
ipCheckEnabled = settings().getBoolean(["server", "ipCheck", "enabled"])
ipCheckTrusted = settings().get(["server", "ipCheck", "trustedSubnets"])
remote_address = get_remote_address(flask.request)
ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"])
ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"])
if user is not None and not user.is_anonymous() and user.is_active():
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
@@ -526,23 +575,24 @@ def passive_login():
flask.session["usersession.id"] = user.session
flask.g.user = user
logger.info("Passively logging in user {} from {}".format(user.get_id(), remote_address))
response = user.asDict()
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
additional_private=ipCheckTrusted)
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
additional_private=ip_check_trusted)
return flask.jsonify(response)
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
and settings().get(["accessControl", "autologinAs"]) is not None \
and settings().get(["accessControl", "localNetworks"]) is not None:
autologinAs = settings().get(["accessControl", "autologinAs"])
localNetworks = netaddr.IPSet([])
for ip in settings().get(["accessControl", "localNetworks"]):
localNetworks.add(ip)
autologin_as = settings().get(["accessControl", "autologinAs"])
local_networks = _local_networks()
logger.debug("Checking if remote address {} is in localNetworks ({!r})".format(remote_address, local_networks))
try:
if netaddr.IPAddress(remoteAddr) in localNetworks:
user = octoprint.server.userManager.findUser(autologinAs)
if netaddr.IPAddress(remote_address) in local_networks:
user = octoprint.server.userManager.findUser(autologin_as)
if user is not None and user.is_active():
user = octoprint.server.userManager.login_user(user)
flask.session["usersession.id"] = user.session
@@ -551,13 +601,15 @@ def passive_login():
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
identity=flask_principal.Identity(user.get_id()))
logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(),
remote_address))
response = user.asDict()
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
additional_private=ipCheckTrusted)
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
additional_private=ip_check_trusted)
return flask.jsonify(response)
except:
logger = logging.getLogger(__name__)
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
logger.exception("Could not autologin user {} for networks {}".format(autologin_as, localNetworks))
return "", 204
@@ -1101,10 +1153,13 @@ def get_flask_user_from_request(request):
import flask_login
from octoprint.settings import settings
user = None
apikey = octoprint.server.util.get_api_key(request)
if settings().getBoolean(["api", "enabled"]) and apikey is not None:
user = octoprint.server.util.get_user_for_apikey(apikey)
else:
if user is None:
user = flask_login.current_user
return user
@@ -1133,28 +1188,34 @@ def redirect_to_tornado(request, target, code=302):
def restricted_access(func):
"""
This combines :py:func:`no_firstrun_access` and ``login_required``.
"""
@functools.wraps(func)
def decorated_view(*args, **kwargs):
return no_firstrun_access(flask_login.login_required(func))(*args, **kwargs)
return decorated_view
def no_firstrun_access(func):
"""
If you decorate a view with this, it will ensure that first setup has been
done for OctoPrint's Access Control plus that any conditions of the
login_required decorator are met (possibly through a session already created
by octoprint.server.util.apiKeyRequestHandler earlier in the request processing).
done for OctoPrint's Access Control.
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
flag from the settings being set to True and the userManager not indicating
that it's user database has been customized from default), the decorator
will cause a HTTP 403 status code to be returned by the decorated resource.
"""
@functools.wraps(func)
def decorated_view(*args, **kwargs):
# if OctoPrint hasn't been set up yet, abort
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
return flask.make_response("OctoPrint isn't setup yet", 403)
return flask_login.login_required(func)(*args, **kwargs)
return func(*args, **kwargs)
return decorated_view
def firstrun_only_access(func):
"""
If you decorate a view with this, it will ensure that first setup has _not_ been
@@ -1334,6 +1395,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
assets = dict(
js=[],
clientjs=[],
css=[],
less=[]
)
@@ -1375,6 +1437,26 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
'gcodeviewer/js/renderer.js'
]
assets["clientjs"] = [
"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"
]
if preferred_stylesheet == "less":
assets["less"].append('less/octoprint.less')
elif preferred_stylesheet == "css":
@@ -1389,9 +1471,11 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
supported_stylesheets = ("css", "less")
assets = dict(bundled=dict(js=DefaultOrderedDict(list),
clientjs=DefaultOrderedDict(list),
css=DefaultOrderedDict(list),
less=DefaultOrderedDict(list)),
external=dict(js=DefaultOrderedDict(list),
clientjs=DefaultOrderedDict(list),
css=DefaultOrderedDict(list),
less=DefaultOrderedDict(list)))
@@ -1421,6 +1505,12 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
continue
assets[asset_key]["js"][name].append('plugin/{name}/{asset}'.format(**locals()))
if "clientjs" in all_assets:
for asset in all_assets["clientjs"]:
if not asset_exists("clientjs", asset):
continue
assets[asset_key]["clientjs"][name].append("plugin/{name}/{asset}".format(**locals()))
if preferred_stylesheet in all_assets:
for asset in all_assets[preferred_stylesheet]:
if not asset_exists(preferred_stylesheet, asset):
+49 -7
View File
@@ -17,6 +17,7 @@ import octoprint.timelapse
import octoprint.server
import octoprint.events
import octoprint.plugin
import octoprint.users
from octoprint.events import Events
from octoprint.settings import settings
@@ -87,6 +88,8 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._eventManager = eventManager
self._pluginManager = pluginManager
self._userManager.register_callback(self._user_manager_callback)
self._remoteAddress = None
self._user = None
@@ -95,6 +98,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._baseRateLimit = 0.5
self._register_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.register")
self._authed_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.authed")
self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit")
self._registered = False
@@ -112,6 +116,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
return "Unconnected {!r}".format(self)
def on_open(self, info):
self._pluginManager.register_message_receiver(self.on_plugin_message)
self._remoteAddress = self._getRemoteAddress(info)
self._logger.info("New connection from client: %s" % self._remoteAddress)
@@ -145,8 +150,9 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._logger.info("Client connection closed: %s" % self._remoteAddress)
self._user = None
self._on_logout()
self._remoteAddress = None
self._pluginManager.unregister_message_receiver(self.on_plugin_message)
def on_message(self, message):
try:
@@ -169,12 +175,10 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
user = self._userManager.findUser(userid=user_id, session=user_session)
if user is not None:
self._user = user
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(),
self._remoteAddress))
self._on_login(user)
else:
self._user = None
self._logger.warn("Unknown user/session combo: {}:{}".format(user_id, user_session))
self._on_logout()
self._register()
@@ -270,6 +274,9 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
if not proceed:
return
self._do_emit(type, payload)
def _do_emit(self, type, payload):
try:
self.send({type: payload})
except Exception as e:
@@ -295,7 +302,6 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._printer.register_callback(self)
self._fileManager.register_slicingprogress_callback(self)
octoprint.timelapse.register_callback(self)
self._pluginManager.register_message_receiver(self.on_plugin_message)
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
for event in octoprint.events.all_events():
@@ -320,7 +326,6 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._printer.unregister_callback(self)
self._fileManager.unregister_slicingprogress_callback(self)
octoprint.timelapse.unregister_callback(self)
self._pluginManager.unregister_message_receiver(self.on_plugin_message)
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
for event in octoprint.events.all_events():
@@ -328,3 +333,40 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._registered = False
def _user_manager_callback(self, action, session_user):
if action != "logout":
# we are only interested in logouts
return
if not self._user or not session_user:
# we need both users set
return
if not isinstance(self._user, octoprint.users.SessionUser) or not isinstance(session_user, octoprint.users.SessionUser):
# and we need both users to be session users
return
if self._user.get_id() == session_user.get_id() and self._user.session == session_user.session:
# our user just logged out
self._on_logout()
def _on_login(self, user):
self._user = user
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(),
self._remoteAddress))
for name, hook in self._authed_hooks.items():
try:
hook(self, self._user)
except:
self._logger.exception("Error processing authed hook handler for plugin {}".format(name))
def _on_logout(self):
self._user = None
for name, hook in self._authed_hooks.items():
try:
hook(self, self._user)
except:
self._logger.exception("Error processing authed hook handler for plugin {}".format(name))
+32 -9
View File
@@ -155,6 +155,7 @@ default_settings = {
"port": 5000,
"firstRun": True,
"startOnceInSafeMode": False,
"incompleteStartup": False,
"seenWizards": {},
"secretKey": None,
"heartbeat": 15 * 60, # 15 min
@@ -294,9 +295,9 @@ default_settings = {
"tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"],
"settings": [
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
"section_features", "features", "webcam", "accesscontrol", "gcodevisualizer", "api",
"section_features", "features", "webcam", "accesscontrol", "gcodevisualizer", "api", "plugin_appkeys",
"section_octoprint", "server", "folders", "appearance", "plugin_logging", "plugin_pluginmanager",
"plugin_softwareupdate", "plugin_announcements", "plugin_backup"
"plugin_softwareupdate", "plugin_announcements", "plugin_backup", "plugin_tracking", "plugin_pi_support"
],
"usersettings": ["access", "interface"],
"wizard": ["access"],
@@ -323,7 +324,7 @@ default_settings = {
"userManager": "octoprint.users.FilebasedUserManager",
"userfile": None,
"autologinLocal": False,
"localNetworks": ["127.0.0.0/8"],
"localNetworks": ["127.0.0.0/8", "::1/128"],
"autologinAs": None,
"trustBasicAuthentication": False,
"checkBasicAuthenticationPassword": True
@@ -355,7 +356,7 @@ default_settings = {
"gcode": {
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
"snippets": {
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}",
"disable_hotends": "{% if printer_profile.extruder.sharedNozzle %}M104 T0 S0\n{% else %}{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}{% endif %}",
"disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}"
}
}
@@ -604,6 +605,8 @@ class Settings(object):
self._basedir = None
assert(isinstance(default_settings, dict))
self._map = HierarchicalChainMap(dict(), default_settings)
self._config = None
@@ -874,6 +877,7 @@ class Settings(object):
try:
self._config = yaml.safe_load(f)
self._mtime = self.last_modified
except yaml.YAMLError as e:
details = e.message
@@ -888,10 +892,12 @@ class Settings(object):
details=details,
line=line,
column=column)
except:
raise
# changed from else to handle cases where the file exists, but is empty / 0 bytes
if not self._config:
if not self._config or not isinstance(self._config, dict):
self._config = dict()
if migrate:
@@ -1304,15 +1310,25 @@ class Settings(object):
return True
return False
def backup(self, suffix, path=None):
def backup(self, suffix=None, path=None, ext=None, hidden=False):
import shutil
if path is None:
path = os.path.dirname(self._configfile)
basename = os.path.basename(self._configfile)
name, ext = os.path.splitext(basename)
backup = os.path.join(path, "{}.{}{}".format(name, suffix, ext))
basename = os.path.basename(self._configfile)
name, default_ext = os.path.splitext(basename)
if ext is None:
ext = default_ext
if suffix is None and ext == default_ext:
raise ValueError("Need a suffix or a different extension")
if suffix is None:
suffix = ""
backup = os.path.join(path, "{}{}.{}{}".format("." if hidden else "", name, suffix, ext))
shutil.copy(self._configfile, backup)
return backup
@@ -1329,7 +1345,14 @@ class Settings(object):
self._logger.exception("Error while saving config.yaml!")
raise
else:
from octoprint.events import eventManager, Events
self.load()
payload = dict(config_hash=self.config_hash,
effective_hash=self.effective_hash)
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
return True
##~~ Internal getter
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more