Merge branch 'rc/maintenance'

This commit is contained in:
Gina Häußge committed 2018-12-10 13:01:23 +01:00
commit 112a8b9c8b
165 files changed
+11893 -7125

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ trim_trailing_whitespace = true
[**.py]
indent_style = tab
indent_size = 4
[src/octoprint/static/js/app/**.js]
indent_style = space
+6 -6
View File
@@ -20,14 +20,14 @@ HEAD
# maintenance is currently the branch for preparation of maintenance release 1.3.9
# so are any fix/... and improve/... branches
maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.9rc4
# staging/maintenance is currently the branch for preparation of 1.3.10rc5
# so is regressionfix/...
staging/maintenance 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
regressionfix/.* 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 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
+3
View File
@@ -91,6 +91,9 @@ 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)
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
+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)!
+97 -3
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.
@@ -23,7 +26,7 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
Host: example.com
X-Api-Key: abcdef...
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`.
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`.
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
@@ -120,3 +123,94 @@ If CORS is not enabled you will get errors like the following::
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
header is present on the requested resource.
.. _sec-api-general-login:
Login
=====
.. http:post:: /api/login
Creates a login session or retrieves information about the currently existing session ("passive login").
Can be used in one of two ways: to login a user via username and password and create a persistent session (usually
from a UI in the browser), or to retrieve information about the active user (from an existing session or an API key)
via the ``passive`` flag.
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
:json passive: If present, performs a passive login only, returning information about the current user that's
active either through an existing session or the used API key
:json user: (active login only) Username
:json pass: (active login only) Password
:json remember: (active login only) Whether to set a "remember me" cookie on the session
:status 200: Successful login
:status 401: Username/password mismatch or unknown user
:status 403: Deactivated account
.. _sec-api-general-logout:
Logout
======
.. http:post:: /api/logout
Ends the current login session of the current user.
Only makes sense in the context of browser based workflows.
Will return a :http:statuscode:`204`.
:status 204: No error
.. _sec-api-general-datamodel:
Data model
==========
.. _sec-api-general-datamodel-login:
Login response
--------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- the user's name/id
* - ``active``
- 1
- boolean
- Whether the user's account is active or not
* - ``admin``
- 1
- boolean
- Whether the user has admin rights or not
* - ``user``
- 1
- boolean
- Whether the user has user rights or not (always ``true``)
* - ``apikey``
- 1
- string or None
- The user's API key, if set
* - ``settings``
- 1
- dict
- The user's settings, if any
* - ``session``
- 1
- string
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
* - ``_is_external_client``
- 1
- boolean
- Whether the client that made the request got detected as external from the local network or not.
+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:
+1 -1
View File
@@ -396,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
-
* - ``feature.sdSupport``
-
* - ``feature.sdReleativePath``
* - ``feature.sdRelativePath``
-
* - ``feature.sdAlwaysAvailable``
-
+67
View File
@@ -0,0 +1,67 @@
.. _sec-bundledplugins-announcements:
Announcement Plugin
===================
The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11).
It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new
plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels
via RSS or Atom feed URLs.
.. _fig-bundledplugins-announcements-example1:
.. figure:: ../images/bundledplugins-announcements-example1.png
:align: center
:alt: Example notification
An example notification from the Announcement Plugin.
.. _fig-bundledplugins-announcements-example2:
.. figure:: ../images/bundledplugins-announcements-example2.png
:align: center
:alt: Announcement reader
The Announcement Plugin's reader dialog.
.. _fig-bundledplugins-announcements-settings:
.. figure:: ../images/bundledplugins-announcements-settings.png
:align: center
:alt: Announcement settings
The Announcement Plugin's settings dialog.
.. _sec-bundledplugins-announcements-configuration:
Configuring the plugin
----------------------
The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog.
On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the
configuration of the existing channels through ``config.yaml``.
The available configuration keys are:
* ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure
that follows this format:
* ``name``: Name of the channel, used e.g. in the title of the displayed notifications.
* ``description``: Description of the channel.
* ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification).
* ``type``: Currently unused.
* ``url``: URL for the feed acting as notification source, must be RSS or Atom format.
* ``enabled_channels``: List of identifiers of enabled channels.
* ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly).
* ``channel_order``: List of channel identifiers in the order they should appear in the UI.
* ``ttl``: Time to live of the channel cache in minutes (default: 6 hours).
* ``display_limit``: Limit of items to display per channel (default: 3).
* ``summary_limit``: Limit of characters to display from each channel entry (default: 300).
.. _sec-bundledplugins-announcements-sourcecode:
Source code
-----------
The source of the Announcement plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/announcements``.
+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``.
+4
View File
@@ -8,8 +8,12 @@ Bundled Plugins
:maxdepth: 2
action_command_prompt.rst
announcements.rst
appkeys.rst
backup.rst
cura.rst
discovery.rst
forcelogin.rst
logging.rst
pluginmanager.rst
printer_safety_check.rst
+2 -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
+13 -1
View File
@@ -562,6 +562,9 @@ Use the following settings to enable or disable OctoPrint features:
- M117
- M118
# whether G90/G91 also influence absolute/relative mode of extruders
g90InfluencesExtruder: false
.. _sec-configuration-config_yaml-folder:
Folder
@@ -1058,6 +1061,15 @@ Use the following settings to configure the server:
# How many days to leave unused entries in the preemptive cache config
until: 7
# Configuration of the client IP check to warn about connections from external networks
ipCheck:
# whether to enable the check, defaults to true
enabled: true
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
trustedSubnets: []
.. note::
@@ -1165,7 +1177,7 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
# A list of filters to display in the terminal tab. Defaults to the filters shown below
terminalFilters:
- name: Suppress temperature messages
regex: '(Send: (N\d+\s+)?M105)|(Recv: ok T:)'
regex: '(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)'
- name: Suppress SD status messages
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
- name: Suppress wait responses
+2
View File
@@ -338,6 +338,8 @@ PrintFailed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``time``: the elapsed time of the print when it failed, in seconds (float)
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
.. deprecated:: 1.3.0
+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:
+1 -1
View File
@@ -3,7 +3,7 @@
Helpers
=======
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
Helpers are methods that plugins can expose to other plugins in order to make common functionality available on the
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
An example for providing some helper functions to the system can be found in the
+183
View File
@@ -402,6 +402,13 @@ octoprint.comm.firmware.info
``firmware_name`` will be ``Some Firmware Name`` in this case.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str firmware_name: The name of the parsed capability
:param dict firmware_data: All data contained in the ``M115`` report
@@ -421,6 +428,13 @@ octoprint.comm.firmware.capabilities
Note that hook handlers will be called once per received capability line.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str capability: The name of the parsed capability
:param bool enabled: Whether the capability is reported as enabled or disabled
@@ -440,6 +454,13 @@ octoprint.comm.protocol.action
No returned value is expected.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example:**
Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware.
@@ -477,6 +498,13 @@ This describes actually two hooks:
trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to
:ref:`the action command hook <sec-plugins-hook-comm-protocol-action>`.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
you will effectively block the send/receive loops, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example**
Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a
@@ -623,6 +651,13 @@ This describes actually four hooks:
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
to one already in the queue will give an error.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the send loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example**
The following hook handler replaces all ``M107`` ("Fan Off", deprecated) with an ``M106 S0`` ("Fan On" with speed
@@ -658,6 +693,13 @@ octoprint.comm.protocol.gcode.received
empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
``return`` statement is used or just nothing is returned explicitly from the handler.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example:**
Looks for the response of an ``M115``, which contains information about the ``MACHINE_TYPE``, among other things.
@@ -687,6 +729,13 @@ octoprint.comm.protocol.gcode.error
Plugins might utilize this hook to handle errors generated by the printer that are recoverable in one way or
the other and should not trigger the normal handling that assumes the worst.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example:**
Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the
@@ -762,6 +811,13 @@ octoprint.comm.protocol.temperatures.received
additional sanity checking to be applied and invalid values to be filtered out. If a handler returns an empty
dictionary or ``None``, no further processing will take place.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example**
The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C.
@@ -1033,6 +1089,54 @@ octoprint.printer.estimation.factory
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
:rtype: class or function
.. _sec-plugins-hook-server-http-after_request:
octoprint.server.api.after_request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: after_request_handlers_hook(*args, **kwargs)
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
usage example.
.. important::
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
.. _sec-plugins-hook-server-http-before_request:
octoprint.server.api.before_request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: after_request_handlers_hook(*args, **kwargs)
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
usage example.
.. important::
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
.. _sec-plugins-hook-server-http-access_validator:
octoprint.server.http.access_validator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: access_validator_hook(request, *args, **kwargs)
Allows adding additional access validators to the default tornado routers.
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled
"Force Login" plugin for a usage example.
.. important::
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
.. _sec-plugins-hook-server-http-bodysize:
octoprint.server.http.bodysize
@@ -1134,6 +1238,85 @@ octoprint.server.http.routes
:return: a list of 3-tuples with additional routes as defined above
:rtype: list
.. _sec-plugins-hook-server-sockjs-authed:
octoprint.server.sockjs.authed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
.. _sec-plugins-hook-server-sockjs-register:
octoprint.server.sockjs.register
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
Allows plugins to prevent a new :ref:`push socket client <sec-api-push>` to be registered to the system.
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
signals to not register the client.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user currently authenticated on the socket - might be None
:return: whether to proceed with registration (``True``) or not (``False``)
:rtype: boolean
.. _sec-plugins-hook-server-sockjs-emit:
octoprint.server.sockjs.emit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection <sec-api-push>`.
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object on which a message is about to be emitted
:param object user: the user currently authenticated on the socket - might be None
:param string message: the message type about to be emitted
:param dict payload: the payload of the message about to be emitted (may be None)
:return: whether to proceed with sending the message (``True``) or not (``False``)
:rtype: boolean
.. _sec-plugins-hook-timelapse-extensions:
octoprint.timelapse.extensions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: timelapse_extension_hook(*args, **kwargs)
Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of
additional file extensions.
**Example**
Allow the management of timelapse GIFs with extension ``gif``.
.. code-block:: python
def get_timelapse_extensions(*args, **kwargs):
return ["gif"]
__plugin_hooks__ = {
"octoprint.timelapse.extensions": get_timelapse_extensions
}
:return: a list of additional file extensions
:rtype: list
.. _sec-plugins-hook-ui-web-templatetypes:
octoprint.ui.web.templatetypes
+6 -7
View File
@@ -12,13 +12,16 @@ import octoprint_setuptools
#-----------------------------------------------------------------------------------------------------------------------
# Supported python versions
PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11
# Requirements for our application
INSTALL_REQUIRES = [
"flask>=0.10.1,<0.11",
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
"regex==2018.11.3", # Current version as of 2018-11-06 is broken. See #2874
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
"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
@@ -32,8 +35,7 @@ INSTALL_REQUIRES = [
"pyserial>=3.4,<3.5",
"netaddr>=0.7.19,<0.8",
"watchdog>=0.8.3,<0.9",
"sarge==0.1.4", # 0.1.5 introduced a breaking change with regards to the async keyword. Pinning
# to 0.1.4 for now to work around this.
"sarge==0.1.5post0",
"netifaces>=0.10.6,<0.11",
"pylru>=1.0.9,<1.1",
"rsa>=3.2.3,<3.3",
@@ -81,9 +83,6 @@ EXTRA_REQUIRES = dict(
]
)
# Additional requirements for setup
SETUP_REQUIRES = []
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
@@ -156,10 +155,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",
+3
View File
@@ -595,6 +595,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")
+3
View File
@@ -71,3 +71,6 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
click.echo("DONE:{}s".format(time.time() - start_time))
click.echo("RESULTS:")
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
if __name__ == "__main__":
gcode_command()
-1
View File
@@ -82,7 +82,6 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover)
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
except FatalStartupError as e:
+6 -9
View File
@@ -256,7 +256,7 @@ class FileManager(object):
file_name = storage_manager.split_path(path)
# we'll use the default printer profile for the backlog since we don't know better
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None)
if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority):
counter += 1
@@ -476,12 +476,9 @@ class FileManager(object):
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
if analysis is None:
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
if queue_entry:
self._analysis_queue.enqueue(queue_entry, high_priority=True)
else:
self._add_analysis_result(destination, path, analysis)
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis)
if queue_entry:
self._analysis_queue.enqueue(queue_entry, high_priority=True)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
@@ -700,7 +697,7 @@ class FileManager(object):
def _on_analysis_finished(self, entry, result):
self._add_analysis_result(entry.location, entry.path, result)
def _analysis_queue_entry(self, destination, path, printer_profile=None):
def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
@@ -709,6 +706,6 @@ class FileManager(object):
file_type = get_file_type(absolute_path)
if file_type:
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile)
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis)
else:
return None
+6 -3
View File
@@ -20,7 +20,7 @@ from octoprint.events import Events, eventManager
from octoprint.settings import settings
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
@@ -33,6 +33,7 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
def __str__(self):
@@ -298,7 +299,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in minutes
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
@@ -341,6 +342,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
import sys
import yaml
if self._current.analysis:
return self._current.analysis
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
@@ -364,7 +367,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
self._aborted = False
p = sarge.run(command, async=True, stdout=sarge.Capture())
p = sarge.run(command, async_=True, stdout=sarge.Capture())
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
+9 -4
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)
@@ -94,7 +95,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = ["octoprint.server.http.*",
"octoprint.printer.factory"]
"octoprint.printer.factory",
"octoprint.timelapse.extensions"]
if plugin_obsolete_hooks is None:
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
@@ -167,7 +169,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
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
@@ -205,7 +208,6 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
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)):
@@ -215,18 +217,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)
+1 -1
View File
@@ -861,7 +861,7 @@ class PluginManager(object):
if plugin.check():
return plugin
else:
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
return None
def _is_plugin_disabled(self, key):
+20 -4
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
@@ -1984,7 +2000,7 @@ class SlicerPlugin(OctoPrintPlugin):
For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information
about the slicing job under the following keys:
_analysis
analysis
Analysis result of the generated machine code as returned by the slicer itself. This should match the
data structure described for the analysis queue of the matching machine code format, e.g.
:class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files.
@@ -49,7 +49,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
#~ AssetPlugin
def get_assets(self):
return dict(js=["js/action_command_prompt.js"])
return dict(js=["js/action_command_prompt.js"],
clientjs=["clientjs/action_command_prompt.js"])
#~ SettingsPlugin
@@ -0,0 +1,25 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintActionCommandPromptClient = function(base) {
this.base = base;
};
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
};
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
var data = {
choice: choice
};
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
};
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
return OctoPrintActionCommandPromptClient;
});
@@ -1,29 +1,3 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintActionCommandPromptClient = function(base) {
this.base = base;
};
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
};
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
var data = {
choice: choice
};
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
};
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
return OctoPrintActionCommandPromptClient;
});
$(function() {
function ActionCommandPromptViewModel(parameters) {
var self = this;
@@ -372,15 +372,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
result = []
if "entries" in feed:
for entry in feed["entries"]:
internal_entry = self._to_internal_entry(entry, read_until=read_until)
if internal_entry:
result.append(internal_entry)
try:
internal_entry = self._to_internal_entry(entry, read_until=read_until)
if internal_entry:
result.append(internal_entry)
except:
self._logger.exception("Error while converting entry from feed, skipping it")
return result
def _to_internal_entry(self, entry, read_until=None):
"""Convert feed entries to internal data structure."""
published = calendar.timegm(entry["published_parsed"])
timestamp = entry.get("published_parsed",
entry.get("updated_parsed",
None))
if timestamp is None:
return None
published = calendar.timegm(timestamp)
read = True
if read_until is not None:
+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>
+925
View File
@@ -0,0 +1,925 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from octoprint.settings import default_settings
from octoprint.plugin.core import FolderOrigin
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.util import is_hidden_path
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
from octoprint.util.platform import is_os_compatible
from octoprint.util.pip import LocalPipCaller
try:
from os import scandir
except ImportError:
from scandir import scandir
try:
import zlib # check if zlib is available
except ImportError:
zlib = None
from flask_babel import gettext
import codecs
import flask
import logging
import os
import requests
import sarge
import shutil
import tempfile
import threading
import time
import zipfile
import json
import sys
import traceback
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
class BackupPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin):
_pip_caller = None
# noinspection PyMissingConstructor
def __init__(self):
self._in_progress = []
self._in_progress_lock = threading.RLock()
##~~ StarupPlugin
def on_after_startup(self):
self._clean_dir_backup(self._settings._basedir,
on_log_progress=self._logger.info)
##~~ AssetPlugin
def get_assets(self):
return dict(js=["js/backup.js"],
clientjs=["clientjs/backup.js"],
css=["css/backup.css"],
less=["less/backup.less"])
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@admin_permission.require(403)
@restricted_access
def get_state(self):
backups = self._get_backups()
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(backups=backups,
backup_in_progress=len(self._in_progress) > 0,
unknown_plugins=unknown_plugins,
restore_supported=is_os_compatible(["!windows"]))
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
@admin_permission.require(403)
@restricted_access
def get_unknown_plugins(self):
# TODO add caching
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(unknown_plugins=unknown_plugins)
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
@admin_permission.require(403)
@restricted_access
def delete_unknown_plugins(self):
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
try:
os.remove(data_file)
except:
pass
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
@admin_permission.require(403)
@restricted_access
def get_backups(self):
backups = self._get_backups()
return flask.jsonify(backups=backups)
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
@admin_permission.require(403)
@restricted_access
def create_backup(self):
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
data = flask.request.json
exclude = data.get("exclude", [])
def on_backup_start(name, temporary_path, exclude):
self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path,
u",".join(exclude) if len(exclude) else "-"))
with self._in_progress_lock:
self._in_progress.append(name)
self._send_client_message("backup_started", payload=dict(name=name))
def on_backup_done(name, final_path, exclude):
with self._in_progress_lock:
self._in_progress.remove(name)
self._send_client_message("backup_done", payload=dict(name=name))
self._logger.info(u"... done creating backup zip.")
def on_backup_error(name, exc_info):
with self._in_progress_lock:
try:
self._in_progress.remove(name)
except ValueError:
# we'll ignore that
pass
self._send_client_message("backup_error", payload=dict(name=name,
error=u"{}".format(exc_info[1])))
self._logger.error(u"Error while creating backup zip", exc_info=exc_info)
thread = threading.Thread(target=self._create_backup,
args=(backup_file,),
kwargs=dict(exclude=exclude,
settings=self._settings,
plugin_manager=self._plugin_manager,
datafolder=self.get_plugin_data_folder(),
on_backup_start=on_backup_start,
on_backup_done=on_backup_done,
on_backup_error=on_backup_error))
thread.daemon = True
thread.start()
response = flask.jsonify(started=True,
name=backup_file)
response.status_code = 201
return response
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
@admin_permission.require(403)
@restricted_access
def delete_backup(self, filename):
backup_folder = self.get_plugin_data_folder()
full_path = os.path.realpath(os.path.join(backup_folder, filename))
if full_path.startswith(backup_folder) \
and os.path.exists(full_path) \
and not is_hidden_path(full_path):
try:
os.remove(full_path)
except:
self._logger.exception(u"Could not delete {}".format(filename))
raise
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
@admin_permission.require(403)
@restricted_access
def perform_restore(self):
if not is_os_compatible(["!windows"]):
return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400)
input_name = "file"
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
if input_upload_path in flask.request.values:
# file to restore was uploaded
path = flask.request.values[input_upload_path]
elif flask.request.json and "path" in flask.request.json:
# existing backup is supposed to be restored
backup_folder = self.get_plugin_data_folder()
path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"]))
if not path.startswith(backup_folder) \
or not os.path.exists(path) \
or is_hidden_path(path):
return flask.abort(404)
else:
return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400)
def on_install_plugins(plugins):
force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"])
def on_log(line):
self._logger.info(line)
self._send_client_message("logline", dict(line=line, type="stdout"))
for plugin in plugins:
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
u"of OctoPrint and the underlying operating system".format(plugin["id"]))
elif not octoprint_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
u"of OctoPrint".format(plugin["id"]))
elif not os_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying "
u"operating system".format(plugin["id"]))
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
octoprint_compatible=octoprint_compatible,
os_compatible=os_compatible))
continue
self._logger.info(u"Installing plugin {}".format(plugin["id"]))
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
self.__class__._install_plugin(plugin,
force_user=force_user,
pip_args=pip_args,
on_log=on_log)
def on_report_unknown_plugins(plugins):
self._send_client_message("unknown_plugins", payload=dict(plugins=plugins))
def on_log_progress(line):
self._logger.info(line)
self._send_client_message("logline", payload=dict(line=line, stream="stdout"))
def on_log_error(line, exc_info=None):
self._logger.error(line, exc_info=exc_info)
self._send_client_message("logline", payload=dict(line=line, stream="stderr"))
if exc_info is not None:
exc_type, exc_value, exc_tb = exc_info
output = traceback.format_exception(exc_type, exc_value, exc_tb)
for line in output:
self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr"))
def on_restore_start(path):
self._send_client_message("restore_started")
def on_restore_done(path):
self._send_client_message("restore_done")
def on_restore_failed(path):
self._send_client_message("restore_failed")
def on_invalid_backup(line):
on_log_error(line)
archive = tempfile.NamedTemporaryFile(delete=False)
archive.close()
shutil.copy(path, archive.name)
path = archive.name
# noinspection PyTypeChecker
thread = threading.Thread(target=self._restore_backup,
args=(path,),
kwargs=dict(settings=self._settings,
plugin_manager=self._plugin_manager,
datafolder=self.get_plugin_data_folder(),
on_install_plugins=on_install_plugins,
on_report_unknown_plugins=on_report_unknown_plugins,
on_invalid_backup=on_invalid_backup,
on_log_progress=on_log_progress,
on_log_error=on_log_error,
on_restore_start=on_restore_start,
on_restore_done=on_restore_done,
on_restore_failed=on_restore_failed))
thread.daemon = True
thread.start()
return flask.jsonify(started=True)
##~~ tornado hook
def route_hook(self, *args, **kwargs):
from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory
from octoprint.util import is_hidden_path
from octoprint.server import app
from octoprint.server.util.tornado import access_validation_factory
from octoprint.server.util.flask import admin_validator
return [
(r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(),
as_attachment=True,
path_validation=path_validation_factory(lambda path: not is_hidden_path(path),
status_code=404),
access_validation=access_validation_factory(app, admin_validator)))
]
def bodysize_hook(self, current_max_body_sizes, *args, **kwargs):
# max upload size of 1GB for the restore endpoint
return [("POST", r"/restore", 1024 * 1024 * 1024)]
##~~ CLI hook
def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
@click.command("backup")
@click.option("--exclude", multiple=True,
help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or "
"'timelapse' to exclude timelapses.")
def backup_command(exclude):
"""
Creates a new backup.
"""
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
click.echo("Creating backup at {}, please wait...".format(backup_file))
self._create_backup(backup_file,
exclude=exclude,
settings=settings,
plugin_manager=cli_group.plugin_manager,
datafolder=datafolder)
click.echo("Done.")
@click.command("restore")
@click.argument("path")
def restore_command(path):
"""
Restores an existing backup from the backup zip provided as argument.
OctoPrint does not need to run for this to proceed.
"""
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
plugin_manager = cli_group.plugin_manager
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
# register plugin manager plugin setting overlays
plugin_info = plugin_manager.get_plugin_info("pluginmanager")
if plugin_info and plugin_info.implementation:
default_settings_overlay = dict(plugins=dict())
default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults()
settings.add_overlay(default_settings_overlay, at_end=True)
if not os.path.isabs(path):
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
path = os.path.join(datafolder, path)
if not os.path.exists(path):
click.echo(u"Backup {} does not exist".format(path), err=True)
sys.exit(-1)
archive = tempfile.NamedTemporaryFile(delete=False)
archive.close()
shutil.copy(path, archive.name)
path = archive.name
def on_install_plugins(plugins):
if not plugins:
return
force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
def log(line):
click.echo(u"\t{}".format(line))
for plugin in plugins:
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
u"OctoPrint and the underlying operating system".format(plugin["id"]))
elif not octoprint_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
u"OctoPrint".format(plugin["id"]))
elif not os_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to the underlying "
u"operating system".format(plugin["id"]))
continue
click.echo(u"Installing plugin {}".format(plugin["id"]))
self.__class__._install_plugin(plugin,
force_user=force_user,
pip_args=pip_args,
on_log=log)
def on_report_unknown_plugins(plugins):
if not plugins:
return
click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.")
for plugin in plugins:
click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
def on_log_progress(line):
click.echo(line)
def on_log_error(line, exc_info=None):
click.echo(line, err=True)
if exc_info is not None:
exc_type, exc_value, exc_tb = exc_info
output = traceback.format_exception(exc_type, exc_value, exc_tb)
for line in output:
click.echo(line.rstrip(), err=True)
if self._restore_backup(path,
settings=settings,
plugin_manager=plugin_manager,
datafolder=datafolder,
on_install_plugins=on_install_plugins,
on_report_unknown_plugins=on_report_unknown_plugins,
on_log_progress=on_log_progress,
on_log_error=on_log_error,
on_invalid_backup=on_log_error):
click.echo(u"Restored from {}".format(path))
else:
click.echo(u"Restoring from {} failed".format(path), err=True)
return [backup_command, restore_command]
##~~ helpers
def _get_backups(self):
backups = []
for entry in scandir(self.get_plugin_data_folder()):
if is_hidden_path(entry.path):
continue
if not entry.is_file():
continue
if not entry.name.endswith(".zip"):
continue
backups.append(dict(name=entry.name,
date=entry.stat().st_mtime,
size=entry.stat().st_size,
url=flask.url_for("index") + "plugin/backup/download/" + entry.name))
return backups
def _get_unknown_plugins(self):
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
if os.path.exists(data_file):
try:
with codecs.open(data_file, mode="r", encoding="utf-8") as f:
unknown_plugins = json.load(f)
assert isinstance(unknown_plugins, list)
assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins))
installed_plugins = self._plugin_manager.plugins
unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
if not unknown_plugins:
# no plugins left uninstalled, delete data file
try:
os.remove(data_file)
except:
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
return unknown_plugins
except:
self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file))
try:
os.remove(data_file)
except:
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
return []
@classmethod
def _clean_dir_backup(cls, basedir,
on_log_progress=None):
basedir_backup = basedir + ".bck"
if os.path.exists(basedir_backup):
def remove_bck():
if callable(on_log_progress):
on_log_progress(u"Found config folder backup from prior restore, deleting it...")
shutil.rmtree(basedir_backup)
if callable(on_log_progress):
on_log_progress(u"... deleted.")
thread = threading.Thread(target=remove_bck)
thread.daemon = True
thread.start()
@classmethod
def _get_disk_size(cls, path):
total = 0
for entry in scandir(path):
if entry.is_dir():
total += cls._get_disk_size(entry.path)
elif entry.is_file():
total += entry.stat().st_size
return total
@classmethod
def _free_space(cls, path, size):
from psutil import disk_usage
return disk_usage(path).free > size
@classmethod
def _get_plugin_repository_data(cls, url, logger=None):
if logger is None:
logger = logging.getLogger(__name__)
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
except:
logger.exception(u"Error while fetching the plugin repository data from {}".format(url))
return dict()
from octoprint.plugins.pluginmanager import map_repository_entry
return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()))
@classmethod
def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None):
if pip_args is None:
pip_args = []
if on_log is None:
on_log = logging.getLogger(__name__).info
# prepare pip caller
def log(prefix, *lines):
for line in lines:
on_log(u"{} {}".format(prefix, line.rstrip()))
def log_call(*lines):
log(u">", *lines)
def log_stdout(*lines):
log(u"<", *lines)
def log_stderr(*lines):
log(u"!", *lines)
if cls._pip_caller is None:
cls._pip_caller = LocalPipCaller(force_user=force_user)
cls._pip_caller.on_log_call = log_call
cls._pip_caller.on_log_stdout = log_stdout
cls._pip_caller.on_log_stderr = log_stderr
# install plugin
pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir']
if plugin.get("follow_dependency_links"):
pip.append("--process-dependency-links")
if force_user:
pip.append("--user")
if pip_args:
pip += pip_args
cls._pip_caller.execute(*pip)
@classmethod
def _create_backup(cls, name,
exclude=None,
settings=None,
plugin_manager=None,
datafolder=None,
on_backup_start=None,
on_backup_done=None,
on_backup_error=None):
try:
if exclude is None:
exclude = []
configfile = settings._configfile
basedir = settings._basedir
temporary_path = os.path.join(datafolder, ".{}".format(name))
final_path = os.path.join(datafolder, name)
size = cls._get_disk_size(basedir)
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
own_folder = datafolder
defaults = [os.path.join(basedir, "config.yaml"),] + \
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
if callable(on_backup_start):
on_backup_start(name, temporary_path, exclude)
with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip:
def add_to_zip(source, target, ignored=None):
if ignored is None:
ignored = []
if source in ignored:
return
if os.path.isdir(source):
for entry in scandir(source):
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
elif os.path.isfile(source):
zip.write(source, arcname=target)
# add metadata
metadata = dict(version=get_octoprint_version_string(),
excludes=exclude)
zip.writestr("metadata.json", json.dumps(metadata))
# backup current config file
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
# backup configured folder paths
for folder in default_settings["folder"].keys():
if folder in exclude:
continue
if folder in ("generated", "logs", "watched",):
continue
add_to_zip(settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[own_folder,])
# backup anything else that might be lying around in our basedir
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
# add list of installed plugins
plugins = []
plugin_folder = settings.global_get_basefolder("plugins")
for key, plugin in plugin_manager.plugins.items():
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
# ignore anything bundled or from the plugins folder we already include in the backup
continue
plugins.append(dict(key=plugin.key,
name=plugin.name,
url=plugin.url))
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
os.rename(temporary_path, final_path)
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
except:
if callable(on_backup_error):
exc_info = sys.exc_info()
try:
on_backup_error(name, exc_info)
finally:
del exc_info
raise
@classmethod
def _restore_backup(cls, path,
settings=None,
plugin_manager=None,
datafolder=None,
on_install_plugins=None,
on_report_unknown_plugins=None,
on_invalid_backup=None,
on_log_progress=None,
on_log_error=None,
on_restore_start=None,
on_restore_done=None,
on_restore_failed=None):
if not is_os_compatible(["!windows"]):
if callable(on_log_error):
on_log_error(u"Restore is not supported on this operating system")
if callable(on_restore_failed):
on_restore_failed(path)
return False
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
basedir = settings._basedir
cls._clean_dir_backup(basedir,
on_log_progress=on_log_progress)
plugin_repo = dict()
repo_url = settings.global_get(["plugins", "pluginmanager", "repository"])
if repo_url:
plugin_repo = cls._get_plugin_repository_data(repo_url)
if callable(on_restore_start):
on_restore_start(path)
try:
with zipfile.ZipFile(path, "r") as zip:
# read metadata
try:
metadata_zipinfo = zip.getinfo("metadata.json")
except KeyError:
if callable(on_invalid_backup):
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
if callable(on_restore_failed):
on_restore_failed(path)
return False
metadata_bytes = zip.read(metadata_zipinfo)
metadata = json.loads(metadata_bytes)
backup_version = get_comparable_version(metadata["version"], base=True)
if backup_version > get_octoprint_version(base=True):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
if callable(on_restore_failed):
on_restore_failed(path)
return False
# unzip to temporary folder
temp = tempfile.mkdtemp()
try:
if callable(on_log_progress):
on_log_progress(u"Unpacking backup to {}...".format(temp))
abstemp = os.path.abspath(temp)
for member in zip.infolist():
abspath = os.path.abspath(os.path.join(temp, member.filename))
if abspath.startswith(abstemp):
zip.extract(member, temp)
# sanity check
configfile = os.path.join(temp, "basedir", "config.yaml")
if not os.path.exists(configfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks config.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
import yaml
with codecs.open(configfile) as f:
configdata = yaml.safe_load(f)
if configdata.get("accessControl", dict()).get("enabled", True):
userfile = os.path.join(temp, "basedir", "users.yaml")
if not os.path.exists(userfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks users.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
if callable(on_log_progress):
on_log_progress(u"Unpacked")
# install available plugins
with codecs.open(os.path.join(temp, "plugin_list.json"), "r") as f:
plugins = json.load(f)
known_plugins = []
unknown_plugins = []
if plugins:
if plugin_repo:
for plugin in plugins:
if plugin["key"] in plugin_manager.plugins:
# already installed
continue
if plugin["key"] in plugin_repo:
# not installed, can be installed from repository url
known_plugins.append(plugin_repo[plugin["key"]])
else:
# not installed, not installable
unknown_plugins.append(plugin)
else:
# no repo, all plugins are not installable
unknown_plugins = plugins
if callable(on_log_progress):
if known_plugins:
on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins))))
if unknown_plugins:
on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins))))
if callable(on_install_plugins):
on_install_plugins(known_plugins)
if callable(on_report_unknown_plugins):
on_report_unknown_plugins(unknown_plugins)
# move config data
basedir_backup = basedir + ".bck"
basedir_extracted = os.path.join(temp, "basedir")
if callable(on_log_progress):
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
os.rename(basedir, basedir_backup)
try:
if callable(on_log_progress):
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
os.rename(basedir_extracted, basedir)
except:
if callable(on_log_error):
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
on_log_error(u"Rolling back old config data")
os.rename(basedir_backup, basedir)
if callable(on_restore_failed):
on_restore_failed(path)
return False
if unknown_plugins:
if callable(on_log_progress):
on_log_progress(u"Writing info file about unknown plugins")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE)
try:
with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f:
json.dump(unknown_plugins, f)
except:
if callable(on_log_error):
on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
exc_info = sys.exc_info())
finally:
if callable(on_log_progress):
on_log_progress(u"Removing temporary unpacked folder")
shutil.rmtree(temp)
except:
exc_info = sys.exc_info()
try:
if callable(on_log_error):
on_log_error(u"Error while running restore", exc_info=exc_info)
if callable(on_restore_failed):
on_restore_failed(path)
finally:
del exc_info
return False
finally:
# remove zip
if callable(on_log_progress):
on_log_progress(u"Removing temporary zip")
os.remove(path)
# restart server
if restart_command:
import sarge
if callable(on_log_progress):
on_log_progress(u"Restarting...")
if callable(on_restore_done):
on_restore_done(path)
try:
sarge.run(restart_command, async_=True)
except:
if callable(on_log_error):
on_log_error(u"Error while restarting via command {}".format(restart_command),
exc_info=sys.exc_info())
on_log_error(u"Please restart OctoPrint manually")
return False
else:
if callable(on_restore_done):
on_restore_done(path)
return True
def _send_client_message(self, message, payload=None):
if payload is None:
payload = dict()
payload["type"] = message
self._plugin_manager.send_plugin_message(self._identifier, payload)
class InsufficientSpace(Exception):
pass
__plugin_name__ = gettext(u"Backup & Restore")
__plugin_author__ = u"Gina Häußge"
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
u"& restore your OctoPrint settings and data.")
__plugin_license__ = u"AGPLv3"
__plugin_implementation__ = BackupPlugin()
__plugin_hooks__ = {
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook
}
@@ -0,0 +1,52 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintBackupClient = function(base) {
this.base = base;
this.url = this.base.getBlueprintUrl("backup");
};
OctoPrintBackupClient.prototype.get = function(refresh, opts) {
return this.base.get(this.url, opts);
};
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
exclude = exclude || [];
var data = {
exclude: exclude
};
return this.base.postJson(this.url + "backup", data, opts);
};
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
return this.base.delete(this.url + "backup/" + backup, opts);
};
OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
var data = {
path: backup
};
return this.base.postJson(this.url + "restore", data, opts);
};
OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) {
data = data || {};
var filename = data.filename || undefined;
return this.base.upload(this.url + "restore", file, filename, data);
};
OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) {
return this.base.delete(this.url + "unknown_plugins", opts);
};
OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient);
return OctoPrintBackupClient;
});
@@ -0,0 +1 @@
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
@@ -0,0 +1,289 @@
$(function() {
function BackupViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settings = parameters[1];
self.backups = new ItemListHelper(
"plugin.backup.backups",
{
"date": function (a, b) {
// sorts descending
if (a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
return 0;
}
},
{
},
"date",
[],
[],
10
);
self.markedForBackupDeletion = ko.observableArray([]);
self.excludeFromBackup = ko.observableArray([]);
self.backupInProgress = ko.observable(false);
self.restoreSupported = ko.observable(true);
self.backupUploadButton = $("#settings-backup-upload");
self.backupUploadData = undefined;
self.backupUploadButton.fileupload({
dataType: "json",
maxNumberOfFiles: 1,
autoUpload: false,
headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
if (data.files.length === 0) {
// no files? ignore
return false;
}
self.backupUploadName(data.files[0].name);
self.backupUploadData = data;
},
done: function(e, data) {
self.backupUploadName(undefined);
self.backupUploadData = undefined;
}
});
self.backupUploadName = ko.observable();
self.restoreInProgress = ko.observable(false);
self.restoreTitle = ko.observable();
self.restoreDialog = undefined;
self.restoreOutput = undefined;
self.unknownPlugins = ko.observableArray([]);
self.loglines = ko.observableArray([]);
self.requestData = function() {
OctoPrint.plugins.backup.get()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
self.backups.updateItems(response.backups);
self.unknownPlugins(response.unknown_plugins);
self.restoreSupported(response.restore_supported);
};
self.createBackup = function() {
var excluded = self.excludeFromBackup();
OctoPrint.plugins.backup.createBackup(excluded)
.done(function() {
self.excludeFromBackup([]);
})
};
self.removeBackup = function(backup) {
var perform = function() {
OctoPrint.plugins.backup.deleteBackup(backup)
.done(function() {
self.requestData();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
perform);
};
self.restoreBackup = function(backup) {
if (!self.restoreSupported()) return;
var perform = function() {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Preparing to restore...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
OctoPrint.plugins.backup.restoreBackup(backup);
};
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
perform);
};
self.performRestoreFromUpload = function() {
if (self.backupUploadData === undefined) return;
var perform = function() {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
self.backupUploadData.submit();
};
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
perform);
};
self.deleteUnknownPluginRecord = function() {
var perform = function() {
OctoPrint.plugins.backup.deleteUnknownPlugins()
.done(function() {
self.requestData();
});
};
showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),
perform);
};
self.markFilesOnPage = function() {
self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
};
self.markAllFiles = function() {
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
};
self.clearMarkedFiles = function() {
self.markedForBackupDeletion.removeAll();
};
self.removeMarkedFiles = function() {
var perform = function() {
self._bulkRemove(self.markedForBackupDeletion())
.done(function() {
self.markedForBackupDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
perform);
};
self.onStartup = function() {
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
};
self.onSettingsShown = function() {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin !== "backup") return;
if (data.type === "backup_done") {
self.requestData();
self.backupInProgress(false);
new PNotify({
title: gettext("Backup created successfully"),
type: "success"
});
} else if (data.type === "backup_started") {
self.backupInProgress(true);
} else if (data.type === "backup_error") {
self.requestData();
self.backupInProgress(false);
new PNotify({
title: gettext("Creating the backup failed"),
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
type: "error",
hide: false
});
} else if (data.type === "restore_started") {
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
self.loglines.push({line: " ", stream: "message"});
} else if (data.type === "restore_failed") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
self.restoreInProgress(false);
} else if (data.type === "restore_done") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
self.restoreInProgress(false);
} else if (data.type === "install_plugin") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}),
stream: "message"
});
} else if (data.type === "plugin_incompatible") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}),
stream: "stderr"
});
} else if (data.type === "unknown_plugins") {
if (data.plugins.length > 0) {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"});
_.each(data.plugins, function(plugin) {
self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"});
});
self.loglines.push({line: " ", stream: "message"});
self.unknownPlugins(data.plugins);
}
} else if (data.type === "logline") {
self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream}));
self._scrollRestoreOutputToEnd();
}
};
self._scrollRestoreOutputToEnd = function() {
self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height());
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function(line) {
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
};
self._bulkRemove = function(files) {
var title, message, handler;
title = gettext("Deleting backups");
message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
handler = function(filename) {
return OctoPrint.plugins.backup.deleteBackup(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
};
var deferred = $.Deferred();
var promise = deferred.promise();
var options = {
title: title,
message: message,
max: files.length,
output: true
};
showProgressModal(options, promise);
var requests = [];
_.each(files, function(filename) {
var request = handler(filename);
requests.push(request)
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
}
OCTOPRINT_VIEWMODELS.push({
construct: BackupViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel"],
elements: ["#settings_plugin_backup"]
});
});
@@ -0,0 +1,52 @@
#settings_plugin_backup_backup_table {
.settings_plugin_backup_name {
}
.settings_plugin_backup_actions {
width: 75px;
text-align: center;
a {
color: black;
}
}
.settings_plugin_backup_date {
width: 200px;
text-align: right;
}
.settings_plugin_backup_size {
width: 100px;
text-align: right;
}
.settings_plugin_backup_checkbox {
text-align: center;
width: 10px;
input[type="checkbox"] {
margin-top: 0;
}
}
}
#settings_plugin_backup_restoredialog_output {
.message {
font-weight: bold;
}
.error {
font-weight: bold;
color: #990000;
}
.stdout {
color: #333333;
}
.stderr {
color: #990000;
}
.call {
color: #000099;
}
}
@@ -0,0 +1,135 @@
<div class="alert" data-bind="visible: unknownPlugins().length > 0">
{% trans %}
Some plugins during the last restore could not be identified and hence not automatically installed.
Please install them manually, they are listed below including their stated homepages:
{% endtrans %}
<ul data-bind="foreach: unknownPlugins">
<li><span data-bind="text: name"></span>: <a data-bind="text: url, attr: {href: url}" target="_blank" rel="noreferrer noopener"></a></li>
</ul>
<small><a href="javascript:void(0)" data-bind="click: deleteUnknownPluginRecord">{{ _('Delete record of unknown plugins') }}</a></small>
</div>
<h3>{{ _('Existing backups') }}</h3>
<div data-bind="visible: backups.allSize() <= 0">
<p>{{ _('There are no backups. Maybe create one below?') }}</p>
</div>
<div data-bind="visible: backups.allSize() > 0">
<p>{{ _('These are the backups of your settings and files that already exist on this OctoPrint instance. You may delete, download or restore them.') }}</p>
<div class="pull-left">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
</ul>
</div>
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForBackupDeletion().length > 0">{{ _('Delete selected') }}</button>
</div>
<table class="table table-condensed table-hover" id="settings_plugin_backup_backup_table">
<thead>
<tr>
<th class="settings_plugin_backup_checkbox"></th>
<th class="settings_plugin_backup_name">{{ _('Name') }}</th>
<th class="settings_plugin_backup_date">{{ _('Date') }}</th>
<th class="settings_plugin_backup_size">{{ _('Size') }}</th>
<th class="settings_plugin_backup_actions">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: backups.paginatedItems">
<tr>
<td class="settings_plugin_backup_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForBackupDeletion"></td>
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a>&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>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: backups.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: backups.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: backups.pages">
<li data-bind="css: { active: $data.number === $root.backups.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.backups.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: backups.currentPage() === backups.lastPage()}"><a href="javascript:void(0)" data-bind="click: backups.nextPage">»</a></li>
</ul>
</div>
</div>
<h3>{{ _('Create backup') }}</h3>
<p>{{ _('Create a new backup of the current state.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="value: 'timelapse', checked: excludeFromBackup"> {{ _('Exclude timelapses from backup') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: createBackup"><i class="fa fa-spinner fa-spin" data-bind="visible: backupInProgress"></i> {{ _('Create backup now') }}</button>
</div>
</div>
</form>
<div data-bind="visible: restoreSupported()">
<h3>{{ _('Restore from uploaded backup') }}</h3>
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Backup file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
</span>
<span class="add-on" data-bind="text: backupUploadName"></span>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
</div>
</div>
</form>
</div>
<div data-bind="visible: !restoreSupported()">
{{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to <a href="%(url)s" target="_blank" rel="noopener noreferrer">restore your backups manually for now</a>.', url='https://faq.octoprint.org/manual-restore') }}
</div>
<div id="settings_plugin_backup_restoredialog" class="modal hide fade">
<div class="modal-header">
<h3>{{ _('Restoring from backup...') }}</h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_backup_restoredialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.restoreInProgress()" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -1,14 +1,22 @@
<h3>{{ _('Access Control') }}</h3>
{% trans %}<p>
{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}<p>
<strong>Please read the following, it is very important for your printer's health!</strong>
</p>
<p>
OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
malicious intent - to gain access to your printer</strong> via an untrustworthy network
and using it in such a way that it is damaged or worse (i.e. causes a fire).
</p>
<p>
If you plan on accessing OctoPrint remotely over the internet, <strong>you should not only rely on the built-in
Access Control mechanisms</strong> however -
<a href="{{ safe_remote_url }}" target="_blank" rel="noopener noreferrer">take additional precautions</a>.
Your OctoPrint enabled printer is a critical home appliance you really should not give anyone who happens to be
connected to the internet access to - even read-only! <strong>An instance available publicly on the internet
will be found, and people will try to break it open.</strong>
</p>
<p>
It looks like you haven't configured access control yet. Please <strong>set up a username and password</strong> for the
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
@@ -36,12 +44,12 @@
</div>
</form>
{% trans %}<p>
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy local network and you don't
need Access Control for other reasons, you may alternatively disable Access Control. You should only
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
</p>
<p>
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
<strong>Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!</strong>
</p>{% endtrans %}
<div class="row-fluid">
+1 -1
View File
@@ -312,7 +312,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
working_dir))
import sarge
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p = sarge.run(args, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p.wait_events()
self._slicing_commands[machinecode_path] = p.commands[0]
+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
@@ -181,6 +181,15 @@ $(function() {
self.uploadDialog.modal("hide");
self.requestData();
self.slicingViewModel.requestData();
},
error: function(jqXHR, textStatus, errorThrown) {
self.uploadBusy(false);
new PNotify({
title: gettext("Profile import failed"),
text: gettext("Could not import the provided profile, it might be invalid. Check <code>octoprint.log</code> for details"),
type: "error",
hide: false
});
}
});
+24 -5
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):
"""
@@ -601,8 +613,14 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
alive message
"""
from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
try:
# noinspection PyCompatibility
from http.server import BaseHTTPRequestHandler
except ImportError:
# noinspection PyCompatibility
from BaseHTTPServer import BaseHTTPRequestHandler
from io import BytesIO
import socket
socket.setdefaulttimeout(timeout)
@@ -617,8 +635,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
class Request(BaseHTTPRequestHandler):
# noinspection PyMissingConstructor
def __init__(self, request_text):
self.rfile = StringIO(request_text)
self.rfile = BytesIO(request_text)
self.raw_requestline = self.rfile.readline()
self.error_code = self.error_message = None
self.parse_request()
@@ -0,0 +1,183 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import flask
import flask_login
from flask_babel import gettext
from collections import defaultdict
import threading
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin):
MAX_BACKLOG_LEN = 100
# noinspection PyMissingConstructor
def __init__(self):
self._message_backlog = defaultdict(list)
self._message_backlog_mutex = threading.RLock()
def get_assets(self):
return dict(
js=["js/viewmodel.js"]
)
def will_handle_ui(self, request):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return False
from octoprint.server.util.flask import passive_login
result = passive_login()
if hasattr(result, "status_code") and result.status_code == 200:
# passive login successful, no need to handle that
return False
else:
return True
def on_ui_render(self, now, request, render_kwargs):
from flask import render_template, make_response
"""
Support theming of the login dialog, just in case the core UI is themed as well.
Example usage by a plugin:
def forcelogin_theming():
from flask import url_for
return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
__plugin_hooks__ = {
"octoprint.plugin.forcelogin.theming": forcelogin_theming
}
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
url_for like in the example above to be prepared for any configured prefix URLs.
"""
additional_assets = []
for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
try:
assets = hook()
if isinstance(assets, (tuple, list)):
additional_assets += assets
except:
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name))
render_kwargs.update(dict(forcelogin_theming=additional_assets))
return make_response(render_template("forcelogin_index.jinja2", **render_kwargs))
def get_ui_custom_tracked_files(self):
from os.path import join as opj
paths = [opj("static", "css", "forcelogin.css"),
opj("static", "js", "main.js"),
opj("static", "js", "viewmodel.js"),
opj("static", "less", "forcelogin.less"),
opj("templates", "parts", "forcelogin_css.jinja2"),
opj("templates", "parts", "forcelogin_javascripts.jinja2"),
opj("templates", "forcelogin_index.jinja2")]
return [opj(self._basefolder, path) for path in paths]
def get_ui_preemptive_caching_enabled(self):
return False
def get_before_request_handlers(self):
def check_login_required():
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return
elif not self._user_manager.enabled:
# ACL isn't enabled
return
if flask.request.endpoint in ("api.login",):
return
user = flask_login.current_user
if user is None or user.is_anonymous() or not user.is_active():
return flask.make_response("Forbidden", 403)
return [check_login_required]
def access_validator(self, request):
if self._user_manager.enabled and not self._user_manager.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
user = get_flask_user_from_request(request)
if user is None or not user.is_authenticated():
raise tornado.web.HTTPError(403)
def socket_register_validator(self, socket, user):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return True
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
if user is not None and not user.is_anonymous() and user.is_active():
return True
with self._message_backlog_mutex:
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
self._message_backlog[socket].append((message, payload))
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
else:
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
return False
__plugin_name__ = "Force Login"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Forces users to login, disables read-only mode."
__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your "
"OctoPrint instance. Only disable this if you are comfortable with this, your "
"OctoPrint instance is not publicly reachable on the internet and you fully "
"trust everyone who has access to your local network!")
__plugin_implementation__ = ForceLoginPlugin()
__plugin_hooks__ = {
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
}
@@ -0,0 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
@@ -0,0 +1,72 @@
/*
* Will get included into the login dialog, NOT into the regular OctoPrint
* web application.
*/
$(function() {
var overlayElement = $("#login-overlay");
var errorElement = $("#login-error");
var offlineElement = $("#login-offline");
var buttonElement = $("#login-button");
var reconnectElement = $("#login-reconnect");
buttonElement.click(function() {
var usernameElement = $("#login-user");
var passwordElement = $("#login-password");
var rememberElement = $("#login-remember");
var username = usernameElement.val();
var password = passwordElement.val();
var remember = rememberElement.checked;
overlayElement.addClass("in");
errorElement.removeClass("in");
OctoPrint.browser.login(username, password, remember)
.done(function() {
location.reload();
})
.fail(function() {
usernameElement.val("");
passwordElement.val("");
overlayElement.removeClass("in");
errorElement.addClass("in");
});
return false;
});
var OctoPrint = window.OctoPrint;
OctoPrint.options.baseurl = BASE_URL;
OctoPrint.socket.onMessage("connected", function(data) {
var payload = data.data;
OctoPrint.options.apikey = payload.apikey;
// update the API key directly in jquery's ajax options too,
// to ensure the fileupload plugin and any plugins still using
// $.ajax directly still work fine too
UI_API_KEY = payload["apikey"];
$.ajaxSetup({
headers: {"X-Api-Key": UI_API_KEY}
});
});
OctoPrint.socket.onConnected = function() {
buttonElement.prop("disabled", false);
offlineElement.removeClass("in");
};
OctoPrint.socket.onDisconnected = function() {
buttonElement.prop("disabled", true);
offlineElement.addClass("in");
};
reconnectElement.click(function() {
OctoPrint.socket.reconnect();
});
OctoPrint.socket.connect();
});
@@ -0,0 +1,17 @@
/*
* View model that takes care to redirect to / on logout in the regular
* OctoPrint web application.
*/
$(function() {
function ForceLoginViewModel(parameters) {
var self = this;
self.onUserLoggedOut = function() {
location.reload();
}
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([ForceLoginViewModel, [], []]);
});
@@ -0,0 +1,90 @@
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
.form-signin-heading, .checkbox {
margin-bottom: 10px;
}
input[type="text"], input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
}
#login-error,
#login-offline {
display: none;
&.in {
display: block;
}
}
#login-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
display: none;
&.in {
display: block;
}
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000000;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.wrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
.outer {
display: table;
width: 100%;
height: 100%;
.inner {
display: table-cell;
vertical-align: middle;
.content {
text-align: center;
color: white;
}
}
}
}
}
@@ -0,0 +1,39 @@
<html>
<head>
<title>OctoPrint Login</title>
{% include "parts/forcelogin_css.jinja2" %}
{% include "parts/forcelogin_javascripts.jinja2" %}
</head>
<body>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
<div id="login-error" class="alert alert-error">{{ _('Incorrect username or password.') }}</div>
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
<input type="text" id="login-user" class="input-block-level" placeholder="{{ _('Username') }}">
<input type="password" id="login-password" class="input-block-level" placeholder="{{ _('Password') }}">
<label class="checkbox">
<input type="checkbox" id="login-remember"> {{ _('Remember me') }}
</label>
<button class="btn btn-block btn-large btn-primary" id="login-button" type="submit">{{ _('Log in') }}</button>
</form>
</div>
<div id="login-overlay">
<div class="background"></div>
<div class="wrapper">
<div class="outer">
<div class="inner">
<div class="content">
<i class="fa fa-spinner fa-spin fa-4x"></i>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,10 @@
<!-- le CSS -->
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
<link rel="stylesheet" href="{{ url_for("plugin.forcelogin.static", filename="css/forcelogin.css") }}">
{% for url in forcelogin_theming %}
<link rel="stylesheet" href="{{ url }}">
{% endfor %}
@@ -0,0 +1,15 @@
<!-- le javascript -->
<script>
var BASE_URL = "{{ url_for('index') }}";
</script>
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
{% assets "js_client" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
<script src="{{ url_for("plugin.forcelogin.static", filename="js/main.js") }}"></script>
@@ -195,6 +195,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
def get_assets(self):
return dict(js=["js/logging.js"],
clientjs=["clientjs/logging.js"],
less=["less/logging.less"],
css=["css/logging.css"])
@@ -0,0 +1,68 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintLoggingClient = function(base) {
this.base = base;
this.baseUrl = this.base.getBlueprintUrl("logging");
this.logsUrl = this.baseUrl + "logs";
this.setupUrl = this.baseUrl + "setup";
};
OctoPrintLoggingClient.prototype.get = function(opts) {
return this.base.get(this.baseUrl, opts);
};
OctoPrintLoggingClient.prototype.listLogs = function(opts) {
return this.base.get(this.logsUrl, opts);
};
OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) {
var fileUrl = this.logsUrl + "/" + file;
return this.base.delete(fileUrl, opts);
};
OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) {
var fileUrl = this.logsUrl + "/" + file;
return this.base.download(fileUrl, opts);
};
OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) {
return this.base.putJson(this.setupUrl + "/levels", config, opts);
};
//~~ wrapper for backwards compatibility
var DeprecatedOctoPrintLogsClient = function(base) {
this.base = base;
this.wrapped = this.base.plugins.logging;
};
DeprecatedOctoPrintLogsClient.prototype.list = function(opts) {
log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead");
return this.wrapped.listLogs(opts);
};
DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) {
log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead");
return this.wrapped.deleteLog(file, opts);
};
DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) {
log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead");
return this.wrapped.downloadLog(file, opts);
};
// register plugin component
OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient);
// also register deprecated client under old endpoint
OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient);
return OctoPrintLoggingClient;
});
@@ -1,72 +1,3 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintLoggingClient = function(base) {
this.base = base;
this.baseUrl = this.base.getBlueprintUrl("logging");
this.logsUrl = this.baseUrl + "logs";
this.setupUrl = this.baseUrl + "setup";
};
OctoPrintLoggingClient.prototype.get = function(opts) {
return this.base.get(this.baseUrl, opts);
};
OctoPrintLoggingClient.prototype.listLogs = function(opts) {
return this.base.get(this.logsUrl, opts);
};
OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) {
var fileUrl = this.logsUrl + "/" + file;
return this.base.delete(fileUrl, opts);
};
OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) {
var fileUrl = this.logsUrl + "/" + file;
return this.base.download(fileUrl, opts);
};
OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) {
return this.base.putJson(this.setupUrl + "/levels", config, opts);
};
//~~ wrapper for backwards compatibility
var DeprecatedOctoPrintLogsClient = function(base) {
this.base = base;
this.wrapped = this.base.plugins.logging;
};
DeprecatedOctoPrintLogsClient.prototype.list = function(opts) {
log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead");
return this.wrapped.listLogs(opts);
};
DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) {
log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead");
return this.wrapped.deleteLog(file, opts);
};
DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) {
log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead");
return this.wrapped.downloadLog(file, opts);
};
// register plugin component
OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient);
// also register deprecated client under old endpoint
OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient);
return OctoPrintLoggingClient;
});
$(function() {
function LoggingViewModel(parameters) {
var self = this;
@@ -1,175 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import flask
import os
from flask_babel import gettext
import octoprint.plugin
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
_CPUINFO_PATH = "/proc/cpuinfo"
# based on https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F
_RPI_REVISION_MAP = {
"Beta": "1B (Beta)",
"0002": "1B",
"0003": "1B",
"0004": "1B",
"0005": "1B",
"0006": "1B",
"0007": "1A",
"0008": "1A",
"0009": "1A",
"000d": "1B",
"000e": "1B",
"000f": "1B",
"0010": "B+",
"0011": "CM1",
"0012": "A+",
"0013": "B+",
"0014": "CM1",
"0015": "A+",
"a01040": "2B",
"a01041": "2B",
"a21041": "2B",
"a22042": "2B",
"900021": "A+",
"900032": "B+",
"900092": "Zero",
"900093": "Zero",
"920093": "Zero",
"9000c1": "Zero W",
"a02082": "3B",
"a020a0": "CM3",
"a22082": "3B",
"a32082": "3B",
}
def get_octopi_version():
with open(_OCTOPI_VERSION_PATH, "r") as f:
version_line = f.readline()
return version_line.strip()
def get_pi_cpuinfo():
fields = dict(revision="Revision",
hardware="Hardware",
serial="Serial")
result = dict()
with open(_CPUINFO_PATH) as f:
for line in f:
if not line:
continue
for key, prefix in fields.items():
if line.startswith(prefix):
result[key] = line[line.index(":") + 1:].strip()
return result
def get_pi_model(hardware, revision):
if hardware not in ("BCM2835",):
return "unknown"
if revision.startswith("1000"):
# strip flag for over-volted (https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F)
revision = revision[4:]
return _RPI_REVISION_MAP.get(revision.lower(), "unknown")
class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin):
# noinspection PyMissingConstructor
def __init__(self):
self._version = None
self._cpuinfo = None
self._model = None
#~~ EnvironmentDetectionPlugin
def get_additional_environment(self):
return dict(version=self._get_version(),
revision=self._get_cpuinfo().get("revision", "unknown"),
model=self._get_model())
#~~ SimpleApiPlugin
def on_api_get(self, request):
return flask.jsonify(version=self._get_version())
#~~ AssetPlugin
def get_assets(self):
return dict(
js=["js/octopi_support.js"],
css=["css/octopi_support.css"]
)
#~~ TemplatePlugin
def get_template_configs(self):
return [
dict(type="about", name="About OctoPi", template="octopi_support_about.jinja2")
]
def get_template_vars(self):
return dict(version=self._get_version())
#~~ Helpers
def _get_version(self):
if self._version is None:
try:
self._version = get_octopi_version()
except:
self._logger.exception("Error while reading OctoPi version from file {}".format(_OCTOPI_VERSION_PATH))
self._version = "unknown"
return self._version
def _get_model(self):
if self._model is None:
try:
cpuinfo = self._get_cpuinfo()
self._model = get_pi_model(cpuinfo.get("hardware", "unknown"),
cpuinfo.get("revision", "unknown"))
except:
self._logger.exception("Error while detecting RPi model")
self._model = "unknown"
return self._model
def _get_cpuinfo(self):
if self._cpuinfo is None:
try:
self._cpuinfo = get_pi_cpuinfo()
except:
self._logger.exception("Error while fetching cpu info")
self._cpuinfo = dict()
return self._cpuinfo
__plugin_name__ = "OctoPi Support Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides additional information about your OctoPi instance in the UI."
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"provide additional information about your OctoPi instance,"
"which will make it more tricky to help you if you need support.")
__plugin_license__ = "AGPLv3"
def __plugin_check__():
from octoprint.util.platform import get_os
return get_os() == "linux" and os.path.exists(_OCTOPI_VERSION_PATH)
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = OctoPiSupportPlugin()
@@ -1,3 +0,0 @@
#octopi_support_footer {
white-space: nowrap;
}
@@ -1,50 +0,0 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintOctoPiSupportClient = function(base) {
this.base = base;
};
OctoPrintOctoPiSupportClient.prototype.get = function(opts) {
return this.base.get(this.base.getSimpleApiUrl("octopi_support"));
};
OctoPrintClient.registerPluginComponent("octopi_support", OctoPrintOctoPiSupportClient);
return OctoPrintOctoPiSupportClient;
});
$(function() {
function OctoPiSupportViewModel(parameters) {
var self = this;
self.requestData = function() {
OctoPrint.plugins.octopi_support.get()
.done(function(response) {
$("#octopi_support_footer").remove();
if (!response.version) return;
var octoPrintVersion = $(".footer span.version");
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
+ " <span class='octopi_version'>" + response.version + "</span></span>")
$(octoPiVersion).insertAfter(octoPrintVersion);
})
};
self.onStartup = function() {
self.requestData();
};
self.onServerReconnect = function() {
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push({
construct: OctoPiSupportViewModel
});
});
@@ -0,0 +1,320 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import flask
import os
import sarge
from flask_babel import gettext
from octoprint.util import RepeatedTimer
import octoprint.plugin
_PROC_DT_MODEL_PATH = "/proc/device-tree/model"
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled"
### uncomment for local debugging
#import sys
#base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
#_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
#_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
#_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
#import itertools
#_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70000"))
# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790
_FLAG_UNDERVOLTAGE = 1 << 0
_FLAG_FREQ_CAPPED = 1 << 1
_FLAG_THROTTLED = 1 << 2
_FLAG_PAST_UNDERVOLTAGE = 1 << 16
_FLAG_PAST_FREQ_CAPPED = 1 << 17
_FLAG_PAST_THROTTLED = 1 << 18
class ThrottleState(object):
@classmethod
def from_value(cls, value=0):
if value == 0:
return ThrottleState()
kwargs = dict(undervoltage=_FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
freq_capped=_FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED,
past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
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
self._past_undervoltage = False
self._past_freq_capped = False
self._past_throttled = False
for key, value in kwargs.items():
local_key = "_{}".format(key)
if hasattr(self, local_key) and isinstance(value, bool):
setattr(self, local_key, value)
@property
def undervoltage(self):
return self.current_undervoltage or self.past_undervoltage
@property
def current_undervoltage(self):
return self._undervoltage
@property
def past_undervoltage(self):
return self._past_undervoltage
@property
def overheat(self):
return self.current_overheat or self.past_overheat
@property
def current_overheat(self):
return self._freq_capped
@property
def past_overheat(self):
return self._past_freq_capped
@property
def issue(self):
return self.current_issue or self.past_issue
@property
def current_issue(self):
return self._undervoltage or self._freq_capped or self._throttled
@property
def past_issue(self):
return self._past_undervoltage or self._past_freq_capped or self._past_throttled
def __eq__(self, other):
if not isinstance(other, ThrottleState):
return False
return self._undervoltage == other._undervoltage \
and self._freq_capped == other._freq_capped \
and self._throttled == other._throttled \
and self._past_undervoltage == other._past_undervoltage \
and self._past_freq_capped == other._past_freq_capped \
and self._past_throttled == other._past_throttled
def as_dict(self):
return dict(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,
current_issue=self.current_issue,
past_issue=self.past_issue)
_proc_dt_model = None
def get_proc_dt_model():
global _proc_dt_model
if _proc_dt_model is None:
with open(_PROC_DT_MODEL_PATH, "r") as f:
_proc_dt_model = f.readline().strip(" \t\r\n\0")
return _proc_dt_model
def get_vcgencmd_throttled_state(command):
output = sarge.get_stdout(command)
#output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging
if not "throttled=0x" in output:
raise ValueError("cannot parse \"{}\" output: {}".format(command, output))
value = output[len("throttled="):].strip(" \t\r\n\0")
value = int(value, 0)
return ThrottleState.from_value(value)
def is_octopi():
return os.path.exists(_OCTOPI_VERSION_PATH)
_octopi_version = None
def get_octopi_version():
global _octopi_version
if _octopi_version is None:
with open(_OCTOPI_VERSION_PATH, "r") as f:
_octopi_version = f.readline().strip(" \t\r\n\0")
return _octopi_version
class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.SettingsPlugin):
# noinspection PyMissingConstructor
def __init__(self):
self._throttle_state = ThrottleState()
self._throttle_check = None
self._throttle_undervoltage = False
self._throttle_overheat = False
self._throttle_functional = True
#~~ EnvironmentDetectionPlugin
def get_additional_environment(self):
result = dict(model=get_proc_dt_model())
if is_octopi():
result.update(dict(octopi_version=get_octopi_version()))
return result
#~~ SimpleApiPlugin
def on_api_get(self, request):
result = dict(throttle_state=self._throttle_state.as_dict())
result.update(self.get_additional_environment())
return flask.jsonify(**result)
#~~ AssetPlugin
def get_assets(self):
return dict(
js=["js/pi_support.js"],
clientjs=["clientjs/pi_support.js"],
css=["css/pi_support.css"]
)
#~~ TemplatePlugin
def get_template_configs(self):
configs = [dict(type="settings", name=gettext("Pi Support"), template="pi_support_settings.jinja2", custom_bindings=False)]
if is_octopi():
configs.append(dict(type="about", name="About OctoPi", template="pi_support_about_octopi.jinja2"))
return configs
def get_template_vars(self):
return self.get_additional_environment()
#~~ StartupPlugin
def on_startup(self, *args, **kwargs):
if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]):
self._check_throttled_state()
self._throttle_check = RepeatedTimer(self._check_throttled_state_interval,
self._check_throttled_state,
condition=self._check_throttled_state_condition)
self._throttle_check.start()
#~~ SettingsPlugin
def get_settings_defaults(self):
return dict(vcgencmd_throttle_check_enabled=True,
vcgencmd_throttle_check_command=_VCGENCMD_THROTTLE)
def get_settings_restricted_paths(self):
return dict(admin=[["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]])
#~~ Helpers
def _check_throttled_state_interval(self):
if self._throttle_state.current_issue:
# check state every 30s if something's currently amiss
return 30
else:
# check state every 5min if nothing's currently amiss
return 300
def _check_throttled_state_condition(self):
return self._throttle_functional
def 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"])
self._logger.debug("Retrieving throttle state via \"{}\"".format(command))
try:
state = get_vcgencmd_throttled_state(command)
except:
self._logger.exception("Got an error while trying to fetch the current throttle state via \"{}\"".format(command))
self._throttle_functional = False
return
if self._throttle_state == state:
# no change
return
self._throttle_state = state
if (not self._throttle_undervoltage and self._throttle_state.undervoltage) \
or (not self._throttle_overheat and self._throttle_state.overheat):
message = "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " \
"by overheating or insufficient power."
if self._throttle_state.undervoltage:
self._throttle_undervoltage = True
message += "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " \
"capable of supplying enough voltage and current to your Pi."
if self._throttle_state.overheat:
self._throttle_overheat = True
message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \
"CPU and GPU."
self._logger.warn(message)
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
state=self._throttle_state.as_dict()))
self._event_bus.fire("plugin_pi_support_throttle_state", self._throttle_state.as_dict())
__plugin_name__ = "Pi Support Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides additional information about your Pi in the UI."
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"provide additional information about your Pi,"
"which will make it more tricky to help you if you need support.")
__plugin_license__ = "AGPLv3"
def __plugin_check__():
try:
proc_dt_model = get_proc_dt_model()
if proc_dt_model is None:
return False
except:
return False
return "raspberry pi" in proc_dt_model.lower()
def __plugin_load__():
plugin = PiSupportPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_helpers__
__plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state)
@@ -0,0 +1,19 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintPiSupportClient = function(base) {
this.base = base;
};
OctoPrintPiSupportClient.prototype.get = function(opts) {
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
};
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
return OctoPrintPiSupportClient;
});
@@ -0,0 +1,8 @@
#octopi_support_footer {
white-space: nowrap;
}
.pi_support_state_pulsate {
animation: pulsate 1s ease-out;
animation-iteration-count: infinite;
}
@@ -0,0 +1,94 @@
$(function() {
function PiSupportViewModel(parameters) {
var self = this;
self.model = ko.observable();
self.currentUndervoltage = ko.observable(false);
self.currentOverheat = ko.observable(false);
self.pastUndervoltage = ko.observable(false);
self.pastOverheat = ko.observable(false);
self.currentIssue = ko.observable(false);
self.pastIssue = ko.observable(false);
self.requestData = function() {
OctoPrint.plugins.pi_support.get()
.done(function(response) {
// Raspberry Pi model
self.model(response.model);
// Throttle state
self.fromThrottleState(response.throttle_state);
// OctoPi version
$("#octopi_support_footer").remove();
if (!response.octopi_version) return;
var octoPrintVersion = $(".footer span.version");
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>");
$(octoPiVersion).insertAfter(octoPrintVersion);
})
};
self.fromThrottleState = function(state) {
self.currentUndervoltage(state.current_undervoltage);
self.pastUndervoltage(state.past_undervoltage);
self.currentOverheat(state.current_overheat);
self.pastOverheat(state.past_overheat);
self.currentIssue(state.current_issue);
self.pastIssue(state.past_issue);
};
self.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();
};
self.onServerReconnect = function() {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin !== "pi_support") return;
if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return;
if (data.type !== "throttle_state") return;
self.fromThrottleState(data.state);
}
}
OCTOPRINT_VIEWMODELS.push({
construct: PiSupportViewModel,
elements: ["#navbar_plugin_pi_support"]
});
});
@@ -2,10 +2,10 @@
<h4>The ready-to-go Raspberry Pi image with OctoPrint</h4>
<p>Version <span class="plugin_octopi_support_version">{{ plugin_octopi_support_version }}</span></p>
<p>Version <span class="plugin_pi_support_octopi_version">{{ plugin_pi_support_octopi_version }}</span>, running on <span class="plugin_pi_support_model">{{ plugin_pi_support_model }}</span></p>
<ul>
<li>Website: <a href="https://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a> &amp; <a href="https://octopi.octoprint.org" target="_blank" rel="noreferrer noopener">octopi.octoprint.org</a></li>
<li>Website: <a href="https://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a></li>
<li>Source Code: <a href="https://github.com/guysoft/OctoPi" target="_blank" rel="noreferrer noopener">github.com/guysoft/OctoPi</a></li>
</ul>
@@ -0,0 +1,4 @@
<a href="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>
@@ -0,0 +1,31 @@
<h3>{{ _('Pi Support') }}</h3>
<p>{{ _('Please restart OctoPrint after changing any of this plugin\'s settings.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.pi_support.vcgencmd_throttle_check_enabled"> {{ _('Enable under voltage and overheat detection via <code>vcgencmd get_throttled</code>') }}
</label>
<span class="help-block">{{ _('This will regularly check with the Pi if something is amiss either with power regulation or CPU/GPU temperature.') }}</span>
</div>
</div>
<div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Command for under voltage/overheat detection') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.pi_support.vcgencmd_throttle_check_command">
<span class="help-block">{{ _('Defaults to <code>/usr/bin/vcgencmd get_throttled</code>. You usually shouldn\'t have to change this.') }}</span>
</div>
</div>
</form>
</div>
</div>
</form>
+51 -58
View File
@@ -15,7 +15,7 @@ from octoprint.server.util.flask import restricted_access, with_revalidation_che
from octoprint.server import admin_permission
from octoprint.util.pip import LocalPipCaller
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
from octoprint.util.platform import get_os
from octoprint.util.platform import get_os, is_os_compatible
from flask import jsonify, make_response
from flask_babel import gettext
@@ -33,6 +33,35 @@ import threading
_DATA_FORMAT_VERSION = "v2"
def map_repository_entry(entry):
result = copy.deepcopy(entry)
if not "follow_dependency_links" in result:
result["follow_dependency_links"] = False
result["is_compatible"] = dict(
octoprint=True,
os=True
)
if "compatibility" in entry:
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(
entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"])
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(
entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"])
return result
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
success_string = "Successfully installed"
failure_string = "Could not install"
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
@@ -111,7 +140,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._console_logger.propagate = False
# decouple repository fetching from server startup
self._fetch_all_data(async=True)
self._fetch_all_data(do_async=True)
##~~ SettingsPlugin
@@ -139,6 +168,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def get_assets(self):
return dict(
js=["js/pluginmanager.js"],
clientjs=["clientjs/pluginmanager.js"],
css=["css/pluginmanager.css"],
less=["less/pluginmanager.less"]
)
@@ -208,7 +238,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
from octoprint.events import Events
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
return
self._fetch_all_data(async=True)
self._fetch_all_data(do_async=True)
##~~ SimpleApiPlugin
@@ -340,10 +370,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
all_plugins_before = self._plugin_manager.find_plugins(existing=dict())
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
success_string = "Successfully installed"
failure_string = "Could not install"
try:
returncode, stdout, stderr = self._call_pip(pip_args)
@@ -459,6 +485,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._plugin_manager.log_all_plugins()
self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version))
self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key,
version=new_plugin.version,
source=source,
source_type=source_type))
result = dict(result=True,
source=source,
source_type=source_type,
@@ -549,6 +580,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._plugin_manager.reload_plugins()
self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key,
version=plugin.version))
result = dict(result=True,
needs_restart=needs_restart,
needs_refresh=needs_refresh,
@@ -667,7 +701,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if strip:
lines = map(lambda x: x.strip(), lines)
self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines]))
self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines",
loglines=[dict(line=line, stream=stream) for line in lines]))
for line in lines:
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
@@ -688,6 +723,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
elif not plugin.enabled and plugin.key not in self._pending_enable:
self._pending_enable.add(plugin.key)
self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key,
version=plugin.version))
def _mark_plugin_disabled(self, plugin, needs_restart=False):
disabled_list = list(self._settings.global_get(["plugins", "_disabled"],
validator=lambda x: isinstance(x, list),
@@ -705,12 +743,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key)
def _fetch_all_data(self, async=False):
self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key,
version=plugin.version))
def _fetch_all_data(self, do_async=False):
def run():
self._repository_available = self._fetch_repository_from_disk()
self._notices_available = self._fetch_notices_from_disk()
if async:
if do_async:
thread = threading.Thread(target=run)
thread.daemon = True
thread.start()
@@ -764,30 +805,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if repo_data is None:
return False
current_os = get_os()
octoprint_version = get_octoprint_version(base=True)
def map_repository_entry(entry):
result = copy.deepcopy(entry)
if not "follow_dependency_links" in result:
result["follow_dependency_links"] = False
result["is_compatible"] = dict(
octoprint=True,
os=True
)
if "compatibility" in entry:
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"],
octoprint_version=octoprint_version)
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
return result
self._repository_plugins = map(map_repository_entry, repo_data)
return True
@@ -859,30 +876,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._notices = notices
return True
@staticmethod
def _is_os_compatible(current_os, compatibility_entries):
"""
Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries``
"""
if len(compatibility_entries) == 0:
# shortcut - no compatibility info means we are compatible
return True
negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries))
positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries)
negative_match = False
if negative_entries:
# check if we are blacklisted
negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries))
positive_match = True
if positive_entries:
# check if we are whitelisted
positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries))
return positive_match and not negative_match
@property
def _reconnect_hooks(self):
reconnect_hooks = self.__class__.RECONNECT_HOOKS
@@ -0,0 +1,82 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintPluginManagerClient = function(base) {
this.base = base;
};
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
var refresh_repo, refresh_notices;
if (_.isPlainObject(refresh)) {
refresh_repo = refresh.repo || false;
refresh_notices = refresh.notices || false;
} else {
refresh_repo = refresh;
refresh_notices = false;
}
var query = [];
if (refresh_repo) query.push("refresh_repository=true");
if (refresh_notices) query.push("refresh_notices=true");
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
};
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
return this.get(true, opts);
};
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) {
return this.get(false, opts);
};
OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks
};
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks,
reinstall: plugin,
force: true
};
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
};
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
};
OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
};
OctoPrintPluginManagerClient.prototype.upload = function(file) {
return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
};
OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
return OctoPrintPluginManagerClient;
});
@@ -1,86 +1,3 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintPluginManagerClient = function(base) {
this.base = base;
};
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
var refresh_repo, refresh_notices;
if (_.isPlainObject(refresh)) {
refresh_repo = refresh.repo || false;
refresh_notices = refresh.notices || false;
} else {
refresh_repo = refresh;
refresh_notices = false;
}
var query = [];
if (refresh_repo) query.push("refresh_repository=true");
if (refresh_notices) query.push("refresh_notices=true");
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
};
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
return this.get(true, opts);
};
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) {
return this.get(false, opts);
};
OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks
};
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks,
reinstall: plugin,
force: true
};
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
};
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
};
OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
};
OctoPrintPluginManagerClient.prototype.upload = function(file) {
return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
};
OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
return OctoPrintPluginManagerClient;
});
$(function() {
function PluginManagerViewModel(parameters) {
var self = this;
@@ -36,9 +36,19 @@ ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower()
CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower()
CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower()
# Creality Ender 3
ENDER3_AUTHOR = " | Author: (Ender3)".lower()
ENDER3_RECEIVED_TEST = lambda line: line and ENDER3_AUTHOR in line.lower()
# iMe on Micro3D
IME_M115_TEST = lambda name, data: name and name.lower().startswith("ime")
# Malyan M200 aka Monoprice Select Mini
MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200"
# Stock Micro3D
MICRO3D_M115_TEST = lambda name, data: name and name.lower().startswith("micro3d")
# Any Repetier versions < 0.92
REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92")
@@ -46,11 +56,12 @@ REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startsw
THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled
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",))
@@ -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);
};
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import octoprint.plugin
import copy
import flask
import os
import threading
@@ -26,9 +27,16 @@ from flask_babel import gettext
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
from octoprint.util import dict_merge, to_unicode
from octoprint.util.version import get_comparable_version
from octoprint.util.pip import LocalPipCaller
import octoprint.settings
MINIMUM_PYTHON = "2.7.9"
MINIMUM_SETUPTOOLS = "5.5.1"
MINIMUM_PIP = "9.0.1"
##~~ Plugin
@@ -42,7 +50,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
DATA_FORMAT_VERSION = "v3"
DATA_FORMAT_VERSION = "v4"
# noinspection PyMissingConstructor
def __init__(self):
@@ -61,6 +69,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache_dirty = False
self._version_cache_timestamp = None
self._environment_supported = True
self._environment_versions = dict()
self._environment_ready = threading.Event()
self._console_logger = None
def initialize(self):
@@ -87,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:
@@ -104,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():
@@ -164,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
@@ -482,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)
@@ -513,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))
@@ -535,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)
@@ -559,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"]
)
@@ -645,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="?",
@@ -778,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()
@@ -897,6 +941,20 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# determine the target version to update to
target_version = information["remote"]["value"]
target_error = False
target_result = None
def trigger_event(success, **additional_payload):
if success:
event = "update_succeeded"
else:
event = "update_failed"
payload = copy.copy(additional_payload)
payload.update(dict(target=target,
from_version=information["local"]["value"],
to_version=target_version))
self._event_bus.fire("plugin_softwareupdate_{}".format(event), payload=payload)
### The actual update procedure starts here...
@@ -911,6 +969,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online)
target_result = ("success", update_result)
self._logger.info("Update of %s to %s successful!" % (target, target_version))
trigger_event(True)
except exceptions.UnknownUpdateType:
self._logger.warn("Update of %s can not be performed, unknown update type" % target)
@@ -923,6 +982,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
except Exception as e:
self._logger.exception("Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this" % target)
trigger_event(False)
if not "ignorable" in populated_check or not populated_check["ignorable"]:
target_error = True
@@ -960,7 +1021,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._logger.info("Restarting...")
try:
util.execute(restart_command, evaluate_returncode=False, async=True)
util.execute(restart_command, evaluate_returncode=False, do_async=True)
except exceptions.ScriptError as e:
self._logger.exception("Error while restarting via command {}".format(restart_command))
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
+6 -5
View File
@@ -124,7 +124,8 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
if targets:
data["check"] = targets
client = create_client(apikey=apikey,
client = create_client(settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
@@ -149,7 +150,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
plugin_message_data = plugin_message["data"]
if plugin_message_type == "updating":
click.echo("Updating {} to {}...".format(plugin_message_data["name"], plugin_message_data["target"]))
click.echo("Updating {} to {}...".format(plugin_message_data.get("name", "unknown"), plugin_message_data.get("version", "n/a")))
elif plugin_message_type == "update_failed":
click.echo("\t... failed :(")
@@ -191,9 +192,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
flags["seen_close"] = True
click.echo("Disconnected from server...")
socket = client.connect_socket(on_message=on_message,
on_open=on_open,
on_close=on_close)
socket = client.create_socket(on_message=on_message,
on_open=on_open,
on_close=on_close)
r = client.post_json("plugin/softwareupdate/update", data=data)
try:
@@ -59,7 +59,9 @@ def _execute(command, **kwargs):
joined_command = command
_log_call(joined_command)
kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
kwargs.update(dict(async_=True,
stdout=sarge.Capture(),
stderr=sarge.Capture()))
try:
p = sarge.run(command, **kwargs)
@@ -0,0 +1,84 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintSoftwareUpdateClient = function(base) {
this.base = base;
var url = this.base.getBlueprintUrl("softwareupdate");
this.checkUrl = url + "check";
this.updateUrl = url + "update";
};
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
force = params.force;
opts = params.opts;
}
entries = entries || [];
if (typeof entries == "string") {
entries = [entries];
}
var data = {};
if (!!force) {
data.force = true;
}
if (entries && entries.length) {
data.check = entries.join(",");
}
return this.base.getWithQuery(this.checkUrl, data, opts);
};
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
}
return this.checkEntries({entries: [], force: force, opts: opts});
};
OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
targets = params.targets;
force = params.force;
opts = params.opts;
}
targets = targets || [];
if (typeof targets === "string") {
targets = [targets];
}
var data = {
targets: targets,
force: !!force
};
return this.base.postJson(this.updateUrl, data, opts);
};
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
}
var data = {
force: !!force
};
return this.base.postJson(this.updateUrl, data, opts);
};
OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient);
return OctoPrintSoftwareUpdateClient;
});
@@ -1,88 +1,3 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintSoftwareUpdateClient = function(base) {
this.base = base;
var url = this.base.getBlueprintUrl("softwareupdate");
this.checkUrl = url + "check";
this.updateUrl = url + "update";
};
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
force = params.force;
opts = params.opts;
}
entries = entries || [];
if (typeof entries == "string") {
entries = [entries];
}
var data = {};
if (!!force) {
data.force = true;
}
if (entries && entries.length) {
data.check = entries.join(",");
}
return this.base.getWithQuery(this.checkUrl, data, opts);
};
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
}
return this.checkEntries({entries: [], force: force, opts: opts});
};
OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
targets = params.targets;
force = params.force;
opts = params.opts;
}
targets = targets || [];
if (typeof targets === "string") {
targets = [targets];
}
var data = {
targets: targets,
force: !!force
};
return this.base.postJson(this.updateUrl, data, opts);
};
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
}
var data = {
force: !!force
};
return this.base.postJson(this.updateUrl, data, opts);
};
OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient);
return OctoPrintSoftwareUpdateClient;
});
$(function() {
function SoftwareUpdateViewModel(parameters) {
var self = this;
@@ -116,6 +31,9 @@ $(function() {
&& !self.octoprintReleasedVersion();
});
self.environmentSupported = ko.observable(true);
self.environmentVersions = ko.observableArray([]);
self.cacheTimestamp = ko.observable();
self.cacheTimestampText = ko.pureComputed(function() {
return formatDate(self.cacheTimestamp());
@@ -132,6 +50,10 @@ $(function() {
&& (!self.config_checkoutFolder() || self.config_checkoutFolder().trim() === '');
});
self.enableUpdate = ko.pureComputed(function() {
return !self.updateInProgress && self.environmentSupported();
});
self.enable_configSave = ko.pureComputed(function() {
return self.config_checkType() === "github_release"
|| (self.config_checkType() === "git_commit" && !self.error_checkoutFolder());
@@ -300,6 +222,9 @@ $(function() {
var octoprint = data.information["octoprint"];
self.octoprintReleasedVersion(!octoprint || octoprint.released_version);
self.environmentSupported(data.environment.supported);
self.environmentVersions(data.environment.versions);
if (data.status === "inProgress") {
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
return;
@@ -314,7 +239,7 @@ $(function() {
_.each(self.versions.items(), function(update_info) {
if (update_info.updateAvailable) {
text += "<li>"
+ "<i class='fa fa-li " + (update_info.updatePossible ? "fa-check" : "fa-remove")+ "'></i>"
+ "<i class='fa fa-li " + (update_info.updatePossible && self.environmentSupported() ? "fa-check" : "fa-remove")+ "'></i>"
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
+ "</li>";
@@ -322,7 +247,11 @@ $(function() {
});
text += "</ul>";
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
if (!self.environmentSupported()) {
text += "<p><small>" + gettext("This version of the Python environment is not supported for direct updates.") + "</small></p>";
} else {
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
}
if (!self.loginState.isAdmin()) {
text += "<p><small>" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "</small></p>";
@@ -15,6 +15,23 @@
<a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
</p>
{% endtrans %}</div>
<div class="alert" data-bind="visible: !environmentSupported()">{% trans %}
<p>
<strong>This version of the Python environment is not supported for direct updates.</strong>
</p>
<p>
To reduce the likelihood of running into update problems in outdated environments, the following minimal
versions are required to use this updater to update OctoPrint or any installed plugins:
</p>
{% endtrans %}
<ul data-bind="foreach: environmentVersions">
<li><span data-bind="text: name"></span>: <span data-bind="text: minimum"></span> ({{ _('you have') }}: <span data-bind="text: current"></span>)</li>
</ul>
{% trans %}
<p>
Please take a look at <a href="https://faq.octoprint.org/unsupported-python-environment" target="_blank">this FAQ entry on how to proceed</a>.
</p>
{% endtrans %}</div>
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
@@ -29,7 +46,7 @@
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: updateAvailable" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
<small class="muted">
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
@@ -59,7 +76,7 @@
</ul>
</div>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.update(); }, enable: !updateInProgress, css: {disabled: updateInProgress}"><i class="fa fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.update(); }, enable: enableUpdate, css: {disabled: !enableUpdate}"><i class="fa fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
<div>
@@ -10,6 +10,7 @@ import logging
import pkg_resources
from octoprint.util.pip import PipCaller, UnknownPip
from octoprint.util.version import get_comparable_version
from .. import exceptions
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
@@ -23,8 +24,13 @@ _pip_callers = dict()
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
def can_perform_update(target, check, online=True):
from .. import MINIMUM_PIP
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
return "pip" in check and pip_caller is not None and pip_caller.available and (online or check.get("offline", False))
return "pip" in check \
and pip_caller is not None \
and pip_caller.available \
and pip_caller.version >= get_comparable_version(MINIMUM_PIP) \
and (online or check.get("offline", False))
def _get_pip_caller(command=None):
key = command
+4 -2
View File
@@ -9,12 +9,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .exceptions import ScriptError
def execute(command, cwd=None, evaluate_returncode=True, async=False):
def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
do_async = kwargs.get("do_async", kwargs.get("async", False))
import sarge
p = None
try:
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async=async)
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=do_async)
except:
returncode = p.returncode if p is not None else None
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
+322
View File
@@ -0,0 +1,322 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from flask_babel import gettext
import requests
import hashlib
import logging
try:
# noinspection PyCompatibility
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
# noinspection PyCompatibility
import concurrent.futures
from octoprint.util import RepeatedTimer
from octoprint.util.version import get_octoprint_version_string
from octoprint.events import Events
TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/"
# noinspection PyMissingConstructor
class TrackingPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.ShutdownPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin):
def __init__(self):
self._environment = None
self._throttle_state = None
self._helpers_get_throttle_state = None
self._printer_connection_parameters = None
self._url = None
self._ping_worker = None
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self._record_next_firmware_info = False
def initialize(self):
self._init_tracking()
##~~ SettingsPlugin
def get_settings_defaults(self):
return dict(enabled=None,
unique_id=None,
server=TRACKING_URL,
ping=15*60,
events=dict(startup=True,
printjob=True,
plugin=True,
update=True,
printer=True,
throttled=True))
def get_settings_restricted_paths(self):
return dict(admin=[["enabled"], ["unique_id"], ["events"]],
never=[["server"], ["ping"]])
def on_settings_save(self, data):
enabled = self._settings.get([b"enabled"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
if enabled is None and self._settings.get([b"enabled"]):
# tracking was just enabled, let's init it and send a startup event
self._init_tracking()
self._track_startup()
##~~ EnvironmentDetectionPlugin
def on_environment_detected(self, environment, *args, **kwargs):
self._environment = environment
##~~ StartupPlugin
def on_after_startup(self):
ping = self._settings.get_int(["ping"])
if ping:
self._ping_worker = RepeatedTimer(ping, self._track_ping)
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):
self._track_shutdown()
##~~ EventHandlerPlugin
def on_event(self, event, payload):
if event.startswith("plugin_pluginmanager_"):
self._track_plugin_event(event, payload)
elif event.startswith("plugin_softwareupdate_"):
self._track_update_event(event, payload)
elif event in ("plugin_pi_support_throttle_state",):
self._throttle_state = payload
self._track_throttle_event(event, payload)
elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
self._track_printjob_event(event, payload)
elif event in (Events.CONNECTED,):
self._printer_connection_parameters = dict(port=payload["port"],
baudrate=payload["baudrate"])
self._record_next_firmware_info = True
elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info:
self._record_next_firmware_info = False
self._track_printer_event(event, payload)
##~~ TemplatePlugin
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Anonymous Usage Tracking"), template="tracking_settings.jinja2", custom_bindings=False),
dict(type="wizard", name=gettext("Anonymous Usage Tracking"), template="tracking_wizard.jinja2", custom_bindings=True, mandatory=True)
]
##~~ AssetPlugin
def get_assets(self):
return dict(js=["js/usage.js"])
##~~ WizardPlugin
def is_wizard_required(self):
return self._settings.get([b"enabled"]) is None
##~~ helpers
def _init_tracking(self):
if not self._settings.get_boolean([b"enabled"]):
return
self._init_id()
self._logger.info("Initialized anonymous tracking")
def _init_id(self):
if self._settings.get_boolean([b"enabled"]) and not self._settings.get([b"unique_id"]):
import uuid
self._settings.set([b"unique_id"], str(uuid.uuid4()))
self._settings.save()
def _track_ping(self):
self._track("ping")
def _track_startup(self):
if not self._settings.get_boolean(["events", "startup"]):
return
payload = dict(version=get_octoprint_version_string(),
os=self._environment[b"os"][b"id"],
python=self._environment[b"python"][b"version"],
pip=self._environment[b"python"][b"pip"],
cores=self._environment[b"hardware"][b"cores"],
freq=self._environment[b"hardware"][b"freq"],
ram=self._environment[b"hardware"][b"ram"])
if b"plugins" in self._environment and b"pi_support" in self._environment[b"plugins"]:
payload[b"pi_model"] = self._environment[b"plugins"][b"pi_support"][b"model"]
if b"octopi_version" in self._environment[b"plugins"][b"pi_support"]:
payload[b"octopi_version"] = self._environment[b"plugins"][b"pi_support"][b"octopi_version"]
self._track("startup", **payload)
def _track_shutdown(self):
if not self._settings.get_boolean(["events", "startup"]):
return
self._track("shutdown")
def _track_plugin_event(self, event, payload):
if not self._settings.get_boolean(["events", "plugin"]):
return
if event.endswith("_installplugin"):
self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_uninstallplugin"):
self._track("uninstall_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_enableplugin"):
self._track("enable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_disableplugin"):
self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
def _track_update_event(self, event, payload):
if not self._settings.get_boolean(["events", "update"]):
return
if event.endswith("_update_succeeded"):
self._track("update_successful", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
elif event.endswith("_update_failed"):
self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
def _track_throttle_event(self, event, payload):
if not self._settings.get_boolean(["events", "throttled"]):
return
args = dict(throttled_now=payload[b"current_issue"],
throttled_past=payload[b"past_issue"],
throttled_mask=payload[b"raw_value"],
throttled_voltage_now=payload[b"current_undervoltage"],
throttled_voltage_past=payload[b"past_undervoltage"],
throttled_overheat_now=payload[b"current_overheat"],
throttled_overheat_past=payload[b"past_overheat"])
if payload[b"current_issue"]:
track_event = "system_throttled"
else:
track_event = "system_unthrottled"
if track_event is not None:
self._track(track_event, **args)
def _track_printjob_event(self, event, payload):
if not self._settings.get_boolean(["events", "printjob"]):
return
sha = hashlib.sha1()
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())
if event == Events.PRINT_STARTED:
track_event = "print_started"
elif event == Events.PRINT_DONE:
try:
elapsed = int(payload.get(b"time"))
except ValueError:
elapsed = "unknown"
args[b"elapsed"] = elapsed
track_event = "print_done"
elif event == Events.PRINT_FAILED:
try:
elapsed = int(payload.get(b"time"))
except ValueError:
elapsed = "unknown"
args[b"elapsed"] = elapsed
args[b"reason"] = payload.get(b"reason", "unknown")
track_event = "print_failed"
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(["events", "printer"]):
return
if event in (Events.FIRMWARE_DATA,):
args = dict(firmware_name=payload["name"])
if self._printer_connection_parameters:
args["printer_port"] = self._printer_connection_parameters["port"]
args["printer_baudrate"] = self._printer_connection_parameters["baudrate"]
self._track("printer_connected", **args)
def _track(self, event, **kwargs):
if not self._settings.get_boolean([b"enabled"]):
return
self._executor.submit(self._do_track, event, **kwargs)
def _do_track(self, event, **kwargs):
if not self._connectivity_checker.online:
return
server = self._settings.get([b"server"])
url = server.format(id=self._settings.get([b"unique_id"]), event=event)
# 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.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))
else:
pass
__plugin_name__ = "Anonymous Usage Tracking"
__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked"
__plugin_url__ = "https://tracking.octoprint.org"
__plugin_author__ = "Gina Häußge"
__plugin_implementation__ = TrackingPlugin()
@@ -0,0 +1,101 @@
$(function() {
function UsageViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
self.setup = ko.observable(false);
self.decision = ko.observable();
self.active = ko.observable();
self.required = false;
self.enableUsage = function() {
self.settingsViewModel.settings.plugins.tracking.enabled(true);
self.decision(true);
self._sendData();
};
self.disableUsage = function() {
self.settingsViewModel.settings.plugins.tracking.enabled(false);
self.decision(false);
self._sendData();
};
self.onBeforeWizardTabChange = function(next, current) {
if (!self.required) return true;
if (!current || !_.startsWith(current, "wizard_plugin_tracking") || self.setup()) {
return true;
}
self._showDecisionNeededDialog();
return false;
};
self.onBeforeWizardFinish = function() {
if (!self.required) return true;
if (self.setup()) {
return true;
}
self._showDecisionNeededDialog();
return false;
};
self.onWizardPreventSettingsRefreshDialog = function() {
return self.active();
};
self.onWizardDetails = function(response) {
self.required = response && response.tracking && response.tracking.required;
};
self._showDecisionNeededDialog = function() {
showMessageDialog({
title: gettext("Please set up anonymous usage tracking"),
message: gettext("You haven't yet decided on whether to enable or disable anonymous usage tracking. You need to either enable or disable it before continuing.")
});
};
self._sendData = function() {
var data = {
plugins: {
tracking: {
enabled: self.settingsViewModel.settings.plugins.tracking.enabled()
}
}
};
self.active(true);
self.settingsViewModel.saveData(data)
.done(function() {
self.setup(true);
self.active(false);
})
.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([
UsageViewModel,
["settingsViewModel"],
"#wizard_plugin_tracking"
]);
});
@@ -0,0 +1,10 @@
{% trans %}
<p>
Anonymous usage tracking provides valuable insights into how many instances running what versions of OctoPrint are out there,
whether they are successfully completing print jobs and various other metrics.
</p>
<p>
By enabling it you help to identify problems with new releases and release candidates early on, and to better
tailor OctoPrint's future development to actual use.
</p>
{% endtrans %}
@@ -0,0 +1,4 @@
<p>{% trans %}
For details on what gets tracked, please refer to <a href="https://tracking.octoprint.org" target="_blank" rel="noopener noreferrer">tracking.octoprint.org</a>
and also the <a href="https://tracking.octoprint.org/privacy" target="_blank" rel="noopener noreferrer">Privacy Policy at tracking.octoprint.org</a>.
{% endtrans %}</p>
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more