Merge branch 'maintenance' into devel
# Conflicts: # AUTHORS.md # src/octoprint/plugins/pluginmanager/__init__.py # src/octoprint/plugins/softwareupdate/__init__.py # src/octoprint/server/__init__.py # src/octoprint/server/api/__init__.py # src/octoprint/server/util/flask.py # src/octoprint/server/util/sockjs.py # src/octoprint/server/util/tornado.py # src/octoprint/static/js/app/client/base.js # src/octoprint/users.py
No files matched your search
@@ -93,7 +93,9 @@ date of first contribution):
|
||||
* [Sven Lohrmann](https://github.com/malnvenshorn)
|
||||
* [Andy Castille](https://github.com/klikini)
|
||||
* [Zachary Nofzinger](https://github.com/ZachNo)
|
||||
* [Gaston Dombiak](https://github.com/gdombiak)
|
||||
* [Brad Fisher](https://github.com/bradcfisher)
|
||||
* [Aldo Hoeben](https://github.com/fieldofview)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
@@ -27,7 +27,7 @@ to **address problems in a timely manner** but also keep it possible for them
|
||||
to **fix bugs, add new and improve on existing functionality** instead of doing
|
||||
nothing but ticket management.
|
||||
|
||||

|
||||

|
||||
|
||||
- **[Read the FAQ](https://faq.octoprint.org)**
|
||||
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
|
||||
@@ -39,11 +39,11 @@ nothing but ticket management.
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
|
||||
such support issues.
|
||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
||||
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
|
||||
`[Brainstorming] New plugin hook for doing some cool stuff`).
|
||||
changes to the plugin system, please get in touch on the
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
|
||||
- If you need **support**, have a **question** or some **other reason** that
|
||||
doesn't fit any of the above categories, the issue tracker is not the right place.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
|
||||
|
||||
No matter what kind of ticket you create, never mix two or more "ticket reasons"
|
||||
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
@@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
> A bot is in place that monitors new tickets, automatically
|
||||
> categorizes them and checks new bug reports for usage of the provided template.
|
||||
> That bot will only bother you if you open a ticket that appears to be a bug (no
|
||||
> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
|
||||
> `[Request]` in the title) without the complete template, and it
|
||||
> will do that only to ensure that all information needed to solve the issue is
|
||||
> available for the maintainers to directly start tackling that problem.
|
||||
|
||||
@@ -301,7 +301,8 @@ the documentation.
|
||||
the discussion going on how best to solve *this* in OctoPrint's plugin
|
||||
system - maybe that's the actual PR you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large or otherwise disruptive changes to the
|
||||
code or appearance, please open a "Brainstorming" ticket first** so
|
||||
code or appearance, please get in touch on the
|
||||
[forums](https://discourse.octoprint.org/c/development)** first so
|
||||
that we can determine if it's a good time for your specific pull
|
||||
request. It might be that we're currently in the process of making
|
||||
heavy changes to the code locations you'd target as well, or your
|
||||
@@ -311,7 +312,8 @@ the documentation.
|
||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
||||
`dev/myNewFeature`)[1].
|
||||
4. Create your pull request **only against the `maintenance` or `devel` branch**:
|
||||
* if it's a bug fix for a bug in the current stable version: `maintenance` branch
|
||||
* if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
|
||||
*small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
|
||||
* otherwise: `devel` branch
|
||||
5. Create **one pull request per feature/bug fix**.
|
||||
6. Make sure there are **only relevant changes** included in your PR. No
|
||||
@@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 2017-11-22: Added note on how to run the unit tests
|
||||
* 2018-03-15: Link to new community forum and some clarifications re bug
|
||||
reporting
|
||||
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
|
||||
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
|
||||
* 2018-10-18: Allow PRs against `maintenance` branch for improvements and small
|
||||
new features, suggest getting in touch on the forum for larger changes
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
@@ -12,8 +12,11 @@ Authorization
|
||||
=============
|
||||
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one, a user specific one if "Access Control" is enabled or an :ref:`App Session Key <sec-api-apps-sessionkey>`.
|
||||
Users are able to generate and revoke their custom API key via the "Change password" dialog.
|
||||
configured one, a user specific one if "Access Control" is enabled or an app and user specific one as generated
|
||||
by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
|
||||
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
|
||||
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
|
||||
|
||||
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
|
||||
@@ -23,7 +26,7 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`.
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`.
|
||||
|
||||
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||
|
||||
@@ -120,3 +123,94 @@ If CORS is not enabled you will get errors like the following::
|
||||
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
|
||||
header is present on the requested resource.
|
||||
|
||||
.. _sec-api-general-login:
|
||||
|
||||
Login
|
||||
=====
|
||||
|
||||
.. http:post:: /api/login
|
||||
|
||||
Creates a login session or retrieves information about the currently existing session ("passive login").
|
||||
|
||||
Can be used in one of two ways: to login a user via username and password and create a persistent session (usually
|
||||
from a UI in the browser), or to retrieve information about the active user (from an existing session or an API key)
|
||||
via the ``passive`` flag.
|
||||
|
||||
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
|
||||
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
|
||||
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
|
||||
|
||||
:json passive: If present, performs a passive login only, returning information about the current user that's
|
||||
active either through an existing session or the used API key
|
||||
:json user: (active login only) Username
|
||||
:json pass: (active login only) Password
|
||||
:json remember: (active login only) Whether to set a "remember me" cookie on the session
|
||||
:status 200: Successful login
|
||||
:status 401: Username/password mismatch or unknown user
|
||||
:status 403: Deactivated account
|
||||
|
||||
.. _sec-api-general-logout:
|
||||
|
||||
Logout
|
||||
======
|
||||
|
||||
.. http:post:: /api/logout
|
||||
|
||||
Ends the current login session of the current user.
|
||||
|
||||
Only makes sense in the context of browser based workflows.
|
||||
|
||||
Will return a :http:statuscode:`204`.
|
||||
|
||||
:status 204: No error
|
||||
|
||||
.. _sec-api-general-datamodel:
|
||||
|
||||
Data model
|
||||
==========
|
||||
|
||||
.. _sec-api-general-datamodel-login:
|
||||
|
||||
Login response
|
||||
--------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- the user's name/id
|
||||
* - ``active``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user's account is active or not
|
||||
* - ``admin``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has admin rights or not
|
||||
* - ``user``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the user has user rights or not (always ``true``)
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- string or None
|
||||
- The user's API key, if set
|
||||
* - ``settings``
|
||||
- 1
|
||||
- dict
|
||||
- The user's settings, if any
|
||||
* - ``session``
|
||||
- 1
|
||||
- string
|
||||
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
|
||||
* - ``_is_external_client``
|
||||
- 1
|
||||
- boolean
|
||||
- Whether the client that made the request got detected as external from the local network or not.
|
||||
@@ -219,7 +219,7 @@ Issue a print head command
|
||||
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
|
||||
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
|
||||
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
|
||||
interpreted as an integer signifying the speed in mm/s, to append to the command.
|
||||
interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
home
|
||||
Homes the print head in all of the given axes. Additional parameters are:
|
||||
@@ -362,6 +362,8 @@ Issue a tool command
|
||||
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
|
||||
|
||||
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
|
||||
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
|
||||
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command.
|
||||
|
||||
flowrate
|
||||
Changes the flow rate factor to apply to extrusion of the tool.
|
||||
|
||||
@@ -47,23 +47,41 @@ Clients must ignore any unknown messages.
|
||||
|
||||
The data model of the attached payloads is described further below.
|
||||
|
||||
OctoPrint's SockJS socket also accepts one command from the client to the server,
|
||||
the ``throttle`` command. Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
OctoPrint's SockJS socket also accepts two commands from the client to the server.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
|
||||
existing user session with the socket. That is of special importance to receive
|
||||
any kind of messages if the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` is enabled
|
||||
(as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated
|
||||
clients.
|
||||
|
||||
.. sourcecode:: javascript
|
||||
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
|
||||
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
Example for a ``auth`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"auth": "someuser:LGZ0trf8By"
|
||||
}
|
||||
|
||||
* ``throttle``: Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
|
||||
.. _sec-api-push-datamodel:
|
||||
|
||||
|
||||
@@ -396,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
-
|
||||
* - ``feature.sdSupport``
|
||||
-
|
||||
* - ``feature.sdReleativePath``
|
||||
* - ``feature.sdRelativePath``
|
||||
-
|
||||
* - ``feature.sdAlwaysAvailable``
|
||||
-
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
.. _sec-bundledplugins-announcements:
|
||||
|
||||
Announcement Plugin
|
||||
===================
|
||||
|
||||
The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11).
|
||||
|
||||
It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new
|
||||
plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels
|
||||
via RSS or Atom feed URLs.
|
||||
|
||||
.. _fig-bundledplugins-announcements-example1:
|
||||
.. figure:: ../images/bundledplugins-announcements-example1.png
|
||||
:align: center
|
||||
:alt: Example notification
|
||||
|
||||
An example notification from the Announcement Plugin.
|
||||
|
||||
.. _fig-bundledplugins-announcements-example2:
|
||||
.. figure:: ../images/bundledplugins-announcements-example2.png
|
||||
:align: center
|
||||
:alt: Announcement reader
|
||||
|
||||
The Announcement Plugin's reader dialog.
|
||||
|
||||
.. _fig-bundledplugins-announcements-settings:
|
||||
.. figure:: ../images/bundledplugins-announcements-settings.png
|
||||
:align: center
|
||||
:alt: Announcement settings
|
||||
|
||||
The Announcement Plugin's settings dialog.
|
||||
|
||||
.. _sec-bundledplugins-announcements-configuration:
|
||||
|
||||
Configuring the plugin
|
||||
----------------------
|
||||
|
||||
The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog.
|
||||
|
||||
On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the
|
||||
configuration of the existing channels through ``config.yaml``.
|
||||
|
||||
The available configuration keys are:
|
||||
|
||||
* ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure
|
||||
that follows this format:
|
||||
|
||||
* ``name``: Name of the channel, used e.g. in the title of the displayed notifications.
|
||||
* ``description``: Description of the channel.
|
||||
* ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification).
|
||||
* ``type``: Currently unused.
|
||||
* ``url``: URL for the feed acting as notification source, must be RSS or Atom format.
|
||||
|
||||
* ``enabled_channels``: List of identifiers of enabled channels.
|
||||
* ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly).
|
||||
* ``channel_order``: List of channel identifiers in the order they should appear in the UI.
|
||||
* ``ttl``: Time to live of the channel cache in minutes (default: 6 hours).
|
||||
* ``display_limit``: Limit of items to display per channel (default: 3).
|
||||
* ``summary_limit``: Limit of characters to display from each channel entry (default: 300).
|
||||
|
||||
.. _sec-bundledplugins-announcements-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Announcement plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/announcements``.
|
||||
@@ -0,0 +1,543 @@
|
||||
.. _sec-bundledplugins-appkeys:
|
||||
|
||||
Application Keys Plugin
|
||||
=======================
|
||||
|
||||
The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10).
|
||||
|
||||
It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it
|
||||
on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed
|
||||
on a per-user base as well as globally by administrators.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-confirmation:
|
||||
.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png
|
||||
:align: center
|
||||
:alt: Confirmation
|
||||
|
||||
The plugin's confirmation generated for a new application key request.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-user_settings:
|
||||
.. figure:: ../images/bundledplugins-appkeys-user_settings.png
|
||||
:align: center
|
||||
:alt: Key management via user settings
|
||||
|
||||
Users can manage the application specific API keys registered to their account via their user settings.
|
||||
|
||||
.. _fig-bundledplugins-appkeys-settings:
|
||||
.. figure:: ../images/bundledplugins-appkeys-settings.png
|
||||
:align: center
|
||||
:alt: Global key management via settings
|
||||
|
||||
Administrators can manage all application specific API keys registered to any user.
|
||||
|
||||
.. _sec-bundledplugins-appkeys-workflow:
|
||||
|
||||
Workflow
|
||||
--------
|
||||
|
||||
The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist
|
||||
of the following steps:
|
||||
|
||||
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
|
||||
enters their username which is also their user ID into the App.
|
||||
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
|
||||
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
|
||||
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
|
||||
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
|
||||
authorization process.
|
||||
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
|
||||
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
|
||||
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
|
||||
signals that no decision has been made yet.
|
||||
6. The User either accepts or denies the access request which makes the Webinterface send a
|
||||
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
|
||||
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
|
||||
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
|
||||
an HTTP :http:statuscode:`404`.
|
||||
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant App
|
||||
participant Webinterface
|
||||
participant Server
|
||||
|
||||
note over User, Server: Step 1, 2 & 3
|
||||
|
||||
User->>App: enters URL of instance to connect to and optional user_id
|
||||
|
||||
App->>Server: GET /plugin/appkeys/probe
|
||||
|
||||
alt Workflow unsupported
|
||||
|
||||
Server->>App: 404
|
||||
App->>User: alternative workflow, copy-paste key manually
|
||||
|
||||
else Workflow supported
|
||||
|
||||
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
|
||||
|
||||
note over User, Server: Step 4
|
||||
|
||||
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
|
||||
Webinterface-->>User: Display confirmation dialog
|
||||
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
|
||||
|
||||
note over User, Server: Step 5
|
||||
|
||||
loop Poll for decision
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 202
|
||||
end
|
||||
|
||||
note over User, Server: Step 6 & 7
|
||||
|
||||
alt User accepts
|
||||
|
||||
User-->>Webinterface: Allow access
|
||||
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (True)
|
||||
Server->>Webinterface: 204
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 200, api_key
|
||||
|
||||
else User denies
|
||||
|
||||
User-->>Webinterface: Deny access
|
||||
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (False)
|
||||
Server->>Webinterface: 204
|
||||
App->>Server: GET /plugin/appkeys/request/<app_token>
|
||||
Server->>App: 404
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api:
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-probe:
|
||||
|
||||
Probe for workflow support
|
||||
..........................
|
||||
|
||||
.. http:get:: /plugin/appkeys/probe
|
||||
|
||||
Probes for support of the workflow.
|
||||
|
||||
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
|
||||
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
|
||||
|
||||
:status 204: the workflow is supported
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-startauthprocess:
|
||||
|
||||
Start authorization process
|
||||
...........................
|
||||
|
||||
.. http:post:: /plugin/appkeys/request
|
||||
|
||||
Starts the authorization process.
|
||||
|
||||
Expects a :ref:`Key request <sec-bundledplugins-appkey-datamodel-keyrequest>` as request body.
|
||||
|
||||
The ``app`` parameter should be a human readable identifier to use
|
||||
for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively,
|
||||
so ``My App`` and ``my APP`` are considered the same application identifiers.
|
||||
|
||||
The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter
|
||||
is left unset, any user will be able to complete the authorization process and grant access to the app with their
|
||||
account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use
|
||||
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
|
||||
is logged in on.
|
||||
|
||||
:json app: application identifier to use for the request, case insensitive
|
||||
:json user: optional user id to restrict the decision to the specified user
|
||||
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-polldecision:
|
||||
|
||||
Poll for decision on existing request
|
||||
.....................................
|
||||
|
||||
.. http:get:: /plugin/appkeys/request/<str:app_token>
|
||||
|
||||
Endpoint generated per authorization request to poll for the result.
|
||||
|
||||
Returns an HTTP :http:statuscode:`202` while no decision has been made yet, an HTTP :http:statuscode:`200` and
|
||||
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
|
||||
HTTP :http:statuscode:`404` if the request has been denied or timed out.
|
||||
|
||||
.. note::
|
||||
|
||||
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
|
||||
for more than 5s.
|
||||
|
||||
:status 200: access granted, API key in response body
|
||||
:status 202: no decision has been made yet, continue polling
|
||||
:status 404: access denied or request timed out
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-decide:
|
||||
|
||||
Decide on existing request
|
||||
..........................
|
||||
|
||||
.. http:post:: /plugin/appkeys/decision/<str:user_token>
|
||||
|
||||
Endpoint to decide on the authorization request.
|
||||
|
||||
Expects a :ref:`Decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` as request body.
|
||||
|
||||
Returns an HTTP :http:statuscode:`204` on success.
|
||||
|
||||
:json decision: boolean value to indicate whether to confirm (``True``) or deny (``False``) access
|
||||
:status 204: success
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-fetchlist:
|
||||
|
||||
Fetch list of existing application keys
|
||||
.......................................
|
||||
|
||||
.. http:get:: /api/plugin/appkeys
|
||||
|
||||
Fetches a list of existing application keys and pending requests registered in the system for the current user.
|
||||
|
||||
If the additional optional parameter ``all`` is provided and the user has administrator rights, fetches a list
|
||||
of *all** application keys and pending requests registered in the system for any user.
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`List response <sec-bundledplugins-appkey-datamodel-listreponse>` in the
|
||||
body upon success.
|
||||
|
||||
:query all: Fetch all application keys and pending requests from all users. Requires administrator rights.
|
||||
|
||||
.. _sec-bundledplugins-appkeys-api-issuecommand:
|
||||
|
||||
Issue an application key command
|
||||
................................
|
||||
|
||||
.. http:post:: /api/plugin/appkeys
|
||||
|
||||
Application key commands allow revoking existing application keys and manually generating new ones. The available
|
||||
commands are:
|
||||
|
||||
revoke
|
||||
Revokes an existing application key. Must belong to the user issuing the command, unless the user has admin rights
|
||||
in which case they make revoke any application key in the system. Expects the key in question as parameter ``key``.
|
||||
|
||||
generate
|
||||
Generates a new application key for the user, using the application identifier provided as parameter ``app``.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
Requires user rights.
|
||||
|
||||
**Example revoke request**
|
||||
|
||||
Revokes the (fictional) key ``aabbccddeeff112233445566``.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/plugin/appkeys HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "revoke",
|
||||
"key": "aabbccddeeff112233445566"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example generate request**
|
||||
|
||||
Generates a new key for application identifier "My awesome application 1.0".
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/plugin/appkeys HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "generate",
|
||||
"key": "My awesome application 1.0"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``revoke`` or ``generate``
|
||||
:json string key: ``revoke`` command: The key to revoke
|
||||
:json string app: ``generate`` command: Application identifier for which to generate a key
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: Invalid or missing parameter
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel:
|
||||
|
||||
Data model
|
||||
----------
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keyrequest:
|
||||
|
||||
Key request
|
||||
...........
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``app``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier to use for the request
|
||||
* - ``user``
|
||||
- 0..1
|
||||
- str
|
||||
- User identifier/name to restrict the request to
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keyresponse:
|
||||
|
||||
Key response
|
||||
............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``apikey``
|
||||
- 1
|
||||
- str
|
||||
- the API key generated for the application
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-decisionrequest:
|
||||
|
||||
Decision request
|
||||
................
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``decision``
|
||||
- 1
|
||||
- boolean
|
||||
- ``True`` if the access request it to be granted, ``False`` otherwise
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-listreponse:
|
||||
|
||||
List response
|
||||
.............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``keys``
|
||||
- 1
|
||||
- list of :ref:`key list entries <sec-bundledplugins-appkey-datamodel-keylistentry>`
|
||||
- Keys registered in the system
|
||||
* - ``pending``
|
||||
- 1
|
||||
- list of :ref:`pending list entries <sec-bundledplugins-appkey-datamodel-pendinglistentry>`
|
||||
- Currently pending authorization requests
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-keylistentry:
|
||||
|
||||
Key list entry
|
||||
..............
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``api_key``
|
||||
- 1
|
||||
- str
|
||||
- API key
|
||||
* - ``app_id``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier
|
||||
* - ``user_id``
|
||||
- 1
|
||||
- str
|
||||
- User ID of the key's owner
|
||||
|
||||
.. _sec-bundledplugins-appkey-datamodel-pendinglistentry:
|
||||
|
||||
Pending list entry
|
||||
..................
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``app_id``
|
||||
- 1
|
||||
- str
|
||||
- Application identifier
|
||||
* - ``user_id``
|
||||
- 0..1
|
||||
- str
|
||||
- optional: User ID of user who can grant or deny request
|
||||
* - ``user_token``
|
||||
- 1
|
||||
- str
|
||||
- Token to grant or deny request
|
||||
|
||||
.. _sec-bundledplugins-appkeys-jsclientlib:
|
||||
|
||||
JavaScript Client Library
|
||||
-------------------------
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.getKeys(opts)
|
||||
|
||||
Retrieves registered keys and pending requests for the current user.
|
||||
|
||||
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.getAllKeys(opts)
|
||||
|
||||
Retrieves registered keys and pending requests for all users.
|
||||
|
||||
Needs administrator rights.
|
||||
|
||||
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.generateKey(app, opts)
|
||||
|
||||
Generates a key for the given ``app`` and the current user.
|
||||
|
||||
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
|
||||
|
||||
:param string app: Application identifier
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.revokeKey(key, opts)
|
||||
|
||||
Revokes the given ``key``. The key must belong to the current user, or the current user must have administrator
|
||||
rights.
|
||||
|
||||
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
|
||||
|
||||
:param string key: Key to revoke
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.decide(token, decision, opts)
|
||||
|
||||
Decides on an existing authorization request.
|
||||
|
||||
See :ref:`Decide on existing request <sec-bundledplugins-appkeys-api-decide>` for more details.
|
||||
|
||||
:param string token: User token for which to make the decision, as pushed to the client via the socket.
|
||||
:param boolean decision: Whether to grant access (``true``) or not (``false``).
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
|
||||
|
||||
Probes for workflow support.
|
||||
|
||||
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` identifier.
|
||||
|
||||
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.requestForUser(app, user, opts)
|
||||
|
||||
Starts a new authorization request for the provided ``app`` and ``user`` identifiers.
|
||||
|
||||
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.checkDecision(token, opts)
|
||||
|
||||
Polls for a decision on an existing authorization request identified by ``token``.
|
||||
|
||||
See :ref:`Poll for decision on existing request <sec-bundledplugins-appkeys-api-polldecision>` for more details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
|
||||
|
||||
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
|
||||
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
|
||||
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
|
||||
for the workflow, the promise is rejected.
|
||||
|
||||
**Example usage**
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
OctoPrint.plugins.appkeys.authenticate("My App", "some_user")
|
||||
.done(function(api_key) {
|
||||
console.log("Got our API key:", api_key);
|
||||
})
|
||||
.fail(function() {
|
||||
console.log("No API key for us");
|
||||
})
|
||||
|
||||
:param string app: Application identifier
|
||||
:param string user: Optional user identifier
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. _sec-bundledplugins-appkeys-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Application Keys plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/appkeys``.
|
||||
@@ -0,0 +1,70 @@
|
||||
.. _sec-bundledplugins-backup:
|
||||
|
||||
Backup Plugin
|
||||
=============
|
||||
|
||||
The OctoPrint Backup Plugin comes bundled with OctoPrint (starting with 1.3.10).
|
||||
|
||||
It allows the creation and restoration of backups of OctoPrint's settings, data and installed plugins [#]_.
|
||||
|
||||
This allows easy migration
|
||||
to newly setup instances as well as making regular backups to prevent data loss.
|
||||
|
||||
.. _fig-bundledplugins-backup-settings:
|
||||
.. figure:: ../images/bundledplugins-backup-settings.png
|
||||
:align: center
|
||||
:alt: OctoPrint Backup Plugin
|
||||
|
||||
The plugin's settings panel with existing backups, the backup creation and restore sections.
|
||||
|
||||
As long as plugins adhere to the standard of storing their data and settings in OctoPrint's plugin data folders, their
|
||||
data will be part of the backup. Note that the backups made by the Backup Plugin will *not* be part of any backups -
|
||||
you'll need to persist the resulting zip files yourself!
|
||||
|
||||
.. _sec-bundledplugins-backup-cli:
|
||||
|
||||
Command line usage
|
||||
------------------
|
||||
|
||||
The Backup Plugin implements a command line interface that allows creation and restoration of backups.
|
||||
It adds two new commands, ``backup:backup`` and ``backup_restore``.
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
$ octoprint plugins backup:backup --help
|
||||
Initializing settings & plugin subsystem...
|
||||
Usage: octoprint plugins backup:backup [OPTIONS]
|
||||
|
||||
Creates a new backup.
|
||||
|
||||
Options:
|
||||
--exclude TEXT Identifiers of data folders to exclude, e.g. 'uploads' to
|
||||
exclude uploads or 'timelapse' to exclude timelapses.
|
||||
--help Show this message and exit.
|
||||
|
||||
$ octoprint plugins backup:restore --help
|
||||
Initializing settings & plugin subsystem...
|
||||
Usage: octoprint plugins backup:restore [OPTIONS] PATH
|
||||
|
||||
Restores an existing backup from the backup zip provided as argument.
|
||||
|
||||
OctoPrint does not need to run for this to proceed.
|
||||
|
||||
Options:
|
||||
--help Show this message and exit.
|
||||
|
||||
.. note::
|
||||
|
||||
The ``backup:backup`` command can be useful in combination with a cronjob to create backups in regular intervals.
|
||||
|
||||
.. _sec-bundledplugins-backup-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the Backup plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/backup``.
|
||||
|
||||
.. [#] Note that only those plugins that are available on `OctoPrint's official plugin repository <https://plugins.octoprint.org>`_
|
||||
can be automatically restored. If you have plugins installed that are not available on there you'll get their
|
||||
names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them.
|
||||
@@ -0,0 +1,35 @@
|
||||
.. _sec-bundledplugins-forcelogin:
|
||||
|
||||
ForceLogin Plugin
|
||||
=================
|
||||
|
||||
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
|
||||
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
|
||||
instead forces users to log in if they want to get any kind of information from OctoPrint.
|
||||
|
||||
.. _fig-bundledplugins-forcelogin:
|
||||
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
|
||||
:align: center
|
||||
:alt: Forced login dialog
|
||||
|
||||
OctoPrint's new forced login dialog.
|
||||
|
||||
.. warning::
|
||||
|
||||
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
|
||||
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
|
||||
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
|
||||
is not OctoPrint itself.
|
||||
|
||||
.. note::
|
||||
|
||||
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
|
||||
the ForceLogin Plugin in OctoPrint's plugin manager.
|
||||
|
||||
.. _sec-bundledplugins-forcelogin-sourcecode:
|
||||
|
||||
Source code
|
||||
-----------
|
||||
|
||||
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
|
||||
its source repository under ``src/octoprint/plugins/forcelogin``.
|
||||
@@ -8,8 +8,12 @@ Bundled Plugins
|
||||
:maxdepth: 2
|
||||
|
||||
action_command_prompt.rst
|
||||
announcements.rst
|
||||
appkeys.rst
|
||||
backup.rst
|
||||
cura.rst
|
||||
discovery.rst
|
||||
forcelogin.rst
|
||||
logging.rst
|
||||
pluginmanager.rst
|
||||
printer_safety_check.rst
|
||||
|
||||
@@ -16,17 +16,12 @@ such identification.
|
||||
|
||||
An example of a warning generated by the Printer Safety Check
|
||||
|
||||
Currently the following firmwares produce this warning:
|
||||
|
||||
* Anet A8 stock firmware
|
||||
Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
for a list of currently identified printers.
|
||||
|
||||
If you know of further printers/printer firmwares that need to be added here, please
|
||||
`get in touch on the forum and provide their response to an M115 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
|
||||
.. note::
|
||||
|
||||
Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
|
||||
|
||||
@@ -1165,7 +1165,7 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
|
||||
# A list of filters to display in the terminal tab. Defaults to the filters shown below
|
||||
terminalFilters:
|
||||
- name: Suppress temperature messages
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv: ok T:)'
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)'
|
||||
- name: Suppress SD status messages
|
||||
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
|
||||
- name: Suppress wait responses
|
||||
|
||||
@@ -31,7 +31,13 @@ Internet!).
|
||||
.. hint::
|
||||
|
||||
If you plan to have your OctoPrint instance accessible over the internet,
|
||||
**always enable Access Control**.
|
||||
**always enable Access Control** and ideally **don't make it accessible to
|
||||
everyone over the internet but instead use a VPN** or at the very least
|
||||
HTTP basic authentication on a layer above OctoPrint.
|
||||
|
||||
A physical device that includes heaters and stepper motors really should not be
|
||||
publicly reachable by everyone with an internet connection, even with access
|
||||
control enabled.
|
||||
|
||||
.. _sec-features-access_control-rerunning_wizard:
|
||||
|
||||
|
||||
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
|
||||
.. code-block:: jinja
|
||||
:caption: Default ``disable_hotends`` snippet
|
||||
|
||||
{% if printer_profile.extruder.sharedNozzle %}
|
||||
M104 T0 S0
|
||||
{% else %}
|
||||
{% for tool in range(printer_profile.extruder.count) %}
|
||||
M104 T{{ tool }} S0
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
The ``disable_bed`` snippet is defined as follows:
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
@@ -80,9 +80,13 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s
|
||||
|
||||
.. seealso::
|
||||
|
||||
`OctoPrint-ForceLogin <https://github.com/OctoPrint/OctoPrint-ForceLogin>`_
|
||||
A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the
|
||||
client library's :ref:`browser component <sec-jsclientlib-browser>` to login the user.
|
||||
:ref:`Application Key Plugin <sec-bundledplugins-appkeys>`
|
||||
A bundled plugin that implements an authorization workflow for third party clients. It adds various additional
|
||||
methods to the JS Client Library.
|
||||
:ref:`ForceLogin Plugin <sec-bundledplugins-forcelogin>`
|
||||
A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and
|
||||
various hooks. Utilizes the client library's :ref:`browser component <sec-jsclientlib-browser>` to login the
|
||||
user.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Helpers
|
||||
=======
|
||||
|
||||
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
|
||||
Helpers are methods that plugins can expose to other plugins in order to make common functionality available on the
|
||||
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
|
||||
|
||||
An example for providing some helper functions to the system can be found in the
|
||||
|
||||
@@ -1089,6 +1089,54 @@ octoprint.printer.estimation.factory
|
||||
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
|
||||
:rtype: class or function
|
||||
|
||||
.. _sec-plugins-hook-server-http-after_request:
|
||||
|
||||
octoprint.server.api.after_request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: after_request_handlers_hook(*args, **kwargs)
|
||||
|
||||
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
|
||||
|
||||
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-before_request:
|
||||
|
||||
octoprint.server.api.before_request
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: after_request_handlers_hook(*args, **kwargs)
|
||||
|
||||
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
|
||||
|
||||
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
|
||||
usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-access_validator:
|
||||
|
||||
octoprint.server.http.access_validator
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: access_validator_hook(request, *args, **kwargs)
|
||||
|
||||
Allows adding additional access validators to the default tornado routers.
|
||||
|
||||
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled
|
||||
"Force Login" plugin for a usage example.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-server-http-bodysize:
|
||||
|
||||
octoprint.server.http.bodysize
|
||||
@@ -1190,6 +1238,45 @@ octoprint.server.http.routes
|
||||
:return: a list of 3-tuples with additional routes as defined above
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-register:
|
||||
|
||||
octoprint.server.sockjs.register
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
|
||||
|
||||
Allows plugins to prevent a new :ref:`push socket client <sec-api-push>` to be registered to the system.
|
||||
|
||||
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
|
||||
signals to not register the client.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object which is about to be registered
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:return: whether to proceed with registration (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-server-sockjs-emit:
|
||||
|
||||
octoprint.server.sockjs.emit
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
|
||||
|
||||
Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection <sec-api-push>`.
|
||||
|
||||
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
|
||||
|
||||
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
|
||||
|
||||
:param object socket: the socket object on which a message is about to be emitted
|
||||
:param object user: the user currently authenticated on the socket - might be None
|
||||
:param string message: the message type about to be emitted
|
||||
:param dict payload: the payload of the message about to be emitted (may be None)
|
||||
:return: whether to proceed with sending the message (``True``) or not (``False``)
|
||||
:rtype: boolean
|
||||
|
||||
.. _sec-plugins-hook-timelapse-extensions:
|
||||
|
||||
octoprint.timelapse.extensions
|
||||
|
||||
@@ -12,6 +12,9 @@ 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.12,<0.13",
|
||||
@@ -79,9 +82,6 @@ EXTRA_REQUIRES = dict(
|
||||
]
|
||||
)
|
||||
|
||||
# Additional requirements for setup
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
@@ -154,10 +154,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",
|
||||
|
||||
@@ -225,6 +225,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
js
|
||||
JavaScript files, such as additional view models
|
||||
jsclient
|
||||
JavaScript files containing additional parts for the JS Client Library (since 1.3.10)
|
||||
css
|
||||
CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode.
|
||||
less
|
||||
@@ -239,6 +241,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=['js/my_file.js', 'js/my_other_file.js'],
|
||||
clientjs=['clientjs/my_file.js'],
|
||||
css=['css/my_styles.css'],
|
||||
less=['less/my_styles.less']
|
||||
)
|
||||
|
||||
@@ -62,7 +62,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/action_command_prompt.js"])
|
||||
return dict(js=["js/action_command_prompt.js"],
|
||||
clientjs=["clientjs/action_command_prompt.js"])
|
||||
|
||||
#~ SettingsPlugin
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
|
||||
var data = {
|
||||
choice: choice
|
||||
};
|
||||
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
|
||||
return OctoPrintActionCommandPromptClient;
|
||||
});
|
||||
@@ -1,29 +1,3 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
|
||||
var data = {
|
||||
choice: choice
|
||||
};
|
||||
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
|
||||
return OctoPrintActionCommandPromptClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function ActionCommandPromptViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -21,7 +21,7 @@ import flask
|
||||
from collections import OrderedDict
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify
|
||||
from flask_babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
@@ -150,7 +150,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
# Blueprint Plugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
|
||||
def get_channel_data(self):
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
@@ -211,7 +211,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
unless=lambda: force)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
|
||||
def channel_command(self, channel):
|
||||
from octoprint.server.util.flask import get_json_command_from_request
|
||||
@@ -391,15 +391,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
result = []
|
||||
if "entries" in feed:
|
||||
for entry in feed["entries"]:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
try:
|
||||
internal_entry = self._to_internal_entry(entry, read_until=read_until)
|
||||
if internal_entry:
|
||||
result.append(internal_entry)
|
||||
except:
|
||||
self._logger.exception("Error while converting entry from feed, skipping it")
|
||||
return result
|
||||
|
||||
def _to_internal_entry(self, entry, read_until=None):
|
||||
"""Convert feed entries to internal data structure."""
|
||||
|
||||
published = calendar.timegm(entry["published_parsed"])
|
||||
timestamp = entry.get("published_parsed",
|
||||
entry.get("updated_parsed",
|
||||
None))
|
||||
if timestamp is None:
|
||||
return None
|
||||
|
||||
published = calendar.timegm(timestamp)
|
||||
|
||||
read = True
|
||||
if read_until is not None:
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import flask
|
||||
import threading
|
||||
import os
|
||||
import yaml
|
||||
import codecs
|
||||
import time
|
||||
from binascii import hexlify
|
||||
from collections import defaultdict
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
||||
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
|
||||
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
|
||||
class AppAlreadyExists(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PendingDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
self.user_token = user_token
|
||||
self.created = monotonic_time()
|
||||
|
||||
if callable(timeout_callback):
|
||||
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
|
||||
self.poll_timeout.start()
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
user_id=self.user_id,
|
||||
user_token=self.user_token)
|
||||
|
||||
|
||||
class ReadyDecision(object):
|
||||
def __init__(self, app_id, app_token, user_id):
|
||||
self.app_id = app_id
|
||||
self.app_token = app_token
|
||||
self.user_id = user_id
|
||||
|
||||
@classmethod
|
||||
def for_pending(cls, pending, user_id):
|
||||
return cls(pending.app_id, pending.app_token, user_id)
|
||||
|
||||
|
||||
class ActiveKey(object):
|
||||
def __init__(self, app_id, api_key, user_id):
|
||||
self.app_id = app_id
|
||||
self.api_key = api_key
|
||||
self.user_id = user_id
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key,
|
||||
user_id=self.user_id)
|
||||
|
||||
def internal(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key)
|
||||
|
||||
@classmethod
|
||||
def for_internal(cls, internal, user_id):
|
||||
return cls(internal["app_id"], internal["api_key"], user_id)
|
||||
|
||||
|
||||
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._pending_decisions = []
|
||||
self._pending_lock = threading.RLock()
|
||||
|
||||
self._ready_decisions = []
|
||||
self._ready_lock = threading.RLock()
|
||||
|
||||
self._keys = defaultdict(list)
|
||||
self._keys_lock = threading.RLock()
|
||||
|
||||
self._key_path = None
|
||||
|
||||
def initialize(self):
|
||||
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
|
||||
self._load_keys()
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="usersettings", name=gettext("Application Keys")),
|
||||
dict(type="settings", name=gettext("Application Keys"))]
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/appkeys.js"],
|
||||
clientjs=["clientjs/appkeys.js"],
|
||||
less=["less/appkeys.less"],
|
||||
css=["css/appkeys.css"])
|
||||
|
||||
##~~ BlueprintPlugin mixin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def handle_probe(self):
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
def handle_request(self):
|
||||
data = flask.request.json
|
||||
if not "app" in data:
|
||||
return flask.make_response("No app name provided", 400)
|
||||
|
||||
app_name = data["app"]
|
||||
user_id = None
|
||||
if "user" in data:
|
||||
user_id = data["user"]
|
||||
|
||||
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
|
||||
app_name=app_name,
|
||||
user_token=user_token,
|
||||
user_id=user_id))
|
||||
response = flask.jsonify(app_token=app_token)
|
||||
response.status_code = 201
|
||||
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
||||
@no_firstrun_access
|
||||
def handle_decision_poll(self, app_token):
|
||||
result = self._get_pending_by_app_token(app_token)
|
||||
if result:
|
||||
for pending_decision in result:
|
||||
pending_decision.poll_timeout.reset()
|
||||
|
||||
response = flask.jsonify(message="Awaiting decision")
|
||||
response.status_code = 202
|
||||
return response
|
||||
|
||||
result = self._get_decision(app_token)
|
||||
if result:
|
||||
return flask.jsonify(api_key=result)
|
||||
|
||||
return flask.abort(404)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
|
||||
@restricted_access
|
||||
def handle_decision(self, user_token):
|
||||
data = flask.request.json
|
||||
if not "decision" in data:
|
||||
return flask.make_response("No decision provided", 400)
|
||||
decision = data["decision"] in valid_boolean_trues
|
||||
user_id = current_user.get_name()
|
||||
|
||||
result = self._set_decision(user_token, decision, user_id)
|
||||
if not result:
|
||||
return flask.abort(404)
|
||||
|
||||
# Close access_request dialog for this request on all open OctoPrint connections
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
return False # No API key required to request API access
|
||||
|
||||
##~~ SimpleApiPlugin mixin
|
||||
|
||||
def get_api_commands(self):
|
||||
return dict(generate=["app"],
|
||||
revoke=["key"])
|
||||
|
||||
def on_api_get(self, request):
|
||||
user_id = current_user.get_name()
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
|
||||
keys = self._all_api_keys()
|
||||
else:
|
||||
keys = self._api_keys_for_user(user_id)
|
||||
|
||||
return flask.jsonify(keys=map(lambda x: x.external(), keys),
|
||||
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
user_id = current_user.get_name()
|
||||
if not user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
if command == "revoke":
|
||||
api_key = data.get("key")
|
||||
if not api_key:
|
||||
return flask.abort(400)
|
||||
|
||||
if not admin_permission.can():
|
||||
user_for_key = self._user_for_api_key(api_key)
|
||||
if user_for_key is None or user_for_key.user_id != user_id:
|
||||
return flask.abort(403)
|
||||
|
||||
self._delete_api_key(api_key)
|
||||
|
||||
elif command == "generate":
|
||||
# manual generateKey
|
||||
app_name = data.get("app")
|
||||
if not app_name:
|
||||
return flask.abort(400)
|
||||
|
||||
self._add_api_key(user_id, app_name.strip())
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
##~~ key validator hook
|
||||
|
||||
def validate_api_key(self, api_key, *args, **kwargs):
|
||||
return self._user_for_api_key(api_key)
|
||||
|
||||
##~~ Helpers
|
||||
|
||||
def _add_pending_decision(self, app_name, user_id=None):
|
||||
app_token = self._generate_key()
|
||||
user_token = self._generate_key()
|
||||
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
|
||||
timeout_callback=self._expire_pending))
|
||||
|
||||
return app_token, user_token
|
||||
|
||||
def _get_pending_by_app_token(self, app_token):
|
||||
result = []
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.app_token == app_token:
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _get_pending_by_user_id(self, user_id):
|
||||
result = []
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.user_id == user_id or data.user_id is None:
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _expire_pending(self, user_token):
|
||||
with self._pending_lock:
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
len_after = len(self._pending_decisions)
|
||||
|
||||
if len_after < len_before:
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
|
||||
def _remove_stale_pending(self):
|
||||
with self._pending_lock:
|
||||
cutoff = monotonic_time() - CUTOFF_TIME
|
||||
len_before = len(self._pending_decisions)
|
||||
self._pending_decisions = filter(lambda x: x.created >= cutoff,
|
||||
self._pending_decisions)
|
||||
len_after = len(self._pending_decisions)
|
||||
if len_after < len_before:
|
||||
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
|
||||
|
||||
def _set_decision(self, user_token, decision, user_id):
|
||||
with self._pending_lock:
|
||||
self._remove_stale_pending()
|
||||
for data in self._pending_decisions:
|
||||
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
|
||||
pending = data
|
||||
break
|
||||
else:
|
||||
return False # not found
|
||||
|
||||
if decision:
|
||||
with self._ready_lock:
|
||||
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
|
||||
|
||||
with self._pending_lock:
|
||||
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
|
||||
|
||||
return True
|
||||
|
||||
def _get_decision(self, app_token):
|
||||
self._remove_stale_pending()
|
||||
|
||||
with self._ready_lock:
|
||||
for data in self._ready_decisions:
|
||||
if data.app_token == app_token:
|
||||
decision = data
|
||||
break
|
||||
else:
|
||||
return False # not found
|
||||
|
||||
api_key = self._add_api_key(decision.user_id, decision.app_id)
|
||||
|
||||
with self._ready_lock:
|
||||
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
|
||||
|
||||
return api_key
|
||||
|
||||
def _add_api_key(self, user_id, app_name):
|
||||
with self._keys_lock:
|
||||
for key in self._keys[user_id]:
|
||||
if key.app_id.lower() == app_name.lower():
|
||||
return key.api_key
|
||||
|
||||
key = ActiveKey(app_name, self._generate_key(), user_id)
|
||||
self._keys[user_id].append(key)
|
||||
self._save_keys()
|
||||
return key.api_key
|
||||
|
||||
def _delete_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
self._keys[user_id] = filter(lambda x: x.api_key != api_key, data)
|
||||
self._save_keys()
|
||||
|
||||
def _user_for_api_key(self, api_key):
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
if filter(lambda x: x.api_key == api_key, data):
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
return None
|
||||
|
||||
def _api_keys_for_user(self, user_id):
|
||||
with self._keys_lock:
|
||||
return self._keys[user_id]
|
||||
|
||||
def _all_api_keys(self):
|
||||
with self._keys_lock:
|
||||
result = []
|
||||
for user_id, keys in self._keys.items():
|
||||
result += keys
|
||||
return result
|
||||
|
||||
def _generate_key(self):
|
||||
return hexlify(os.urandom(16))
|
||||
|
||||
def _load_keys(self):
|
||||
with self._keys_lock:
|
||||
if not os.path.exists(self._key_path):
|
||||
return
|
||||
|
||||
try:
|
||||
with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
|
||||
persisted = yaml.safe_load(f)
|
||||
except:
|
||||
self._logger.exception("Could not load application keys from {}".format(self._key_path))
|
||||
return
|
||||
|
||||
if not isinstance(persisted, dict):
|
||||
return
|
||||
|
||||
keys = defaultdict(list)
|
||||
for user_id, persisted_keys in persisted.items():
|
||||
keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
|
||||
self._keys = keys
|
||||
|
||||
def _save_keys(self):
|
||||
with self._keys_lock:
|
||||
to_persist = dict()
|
||||
for user_id, keys in self._keys.items():
|
||||
to_persist[user_id] = [x.internal() for x in keys]
|
||||
|
||||
try:
|
||||
with atomic_write(self._key_path) as f:
|
||||
yaml.safe_dump(to_persist, f)
|
||||
except:
|
||||
self._logger.exception("Could not write application keys to {}".format(self._key_path))
|
||||
|
||||
__plugin_name__ = u"Application Keys Plugin"
|
||||
__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys"
|
||||
__plugin_author__ = u"Gina Häußge, Aldo Hoeben"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to "
|
||||
u"obtain an API key without you manually copy-pasting it.")
|
||||
__plugin_implementation__ = AppKeysPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintAppKeysClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
|
||||
return this.base.simpleApiGet("appkeys", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
|
||||
return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.probe = function(opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
|
||||
return this.requestForUser(app, undefined, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
|
||||
var deferred = $.Deferred();
|
||||
var client = this;
|
||||
|
||||
client.probe()
|
||||
.done(function() {
|
||||
client.requestForUser(app, user)
|
||||
.done(function(response) {
|
||||
var token = response.app_token;
|
||||
if (!token) {
|
||||
// no token received, something went wrong
|
||||
deferred.reject();
|
||||
return;
|
||||
}
|
||||
|
||||
var interval = 1000;
|
||||
var poll = function() {
|
||||
client.checkDecision(token)
|
||||
.done(function(response) {
|
||||
if (response.api_key) {
|
||||
// got a decision, resolve the promise
|
||||
deferred.resolve(response.api_key);
|
||||
} else {
|
||||
// no decision yet, poll a bit more
|
||||
deferred.notify();
|
||||
window.setTimeout(poll, interval);
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
};
|
||||
window.setTimeout(poll, interval);
|
||||
})
|
||||
.fail(function() {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
})
|
||||
.fail(function() {
|
||||
// workflow unsupported
|
||||
deferred.reject();
|
||||
});
|
||||
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient);
|
||||
return OctoPrintAppKeysClient;
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}
|
||||
@@ -0,0 +1,308 @@
|
||||
$(function() {
|
||||
function UserAppKeysViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.userkeys",
|
||||
{
|
||||
"app": function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
|
||||
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"app",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
);
|
||||
self.pending = {};
|
||||
self.openRequests = {};
|
||||
|
||||
self.editorApp = ko.observable();
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getKeys()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
self.pending = response.pending;
|
||||
_.each(self.pending, function(data, token) {
|
||||
self.openRequests[token] = self.promptForAccess(data.app_id, token);
|
||||
})
|
||||
};
|
||||
|
||||
self.generateKey = function() {
|
||||
return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
|
||||
.done(self.requestData)
|
||||
.done(function() {
|
||||
self.editorApp("");
|
||||
});
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.allowApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, true)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.denyApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, false)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.promptForAccess = function(app, token) {
|
||||
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
|
||||
message = _.sprintf(message, {app: app});
|
||||
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
|
||||
return new PNotify({
|
||||
title: gettext("Access Request"),
|
||||
text: message,
|
||||
hide: false,
|
||||
icon: "fa fa-key",
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Allow"),
|
||||
click: function(notice) {
|
||||
self.allowApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}, {
|
||||
text: gettext("Deny"),
|
||||
click: function(notice) {
|
||||
self.denyApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
},
|
||||
buttons: {
|
||||
sticker: false,
|
||||
closer: false
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onUserSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "appkeys") {
|
||||
return;
|
||||
}
|
||||
|
||||
var app, token, user;
|
||||
|
||||
if (data.type === "request_access" && self.loginState.isUser()) {
|
||||
app = data.app_name;
|
||||
token = data.user_token;
|
||||
user = data.user_id;
|
||||
|
||||
if (user && user !== self.loginState.username()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.pending[token] !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.openRequests[token] = self.promptForAccess(app, token);
|
||||
|
||||
} else if (data.type === "end_request") {
|
||||
token = data.user_token;
|
||||
|
||||
if (self.openRequests[token] !== undefined) {
|
||||
// another instance responded to the access request before the current user did
|
||||
if (self.openRequests[token].state !== "closed") {
|
||||
self.openRequests[token].remove();
|
||||
}
|
||||
delete self.openRequests[token]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function AllAppKeysViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.allkeys",
|
||||
{
|
||||
"user_app": function (a, b) {
|
||||
// sorts ascending, first by user, then by app
|
||||
if (a["user_id"] > b["user_id"]) return 1;
|
||||
if (a["user_id"] < b["user_id"]) return -1;
|
||||
|
||||
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
|
||||
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"user_app",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
self.users = ko.observableArray([]);
|
||||
self.apps = ko.observableArray([]);
|
||||
|
||||
self.markedForDeletion = ko.observableArray([]);
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getAllKeys()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
|
||||
var users = [];
|
||||
var apps = [];
|
||||
_.each(response.keys, function(key) {
|
||||
users.push(key.user_id);
|
||||
apps.push(key.app_id.toLowerCase());
|
||||
});
|
||||
|
||||
users = _.uniq(users);
|
||||
users.sort();
|
||||
self.users(users);
|
||||
|
||||
apps = _.uniq(apps);
|
||||
apps.sort();
|
||||
self.apps(apps);
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.revokeMarked = function() {
|
||||
var perform = function() {
|
||||
self._bulkRevoke(self.markedForDeletion())
|
||||
.done(function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markAllOnPageForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
|
||||
};
|
||||
|
||||
self.markAllForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
|
||||
};
|
||||
|
||||
self.markAllByUserForDeletion = function(user) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
|
||||
};
|
||||
|
||||
self.markAllByAppForDeletion = function(app) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); })
|
||||
};
|
||||
|
||||
self.markAllByFilterForDeletion = function(filter) {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))));
|
||||
};
|
||||
|
||||
self.clearMarked = function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
};
|
||||
|
||||
self._bulkRevoke = function(keys) {
|
||||
var title, message, handler;
|
||||
|
||||
title = gettext("Revoking application keys");
|
||||
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length});
|
||||
handler = function(key) {
|
||||
return OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: keys.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(keys, function(key) {
|
||||
var request = handler(key);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UserAppKeysViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#usersettings_plugin_appkeys"]
|
||||
]);
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AllAppKeysViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#settings_plugin_appkeys"]
|
||||
])
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
#settings_plugin_appkeys_userkeys_table,
|
||||
#settings_plugin_appkeys_allkeys_table {
|
||||
.settings_plugin_appkeys_app {
|
||||
}
|
||||
.settings_plugin_appkeys_actions {
|
||||
width: 75px;
|
||||
text-align: center;
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
}
|
||||
.settings_plugin_appkeys_user {
|
||||
width: 100px;
|
||||
}
|
||||
.settings_plugin_appkeys_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<div data-bind="visible: keys.allSize() <= 0">
|
||||
<p>{{ _('There are no application keys registered yet.') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: keys.allSize() > 0">
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllOnPageForDeletion">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllForDeletion">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li class="dropdown-submenu">
|
||||
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by user...') }}</a>
|
||||
<ul class="dropdown-menu" data-bind="foreach: users">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByUserForDeletion($data) }, text: $data"></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="dropdown-submenu">
|
||||
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by app...') }}</a>
|
||||
<ul class="dropdown-menu" data-bind="foreach: apps">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByAppForDeletion($data) }, text: $data"></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarked">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: revokeMarked, enable: markedForDeletion().length > 0">{{ _('Revoke selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_allkeys_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_appkeys_checkbox"></th>
|
||||
<th class="settings_plugin_appkeys_user">{{ _('User') }}</th>
|
||||
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
|
||||
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_checkbox"><input type="checkbox" data-bind="value: api_key, checked: $root.markedForDeletion"></td>
|
||||
<td class="settings_plugin_appkeys_user"><span data-bind="text: user_id"></span></td>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: keys.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,49 @@
|
||||
<legend>{{ _('Registered application keys') }}</legend>
|
||||
|
||||
<div data-bind="visible: keys.allSize() <= 0">
|
||||
<p>{{ _('There are no application keys registered yet.') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: keys.allSize() > 0">
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_userkeys_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
|
||||
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: keys.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
|
||||
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: keys.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('Manually generate an application key') }}</legend>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Application identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" data-bind="value: editorApp">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="click: generateKey">{{ _('Generate') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,881 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.plugin.core import FolderOrigin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server.util.flask import no_firstrun_access
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
try:
|
||||
import zlib # check if zlib is available
|
||||
except ImportError:
|
||||
zlib = None
|
||||
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import codecs
|
||||
import flask
|
||||
import logging
|
||||
import os
|
||||
import requests
|
||||
import sarge
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
import json
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
|
||||
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
|
||||
|
||||
|
||||
class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin):
|
||||
|
||||
_pip_caller = None
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._in_progress = []
|
||||
self._in_progress_lock = threading.RLock()
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="ACCESS",
|
||||
name="Backup access",
|
||||
description=gettext("Allows access to backups and restores"),
|
||||
roles=["access"],
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
]
|
||||
|
||||
##~~ StarupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
self._clean_dir_backup(self._settings._basedir,
|
||||
on_log_progress=self._logger.info)
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/backup.js"],
|
||||
clientjs=["clientjs/backup.js"],
|
||||
css=["css/backup.css"],
|
||||
less=["less/backup.less"])
|
||||
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_state(self):
|
||||
backups = self._get_backups()
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(backups=backups,
|
||||
backup_in_progress=len(self._in_progress) > 0,
|
||||
unknown_plugins=unknown_plugins)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_unknown_plugins(self):
|
||||
# TODO add caching
|
||||
unknown_plugins = self._get_unknown_plugins()
|
||||
return flask.jsonify(unknown_plugins=unknown_plugins)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def delete_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
pass
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def get_backups(self):
|
||||
backups = self._get_backups()
|
||||
return flask.jsonify(backups=backups)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def create_backup(self):
|
||||
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
|
||||
|
||||
data = flask.request.json
|
||||
exclude = data.get("exclude", [])
|
||||
|
||||
def on_backup_start(name, temporary_path, exclude):
|
||||
self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path,
|
||||
u",".join(exclude) if len(exclude) else "-"))
|
||||
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.append(name)
|
||||
self._send_client_message("backup_started", payload=dict(name=name))
|
||||
|
||||
def on_backup_done(name, final_path, exclude):
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.remove(name)
|
||||
self._send_client_message("backup_done", payload=dict(name=name))
|
||||
|
||||
self._logger.info(u"... done creating backup zip.")
|
||||
|
||||
|
||||
thread = threading.Thread(target=self._create_backup,
|
||||
args=(backup_file,),
|
||||
kwargs=dict(exclude=exclude,
|
||||
settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_backup_start=on_backup_start,
|
||||
on_backup_done=on_backup_done))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
response = flask.jsonify(started=True,
|
||||
name=backup_file)
|
||||
response.status_code = 201
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def delete_backup(self, filename):
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
full_path = os.path.realpath(os.path.join(backup_folder, filename))
|
||||
if full_path.startswith(backup_folder) \
|
||||
and os.path.exists(full_path) \
|
||||
and not is_hidden_path(full_path):
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except:
|
||||
self._logger.exception(u"Could not delete {}".format(filename))
|
||||
raise
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
|
||||
def perform_restore(self):
|
||||
input_name = "file"
|
||||
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
||||
|
||||
if input_upload_path in flask.request.values:
|
||||
# file to restore was uploaded
|
||||
path = flask.request.values[input_upload_path]
|
||||
|
||||
elif flask.request.json and "path" in flask.request.json:
|
||||
# existing backup is supposed to be restored
|
||||
backup_folder = self.get_plugin_data_folder()
|
||||
path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"]))
|
||||
if not path.startswith(backup_folder) \
|
||||
or not os.path.exists(path) \
|
||||
or is_hidden_path(path):
|
||||
return flask.abort(404)
|
||||
|
||||
else:
|
||||
return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400)
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def on_log(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", dict(line=line, type="stdout"))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = plugin["compatibility"]["octoprint"]
|
||||
os_compatible = plugin["compatibility"]["os"]
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
|
||||
u"of OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
|
||||
octoprint_compatible=octoprint_compatible,
|
||||
os_compatible=os_compatible))
|
||||
continue
|
||||
|
||||
self._logger.info(u"Installing plugin {}".format(plugin["id"]))
|
||||
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=on_log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
self._send_client_message("unknown_plugins", payload=dict(plugins=plugins))
|
||||
|
||||
def on_log_progress(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stdout"))
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
self._logger.error(line, exc_info=exc_info)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stderr"))
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr"))
|
||||
|
||||
def on_restore_start(path):
|
||||
self._send_client_message("restore_started")
|
||||
|
||||
def on_restore_done(path):
|
||||
self._send_client_message("restore_done")
|
||||
|
||||
def on_restore_failed(path):
|
||||
self._send_client_message("restore_failed")
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
archive.close()
|
||||
shutil.copy(path, archive.name)
|
||||
path = archive.name
|
||||
|
||||
# noinspection PyTypeChecker
|
||||
thread = threading.Thread(target=self._restore_backup,
|
||||
args=(path,),
|
||||
kwargs=dict(settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_restore_start=on_restore_start,
|
||||
on_restore_done=on_restore_done,
|
||||
on_restore_failed=on_restore_failed))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return flask.jsonify(started=True)
|
||||
|
||||
##~~ tornado hook
|
||||
|
||||
def route_hook(self, *args, **kwargs):
|
||||
from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.server import app
|
||||
from octoprint.server.util.tornado import access_validation_factory
|
||||
from octoprint.server.util.flask import admin_validator
|
||||
|
||||
return [
|
||||
(r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(),
|
||||
as_attachment=True,
|
||||
path_validation=path_validation_factory(lambda path: not is_hidden_path(path),
|
||||
status_code=404),
|
||||
access_validation=access_validation_factory(app, admin_validator)))
|
||||
]
|
||||
|
||||
def bodysize_hook(self, current_max_body_sizes, *args, **kwargs):
|
||||
# max upload size of 1GB for the restore endpoint
|
||||
return [("POST", r"/restore", 1024 * 1024 * 1024)]
|
||||
|
||||
##~~ CLI hook
|
||||
|
||||
def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
import click
|
||||
|
||||
@click.command("backup")
|
||||
@click.option("--exclude", multiple=True,
|
||||
help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or "
|
||||
"'timelapse' to exclude timelapses.")
|
||||
def backup_command(exclude):
|
||||
"""
|
||||
Creates a new backup.
|
||||
"""
|
||||
|
||||
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
|
||||
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
|
||||
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
click.echo("Creating backup at {}, please wait...".format(backup_file))
|
||||
self._create_backup(backup_file,
|
||||
exclude=exclude,
|
||||
settings=settings,
|
||||
plugin_manager=cli_group.plugin_manager,
|
||||
datafolder=datafolder)
|
||||
click.echo("Done.")
|
||||
|
||||
@click.command("restore")
|
||||
@click.argument("path")
|
||||
def restore_command(path):
|
||||
"""
|
||||
Restores an existing backup from the backup zip provided as argument.
|
||||
|
||||
OctoPrint does not need to run for this to proceed.
|
||||
"""
|
||||
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
|
||||
plugin_manager = cli_group.plugin_manager
|
||||
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
# register plugin manager plugin setting overlays
|
||||
plugin_info = plugin_manager.get_plugin_info("pluginmanager")
|
||||
if plugin_info and plugin_info.implementation:
|
||||
default_settings_overlay = dict(plugins=dict())
|
||||
default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults()
|
||||
settings.add_overlay(default_settings_overlay, at_end=True)
|
||||
|
||||
if not os.path.isabs(path):
|
||||
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
path = os.path.join(datafolder, path)
|
||||
|
||||
if not os.path.exists(path):
|
||||
click.echo(u"Backup {} does not exist".format(path), err=True)
|
||||
sys.exit(-1)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
archive.close()
|
||||
shutil.copy(path, archive.name)
|
||||
path = archive.name
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
|
||||
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def log(line):
|
||||
click.echo(u"\t{}".format(line))
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = plugin["compatibility"]["octoprint"]
|
||||
os_compatible = plugin["compatibility"]["os"]
|
||||
compatible = octoprint_compatible and os_compatible
|
||||
if not compatible:
|
||||
if not octoprint_compatible and not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint and the underlying operating system".format(plugin["id"]))
|
||||
elif not octoprint_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
|
||||
u"OctoPrint".format(plugin["id"]))
|
||||
elif not os_compatible:
|
||||
click.echo(u"Cannot install plugin {}, it is incompatible to the underlying "
|
||||
u"operating system".format(plugin["id"]))
|
||||
continue
|
||||
|
||||
click.echo(u"Installing plugin {}".format(plugin["id"]))
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
if not plugins:
|
||||
return
|
||||
|
||||
click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.")
|
||||
for plugin in plugins:
|
||||
click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
|
||||
|
||||
def on_log_progress(line):
|
||||
click.echo(line)
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
click.echo(line, err=True)
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
click.echo(line.rstrip(), err=True)
|
||||
|
||||
if self._restore_backup(path,
|
||||
settings=settings,
|
||||
plugin_manager=plugin_manager,
|
||||
datafolder=datafolder,
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error):
|
||||
click.echo(u"Restored from {}".format(path))
|
||||
else:
|
||||
click.echo(u"Restoring from {} failed".format(path), err=True)
|
||||
|
||||
return [backup_command, restore_command]
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def _get_backups(self):
|
||||
backups = []
|
||||
for entry in scandir(self.get_plugin_data_folder()):
|
||||
if is_hidden_path(entry.path):
|
||||
continue
|
||||
if not entry.is_file():
|
||||
continue
|
||||
if not entry.name.endswith(".zip"):
|
||||
continue
|
||||
|
||||
backups.append(dict(name=entry.name,
|
||||
date=entry.stat().st_mtime,
|
||||
size=entry.stat().st_size,
|
||||
url=flask.url_for("index") + "plugin/backup/download/" + entry.name))
|
||||
return backups
|
||||
|
||||
def _get_unknown_plugins(self):
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
if os.path.exists(data_file):
|
||||
try:
|
||||
with codecs.open(data_file, mode="r", encoding="utf-8") as f:
|
||||
unknown_plugins = json.load(f)
|
||||
|
||||
assert isinstance(unknown_plugins, list)
|
||||
assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins))
|
||||
|
||||
installed_plugins = self._plugin_manager.plugins
|
||||
unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
|
||||
if not unknown_plugins:
|
||||
# no plugins left uninstalled, delete data file
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return unknown_plugins
|
||||
except:
|
||||
self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file))
|
||||
try:
|
||||
os.remove(data_file)
|
||||
except:
|
||||
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
|
||||
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def _clean_dir_backup(cls, basedir,
|
||||
on_log_progress=None):
|
||||
basedir_backup = basedir + ".bck"
|
||||
|
||||
if os.path.exists(basedir_backup):
|
||||
def remove_bck():
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Found config folder backup from prior restore, deleting it...")
|
||||
shutil.rmtree(basedir_backup)
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"... deleted.")
|
||||
|
||||
thread = threading.Thread(target=remove_bck)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
@classmethod
|
||||
def _get_disk_size(cls, path):
|
||||
total = 0
|
||||
for entry in scandir(path):
|
||||
if entry.is_dir():
|
||||
total += cls._get_disk_size(entry.path)
|
||||
elif entry.is_file():
|
||||
total += entry.stat().st_size
|
||||
return total
|
||||
|
||||
@classmethod
|
||||
def _free_space(cls, path, size):
|
||||
from psutil import disk_usage
|
||||
return disk_usage(path).free > size
|
||||
|
||||
@classmethod
|
||||
def _get_plugin_repository_data(cls, url, logger=None):
|
||||
if logger is None:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
except:
|
||||
logger.exception(u"Error while fetching the plugin repository data from {}".format(url))
|
||||
return dict()
|
||||
|
||||
from octoprint.plugins.pluginmanager import map_repository_entry
|
||||
return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()))
|
||||
|
||||
@classmethod
|
||||
def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None):
|
||||
if pip_args is None:
|
||||
pip_args = []
|
||||
|
||||
if on_log is None:
|
||||
on_log = logging.getLogger(__name__).info
|
||||
|
||||
# prepare pip caller
|
||||
def log(prefix, *lines):
|
||||
for line in lines:
|
||||
on_log(u"{} {}".format(prefix, line.rstrip()))
|
||||
|
||||
def log_call(*lines):
|
||||
log(u">", *lines)
|
||||
|
||||
def log_stdout(*lines):
|
||||
log(u"<", *lines)
|
||||
|
||||
def log_stderr(*lines):
|
||||
log(u"!", *lines)
|
||||
|
||||
if cls._pip_caller is None:
|
||||
cls._pip_caller = LocalPipCaller(force_user=force_user)
|
||||
|
||||
cls._pip_caller.on_log_call = log_call
|
||||
cls._pip_caller.on_log_stdout = log_stdout
|
||||
cls._pip_caller.on_log_stderr = log_stderr
|
||||
|
||||
# install plugin
|
||||
pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir']
|
||||
|
||||
if plugin.get("follow_dependency_links"):
|
||||
pip.append("--process-dependency-links")
|
||||
|
||||
if force_user:
|
||||
pip.append("--user")
|
||||
|
||||
if pip_args:
|
||||
pip += pip_args
|
||||
|
||||
cls._pip_caller.execute(*pip)
|
||||
|
||||
@classmethod
|
||||
def _create_backup(cls, name,
|
||||
exclude=None,
|
||||
settings=None,
|
||||
plugin_manager=None,
|
||||
datafolder=None,
|
||||
on_backup_start=None,
|
||||
on_backup_done=None):
|
||||
if exclude is None:
|
||||
exclude = []
|
||||
|
||||
configfile = settings._configfile
|
||||
basedir = settings._basedir
|
||||
|
||||
temporary_path = os.path.join(datafolder, ".{}".format(name))
|
||||
final_path = os.path.join(datafolder, name)
|
||||
|
||||
size = cls._get_disk_size(basedir)
|
||||
if not cls._free_space(os.path.dirname(temporary_path), size):
|
||||
raise InsufficientSpace()
|
||||
|
||||
own_folder = datafolder
|
||||
defaults = [os.path.join(basedir, "config.yaml"),] + \
|
||||
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
|
||||
|
||||
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
|
||||
|
||||
if callable(on_backup_start):
|
||||
on_backup_start(name, temporary_path, exclude)
|
||||
|
||||
with zipfile.ZipFile(temporary_path, "w", compression) as zip:
|
||||
def add_to_zip(source, target, ignored=None):
|
||||
if ignored is None:
|
||||
ignored = []
|
||||
|
||||
if source in ignored:
|
||||
return
|
||||
|
||||
if os.path.isdir(source):
|
||||
for entry in scandir(source):
|
||||
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
|
||||
elif os.path.isfile(source):
|
||||
zip.write(source, arcname=target)
|
||||
|
||||
# add metadata
|
||||
metadata = dict(version=get_octoprint_version_string(),
|
||||
excludes=exclude)
|
||||
zip.writestr("metadata.json", json.dumps(metadata))
|
||||
|
||||
# backup current config file
|
||||
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
|
||||
|
||||
# backup configured folder paths
|
||||
for folder in default_settings["folder"].keys():
|
||||
if folder in exclude:
|
||||
continue
|
||||
add_to_zip(settings.global_get_basefolder(folder),
|
||||
"basedir/" + folder.replace("_", "/"),
|
||||
ignored=[own_folder,])
|
||||
|
||||
# backup anything else that might be lying around in our basedir
|
||||
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
|
||||
|
||||
# add list of installed plugins
|
||||
plugins = []
|
||||
plugin_folder = settings.global_get_basefolder("plugins")
|
||||
for key, plugin in plugin_manager.plugins.items():
|
||||
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
|
||||
# ignore anything bundled or from the plugins folder we already include in the backup
|
||||
continue
|
||||
|
||||
plugins.append(dict(key=plugin.key,
|
||||
name=plugin.name,
|
||||
url=plugin.url))
|
||||
|
||||
if len(plugins):
|
||||
zip.writestr("plugin_list.json", json.dumps(plugins))
|
||||
|
||||
os.rename(temporary_path, final_path)
|
||||
|
||||
if callable(on_backup_done):
|
||||
on_backup_done(name, final_path, exclude)
|
||||
|
||||
@classmethod
|
||||
def _restore_backup(cls, path,
|
||||
settings=None,
|
||||
plugin_manager=None,
|
||||
datafolder=None,
|
||||
on_install_plugins=None,
|
||||
on_report_unknown_plugins=None,
|
||||
on_invalid_backup=None,
|
||||
on_log_progress=None,
|
||||
on_log_error=None,
|
||||
on_restore_start=None,
|
||||
on_restore_done=None,
|
||||
on_restore_failed=None):
|
||||
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
basedir = settings._basedir
|
||||
cls._clean_dir_backup(basedir,
|
||||
on_log_progress=on_log_progress)
|
||||
|
||||
plugin_repo = dict()
|
||||
repo_url = settings.global_get(["plugins", "pluginmanager", "repository"])
|
||||
if repo_url:
|
||||
plugin_repo = cls._get_plugin_repository_data(repo_url)
|
||||
|
||||
if callable(on_restore_start):
|
||||
on_restore_start(path)
|
||||
|
||||
try:
|
||||
|
||||
with zipfile.ZipFile(path, "r") as zip:
|
||||
# read metadata
|
||||
try:
|
||||
metadata_zipinfo = zip.getinfo("metadata.json")
|
||||
except KeyError:
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
|
||||
return False
|
||||
|
||||
metadata_bytes = zip.read(metadata_zipinfo)
|
||||
metadata = json.loads(metadata_bytes)
|
||||
|
||||
backup_version = get_comparable_version(metadata["version"])
|
||||
if backup_version > get_octoprint_version():
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
|
||||
return False
|
||||
|
||||
# unzip to temporary folder
|
||||
temp = tempfile.mkdtemp()
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacking backup to {}...".format(temp))
|
||||
abstemp = os.path.abspath(temp)
|
||||
for member in zip.infolist():
|
||||
abspath = os.path.abspath(os.path.join(temp, member.filename))
|
||||
if abspath.startswith(abstemp):
|
||||
zip.extract(member, temp)
|
||||
|
||||
# sanity check
|
||||
configfile = os.path.join(temp, "basedir", "config.yaml")
|
||||
if not os.path.exists(configfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks config.yaml")
|
||||
return False
|
||||
|
||||
import yaml
|
||||
|
||||
with codecs.open(configfile) as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
|
||||
if configdata.get("accessControl", dict()).get("enabled", True):
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup(u"Backup lacks users.yaml")
|
||||
return False
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Unpacked")
|
||||
|
||||
# install available plugins
|
||||
with codecs.open(os.path.join(temp, "plugin_list.json"), "r") as f:
|
||||
plugins = json.load(f)
|
||||
|
||||
known_plugins = []
|
||||
unknown_plugins = []
|
||||
if plugins:
|
||||
if plugin_repo:
|
||||
for plugin in plugins:
|
||||
if plugin["key"] in plugin_manager.plugins:
|
||||
# already installed
|
||||
continue
|
||||
|
||||
if plugin["key"] in plugin_repo:
|
||||
# not installed, can be installed from repository url
|
||||
known_plugins.append(plugin_repo[plugin["key"]])
|
||||
else:
|
||||
# not installed, not installable
|
||||
unknown_plugins.append(plugin)
|
||||
|
||||
else:
|
||||
# no repo, all plugins are not installable
|
||||
unknown_plugins = plugins
|
||||
|
||||
if callable(on_log_progress):
|
||||
if known_plugins:
|
||||
on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins))))
|
||||
if unknown_plugins:
|
||||
on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins))))
|
||||
|
||||
if callable(on_install_plugins):
|
||||
on_install_plugins(known_plugins)
|
||||
|
||||
if callable(on_report_unknown_plugins):
|
||||
on_report_unknown_plugins(unknown_plugins)
|
||||
|
||||
# move config data
|
||||
basedir_backup = basedir + ".bck"
|
||||
basedir_extracted = os.path.join(temp, "basedir")
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
|
||||
os.rename(basedir, basedir_backup)
|
||||
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
|
||||
os.rename(basedir_extracted, basedir)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
|
||||
on_log_error(u"Rolling back old config data")
|
||||
|
||||
os.rename(basedir_backup, basedir)
|
||||
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if unknown_plugins:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Writing info file about unknown plugins")
|
||||
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE)
|
||||
try:
|
||||
with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f:
|
||||
json.dump(unknown_plugins, f)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
|
||||
exc_info = sys.exc_info())
|
||||
|
||||
finally:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary unpacked folder")
|
||||
shutil.rmtree(temp)
|
||||
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while running restore", exc_info=sys.exc_info())
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
finally:
|
||||
# remove zip
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Removing temporary zip")
|
||||
os.remove(path)
|
||||
|
||||
# restart server
|
||||
if restart_command:
|
||||
import sarge
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(u"Restarting...")
|
||||
try:
|
||||
sarge.run(restart_command, async_=True)
|
||||
except:
|
||||
if callable(on_log_error):
|
||||
on_log_error(u"Error while restarting via command {}".format(restart_command),
|
||||
exc_info=sys.exc_info())
|
||||
on_log_error(u"Please restart OctoPrint manually")
|
||||
return False
|
||||
|
||||
if callable(on_restore_done):
|
||||
on_restore_done(path)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _send_client_message(self, message, payload=None):
|
||||
if payload is None:
|
||||
payload = dict()
|
||||
payload["type"] = message
|
||||
self._plugin_manager.send_plugin_message(self._identifier, payload)
|
||||
|
||||
|
||||
|
||||
class InsufficientSpace(Exception):
|
||||
pass
|
||||
|
||||
__plugin_name__ = gettext(u"Backup & Restore")
|
||||
__plugin_author__ = u"Gina Häußge"
|
||||
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
|
||||
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
|
||||
u"& restore your OctoPrint settings and data.")
|
||||
__plugin_license__ = u"AGPLv3"
|
||||
__plugin_implementation__ = BackupPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
|
||||
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
|
||||
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintBackupClient = function(base) {
|
||||
this.base = base;
|
||||
this.url = this.base.getBlueprintUrl("backup");
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.url, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
|
||||
exclude = exclude || [];
|
||||
|
||||
var data = {
|
||||
exclude: exclude
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url + "backup", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
|
||||
return this.base.delete(this.url + "backup/" + backup, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
|
||||
var data = {
|
||||
path: backup
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url + "restore", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) {
|
||||
data = data || {};
|
||||
|
||||
var filename = data.filename || undefined;
|
||||
return this.base.upload(this.url + "restore", file, filename, data);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) {
|
||||
return this.base.delete(this.url + "unknown_plugins", opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient);
|
||||
return OctoPrintBackupClient;
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
|
||||
@@ -0,0 +1,263 @@
|
||||
$(function() {
|
||||
function BackupViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
self.backups = new ItemListHelper(
|
||||
"plugin.backup.backups",
|
||||
{
|
||||
"date": function (a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"date",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
|
||||
self.markedForBackupDeletion = ko.observableArray([]);
|
||||
|
||||
self.excludeFromBackup = ko.observableArray([]);
|
||||
self.backupInProgress = ko.observable(false);
|
||||
|
||||
self.backupUploadButton = $("#settings-backup-upload");
|
||||
self.backupUploadData = undefined;
|
||||
self.backupUploadButton.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
if (data.files.length === 0) {
|
||||
// no files? ignore
|
||||
return false;
|
||||
}
|
||||
|
||||
self.backupUploadName(data.files[0].name);
|
||||
self.backupUploadData = data;
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.backupUploadName(undefined);
|
||||
self.backupUploadData = undefined;
|
||||
}
|
||||
});
|
||||
self.backupUploadName = ko.observable();
|
||||
self.restoreInProgress = ko.observable(false);
|
||||
self.restoreTitle = ko.observable();
|
||||
self.restoreDialog = undefined;
|
||||
self.restoreOutput = undefined;
|
||||
self.unknownPlugins = ko.observableArray([]);
|
||||
|
||||
self.loglines = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.backup.get()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.backups.updateItems(response.backups);
|
||||
self.unknownPlugins(response.unknown_plugins);
|
||||
};
|
||||
|
||||
self.createBackup = function() {
|
||||
var excluded = self.excludeFromBackup();
|
||||
OctoPrint.plugins.backup.createBackup(excluded)
|
||||
.done(function() {
|
||||
self.excludeFromBackup([]);
|
||||
})
|
||||
};
|
||||
|
||||
self.removeBackup = function(backup) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteBackup(backup)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.restoreBackup = function(backup) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.performRestoreFromUpload = function() {
|
||||
if (self.backupUploadData === undefined) return;
|
||||
|
||||
var perform = function() {
|
||||
self.backupUploadData.submit();
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.deleteUnknownPluginRecord = function() {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteUnknownPlugins()
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markFilesOnPage = function() {
|
||||
self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
|
||||
};
|
||||
|
||||
self.markAllFiles = function() {
|
||||
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedFiles = function() {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.removeMarkedFiles = function() {
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForBackupDeletion())
|
||||
.done(function() {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
|
||||
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "backup") return;
|
||||
|
||||
if (data.type === "backup_done") {
|
||||
self.requestData();
|
||||
self.backupInProgress(false);
|
||||
} else if (data.type === "backup_started") {
|
||||
self.backupInProgress(true);
|
||||
} else if (data.type === "restore_started") {
|
||||
self.restoreInProgress(true);
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
} else if (data.type === "restore_failed") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "restore_done") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
|
||||
self.restoreInProgress(false);
|
||||
} else if (data.type === "install_plugin") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}),
|
||||
stream: "message"
|
||||
});
|
||||
} else if (data.type === "plugin_incompatible") {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({
|
||||
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}),
|
||||
stream: "stderr"
|
||||
});
|
||||
} else if (data.type === "unknown_plugins") {
|
||||
if (data.plugins.length > 0) {
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"});
|
||||
_.each(data.plugins, function(plugin) {
|
||||
self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"});
|
||||
});
|
||||
self.loglines.push({line: " ", stream: "message"});
|
||||
self.unknownPlugins(data.plugins);
|
||||
}
|
||||
} else if (data.type === "logline") {
|
||||
self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream}));
|
||||
self._scrollRestoreOutputToEnd();
|
||||
}
|
||||
};
|
||||
|
||||
self._scrollRestoreOutputToEnd = function() {
|
||||
self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height());
|
||||
};
|
||||
|
||||
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
};
|
||||
|
||||
self._bulkRemove = function(files) {
|
||||
var title, message, handler;
|
||||
|
||||
title = gettext("Deleting backups");
|
||||
message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
|
||||
handler = function(filename) {
|
||||
return OctoPrint.plugins.backup.deleteBackup(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: files.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function(filename) {
|
||||
var request = handler(filename);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: BackupViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#settings_plugin_backup"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
#settings_plugin_backup_backup_table {
|
||||
.settings_plugin_backup_name {
|
||||
}
|
||||
.settings_plugin_backup_actions {
|
||||
width: 75px;
|
||||
text-align: center;
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
}
|
||||
.settings_plugin_backup_date {
|
||||
width: 200px;
|
||||
text-align: right;
|
||||
}
|
||||
.settings_plugin_backup_size {
|
||||
width: 100px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.settings_plugin_backup_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_backup_restoredialog_output {
|
||||
.message {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.error {
|
||||
font-weight: bold;
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.stdout {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.stderr {
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.call {
|
||||
color: #000099;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<div class="alert" data-bind="visible: unknownPlugins().length > 0">
|
||||
{% trans %}
|
||||
Some plugins during the last restore could not be identified and hence not automatically installed.
|
||||
Please install them manually, they are listed below including their stated homepages:
|
||||
{% endtrans %}
|
||||
<ul data-bind="foreach: unknownPlugins">
|
||||
<li><span data-bind="text: name"></span>: <a data-bind="text: url, attr: {href: url}" target="_blank" rel="noreferrer noopener"></a></li>
|
||||
</ul>
|
||||
<small><a href="javascript:void(0)" data-bind="click: deleteUnknownPluginRecord">{{ _('Delete record of unknown plugins') }}</a></small>
|
||||
</div>
|
||||
|
||||
|
||||
<h3>{{ _('Existing backups') }}</h3>
|
||||
|
||||
<div data-bind="visible: backups.allSize() <= 0">
|
||||
<p>{{ _('There are no backups. Maybe create one below?') }}</p>
|
||||
</div>
|
||||
<div data-bind="visible: backups.allSize() > 0">
|
||||
<p>{{ _('These are the backups of your settings and files that already exist on this OctoPrint instance. You may delete, download or restore them.') }}</p>
|
||||
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForBackupDeletion().length > 0">{{ _('Delete selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-condensed table-hover" id="settings_plugin_backup_backup_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_backup_checkbox"></th>
|
||||
<th class="settings_plugin_backup_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_backup_date">{{ _('Date') }}</th>
|
||||
<th class="settings_plugin_backup_size">{{ _('Size') }}</th>
|
||||
<th class="settings_plugin_backup_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: backups.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_backup_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForBackupDeletion"></td>
|
||||
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
|
||||
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
|
||||
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a> | <a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a> | <a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: backups.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: backups.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: backups.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.backups.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.backups.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: backups.currentPage() === backups.lastPage()}"><a href="javascript:void(0)" data-bind="click: backups.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Create backup') }}</h3>
|
||||
|
||||
<p>{{ _('Create a new backup of the current state.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: 'timelapse', checked: excludeFromBackup"> {{ _('Exclude timelapses from backup') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: createBackup"><i class="fa fa-spinner fa-spin" data-bind="visible: backupInProgress"></i> {{ _('Create backup now') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<h3>{{ _('Restore from uploaded backup') }}</h3>
|
||||
|
||||
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Backup file') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="btn fileinput-button">
|
||||
<span>{{ _('Browse...') }}</span>
|
||||
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
|
||||
</span>
|
||||
<span class="add-on" data-bind="text: backupUploadName"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div id="settings_plugin_backup_restoredialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<h3>{{ _('Restoring from backup...') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_backup_restoredialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.restoreInProgress()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,14 +1,22 @@
|
||||
<h3>{{ _('Access Control') }}</h3>
|
||||
|
||||
{% trans %}<p>
|
||||
{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}<p>
|
||||
<strong>Please read the following, it is very important for your printer's health!</strong>
|
||||
</p>
|
||||
<p>
|
||||
OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
|
||||
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
|
||||
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
|
||||
malicious intent - to gain access to your printer</strong> via an untrustworthy network
|
||||
and using it in such a way that it is damaged or worse (i.e. causes a fire).
|
||||
</p>
|
||||
<p>
|
||||
If you plan on accessing OctoPrint remotely over the internet, <strong>you should not only rely on the built-in
|
||||
Access Control mechanisms</strong> however -
|
||||
<a href="{{ safe_remote_url }}" target="_blank" rel="noopener noreferrer">take additional precautions</a>.
|
||||
Your OctoPrint enabled printer is a critical home appliance you really should not give anyone who happens to be
|
||||
connected to the internet access to - even read-only! <strong>An instance available publicly on the internet
|
||||
will be found, and people will try to break it open.</strong>
|
||||
</p>
|
||||
<p>
|
||||
It looks like you haven't configured access control yet. Please <strong>set up a username and password</strong> for the
|
||||
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
|
||||
@@ -36,12 +44,12 @@
|
||||
</div>
|
||||
</form>
|
||||
{% trans %}<p>
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy local network and you don't
|
||||
need Access Control for other reasons, you may alternatively disable Access Control. You should only
|
||||
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
|
||||
<strong>Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!</strong>
|
||||
</p>{% endtrans %}
|
||||
|
||||
<div class="row-fluid">
|
||||
|
||||
@@ -359,6 +359,8 @@ class Profile(object):
|
||||
regex_print_temperature = re.compile("print_temperature(\d?)")
|
||||
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
|
||||
|
||||
regex_broken_replacements = re.compile("\?([a-zA-Z0-9_]*)\?")
|
||||
|
||||
@classmethod
|
||||
def from_cura_ini(cls, path):
|
||||
import logging
|
||||
@@ -685,9 +687,9 @@ class Profile(object):
|
||||
gcode = defaults[key]
|
||||
|
||||
if key in ("start_gcode", "end_gcode"):
|
||||
return gcode[extruder_count-1]
|
||||
return self.regex_broken_replacements.sub("{\\1}", gcode[extruder_count-1])
|
||||
else:
|
||||
return gcode
|
||||
return self.regex_broken_replacements.sub("{\\1}", gcode)
|
||||
|
||||
def get_profile_string(self):
|
||||
import base64
|
||||
@@ -749,17 +751,16 @@ class Profile(object):
|
||||
|
||||
if key == "start_gcode":
|
||||
contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count)
|
||||
prefix += self.get_start_gcode_prefix(contents)
|
||||
prefix += self.get_start_gcode_prefix(contents, extruder_count=extruder_count)
|
||||
|
||||
else:
|
||||
contents = self.get_gcode_template(key, extruder_count=extruder_count)
|
||||
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
|
||||
|
||||
def get_start_gcode_prefix(self, contents):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
def get_start_gcode_prefix(self, contents, extruder_count=1):
|
||||
prefix = ""
|
||||
without_comments = Profile.regex_strip_comments.sub("", contents)
|
||||
|
||||
gcode_parameter_key = "S"
|
||||
if self.get("gcode_flavor") == GcodeFlavors.MACH3:
|
||||
@@ -773,12 +774,12 @@ class Profile(object):
|
||||
bed_temp = 0
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
bed_temp = self.get_float("print_bed_temperature")
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in without_comments
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M140 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp)
|
||||
|
||||
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
|
||||
if temp > 0 and not "{print_temperature}" in without_comments:
|
||||
if extruder_count > 0:
|
||||
def temp_line(temp, extruder, param, template):
|
||||
t = temp
|
||||
|
||||
@@ -181,6 +181,15 @@ $(function() {
|
||||
self.uploadDialog.modal("hide");
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
self.uploadBusy(false);
|
||||
new PNotify({
|
||||
title: gettext("Profile import failed"),
|
||||
text: gettext("Could not import the provided profile, it might be invalid. Check <code>octoprint.log</code> for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -194,8 +194,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
params["txtRecord"] = pybonjour.TXTRecord(txt_record)
|
||||
|
||||
key = (reg_type, port)
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
|
||||
|
||||
counter = 1
|
||||
while True:
|
||||
try:
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self._logger.info(u"Registered '{name}' for {regtype}".format(**params))
|
||||
return True
|
||||
except pybonjour.BonjourError as be:
|
||||
if be.errorCode == pybonjour.kDNSServiceErr_NameConflict:
|
||||
# Name already registered by different service, let's try a counter postfix. See #2852
|
||||
counter += 1
|
||||
params["name"] = u"{} ({})".format(name, counter)
|
||||
else:
|
||||
raise
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import flask
|
||||
import flask_login
|
||||
from flask_babel import gettext
|
||||
|
||||
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/viewmodel.js"]
|
||||
)
|
||||
|
||||
def will_handle_ui(self, request):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return False
|
||||
|
||||
from octoprint.server.util.flask import passive_login
|
||||
|
||||
result = passive_login()
|
||||
if hasattr(result, "status_code") and result.status_code == 200:
|
||||
# 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.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return
|
||||
|
||||
if flask.request.endpoint in ("api.login",):
|
||||
return
|
||||
|
||||
user = flask_login.current_user
|
||||
if user is None or user.is_anonymous or not user.is_active:
|
||||
return flask.make_response("Forbidden", 403)
|
||||
|
||||
return [check_login_required]
|
||||
|
||||
def access_validator(self, request):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return
|
||||
|
||||
import tornado.web
|
||||
from octoprint.server.util.flask import get_flask_user_from_request
|
||||
|
||||
user = get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated():
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
def socket_register_validator(self, socket, user):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
|
||||
return user is not None and not user.is_anonymous and user.is_active
|
||||
|
||||
def socket_emit_validator(self, socket, user, message, payload):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
|
||||
if message in ("connected", "reauthRequired"):
|
||||
return True
|
||||
|
||||
return user is not None and not user.is_anonymous and user.is_active
|
||||
|
||||
|
||||
__plugin_name__ = "Force Login"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Forces users to login, disables read-only mode."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your "
|
||||
"OctoPrint instance. Only disable this if you are comfortable with this, your "
|
||||
"OctoPrint instance is not publicly reachable on the internet and you fully "
|
||||
"trust everyone who has access to your local network!")
|
||||
|
||||
__plugin_implementation__ = ForceLoginPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
|
||||
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
|
||||
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
|
||||
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Will get included into the login dialog, NOT into the regular OctoPrint
|
||||
* web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
var overlayElement = $("#login-overlay");
|
||||
var errorElement = $("#login-error");
|
||||
var offlineElement = $("#login-offline");
|
||||
var buttonElement = $("#login-button");
|
||||
var reconnectElement = $("#login-reconnect");
|
||||
|
||||
buttonElement.click(function() {
|
||||
var usernameElement = $("#login-user");
|
||||
var passwordElement = $("#login-password");
|
||||
var rememberElement = $("#login-remember");
|
||||
|
||||
var username = usernameElement.val();
|
||||
var password = passwordElement.val();
|
||||
var remember = rememberElement.checked;
|
||||
|
||||
overlayElement.addClass("in");
|
||||
errorElement.removeClass("in");
|
||||
|
||||
OctoPrint.browser.login(username, password, remember)
|
||||
.done(function() {
|
||||
location.reload();
|
||||
})
|
||||
.fail(function() {
|
||||
usernameElement.val("");
|
||||
passwordElement.val("");
|
||||
|
||||
overlayElement.removeClass("in");
|
||||
errorElement.addClass("in");
|
||||
});
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
var OctoPrint = window.OctoPrint;
|
||||
|
||||
OctoPrint.options.baseurl = BASE_URL;
|
||||
|
||||
OctoPrint.socket.onMessage("connected", function(data) {
|
||||
var payload = data.data;
|
||||
OctoPrint.options.apikey = payload.apikey;
|
||||
|
||||
// update the API key directly in jquery's ajax options too,
|
||||
// to ensure the fileupload plugin and any plugins still using
|
||||
// $.ajax directly still work fine too
|
||||
UI_API_KEY = payload["apikey"];
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
});
|
||||
|
||||
OctoPrint.socket.onConnected = function() {
|
||||
buttonElement.prop("disabled", false);
|
||||
offlineElement.removeClass("in");
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function() {
|
||||
buttonElement.prop("disabled", true);
|
||||
offlineElement.addClass("in");
|
||||
};
|
||||
|
||||
reconnectElement.click(function() {
|
||||
OctoPrint.socket.reconnect();
|
||||
});
|
||||
|
||||
OctoPrint.socket.connect();
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* View model that takes care to redirect to / on logout in the regular
|
||||
* OctoPrint web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
function ForceLoginViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([ForceLoginViewModel, [], []]);
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
body {
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.form-signin {
|
||||
max-width: 300px;
|
||||
padding: 19px 29px 29px;
|
||||
margin: 0 auto 20px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #e5e5e5;
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
|
||||
.form-signin-heading, .checkbox {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
input[type="text"], input[type="password"] {
|
||||
font-size: 16px;
|
||||
height: auto;
|
||||
margin-bottom: 15px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
}
|
||||
|
||||
#login-error,
|
||||
#login-offline {
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
#login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.background {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #000000;
|
||||
filter:alpha(opacity=50);
|
||||
-moz-opacity:0.5;
|
||||
-khtml-opacity: 0.5;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
|
||||
.outer {
|
||||
display: table;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.inner {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
|
||||
.content {
|
||||
text-align: center;
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>OctoPrint Login</title>
|
||||
|
||||
{% include "parts/forcelogin_css.jinja2" %}
|
||||
|
||||
{% include "parts/forcelogin_javascripts.jinja2" %}
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin">
|
||||
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
|
||||
|
||||
<div id="login-error" class="alert alert-error">{{ _('Incorrect username or password.') }}</div>
|
||||
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
|
||||
|
||||
<input type="text" id="login-user" class="input-block-level" placeholder="{{ _('Username') }}">
|
||||
<input type="password" id="login-password" class="input-block-level" placeholder="{{ _('Password') }}">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="login-remember"> {{ _('Remember me') }}
|
||||
</label>
|
||||
<button class="btn btn-block btn-large btn-primary" id="login-button" type="submit">{{ _('Log in') }}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="login-overlay">
|
||||
<div class="background"></div>
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<i class="fa fa-spinner fa-spin fa-4x"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,10 @@
|
||||
<!-- le CSS -->
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("plugin.forcelogin.static", filename="css/forcelogin.css") }}">
|
||||
|
||||
{% for url in forcelogin_theming %}
|
||||
<link rel="stylesheet" href="{{ url }}">
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,15 @@
|
||||
<!-- le javascript -->
|
||||
|
||||
<script>
|
||||
var BASE_URL = "{{ url_for('index') }}";
|
||||
</script>
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
{% assets "js_client" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
<script src="{{ url_for("plugin.forcelogin.static", filename="js/main.js") }}"></script>
|
||||
@@ -8,7 +8,7 @@ import octoprint.plugin
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import redirect_to_tornado, require_firstrun
|
||||
from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
@@ -41,7 +41,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
]
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_all(self):
|
||||
files = self._getLogFiles()
|
||||
@@ -52,7 +52,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
setup=dict(loggers=loggers, levels=levels))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_log_files(self):
|
||||
files = self._getLogFiles()
|
||||
@@ -60,13 +60,13 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return jsonify(files=files, free=free, total=total)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def download_log(self, filename):
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def delete_log(self, filename):
|
||||
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
|
||||
@@ -78,7 +78,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_logging_setup(self):
|
||||
loggers = self._get_available_loggers()
|
||||
@@ -86,13 +86,13 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return jsonify(loggers=loggers, levels=levels)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_logging_levels_api(self):
|
||||
return jsonify(self._get_logging_levels())
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def set_logging_levels_api(self):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
@@ -208,6 +208,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;
|
||||
|
||||
@@ -193,6 +193,7 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/pi_support.js"],
|
||||
clientjs=["clientjs/pi_support.js"],
|
||||
css=["css/pi_support.css"]
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPiSupportClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPiSupportClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
|
||||
return OctoPrintPiSupportClient;
|
||||
});
|
||||
|
||||
@@ -1,22 +1,3 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPiSupportClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPiSupportClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
|
||||
return OctoPrintPiSupportClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
|
||||
function PiSupportViewModel(parameters) {
|
||||
|
||||
@@ -11,11 +11,11 @@ import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import get_os
|
||||
from octoprint.util.platform import get_os, is_os_compatible
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask_babel import gettext
|
||||
@@ -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,
|
||||
@@ -155,6 +184,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/pluginmanager.js"],
|
||||
clientjs=["clientjs/pluginmanager.js"],
|
||||
css=["css/pluginmanager.css"],
|
||||
less=["less/pluginmanager.less"]
|
||||
)
|
||||
@@ -183,7 +213,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403)
|
||||
def upload_archive(self):
|
||||
import flask
|
||||
@@ -358,10 +388,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)
|
||||
|
||||
@@ -797,31 +823,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if repo_data is None:
|
||||
return False
|
||||
|
||||
current_os = get_os()
|
||||
octoprint_version = get_octoprint_version(base=True)
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = copy.deepcopy(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True
|
||||
)
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
|
||||
result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"],
|
||||
octoprint_version=octoprint_version)
|
||||
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
|
||||
|
||||
return result
|
||||
|
||||
self._repository_plugins = list(map(map_repository_entry, repo_data))
|
||||
self._repository_plugins = map(map_repository_entry, repo_data)
|
||||
return True
|
||||
|
||||
def _fetch_notices_from_disk(self):
|
||||
@@ -892,30 +894,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;
|
||||
|
||||
@@ -91,6 +91,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;
|
||||
|
||||
@@ -24,13 +24,21 @@ from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import VERSION, REVISION, BRANCH
|
||||
from octoprint.access import USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util import dict_merge, to_unicode
|
||||
from octoprint.util.version import get_comparable_version
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
import octoprint.settings
|
||||
|
||||
|
||||
MINIMUM_PYTHON = "2.7.9"
|
||||
MINIMUM_SETUPTOOLS = "5.5.1"
|
||||
MINIMUM_PIP = "9.0.1"
|
||||
|
||||
|
||||
##~~ Plugin
|
||||
|
||||
class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
@@ -43,7 +51,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
|
||||
DATA_FORMAT_VERSION = "v3"
|
||||
DATA_FORMAT_VERSION = "v4"
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
@@ -62,6 +70,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = None
|
||||
|
||||
self._environment_supported = False
|
||||
self._environment_versions = dict()
|
||||
self._environment_ready = threading.Event()
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
def initialize(self):
|
||||
@@ -108,6 +120,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# the server startup
|
||||
def fetch_data():
|
||||
self.get_current_versions()
|
||||
self._check_environment()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
@@ -181,6 +194,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
|
||||
@@ -489,7 +520,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
#~~ BluePrint API
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403)
|
||||
def check_for_update(self):
|
||||
if "check" in flask.request.values:
|
||||
@@ -500,11 +531,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
force = flask.request.values.get("force", "false") in octoprint.settings.valid_boolean_trues
|
||||
|
||||
def view():
|
||||
self._environment_ready.wait()
|
||||
|
||||
try:
|
||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||
return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible and self._environment_supported else "updateAvailable" if update_available else "current",
|
||||
information=information,
|
||||
timestamp=self._version_cache_timestamp))
|
||||
timestamp=self._version_cache_timestamp,
|
||||
environment=dict(supported=self._environment_supported,
|
||||
versions=[dict(name=gettext("Python"), current=self._environment_versions.get("python", "unknown"), minimum=MINIMUM_PYTHON),
|
||||
dict(name=gettext("pip"), current=self._environment_versions.get("pip", "unknown"), minimum=MINIMUM_PIP),
|
||||
dict(name=gettext("setuptools"), current=self._environment_versions.get("setuptools", "unknown"), minimum=MINIMUM_SETUPTOOLS)])))
|
||||
except exceptions.ConfigurationInvalid as e:
|
||||
return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
|
||||
|
||||
@@ -531,6 +568,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(str(data.get("online", None)))
|
||||
|
||||
hash.update(",".join(targets))
|
||||
|
||||
hash.update(str(self._environment_supported))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
hash.update(str(self._connectivity_checker.online))
|
||||
hash.update(str(self._update_in_progress))
|
||||
@@ -546,13 +585,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
|
||||
def perform_update(self):
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
# do not update while a print job is running
|
||||
return flask.make_response("Printer is currently printing or paused", 409)
|
||||
|
||||
if not self._environment_supported:
|
||||
return flask.make_response("Direct updates are not supported in this Python environment", 409)
|
||||
|
||||
if not "application/json" in flask.request.headers["Content-Type"]:
|
||||
return flask.make_response("Expected content-type JSON", 400)
|
||||
|
||||
@@ -579,6 +621,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
return dict(
|
||||
css=["css/softwareupdate.css"],
|
||||
js=["js/softwareupdate.js"],
|
||||
clientjs=["clientjs/softwareupdate.js"],
|
||||
less=["less/softwareupdate.less"]
|
||||
)
|
||||
|
||||
@@ -665,6 +708,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="?",
|
||||
@@ -798,6 +842,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()
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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;
|
||||
@@ -117,6 +32,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());
|
||||
@@ -133,6 +51,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());
|
||||
@@ -301,6 +223,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;
|
||||
@@ -315,7 +240,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>";
|
||||
@@ -323,7 +248,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.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) {
|
||||
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
|
||||
|
||||
@@ -201,6 +201,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
sha = hashlib.sha1()
|
||||
sha.update(payload.get("name"))
|
||||
sha.update(self._settings.get([b"unique_id"]))
|
||||
|
||||
track_event = None
|
||||
args = dict(origin=payload.get(b"origin"), file=sha.hexdigest())
|
||||
|
||||
@@ -647,6 +647,19 @@ class VirtualPrinter(object):
|
||||
else:
|
||||
time.sleep(_timeout)
|
||||
|
||||
def _gcode_G33(self, data):
|
||||
self._send("G33 Auto Calibrate")
|
||||
self._send("Will take ~60s")
|
||||
timeout = 60
|
||||
|
||||
if self._sendBusy and self._busyInterval > 0:
|
||||
until = time.time() + timeout
|
||||
while time.time() < until:
|
||||
time.sleep(self._busyInterval)
|
||||
self._send("busy:processing")
|
||||
else:
|
||||
time.sleep(timeout)
|
||||
|
||||
##~~ further helpers
|
||||
|
||||
def _calculate_checksum(self, line):
|
||||
@@ -719,6 +732,10 @@ class VirtualPrinter(object):
|
||||
| Triggers a resend error with a missing checksum
|
||||
trigger_missing_lineno
|
||||
| Triggers a "no line number with checksum" error w/o resend request
|
||||
trigger_fatal_error_marlin
|
||||
| Triggers a fatal error/simulated heater fail, Marlin style
|
||||
trigger_fatal_error_repetier
|
||||
| Triggers a fatal error/simulated heater fail, Repetier style
|
||||
drop_connection
|
||||
| Drops the serial connection
|
||||
prepare_ok <broken ok>
|
||||
@@ -769,6 +786,11 @@ class VirtualPrinter(object):
|
||||
self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, checksum=False))
|
||||
elif data == "trigger_missing_lineno":
|
||||
self._prepared_errors.append(lambda cur, last, line: self._send(self._error("lineno_missing", last)))
|
||||
elif data == "trigger_fatal_error_marlin":
|
||||
self._send("Error:Thermal Runaway, system stopped! Heater_ID: bed")
|
||||
self._send("Error:Printer halted. kill() called!")
|
||||
elif data == "trigger_fatal_error_repetier":
|
||||
self._send("fatal: Heater/sensor error - Printer stopped and heaters disabled due to this error. Fix error and restart with M999.")
|
||||
elif data == "drop_connection":
|
||||
self._debug_drop_connection = True
|
||||
elif data == "reset":
|
||||
|
||||
@@ -231,12 +231,14 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def extrude(self, amount, tags=None, *args, **kwargs):
|
||||
def extrude(self, amount, speed=None, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Extrude ``amount`` millimeters of material from the tool.
|
||||
|
||||
Arguments:
|
||||
amount (int, float): The amount of material to extrude in mm
|
||||
speed (int, None): Speed at which to extrude (F parameter). If set to ``None`` (or left out)
|
||||
the maximum speed of E axis from the printer profile will be used.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@@ -366,12 +366,22 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"],
|
||||
tags=kwargs.get("tags", set) | {"trigger:printer.home"})
|
||||
|
||||
def extrude(self, amount, *args, **kwargs):
|
||||
def extrude(self, amount, speed=None, *args, **kwargs):
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
||||
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
extrusion_speed = printer_profile["axes"]["e"]["speed"]
|
||||
|
||||
# Use specified speed (if any)
|
||||
max_e_speed = printer_profile["axes"]["e"]["speed"]
|
||||
|
||||
if speed is None:
|
||||
# No speed was specified so default to value configured in printer profile
|
||||
extrusion_speed = max_e_speed
|
||||
else:
|
||||
# Make sure that specified value is not greater than maximum as defined in printer profile
|
||||
extrusion_speed = min([speed, max_e_speed])
|
||||
|
||||
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"],
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"})
|
||||
|
||||
|
||||
@@ -578,14 +578,27 @@ class Server(object):
|
||||
|
||||
##~~ Permission validators
|
||||
|
||||
timelapse_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.TIMELAPSE_LIST))
|
||||
download_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.FILES_DOWNLOAD))
|
||||
log_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.PLUGIN_LOGGING_MANAGE))
|
||||
camera_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.WEBCAM))
|
||||
access_validators_from_plugins = []
|
||||
for plugin, hook in pluginManager.get_hooks("octoprint.server.http.access_validator").items():
|
||||
try:
|
||||
access_validators_from_plugins.append(util.tornado.access_validation_factory(app, hook))
|
||||
except:
|
||||
self._logger.exception("Error while adding tornado access validator from plugin {}".format(plugin))
|
||||
access_validator = dict(access_validation=util.tornado.validation_chain(*access_validators_from_plugins))
|
||||
|
||||
timelapse_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.TIMELAPSE_LIST),] + access_validators_from_plugins
|
||||
download_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.FILES_DOWNLOAD),] + access_validators_from_plugins
|
||||
log_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.PLUGIN_LOGGING_MANAGE),] + access_validators_from_plugins
|
||||
camera_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.WEBCAM),] + access_validators_from_plugins
|
||||
|
||||
timelapse_permission_validator = dict(access_validation=util.tornado.validation_chain(*timelapse_validators))
|
||||
download_permission_validator = dict(access_validation=util.tornado.validation_chain(*download_validators))
|
||||
log_permission_validator = dict(access_validation=util.tornado.validation_chain(*log_validators))
|
||||
camera_permission_validator = dict(access_validation=util.tornado.validation_chain(*camera_validators))
|
||||
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path),
|
||||
status_code=404))
|
||||
timelapse_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path) and octoprint.timelapse.valid_timelapse(path),
|
||||
timelapse_path_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path) and octoprint.timelapse.valid_timelapse(path),
|
||||
status_code=404))
|
||||
|
||||
def joined_dict(*dicts):
|
||||
@@ -605,7 +618,7 @@ class Server(object):
|
||||
(r"/downloads/timelapse/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
|
||||
timelapse_permission_validator,
|
||||
download_handler_kwargs,
|
||||
timelapse_validator)),
|
||||
timelapse_path_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads"),
|
||||
as_attachment=True,
|
||||
name_generator=download_name_generator),
|
||||
@@ -619,7 +632,7 @@ class Server(object):
|
||||
log_permission_validator)),
|
||||
# camera snapshot
|
||||
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, joined_dict(dict(url=self._settings.get(["webcam", "snapshot"]),
|
||||
as_attachment=True),
|
||||
as_attachment=True),
|
||||
camera_permission_validator)),
|
||||
# generated webassets
|
||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"))),
|
||||
@@ -1150,16 +1163,25 @@ class Server(object):
|
||||
def _setup_blueprints(self):
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.apps import apps, clear_registered_app
|
||||
import octoprint.server.views
|
||||
|
||||
app.register_blueprint(api, url_prefix="/api")
|
||||
app.register_blueprint(apps, url_prefix="/apps")
|
||||
import octoprint.server.views # do not remove or the index view won't be found
|
||||
|
||||
blueprints = OrderedDict()
|
||||
blueprints["/api"] = api
|
||||
blueprints["/apps"] = apps
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
self._register_blueprint_plugins()
|
||||
blueprints.update(self._prepare_blueprint_plugins())
|
||||
|
||||
# and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves
|
||||
self._register_asset_plugins()
|
||||
blueprints.update(self._prepare_asset_plugins())
|
||||
|
||||
# make sure all before/after_request hook results are attached as well
|
||||
self._add_plugin_request_handlers_to_blueprints(*blueprints.values())
|
||||
|
||||
# register everything with the system
|
||||
for url_prefix, blueprint in blueprints.items():
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
|
||||
global pluginLifecycleManager
|
||||
def clear_apps(name, plugin):
|
||||
@@ -1167,27 +1189,37 @@ class Server(object):
|
||||
pluginLifecycleManager.add_callback("enabled", clear_apps)
|
||||
pluginLifecycleManager.add_callback("disabled", clear_apps)
|
||||
|
||||
def _register_blueprint_plugins(self):
|
||||
def _prepare_blueprint_plugins(self):
|
||||
blueprints = OrderedDict()
|
||||
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin)
|
||||
for plugin in blueprint_plugins:
|
||||
try:
|
||||
self._register_blueprint_plugin(plugin)
|
||||
blueprint, prefix = self._prepare_blueprint_plugin(plugin)
|
||||
blueprints[prefix] = blueprint
|
||||
except:
|
||||
self._logger.exception("Error while registering blueprint of plugin {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
|
||||
def _register_asset_plugins(self):
|
||||
return blueprints
|
||||
|
||||
def _prepare_asset_plugins(self):
|
||||
blueprints = OrderedDict()
|
||||
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for plugin in asset_plugins:
|
||||
if isinstance(plugin, octoprint.plugin.BlueprintPlugin):
|
||||
continue
|
||||
try:
|
||||
self._register_asset_plugin(plugin)
|
||||
blueprint, prefix = self._prepare_asset_plugin(plugin)
|
||||
blueprints[prefix] = blueprint
|
||||
except:
|
||||
self._logger.exception("Error while registering assets of plugin {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
|
||||
def _register_blueprint_plugin(self, plugin):
|
||||
return blueprints
|
||||
|
||||
def _prepare_blueprint_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
blueprint = plugin.get_blueprint()
|
||||
if blueprint is None:
|
||||
@@ -1209,7 +1241,9 @@ class Server(object):
|
||||
if self._logger:
|
||||
self._logger.debug("Registered API of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix))
|
||||
|
||||
def _register_asset_plugin(self, plugin):
|
||||
return blueprint, url_prefix
|
||||
|
||||
def _prepare_asset_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
|
||||
url_prefix = "/plugin/{name}".format(name=name)
|
||||
@@ -1219,6 +1253,32 @@ class Server(object):
|
||||
if self._logger:
|
||||
self._logger.debug("Registered assets of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix))
|
||||
|
||||
return blueprint, url_prefix
|
||||
|
||||
def _add_plugin_request_handlers_to_blueprints(self, *blueprints):
|
||||
before_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.before_request")
|
||||
after_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.after_request")
|
||||
|
||||
for plugin, hook in before_hooks.items():
|
||||
for blueprint in blueprints:
|
||||
try:
|
||||
result = hook()
|
||||
if isinstance(result, (list, tuple)):
|
||||
for h in result:
|
||||
blueprint.before_request(h)
|
||||
except:
|
||||
self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin))
|
||||
|
||||
for plugin, hook in after_hooks.items():
|
||||
for blueprint in blueprints:
|
||||
try:
|
||||
result = hook()
|
||||
if isinstance(result, (list, tuple)):
|
||||
for h in result:
|
||||
blueprint.after_request(h)
|
||||
except:
|
||||
self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin))
|
||||
|
||||
def _setup_assets(self):
|
||||
global app
|
||||
global assets
|
||||
@@ -1431,13 +1491,15 @@ class Server(object):
|
||||
js_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["js"],
|
||||
filters="js_delimiter_bundler")
|
||||
|
||||
clientjs_core = dynamic_core_assets["clientjs"] + \
|
||||
all_assets_for_plugins(dynamic_plugin_assets["bundled"]["clientjs"])
|
||||
clientjs_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["clientjs"],
|
||||
filters="js_delimiter_bundler")
|
||||
|
||||
js_libs_bundle = Bundle(*js_libs,
|
||||
output="webassets/packed_libs.js",
|
||||
filters=",".join(js_filters))
|
||||
|
||||
js_client_bundle = Bundle(*js_client,
|
||||
output="webassets/packed_client.js",
|
||||
filters=",".join(js_filters))
|
||||
js_core_bundle = Bundle(*js_core,
|
||||
output="webassets/packed_core.js",
|
||||
filters=",".join(js_filters))
|
||||
@@ -1453,6 +1515,21 @@ class Server(object):
|
||||
output="webassets/packed_app.js",
|
||||
filters=",".join(js_filters))
|
||||
|
||||
js_client_core_bundle = Bundle(*clientjs_core,
|
||||
output="webassets/packed_client_core.js",
|
||||
filters=",".join(js_filters))
|
||||
|
||||
if len(clientjs_plugins) == 0:
|
||||
js_client_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
js_client_plugins_bundle = Bundle(*clientjs_plugins.values(),
|
||||
output="webassets/packed_client_plugins.js",
|
||||
filters=",".join(js_plugin_filters))
|
||||
|
||||
js_client_bundle = Bundle(js_client_core_bundle, js_client_plugins_bundle,
|
||||
output="webassets/packed_client.js",
|
||||
filters=",".join(js_filters))
|
||||
|
||||
# -- CSS -------------------------------------------------------------------------------------------------------
|
||||
|
||||
css_filters = ["cssrewrite"]
|
||||
@@ -1512,6 +1589,11 @@ class Server(object):
|
||||
# -- asset registration ----------------------------------------------------------------------------------------
|
||||
|
||||
assets.register("js_libs", js_libs_bundle)
|
||||
assets.register("js_client_core", js_client_core_bundle)
|
||||
for plugin, bundle in clientjs_plugins.items():
|
||||
# register our collected clientjs plugin bundles so that they are bound to the environment
|
||||
assets.register("js_client_plugin_{}".format(plugin), bundle)
|
||||
assets.register("js_client_plugins", js_client_plugins_bundle)
|
||||
assets.register("js_client", js_client_bundle)
|
||||
assets.register("js_core", js_core_bundle)
|
||||
for plugin, bundle in js_plugins.items():
|
||||
|
||||
@@ -12,12 +12,13 @@ from flask_login import login_user, logout_user, current_user
|
||||
from flask_principal import Identity, identity_changed, AnonymousIdentity
|
||||
|
||||
import octoprint.access.users
|
||||
import octoprint.util.net as util_net
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request, passive_login
|
||||
from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request, passive_login, get_remote_address
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
|
||||
@@ -73,7 +74,7 @@ def pluginData(name):
|
||||
#~~ commands for plugins
|
||||
|
||||
@api.route("/plugin/<string:name>", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def pluginCommand(name):
|
||||
api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations(lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin)
|
||||
|
||||
@@ -169,7 +170,7 @@ def wizardFinish():
|
||||
|
||||
|
||||
@api.route("/state", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def apiPrinterState():
|
||||
return make_response(("/api/state has been deprecated, use /api/printer instead", 405, []))
|
||||
|
||||
@@ -215,7 +216,16 @@ def login():
|
||||
g.user = user
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user)
|
||||
|
||||
remote_addr = get_remote_address(request)
|
||||
logging.getLogger(__name__).info("Actively logging in user {} from {}".format(user.get_id(), remote_addr))
|
||||
|
||||
response = user.as_dict()
|
||||
response["_is_external_client"] = s().getBoolean(["server", "ipCheck", "enabled"]) \
|
||||
and not util_net.is_lan_address(remote_addr,
|
||||
additional_private=s().get(["server", "ipCheck", "trustedSubnets"]))
|
||||
return jsonify(response)
|
||||
|
||||
return make_response(("User unknown or password incorrect", 401, []))
|
||||
|
||||
elif "passive" in data:
|
||||
@@ -245,7 +255,7 @@ def _logout(user):
|
||||
|
||||
|
||||
@api.route("/util/test", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.ADMIN.require(403)
|
||||
def utilTest():
|
||||
valid_commands = dict(
|
||||
|
||||
@@ -14,7 +14,7 @@ import octoprint.access.users as users
|
||||
|
||||
from octoprint.server import SUCCESS, groupManager, userManager
|
||||
from octoprint.server.api import api, valid_boolean_trues
|
||||
from octoprint.server.util.flask import require_firstrun
|
||||
from octoprint.server.util.flask import no_firstrun_access
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
#~~ permission api
|
||||
@@ -26,14 +26,14 @@ def get_permissions():
|
||||
#~~ group api
|
||||
|
||||
@api.route("/access/groups", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def get_groups():
|
||||
return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups)))
|
||||
|
||||
|
||||
@api.route("/access/groups", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def add_group():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
@@ -65,7 +65,7 @@ def add_group():
|
||||
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def get_group(key):
|
||||
group = groupManager.find_group(key)
|
||||
@@ -76,7 +76,7 @@ def get_group(key):
|
||||
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["PUT"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def update_group(key):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
@@ -109,7 +109,7 @@ def update_group(key):
|
||||
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def remove_group(key):
|
||||
try:
|
||||
@@ -123,7 +123,7 @@ def remove_group(key):
|
||||
#~~ user api
|
||||
|
||||
@api.route("/access/users", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def get_users():
|
||||
if not userManager.enabled:
|
||||
@@ -133,7 +133,7 @@ def get_users():
|
||||
|
||||
|
||||
@api.route("/access/users", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def add_user():
|
||||
if not userManager.enabled:
|
||||
@@ -172,7 +172,7 @@ def add_user():
|
||||
|
||||
|
||||
@api.route("/access/users/<username>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def get_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
@@ -188,7 +188,7 @@ def get_user(username):
|
||||
|
||||
|
||||
@api.route("/access/users/<username>", methods=["PUT"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def update_user(username):
|
||||
if not userManager.enabled:
|
||||
@@ -228,7 +228,7 @@ def update_user(username):
|
||||
|
||||
|
||||
@api.route("/access/users/<username>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def remove_user(username):
|
||||
if not userManager.enabled:
|
||||
@@ -242,7 +242,7 @@ def remove_user(username):
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/password", methods=["PUT"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def change_password_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
@@ -273,7 +273,7 @@ def change_password_for_user(username):
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/settings", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def get_settings_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
@@ -287,7 +287,7 @@ def get_settings_for_user(username):
|
||||
return make_response("Unknown user: %s" % username, 404)
|
||||
|
||||
@api.route("/access/users/<username>/settings", methods=["PATCH"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def change_settings_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
@@ -310,7 +310,7 @@ def change_settings_for_user(username):
|
||||
return make_response("Unknown user: %s" % username, 404)
|
||||
|
||||
@api.route("/access/users/<username>/apikey", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def delete_apikey_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
@@ -326,7 +326,7 @@ def delete_apikey_for_user(username):
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/apikey", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def generate_apikey_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@@ -10,7 +10,7 @@ from flask import request, jsonify, make_response
|
||||
from octoprint.settings import settings
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request
|
||||
from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
@api.route("/connection", methods=["GET"])
|
||||
@@ -28,7 +28,7 @@ def connectionState():
|
||||
|
||||
|
||||
@api.route("/connection", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONNECTION.require(403)
|
||||
def connectionCommand():
|
||||
valid_commands = {
|
||||
|
||||
@@ -10,7 +10,7 @@ from flask import request, jsonify, make_response, url_for
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT, current_user
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request, with_revalidation_checking
|
||||
from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request, with_revalidation_checking
|
||||
from octoprint.server.api import api
|
||||
from octoprint.events import Events
|
||||
from octoprint.access.permissions import Permissions
|
||||
@@ -20,6 +20,7 @@ import octoprint.filemanager.util
|
||||
import octoprint.filemanager.storage
|
||||
import octoprint.slicing
|
||||
|
||||
import os
|
||||
import psutil
|
||||
import hashlib
|
||||
import logging
|
||||
@@ -136,7 +137,7 @@ def readGcodeFilesForOrigin(origin):
|
||||
|
||||
|
||||
def _getFileDetails(origin, path, recursive=True):
|
||||
parent, path = fileManager.split_path(origin, path)
|
||||
parent, path = os.path.split(path)
|
||||
files = _getFileList(origin, path=parent, recursive=recursive)
|
||||
|
||||
for f in files:
|
||||
@@ -267,7 +268,7 @@ def _isBusy(target, path):
|
||||
return any(target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1]) for x in fileManager.get_busy_files())
|
||||
|
||||
@api.route("/files/<string:target>", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.FILES_UPLOAD.require(403)
|
||||
def uploadGcodeFile(target):
|
||||
input_name = "file"
|
||||
@@ -483,7 +484,7 @@ def readGcodeFile(target, filename):
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
def gcodeFileCommand(filename, target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
@@ -750,7 +751,7 @@ def gcodeFileCommand(filename, target):
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.FILES_DELETE.require(403)
|
||||
def deleteGcodeFile(filename, target):
|
||||
if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename):
|
||||
|
||||
@@ -8,12 +8,12 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from flask import request, make_response, jsonify
|
||||
|
||||
from octoprint.server import printer, NO_CONTENT, current_user
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request
|
||||
from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request
|
||||
from octoprint.server.api import api
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
@api.route("/job", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.PRINT.require(403)
|
||||
def controlJob():
|
||||
if not printer.is_operational():
|
||||
|
||||
@@ -21,7 +21,7 @@ from flask import request, jsonify, make_response
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import require_firstrun
|
||||
from octoprint.server.util.flask import no_firstrun_access
|
||||
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.access.permissions import Permissions
|
||||
@@ -29,7 +29,7 @@ from octoprint.access.permissions import Permissions
|
||||
from flask_babel import Locale
|
||||
|
||||
@api.route("/languages", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def getInstalledLanguagePacks():
|
||||
translation_folder = settings().getBaseFolder("translations", check_writable=False)
|
||||
@@ -87,7 +87,7 @@ def getInstalledLanguagePacks():
|
||||
return jsonify(language_packs=result)
|
||||
|
||||
@api.route("/languages", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def uploadLanguagePack():
|
||||
input_name = "file"
|
||||
@@ -115,7 +115,7 @@ def uploadLanguagePack():
|
||||
return getInstalledLanguagePacks()
|
||||
|
||||
@api.route("/languages/<string:locale>/<string:pack>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def deleteInstalledLanguagePack(locale, pack):
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import re
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request
|
||||
from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request
|
||||
|
||||
from octoprint.printer import UnknownScript
|
||||
|
||||
@@ -60,7 +60,7 @@ def printerState():
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerToolCommand():
|
||||
if not printer.is_operational():
|
||||
@@ -133,9 +133,10 @@ def printerToolCommand():
|
||||
return make_response("Printer is currently printing", 409)
|
||||
|
||||
amount = data["amount"]
|
||||
speed = data.get("speed", None)
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
||||
printer.extrude(amount, tags=tags)
|
||||
printer.extrude(amount, speed=speed, tags=tags)
|
||||
|
||||
elif command == "flowrate":
|
||||
factor = data["factor"]
|
||||
@@ -150,7 +151,7 @@ def printerToolCommand():
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerToolState():
|
||||
if not printer.is_operational():
|
||||
@@ -163,7 +164,7 @@ def printerToolState():
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerBedCommand():
|
||||
if not printer.is_operational():
|
||||
@@ -210,7 +211,7 @@ def printerBedCommand():
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerBedState():
|
||||
if not printer.is_operational():
|
||||
@@ -230,7 +231,7 @@ def printerBedState():
|
||||
|
||||
|
||||
@api.route("/printer/printhead", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerPrintheadCommand():
|
||||
valid_commands = {
|
||||
@@ -294,7 +295,7 @@ def printerPrintheadCommand():
|
||||
|
||||
|
||||
@api.route("/printer/sd", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerSdCommand():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
@@ -325,7 +326,7 @@ def printerSdCommand():
|
||||
|
||||
|
||||
@api.route("/printer/sd", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerSdState():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
@@ -338,7 +339,7 @@ def printerSdState():
|
||||
|
||||
|
||||
@api.route("/printer/command", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerCommand():
|
||||
if not printer.is_operational():
|
||||
@@ -399,7 +400,7 @@ def printerCommand():
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/printer/command/custom", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONTROL.require(403)
|
||||
def getCustomControls():
|
||||
# TODO: document me
|
||||
|
||||
@@ -14,7 +14,7 @@ from werkzeug.exceptions import BadRequest
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.server.api import api, NO_CONTENT, valid_boolean_trues
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
from octoprint.server import printerProfileManager
|
||||
@@ -40,14 +40,14 @@ def _etag(lm=None):
|
||||
@with_revalidation_checking(etag_factory=_etag,
|
||||
lastmodified_factory=_lastmodified,
|
||||
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONNECTION.require(403)
|
||||
def printerProfilesList():
|
||||
all_profiles = printerProfileManager.get_all()
|
||||
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
|
||||
|
||||
@api.route("/printerprofiles", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesAdd():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
@@ -102,7 +102,7 @@ def printerProfilesAdd():
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.CONNECTION.require(403)
|
||||
def printerProfilesGet(identifier):
|
||||
profile = printerProfileManager.get(identifier)
|
||||
@@ -112,7 +112,7 @@ def printerProfilesGet(identifier):
|
||||
return jsonify(_convert_profile(profile))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesDelete(identifier):
|
||||
current_profile = printerProfileManager.get_current()
|
||||
@@ -127,7 +127,7 @@ def printerProfilesDelete(identifier):
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["PATCH"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesUpdate(identifier):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
|
||||
@@ -16,7 +16,7 @@ from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
from octoprint.server import admin_permission, printer, pluginManager
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -157,6 +157,7 @@ def getSettings():
|
||||
"blockM0M1": s.getBoolean(["serial", "blockM0M1"]),
|
||||
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
|
||||
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
|
||||
"abortHeatupOnCancel": s.getBoolean(["serial", "abortHeatupOnCancel"]),
|
||||
"supportResendsWithoutOk": s.get(["serial", "supportResendsWithoutOk"]),
|
||||
"waitForStart": s.getBoolean(["serial", "waitForStartOnConnect"]),
|
||||
"alwaysSendChecksum": s.getBoolean(["serial", "alwaysSendChecksum"]),
|
||||
@@ -174,7 +175,8 @@ def getSettings():
|
||||
"maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"]),
|
||||
"capAutoreportTemp": s.getBoolean(["serial", "capabilities", "autoreport_temp"]),
|
||||
"capAutoreportSdStatus": s.getBoolean(["serial", "capabilities", "autoreport_sdstatus"]),
|
||||
"capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"])
|
||||
"capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"]),
|
||||
"capEmergencyParser": s.getBoolean(["serial", "capabilities", "emergency_parser"])
|
||||
},
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
@@ -280,7 +282,7 @@ def _get_plugin_settings():
|
||||
|
||||
|
||||
@api.route("/settings", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def setSettings():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
@@ -305,7 +307,7 @@ def setSettings():
|
||||
|
||||
|
||||
@api.route("/settings/apikey", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def generateApiKey():
|
||||
apikey = settings().generateApiKey()
|
||||
@@ -313,14 +315,14 @@ def generateApiKey():
|
||||
|
||||
|
||||
@api.route("/settings/apikey", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def deleteApiKey():
|
||||
settings().deleteApiKey()
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/settings/templates", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def fetchTemplateData():
|
||||
from octoprint.server.views import fetch_template_data
|
||||
@@ -419,17 +421,17 @@ def _saveSettings(data):
|
||||
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"])
|
||||
if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
|
||||
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"], minimum=1.0)
|
||||
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"], minimum=1.0)
|
||||
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"], minimum=1.0)
|
||||
if "timeoutCommunicationBusy" in data["serial"]: s.setFloat(["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"], minimum=1.0)
|
||||
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"], minimum=1.0)
|
||||
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"], minimum=1.0)
|
||||
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"], minimum=0.0)
|
||||
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"], minimum=1.0)
|
||||
if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"], minimum=0.0)
|
||||
if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat(["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"], minimum=0.0)
|
||||
if "timeoutPositionLogWait" in data["serial"]: s.setFloat(["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"], minimum=1.0)
|
||||
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"], min=1.0)
|
||||
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"], min=1.0)
|
||||
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"], min=1.0)
|
||||
if "timeoutCommunicationBusy" in data["serial"]: s.setFloat(["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"], min=1.0)
|
||||
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"], min=1.0)
|
||||
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"], min=1.0)
|
||||
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"], min=0.0)
|
||||
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"], min=1.0)
|
||||
if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"], min=0.0)
|
||||
if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat(["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"], min=0.0)
|
||||
if "timeoutPositionLogWait" in data["serial"]: s.setFloat(["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"], min=1.0)
|
||||
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
|
||||
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
|
||||
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
|
||||
@@ -456,12 +458,14 @@ def _saveSettings(data):
|
||||
if "blockWhileDwelling" in data["serial"]: s.setBoolean(["serial", "blockWhileDwelling"], data["serial"]["blockWhileDwelling"])
|
||||
if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"])
|
||||
if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"])
|
||||
if "abortHeatupOnCancel" in data["serial"]: s.setBoolean(["serial", "abortHeatupOnCancel"], data["serial"]["abortHeatupOnCancel"])
|
||||
if "maxTimeoutsIdle" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"])
|
||||
if "maxTimeoutsPrinting" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"])
|
||||
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
|
||||
if "capAutoreportTemp" in data["serial"]: s.setBoolean(["serial", "capabilities", "autoreport_temp"], data["serial"]["capAutoreportTemp"])
|
||||
if "capAutoreportSdStatus" in data["serial"]: s.setBoolean(["serial", "capabilities", "autoreport_sdstatus"], data["serial"]["capAutoreportSdStatus"])
|
||||
if "capBusyProtocol" in data["serial"]: s.setBoolean(["serial", "capabilities", "busy_protocol"], data["serial"]["capBusyProtocol"])
|
||||
if "capEmergencyParser" in data["serial"]: s.setBoolean(["serial", "capabilities", "emergency_parser"], data["serial"]["capEmergencyParser"])
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"]: s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
|
||||
@@ -9,7 +9,7 @@ from flask import request, jsonify, make_response, url_for
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
from octoprint.server import slicingManager
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
@@ -103,7 +103,7 @@ def slicingListAll():
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SLICE.require(403)
|
||||
def slicingListSlicerProfiles(slicer):
|
||||
configured = False
|
||||
@@ -116,7 +116,7 @@ def slicingListSlicerProfiles(slicer):
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SLICE.require(403)
|
||||
def slicingGetSlicerProfile(slicer, name):
|
||||
try:
|
||||
@@ -131,7 +131,7 @@ def slicingGetSlicerProfile(slicer, name):
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def slicingAddSlicerProfile(slicer, name):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
@@ -167,7 +167,7 @@ def slicingAddSlicerProfile(slicer, name):
|
||||
return r
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def slicingPatchSlicerProfile(slicer, name):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
@@ -211,7 +211,7 @@ def slicingPatchSlicerProfile(slicer, name):
|
||||
return jsonify(_getSlicingProfileData(slicer, name, saved_profile))
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def slicingDelSlicerProfile(slicer, name):
|
||||
try:
|
||||
|
||||
@@ -16,12 +16,12 @@ from octoprint.settings import settings as s
|
||||
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import require_firstrun, get_remote_address
|
||||
from octoprint.server.util.flask import no_firstrun_access, get_remote_address
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.logging import prefix_multilines
|
||||
|
||||
@api.route("/system", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SYSTEM.require(403)
|
||||
def performSystemAction():
|
||||
logging.getLogger(__name__).warn("Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/<action>".format(get_remote_address(request)))
|
||||
@@ -37,7 +37,7 @@ def performSystemAction():
|
||||
|
||||
|
||||
@api.route("/system/commands", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SYSTEM.require(403)
|
||||
def retrieveSystemCommands():
|
||||
return jsonify(core=_to_client_specs(_get_core_command_specs()),
|
||||
@@ -45,7 +45,7 @@ def retrieveSystemCommands():
|
||||
|
||||
|
||||
@api.route("/system/commands/<string:source>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SYSTEM.require(403)
|
||||
def retrieveSystemCommandsForSource(source):
|
||||
if source == "core":
|
||||
@@ -59,7 +59,7 @@ def retrieveSystemCommandsForSource(source):
|
||||
|
||||
|
||||
@api.route("/system/commands/<string:source>/<string:command>", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.SYSTEM.require(403)
|
||||
def executeSystemCommand(source, command):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -16,7 +16,7 @@ import octoprint.util as util
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
from octoprint.server import admin_permission, printer
|
||||
from octoprint.server.util.flask import redirect_to_tornado, require_firstrun, get_json_command_from_request, with_revalidation_checking
|
||||
from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access, get_json_command_from_request, with_revalidation_checking
|
||||
from octoprint.server.api import api
|
||||
|
||||
from octoprint.server import NO_CONTENT
|
||||
@@ -76,7 +76,7 @@ def _etag(unrendered, lm=None):
|
||||
@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("unrendered", "false") in valid_boolean_trues, lm=lm),
|
||||
lastmodified_factory=lambda: _lastmodified(request.values.get("unrendered", "false") in valid_boolean_trues),
|
||||
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.TIMELAPSE_LIST.require(403)
|
||||
def getTimelapseData():
|
||||
timelapse = octoprint.timelapse.current
|
||||
@@ -122,14 +122,14 @@ def getTimelapseData():
|
||||
|
||||
|
||||
@api.route("/timelapse/<filename>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.TIMELAPSE_DOWNLOAD.require(403)
|
||||
def downloadTimelapse(filename):
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/timelapse/" + filename)
|
||||
|
||||
|
||||
@api.route("/timelapse/<filename>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.TIMELAPSE_DELETE.require(403)
|
||||
def deleteTimelapse(filename):
|
||||
timelapse_folder = settings().getBaseFolder("timelapse")
|
||||
@@ -148,7 +148,7 @@ def deleteTimelapse(filename):
|
||||
|
||||
|
||||
@api.route("/timelapse/unrendered/<name>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.TIMELAPSE_DELETE.require(403)
|
||||
def deleteUnrenderedTimelapse(name):
|
||||
octoprint.timelapse.delete_unrendered_timelapse(name)
|
||||
@@ -156,7 +156,7 @@ def deleteUnrenderedTimelapse(name):
|
||||
|
||||
|
||||
@api.route("/timelapse/unrendered/<name>", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.TIMELAPSE_ADMIN.require(403)
|
||||
def processUnrenderedTimelapseCommand(name):
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
@@ -177,7 +177,7 @@ def processUnrenderedTimelapseCommand(name):
|
||||
|
||||
|
||||
@api.route("/timelapse", methods=["POST"])
|
||||
@require_firstrun
|
||||
@no_firstrun_access
|
||||
@Permissions.TIMELAPSE_ADMIN.require(403)
|
||||
def setTimelapseConfig():
|
||||
data = request.get_json(silent=True)
|
||||
|
||||
@@ -32,6 +32,7 @@ import octoprint.plugin
|
||||
|
||||
from octoprint.util import DefaultOrderedDict
|
||||
from octoprint.util.json import JsonEncoding
|
||||
from octoprint.util.net import is_lan_address
|
||||
|
||||
from werkzeug.local import LocalProxy
|
||||
from werkzeug.contrib.cache import BaseCache
|
||||
@@ -513,6 +514,10 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
|
||||
def passive_login():
|
||||
user = flask_login.current_user
|
||||
|
||||
remoteAddr = get_remote_address(flask.request)
|
||||
ipCheckEnabled = settings().getBoolean(["server", "ipCheck", "enabled"])
|
||||
ipCheckTrusted = settings().get(["server", "ipCheck", "trustedSubnets"])
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
# noinspection PyProtectedMember
|
||||
user = user._get_current_object()
|
||||
@@ -531,6 +536,7 @@ def passive_login():
|
||||
|
||||
if user is not None and user.is_active:
|
||||
# login known user
|
||||
logging.getLogger(__name__).info("Passively logging in user {} from {}".format(user.get_id(), remoteAddr))
|
||||
user = login(user)
|
||||
|
||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
@@ -543,17 +549,21 @@ def passive_login():
|
||||
localNetworks.add(ip)
|
||||
|
||||
try:
|
||||
remoteAddr = get_remote_address(flask.request)
|
||||
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||
autologin_user = octoprint.server.userManager.find_user(autologinAs)
|
||||
if autologin_user is not None and user.is_active:
|
||||
autologin_user = octoprint.server.userManager.login_user(autologin_user)
|
||||
|
||||
logging.getLogger(__name__).info("Passively logging in user {} from {} via autologin".format(user.get_id(), remoteAddr))
|
||||
user = login(autologin_user)
|
||||
except:
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||
|
||||
return flask.jsonify(user)
|
||||
response = user.as_dict()
|
||||
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
|
||||
additional_private=ipCheckTrusted)
|
||||
return flask.jsonify(response)
|
||||
|
||||
|
||||
#~~ cache decorator for cacheable views
|
||||
@@ -1063,7 +1073,7 @@ def permission_validator(request, permission):
|
||||
:param request: The required permission
|
||||
"""
|
||||
|
||||
user = _get_flask_user_from_request(request)
|
||||
user = get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated or not user.has_permission(permission):
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
@@ -1076,7 +1086,7 @@ def admin_validator(request):
|
||||
def user_validator(request):
|
||||
return True
|
||||
|
||||
def _get_flask_user_from_request(request):
|
||||
def get_flask_user_from_request(request):
|
||||
"""
|
||||
Retrieves the current flask user from the request context. Uses API key if available, otherwise the current
|
||||
user session if available.
|
||||
@@ -1121,24 +1131,15 @@ def redirect_to_tornado(request, target, code=302):
|
||||
|
||||
def restricted_access(func):
|
||||
"""
|
||||
If you decorate a view with this, it will ensure that first setup has been
|
||||
done for OctoPrint's Access Control plus that any conditions of the
|
||||
login_required decorator are met (possibly through a session already created
|
||||
by octoprint.server.util.apiKeyRequestHandler earlier in the request processing).
|
||||
|
||||
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
|
||||
flag from the settings being set to True and the userManager not indicating
|
||||
that it's user database has been customized from default), the decorator
|
||||
will cause a HTTP 403 status code to be returned by the decorated resource.
|
||||
This combines :py:func:`no_firstrun_access` and ``login_required``.
|
||||
"""
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
return require_firstrun(flask_login.login_required(func))(*args, **kwargs)
|
||||
|
||||
return no_firstrun_access(flask_login.login_required(func))(*args, **kwargs)
|
||||
return decorated_view
|
||||
|
||||
|
||||
def require_firstrun(func):
|
||||
def no_firstrun_access(func):
|
||||
"""
|
||||
If you decorate a view with this, it will ensure that first setup has been
|
||||
done for OctoPrint's Access Control.
|
||||
@@ -1151,10 +1152,8 @@ def require_firstrun(func):
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
# if OctoPrint hasn't been set up yet, abort
|
||||
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (
|
||||
octoprint.server.userManager is None or not octoprint.server.userManager.has_been_customized()):
|
||||
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
|
||||
return flask.make_response("OctoPrint isn't setup yet", 403)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return decorated_view
|
||||
@@ -1338,6 +1337,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
|
||||
def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
assets = dict(
|
||||
js=[],
|
||||
clientjs=[],
|
||||
css=[],
|
||||
less=[]
|
||||
)
|
||||
@@ -1381,6 +1381,26 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
'gcodeviewer/js/renderer.js'
|
||||
]
|
||||
|
||||
assets["clientjs"] = [
|
||||
"js/app/client/base.js",
|
||||
"js/app/client/socket.js",
|
||||
"js/app/client/browser.js",
|
||||
"js/app/client/connection.js",
|
||||
"js/app/client/control.js",
|
||||
"js/app/client/files.js",
|
||||
"js/app/client/job.js",
|
||||
"js/app/client/languages.js",
|
||||
"js/app/client/printer.js",
|
||||
"js/app/client/printerprofiles.js",
|
||||
"js/app/client/settings.js",
|
||||
"js/app/client/slicing.js",
|
||||
"js/app/client/system.js",
|
||||
"js/app/client/timelapse.js",
|
||||
"js/app/client/users.js",
|
||||
"js/app/client/util.js",
|
||||
"js/app/client/wizard.js"
|
||||
]
|
||||
|
||||
if preferred_stylesheet == "less":
|
||||
assets["less"].append('less/octoprint.less')
|
||||
elif preferred_stylesheet == "css":
|
||||
@@ -1395,9 +1415,11 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
assets = dict(bundled=dict(js=DefaultOrderedDict(list),
|
||||
clientjs=DefaultOrderedDict(list),
|
||||
css=DefaultOrderedDict(list),
|
||||
less=DefaultOrderedDict(list)),
|
||||
external=dict(js=DefaultOrderedDict(list),
|
||||
clientjs=DefaultOrderedDict(list),
|
||||
css=DefaultOrderedDict(list),
|
||||
less=DefaultOrderedDict(list)))
|
||||
|
||||
@@ -1427,6 +1449,12 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
continue
|
||||
assets[asset_key]["js"][name].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
|
||||
if "clientjs" in all_assets:
|
||||
for asset in all_assets["clientjs"]:
|
||||
if not asset_exists("clientjs", asset):
|
||||
continue
|
||||
assets[asset_key]["clientjs"][name].append("plugin/{name}/{asset}".format(**locals()))
|
||||
|
||||
if preferred_stylesheet in all_assets:
|
||||
for asset in all_assets[preferred_stylesheet]:
|
||||
if not asset_exists(preferred_stylesheet, asset):
|
||||
|
||||
@@ -104,11 +104,21 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
self._lastCurrent = 0
|
||||
self._baseRateLimit = 0.5
|
||||
|
||||
self._register_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.register")
|
||||
self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit")
|
||||
|
||||
self._registered = False
|
||||
|
||||
@staticmethod
|
||||
def _get_remote_address(info):
|
||||
forwarded_for = info.headers.get("X-Forwarded-For")
|
||||
if forwarded_for is not None:
|
||||
return forwarded_for.split(",")[0]
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
if forwardedFor is not None:
|
||||
return forwardedFor.split(",")[0]
|
||||
return info.ip
|
||||
|
||||
def __str__(self):
|
||||
@@ -136,15 +146,15 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
config_hash = settings().config_hash
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", payload=dict(apikey=octoprint.server.UI_API_KEY,
|
||||
version=octoprint.server.VERSION,
|
||||
display_version=octoprint.server.DISPLAY_VERSION,
|
||||
branch=octoprint.server.BRANCH,
|
||||
plugin_hash=plugin_hash.hexdigest(),
|
||||
config_hash=config_hash,
|
||||
debug=octoprint.server.debug,
|
||||
safe_mode=octoprint.server.safe_mode,
|
||||
permissions=[permission.as_dict() for permission in Permissions.all()]))
|
||||
self._emit("connected", dict(apikey=octoprint.server.UI_API_KEY,
|
||||
version=octoprint.server.VERSION,
|
||||
display_version=octoprint.server.DISPLAY_VERSION,
|
||||
branch=octoprint.server.BRANCH,
|
||||
plugin_hash=plugin_hash.hexdigest(),
|
||||
config_hash=config_hash,
|
||||
debug=octoprint.server.debug,
|
||||
safe_mode=octoprint.server.safe_mode,
|
||||
permissions=[permission.as_dict() for permission in Permissions.all()]))
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
||||
self._register()
|
||||
@@ -174,7 +184,8 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
if not len(parts) == 2:
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
self._logger.warn("Got invalid auth message from client {}, ignoring: {!r}".format(self._remoteAddress, message["auth"]))
|
||||
self._logger.warn("Got invalid auth message from client {}, ignoring: {!r]".format(self._remoteAddress,
|
||||
message["auth"]))
|
||||
else:
|
||||
user_id, user_session = parts
|
||||
user = self._userManager.find_user(userid=user_id, session=user_session)
|
||||
@@ -182,12 +193,16 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
if user is not None:
|
||||
self._user = user
|
||||
self._reregister()
|
||||
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(), self._remoteAddress))
|
||||
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(),
|
||||
self._remoteAddress))
|
||||
|
||||
else:
|
||||
self._user = self._userManager.anonymous_user_factory()
|
||||
self._reregister()
|
||||
self._logger.warn("Unknown user/session combo: {}:{}".format(user_id, user_session))
|
||||
|
||||
self._register()
|
||||
|
||||
elif "throttle" in message:
|
||||
try:
|
||||
throttle = int(message["throttle"])
|
||||
@@ -307,6 +322,19 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
def _register(self):
|
||||
"""Register this socket with the system if STATUS permission is available."""
|
||||
|
||||
proceed = True
|
||||
for name, hook in self._register_hooks.items():
|
||||
try:
|
||||
proceed = proceed and hook(self, self._user)
|
||||
except:
|
||||
self._logger.exception("Error processing register hook handler for plugin {}".format(name))
|
||||
|
||||
if not proceed:
|
||||
return
|
||||
|
||||
if self._registered:
|
||||
return
|
||||
|
||||
if not self._user.has_permission(Permissions.STATUS):
|
||||
return
|
||||
|
||||
@@ -361,6 +389,16 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
if payload is None:
|
||||
payload = dict()
|
||||
|
||||
proceed = True
|
||||
for name, hook in self._emit_hooks.items():
|
||||
try:
|
||||
proceed = proceed and hook(self, self._user, type, payload)
|
||||
except:
|
||||
self._logger.exception("Error processing emit hook handler from plugin {}".format(name))
|
||||
|
||||
if not proceed:
|
||||
return
|
||||
|
||||
if permissions is None:
|
||||
permissions = self._emit_permissions.get(type, self._emit_permissions["*"])
|
||||
|
||||
|
||||
@@ -1127,7 +1127,7 @@ class GlobalHeaderTransform(tornado.web.OutputTransform):
|
||||
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
|
||||
|
||||
|
||||
def access_validation_factory(app, login_manager, validator, permission):
|
||||
def access_validation_factory(app, validator, *args):
|
||||
"""
|
||||
Creates an access validation wrapper using the supplied validator.
|
||||
|
||||
@@ -1146,8 +1146,8 @@ def access_validation_factory(app, login_manager, validator, permission):
|
||||
wsgi_environ = WsgiInputContainer.environ(request)
|
||||
with app.request_context(wsgi_environ):
|
||||
app.session_interface.open_session(app, flask.request)
|
||||
login_manager.reload_user()
|
||||
validator(flask.request, permission)
|
||||
app.login_manager.reload_user()
|
||||
validator(flask.request, *args)
|
||||
return f
|
||||
|
||||
def path_validation_factory(path_filter, status_code=404):
|
||||
@@ -1162,3 +1162,9 @@ def path_validation_factory(path_filter, status_code=404):
|
||||
if not path_filter(path):
|
||||
raise tornado.web.HTTPError(status_code)
|
||||
return f
|
||||
|
||||
def validation_chain(*validators):
|
||||
def f(request):
|
||||
for validator in validators:
|
||||
validator(request)
|
||||
return f
|
||||
@@ -121,6 +121,7 @@ default_settings = {
|
||||
"supportResendsWithoutOk": "detect",
|
||||
"logPositionOnPause": True,
|
||||
"logPositionOnCancel": False,
|
||||
"abortHeatupOnCancel": True,
|
||||
"waitForStartOnConnect": False,
|
||||
"alwaysSendChecksum": False,
|
||||
"neverSendChecksum": False,
|
||||
@@ -141,7 +142,8 @@ default_settings = {
|
||||
"capabilities": {
|
||||
"autoreport_temp": True,
|
||||
"autoreport_sdstatus": True,
|
||||
"busy_protocol": True
|
||||
"busy_protocol": True,
|
||||
"emergency_parser": True
|
||||
},
|
||||
|
||||
# command specific flags
|
||||
@@ -198,6 +200,10 @@ default_settings = {
|
||||
"preemptiveCache": {
|
||||
"exceptions": [],
|
||||
"until": 7
|
||||
},
|
||||
"ipCheck": {
|
||||
"enabled": True,
|
||||
"trustedSubnets": []
|
||||
}
|
||||
},
|
||||
"webcam": {
|
||||
@@ -290,7 +296,8 @@ default_settings = {
|
||||
"settings": [
|
||||
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
||||
"section_features", "features", "webcam", "accesscontrol", "gcodevisualizer", "api",
|
||||
"section_octoprint", "server", "folders", "appearance", "plugin_logging", "plugin_pluginmanager", "plugin_softwareupdate", "plugin_announcements"
|
||||
"section_octoprint", "server", "folders", "appearance", "plugin_logging", "plugin_pluginmanager",
|
||||
"plugin_softwareupdate", "plugin_announcements", "plugin_backup"
|
||||
],
|
||||
"usersettings": ["access", "interface"],
|
||||
"wizard": ["access"],
|
||||
@@ -342,7 +349,7 @@ default_settings = {
|
||||
"apps": {}
|
||||
},
|
||||
"terminalFilters": [
|
||||
{ "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?(B|T\d*):)" },
|
||||
{ "name": "Suppress temperature messages", "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)|(Recv: Not SD printing)" },
|
||||
{ "name": "Suppress wait responses", "regex": "Recv: wait"}
|
||||
],
|
||||
@@ -353,7 +360,7 @@ default_settings = {
|
||||
"gcode": {
|
||||
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
|
||||
"snippets": {
|
||||
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}",
|
||||
"disable_hotends": "{% if printer_profile.extruder.sharedNozzle %}M104 T0 S0\n{% else %}{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}{% endif %}",
|
||||
"disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}"
|
||||
}
|
||||
}
|
||||
@@ -411,10 +418,11 @@ default_settings = {
|
||||
"preparedOks": [],
|
||||
"okFormatString": "ok",
|
||||
"m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0",
|
||||
"m115ReportCapabilities": False,
|
||||
"m115ReportCapabilities": True,
|
||||
"capabilities": {
|
||||
"AUTOREPORT_TEMP": True,
|
||||
"AUTOREPORT_SD_STATUS": True
|
||||
"AUTOREPORT_SD_STATUS": True,
|
||||
"EMERGENCY_PARSER": True
|
||||
},
|
||||
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
|
||||
"ambientTemperature": 21.3,
|
||||
@@ -601,6 +609,8 @@ class Settings(object):
|
||||
|
||||
self._basedir = None
|
||||
|
||||
assert(isinstance(default_settings, dict))
|
||||
|
||||
self._map = HierarchicalChainMap(dict(), default_settings)
|
||||
|
||||
self._config = None
|
||||
@@ -871,6 +881,7 @@ class Settings(object):
|
||||
try:
|
||||
self._config = yaml.safe_load(f)
|
||||
self._mtime = self.last_modified
|
||||
|
||||
except yaml.YAMLError as e:
|
||||
details = e.message
|
||||
|
||||
@@ -885,10 +896,12 @@ class Settings(object):
|
||||
details=details,
|
||||
line=line,
|
||||
column=column)
|
||||
|
||||
except:
|
||||
raise
|
||||
|
||||
# changed from else to handle cases where the file exists, but is empty / 0 bytes
|
||||
if not self._config:
|
||||
if not self._config or not isinstance(self._config, dict):
|
||||
self._config = dict()
|
||||
|
||||
if migrate:
|
||||
@@ -1587,7 +1600,7 @@ class Settings(object):
|
||||
|
||||
#~~ setter
|
||||
|
||||
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None, error_on_path=False):
|
||||
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None, error_on_path=False, *args, **kwargs):
|
||||
if not path:
|
||||
if error_on_path:
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
@@ -115,7 +115,7 @@
|
||||
if (this.options.apikey) {
|
||||
headers["X-Api-Key"] = this.options.apikey;
|
||||
}
|
||||
if (this.options.locale) {
|
||||
if (this.options.locale !== undefined) {
|
||||
headers["X-Locale"] = this.options.locale;
|
||||
}
|
||||
|
||||
|
||||
@@ -708,11 +708,19 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
var proceed = options.proceed || gettext("Proceed");
|
||||
var proceedClass = options.proceedClass || "danger";
|
||||
var onproceed = options.onproceed || undefined;
|
||||
var oncancel = options.oncancel || undefined;
|
||||
var onclose = options.onclose || undefined;
|
||||
var dialogClass = options.dialogClass || "";
|
||||
var nofade = options.nofade || false;
|
||||
var noclose = options.noclose || false;
|
||||
|
||||
var modalHeader;
|
||||
if (noclose) {
|
||||
modalHeader = $('<h3>' + title + '</h3>');
|
||||
} else {
|
||||
modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">×</a><h3>' + title + '</h3>');
|
||||
}
|
||||
|
||||
var modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">×</a><h3>' + title + '</h3>');
|
||||
var modalBody;
|
||||
if (html) {
|
||||
modalBody = $(html);
|
||||
@@ -740,7 +748,13 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
onclose(event);
|
||||
}
|
||||
});
|
||||
modal.modal("show");
|
||||
|
||||
var modalOptions = {};
|
||||
if (noclose) {
|
||||
modalOptions.backdrop = "static";
|
||||
modalOptions.keyboard = false;
|
||||
}
|
||||
modal.modal(modalOptions);
|
||||
|
||||
proceedButton.click(function(e) {
|
||||
e.preventDefault();
|
||||
@@ -749,6 +763,11 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
}
|
||||
modal.modal("hide");
|
||||
});
|
||||
cancelButton.click(function(e) {
|
||||
if (oncancel && _.isFunction(oncancel)) {
|
||||
oncancel(e);
|
||||
}
|
||||
});
|
||||
|
||||
return modal;
|
||||
}
|
||||
|
||||
@@ -61,6 +61,9 @@ $(function() {
|
||||
self.fromResponse = function(response) {
|
||||
var ports = response.options.ports;
|
||||
var baudrates = response.options.baudrates;
|
||||
var currentPort = response.current.port;
|
||||
var currentBaudrate = response.current.baudrate;
|
||||
var currentPrinterProfile = response.current.printerProfile;
|
||||
var portPreference = response.options.portPreference;
|
||||
var baudratePreference = response.options.baudratePreference;
|
||||
var printerPreference = response.options.printerProfilePreference;
|
||||
@@ -69,12 +72,27 @@ $(function() {
|
||||
self.portOptions(ports);
|
||||
self.baudrateOptions(baudrates);
|
||||
|
||||
if (!self.selectedPort() && ports && ports.indexOf(portPreference) >= 0)
|
||||
self.selectedPort(portPreference);
|
||||
if (!self.selectedBaudrate() && baudrates && baudrates.indexOf(baudratePreference) >= 0)
|
||||
self.selectedBaudrate(baudratePreference);
|
||||
if (!self.selectedPrinter() && printerProfiles && printerProfiles.indexOf(printerPreference) >= 0)
|
||||
self.selectedPrinter(printerPreference);
|
||||
if (!self.selectedPort() && ports) {
|
||||
if (ports.indexOf(currentPort) >= 0) {
|
||||
self.selectedPort(currentPort);
|
||||
} else if (ports.indexOf(portPreference) >= 0) {
|
||||
self.selectedPort(portPreference);
|
||||
}
|
||||
}
|
||||
if (!self.selectedBaudrate() && baudrates) {
|
||||
if (baudrates.indexOf(currentBaudrate) >= 0) {
|
||||
self.selectedBaudrate(currentBaudrate);
|
||||
} else if (baudrates.indexOf(baudratePreference) >= 0) {
|
||||
self.selectedBaudrate(baudratePreference);
|
||||
}
|
||||
}
|
||||
if (!self.selectedPrinter() && printerProfiles) {
|
||||
if (printerProfiles.indexOf(currentPrinterProfile) >= 0) {
|
||||
self.selectedPrinter(currentPrinterProfile);
|
||||
} else if (printerProfiles.indexOf(printerPreference) >= 0) {
|
||||
self.selectedPrinter(printerPreference);
|
||||
}
|
||||
}
|
||||
|
||||
self.saveSettings(false);
|
||||
};
|
||||
@@ -162,7 +180,11 @@ $(function() {
|
||||
|
||||
self.onEventSettingsUpdated = function() {
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
self.onEventConnected = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
var connectionTab = $("#connection");
|
||||
|
||||