diff --git a/.editorconfig b/.editorconfig index d8d42bbc9..bf65494f2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,6 +11,7 @@ trim_trailing_whitespace = true [**.py] indent_style = tab +indent_size = 4 [src/octoprint/static/js/app/**.js] indent_style = space diff --git a/.versioneer-lookup b/.versioneer-lookup index 788d23da4..ae23a1c14 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -20,14 +20,14 @@ HEAD # maintenance is currently the branch for preparation of maintenance release 1.3.9 # so are any fix/... and improve/... branches -maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev -fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev -improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev +fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev +improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -# staging/maintenance is currently the branch for preparation of 1.3.9rc4 +# staging/maintenance is currently the branch for preparation of 1.3.9rc5 # so is regressionfix/... -staging/maintenance 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev -regressionfix/.* 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev +staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev +regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev # every other branch is a development branch and thus gets resolved to 1.4.0-dev for now .* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev diff --git a/AUTHORS.md b/AUTHORS.md index 09e51f9cf..817dbb53f 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -92,6 +92,7 @@ date of first contribution): * [Sven Lohrmann](https://github.com/malnvenshorn) * [Andy Castille](https://github.com/klikini) * [Gaston Dombiak](https://github.com/gdombiak) + * [Brad Fisher](https://github.com/bradcfisher) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/docs/api/general.rst b/docs/api/general.rst index 4232a96c9..edc54ed78 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -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 `. -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 ` (since 1.3.10). + +Clients are advised to implement the :ref:`Application Keys Plugin 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 ` 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 `. + * - ``_is_external_client`` + - 1 + - boolean + - Whether the client that made the request got detected as external from the local network or not. diff --git a/docs/api/push.rst b/docs/api/push.rst index 7d8813867..87e40bf5d 100644 --- a/docs/api/push.rst +++ b/docs/api/push.rst @@ -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 ` 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 `. - { - "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: diff --git a/docs/api/settings.rst b/docs/api/settings.rst index f87887536..c485f0a95 100644 --- a/docs/api/settings.rst +++ b/docs/api/settings.rst @@ -396,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted: - * - ``feature.sdSupport`` - - * - ``feature.sdReleativePath`` + * - ``feature.sdRelativePath`` - * - ``feature.sdAlwaysAvailable`` - diff --git a/docs/bundledplugins/announcements.rst b/docs/bundledplugins/announcements.rst new file mode 100644 index 000000000..44dfe63e1 --- /dev/null +++ b/docs/bundledplugins/announcements.rst @@ -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``. diff --git a/docs/bundledplugins/appkeys.rst b/docs/bundledplugins/appkeys.rst new file mode 100644 index 000000000..ceba6d89d --- /dev/null +++ b/docs/bundledplugins/appkeys.rst @@ -0,0 +1,511 @@ +.. _sec-bundledplugins-appkeys: + +Application Keys Plugin +======================= + +The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10). + +It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it +on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed +on a per-user base as well as globally by administrators. + +.. _fig-bundledplugins-appkeys-confirmation: +.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png + :align: center + :alt: Confirmation + + The plugin's confirmation generated for a new application key request. + +.. _fig-bundledplugins-appkeys-user_settings: +.. figure:: ../images/bundledplugins-appkeys-user_settings.png + :align: center + :alt: Key management via user settings + + Users can manage the application specific API keys registered to their account via their user settings. + +.. _fig-bundledplugins-appkeys-settings: +.. figure:: ../images/bundledplugins-appkeys-settings.png + :align: center + :alt: Global key management via settings + + Administrators can manage all application specific API keys registered to any user. + +.. _sec-bundledplugins-appkeys-workflow: + +Workflow +-------- + +The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist +of the following steps: + + 1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also + enters their username which is also their user ID into the App. + 2. The App sends a :ref:`key request ` to the Server to start the + authorization process. + 3. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the + App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`. + 4. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202` + signals that no decision has been made yet. + 5. The User either accepts or denies the access request which makes the Webinterface send a + :ref:`decision request ` to the Server. + 6. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached + :ref:`API key response `. If they deny it, the App will receive + an HTTP :http:statuscode:`404`. + + +.. mermaid:: + + sequenceDiagram + participant User + participant App + participant Webinterface + participant Server + + note over User, Server: Step 1 & 2 + + User->>App: enters URL of instance to connect to + + alt Limit to specific user + User->>App: enters user_id + App->>Server: POST /plugin/appkeys/request, (app_name, user_id) + else + App->>Server: POST /plugin/appkeys/request, (app_name) + end + + note over User, Server: Step 3 + + Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id) + Webinterface-->>User: Display confirmation dialog + Server->>App: 201, Location: /plugin/appkeys/request/ + + note over User, Server: Step 4 + + loop + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 202 + end + + note over User, Server: Step 5 & 6 + + alt User accepts + + User-->>Webinterface: Allow access + Webinterface->>Server: POST /plugin/appkeys/decision/, (True) + Server->>Webinterface: 204 + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 200, api_key + + else User denies + + User-->>Webinterface: Deny access + Webinterface->>Server: POST /plugin/appkeys/decision/, (False) + Server->>Webinterface: 204 + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 404 + + end + +.. _sec-bundledplugins-appkeys-api: + +API +--- + +.. _sec-bundledplugins-appkeys-api-startauthprocess: + +Start authorization process +........................... + +.. http:post:: /plugin/appkeys/request + + Starts the authorization process. + + Expects a :ref:`Key request ` as request body. + + The ``app`` parameter should be a human readable identifier to use + for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively, + so ``My App`` and ``my APP`` are considered the same application identifiers. + + The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter + is left unset, any user will be able to complete the authorization process and grant access to the app with their + account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use + it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me`` + is logged in on. + + .. note:: + + If this endpoint produces an HTTP :http:statuscode:`404` and the instance URL is correct, the bundled + Application Keys Plugin has in all likelihood been disabled by the user. Fall back on manual API key copy-pasting + by the user. + + :json app: application identifier to use for the request, case insensitive + :json user: optional user id to restrict the decision to the specified user + :status 201: authorization process started, polling URL to query can be found in ``Location`` header + +.. _sec-bundledplugins-appkeys-api-polldecision: + +Poll for decision on existing request +..................................... + +.. http:get:: /plugin/appkeys/request/ + + 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 ` if access has been granted and an + HTTP :http:statuscode:`404` if the request has been denied or timed out. + + :status 200: access granted, API key in response body + :status 202: no decision has been made yet, continue polling + :status 404: access denied or request timed out + +.. _sec-bundledplugins-appkeys-api-decide: + +Decide on existing request +.......................... + +.. http:post:: /plugin/appkeys/decision/ + + Endpoint to decide on the authorization request. + + Expects a :ref:`Decision request ` 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 ` 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 ` + - Keys registered in the system + * - ``pending`` + - 1 + - list of :ref:`pending list entries ` + - 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 ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery 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 ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery 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 ` for details. + + :param string app: Application identifier + :param object opts: Additional options for the request + :returns Promise: A `jQuery 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 ` for details. + + :param string key: Key to revoke + :param object opts: Additional options for the request + :returns Promise: A `jQuery 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 ` 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 `_ 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 ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery 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 ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery 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 ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts) + + Convenience function that issues a request and then automatically starts polling for a decision on the returned + polling endpoint every 1s, until either a positive or negative decision is returned. On success the returned + promise is resolved with the generated API key as argument. + + **Example usage** + + .. sourcecode:: javascript + + OctoPrint.plugins.appkeys.authenticate("My App", "some_user") + .done(function(api_key) { + console.log("Got our API key:", api_key); + }) + .fail(function() { + console.log("No API key for us"); + }) + + :param string app: Application identifier + :param string user: Optional user identifier + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ 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``. diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst new file mode 100644 index 000000000..350d40508 --- /dev/null +++ b/docs/bundledplugins/backup.rst @@ -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 `_ + 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. diff --git a/docs/bundledplugins/forcelogin.rst b/docs/bundledplugins/forcelogin.rst new file mode 100644 index 000000000..e5214f79f --- /dev/null +++ b/docs/bundledplugins/forcelogin.rst @@ -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``. diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index 26a520699..8bf1d5d35 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -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 diff --git a/docs/bundledplugins/printer_safety_check.rst b/docs/bundledplugins/printer_safety_check.rst index 89974de48..6770056cb 100644 --- a/docs/bundledplugins/printer_safety_check.rst +++ b/docs/bundledplugins/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 `_ +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 `_. -.. seealso:: - - `Entry on the "unsafe firmware" warning in OctoPrint's FAQ `_ - .. note:: Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 9149f1324..ec3b71f7e 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -1165,7 +1165,7 @@ Use `Javascript regular expressions `_ - A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the - client library's :ref:`browser component ` to login the user. + :ref:`Application Key Plugin ` + 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 ` + 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 ` to login the + user. .. toctree:: :maxdepth: 3 diff --git a/docs/plugins/helpers.rst b/docs/plugins/helpers.rst index c411d3776..f8c5424f3 100644 --- a/docs/plugins/helpers.rst +++ b/docs/plugins/helpers.rst @@ -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 diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 5f4d156bf..4d20367da 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -402,6 +402,13 @@ octoprint.comm.firmware.info ``firmware_name`` will be ``Some Firmware Name`` in this case. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. :param str firmware_name: The name of the parsed capability :param dict firmware_data: All data contained in the ``M115`` report @@ -421,6 +428,13 @@ octoprint.comm.firmware.capabilities Note that hook handlers will be called once per received capability line. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. :param str capability: The name of the parsed capability :param bool enabled: Whether the capability is reported as enabled or disabled @@ -440,6 +454,13 @@ octoprint.comm.protocol.action No returned value is expected. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example:** Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware. @@ -477,6 +498,13 @@ This describes actually two hooks: trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to :ref:`the action command hook `. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as + you will effectively block the send/receive loops, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example** Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a @@ -623,6 +651,13 @@ This describes actually four hooks: Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type`` to one already in the queue will give an error. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the send loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example** The following hook handler replaces all ``M107`` ("Fan Off", deprecated) with an ``M106 S0`` ("Fan On" with speed @@ -658,6 +693,13 @@ octoprint.comm.protocol.gcode.received empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty ``return`` statement is used or just nothing is returned explicitly from the handler. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example:** Looks for the response of an ``M115``, which contains information about the ``MACHINE_TYPE``, among other things. @@ -687,6 +729,13 @@ octoprint.comm.protocol.gcode.error Plugins might utilize this hook to handle errors generated by the printer that are recoverable in one way or the other and should not trigger the normal handling that assumes the worst. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example:** Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the @@ -762,6 +811,13 @@ octoprint.comm.protocol.temperatures.received additional sanity checking to be applied and invalid values to be filtered out. If a handler returns an empty dictionary or ``None``, no further processing will take place. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example** The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C. @@ -1033,6 +1089,54 @@ octoprint.printer.estimation.factory :return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method :rtype: class or function +.. _sec-plugins-hook-server-http-after_request: + +octoprint.server.api.after_request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: after_request_handlers_hook(*args, **kwargs) + + Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins. + + Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a + usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + +.. _sec-plugins-hook-server-http-before_request: + +octoprint.server.api.before_request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: after_request_handlers_hook(*args, **kwargs) + + Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins. + + Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a + usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + +.. _sec-plugins-hook-server-http-access_validator: + +octoprint.server.http.access_validator +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: access_validator_hook(request, *args, **kwargs) + + Allows adding additional access validators to the default tornado routers. + + Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled + "Force Login" plugin for a usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + .. _sec-plugins-hook-server-http-bodysize: octoprint.server.http.bodysize @@ -1134,6 +1238,71 @@ octoprint.server.http.routes :return: a list of 3-tuples with additional routes as defined above :rtype: list +.. _sec-plugins-hook-server-sockjs-register: + +octoprint.server.sockjs.register +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: socket_registration_hook(socket, user, *args, **kwargs): + + Allows plugins to prevent a new :ref:`push socket client ` 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 ` 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 `. + + Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it. + + See the bundled :ref:`Forcelogin Plugin ` for an example on how to utilize this. + + :param object socket: the socket object on which a message is about to be emitted + :param object user: the user currently authenticated on the socket - might be None + :param string message: the message type about to be emitted + :param dict payload: the payload of the message about to be emitted (may be None) + :return: whether to proceed with sending the message (``True``) or not (``False``) + :rtype: boolean + +.. _sec-plugins-hook-timelapse-extensions: + +octoprint.timelapse.extensions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: timelapse_extension_hook(*args, **kwargs) + + Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of + additional file extensions. + + **Example** + + Allow the management of timelapse GIFs with extension ``gif``. + + .. code-block:: python + + def get_timelapse_extensions(*args, **kwargs): + return ["gif"] + + __plugin_hooks__ = { + "octoprint.timelapse.extensions": get_timelapse_extensions + } + + :return: a list of additional file extensions + :rtype: list + .. _sec-plugins-hook-ui-web-templatetypes: octoprint.ui.web.templatetypes diff --git a/setup.py b/setup.py index 8c0f76646..0a58b8523 100644 --- a/setup.py +++ b/setup.py @@ -12,46 +12,52 @@ import octoprint_setuptools #----------------------------------------------------------------------------------------------------------------------- +# Supported python versions +PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11 + # Requirements for our application INSTALL_REQUIRES = [ - "flask>=0.10.1,<0.11", - "Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't - # guarantee backwards compatibility for plugins and such with that - # version, hence we need to pin to a lower version for now. See #1697 - "werkzeug>=0.8.3,<0.9", - "tornado==4.5.3", - #"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a - # vendored one - "PyYAML>=3.10,<3.11", - "Flask-Login>=0.2.11,<0.3", - "Flask-Principal>=0.3.5,<0.4", - "Flask-Babel>=0.9,<0.10", - "Flask-Assets>=0.10,<0.11", - "markdown>=2.6.9,<2.7", + # the following dependencies are non trivial to update since later versions introduce backwards incompatible + # changes that might affect plugins, or due to other observed problems + + "flask>=0.10.1,<0.11", # newer versions require newer Jinja versions + "Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't + # guarantee backwards compatibility for plugins and such with that + # version, hence we need to pin to a lower version for now. See #1697 + "tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585 + "Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3 + + # anything below this should be checked on releases for new versions + + "Flask-Principal>=0.4,<0.5", + "Flask-Babel>=0.12,<0.13", + "Flask-Assets>=0.12,<0.13", + "werkzeug>=0.14.1,<0.15", + "PyYAML>=3.13,<4", + "markdown>=3.0,<3.1", "pyserial>=3.4,<3.5", "netaddr>=0.7.19,<0.8", - "watchdog>=0.8.3,<0.9", - "sarge==0.1.4", # 0.1.5 introduced a breaking change with regards to the async keyword. Pinning - # to 0.1.4 for now to work around this. - "netifaces>=0.10.6,<0.11", - "pylru>=1.0.9,<1.1", - "rsa>=3.2.3,<3.3", + "watchdog>=0.9.0,<0.10", + "sarge==0.1.5post0", + "netifaces>=0.10.7,<0.11", + "pylru>=1.1,<1.2", + "rsa>=4.0,<5", "pkginfo>=1.4.2,<1.5", - "requests>=2.18.4,<3", - "semantic_version>=2.4.2,<2.5", - "psutil>=5.4.6,<5.5", - "Click>=6.2,<6.3", + "requests>=2.20.0,<3", + "semantic_version>=2.6,<2.7", + "psutil>=5.4.8,<5.5", + "Click>=7,<8", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", "chainmap>=1.0.2,<1.1", - "future>=0.15.2,<0.16", - "scandir>=1.3,<1.4", - "websocket-client>=0.40.0,<0.41", - "python-dateutil>=2.6.1,<2.7", + "future>=0.17,<0.18", + "scandir>=1.9,<1.10", + "websocket-client>=0.53,<0.54", + "python-dateutil>=2.7.5,<2.8", "wrapt>=1.10.11,<1.11", - "futures>=3.1.1,<3.2", - "emoji>=0.4.5,<0.5", - "monotonic>=1.3,<1.4", + "futures>=3.2,<3.3", + "emoji>=0.5.1,<0.6", + "monotonic>=1.5,<1.6", "frozendict>=1.2,<1.3" ] @@ -64,11 +70,11 @@ EXTRA_REQUIRES = dict( develop=[ # Testing dependencies "mock>=2.0.0,<3", - "nose>=1.3.0,<1.4", + "nose>=1.3.7,<1.4", "ddt", # Documentation dependencies - "sphinx>=1.6,<1.7", + "sphinx>=1.8.1,<1.9", "sphinxcontrib-httpdomain", "sphinxcontrib-mermaid>=0.3", "sphinx_rtd_theme", @@ -76,13 +82,10 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint plugins plugins=[ - "cookiecutter>=1.4,<1.7" + "cookiecutter>=1.6,<1.7" ] ) -# Additional requirements for setup -SETUP_REQUIRES = [] - # Dependency links for any of the aforementioned dependencies DEPENDENCY_LINKS = [] @@ -155,10 +158,10 @@ def params(): long_description = read_file_contents(os.path.join(here, "README.md")) long_description_content_type = "text/markdown" + python_requires = PYTHON_REQUIRES install_requires = INSTALL_REQUIRES extras_require = EXTRA_REQUIRES dependency_links = DEPENDENCY_LINKS - setup_requires = SETUP_REQUIRES classifiers = [ "Development Status :: 5 - Production/Stable", diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 34c90d78d..bb69de05c 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -71,3 +71,6 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle click.echo("DONE:{}s".format(time.time() - start_time)) click.echo("RESULTS:") click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True)) + +if __name__ == "__main__": + gcode_command() diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 5fed71e5a..dc9ff6cbf 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -82,7 +82,6 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi ignore_blacklist=ignore_blacklist, after_safe_mode=log_startup, after_environment_detector=log_register_rollover) - settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components except FatalStartupError as e: diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 01622b837..44cd9e4f1 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -256,7 +256,7 @@ class FileManager(object): file_name = storage_manager.split_path(path) # we'll use the default printer profile for the backlog since we don't know better - queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default()) + queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None) if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority): counter += 1 @@ -476,12 +476,9 @@ class FileManager(object): path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display) - if analysis is None: - queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile) - if queue_entry: - self._analysis_queue.enqueue(queue_entry, high_priority=True) - else: - self._add_analysis_result(destination, path, analysis) + queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis) + if queue_entry: + self._analysis_queue.enqueue(queue_entry, high_priority=True) _, name = self._storage(destination).split_path(path_in_storage) eventManager().fire(Events.FILE_ADDED, dict(storage=destination, @@ -700,7 +697,7 @@ class FileManager(object): def _on_analysis_finished(self, entry, result): self._add_analysis_result(entry.location, entry.path, result) - def _analysis_queue_entry(self, destination, path, printer_profile=None): + def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None): if printer_profile is None: printer_profile = self._printer_profile_manager.get_current_or_default() @@ -709,6 +706,6 @@ class FileManager(object): file_type = get_file_type(absolute_path) if file_type: - return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile) + return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis) else: return None diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index ad24a3e4f..b8b9dd246 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -20,7 +20,7 @@ from octoprint.events import Events, eventManager from octoprint.settings import settings -class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")): +class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")): """ A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary for processing. @@ -33,6 +33,7 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio location (str): Location the file is located on. absolute_path (str): Absolute path on disk through which to access the file. printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis. + analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none. """ def __str__(self): @@ -298,7 +299,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): - * **Key** * **Description** - * ``estimatedPrintTime`` - * Estimated time the file take to print, in minutes + * Estimated time the file take to print, in seconds - * ``filament`` * Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for the second and so on. For each tool extruded length and volume (based on diameter) are provided. @@ -341,6 +342,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): import sys import yaml + if self._current.analysis: + return self._current.analysis try: throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \ else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) @@ -364,7 +367,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): self._logger.info("Invoking analysis command: {}".format(" ".join(command))) self._aborted = False - p = sarge.run(command, async=True, stdout=sarge.Capture()) + p = sarge.run(command, async_=True, stdout=sarge.Capture()) while len(p.commands) == 0: # somewhat ugly... we can't use wait_events because diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index fa24ccf0a..0ebbbc664 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -94,7 +94,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en if plugin_restart_needing_hooks is None: plugin_restart_needing_hooks = ["octoprint.server.http.*", - "octoprint.printer.factory"] + "octoprint.printer.factory", + "octoprint.timelapse.extensions"] if plugin_obsolete_hooks is None: plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index d92ed0a80..54566de4f 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -861,7 +861,7 @@ class PluginManager(object): if plugin.check(): return plugin else: - self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin))) + self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) return None def _is_plugin_disabled(self, key): diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 79306a4ec..70f7c23e4 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -225,6 +225,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin): js JavaScript files, such as additional view models + jsclient + JavaScript files containing additional parts for the JS Client Library (since 1.3.10) css CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode. less @@ -239,6 +241,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin): def get_assets(self): return dict( js=['js/my_file.js', 'js/my_other_file.js'], + clientjs=['clientjs/my_file.js'], css=['css/my_styles.css'], less=['less/my_styles.less'] ) @@ -1984,7 +1987,7 @@ class SlicerPlugin(OctoPrintPlugin): For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information about the slicing job under the following keys: - _analysis + analysis Analysis result of the generated machine code as returned by the slicer itself. This should match the data structure described for the analysis queue of the matching machine code format, e.g. :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files. diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 0dd9a4be2..8900c5d7a 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -49,7 +49,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ AssetPlugin def get_assets(self): - return dict(js=["js/action_command_prompt.js"]) + return dict(js=["js/action_command_prompt.js"], + clientjs=["clientjs/action_command_prompt.js"]) #~ SettingsPlugin diff --git a/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js new file mode 100644 index 000000000..9ba9b4a14 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js @@ -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; +}); diff --git a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js index 6298a5338..e077903a2 100644 --- a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js +++ b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js @@ -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; diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index bccea5198..8ff8e289a 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -372,15 +372,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, result = [] if "entries" in feed: for entry in feed["entries"]: - internal_entry = self._to_internal_entry(entry, read_until=read_until) - if internal_entry: - result.append(internal_entry) + try: + internal_entry = self._to_internal_entry(entry, read_until=read_until) + if internal_entry: + result.append(internal_entry) + except: + self._logger.exception("Error while converting entry from feed, skipping it") return result def _to_internal_entry(self, entry, read_until=None): """Convert feed entries to internal data structure.""" - published = calendar.timegm(entry["published_parsed"]) + timestamp = entry.get("published_parsed", + entry.get("updated_parsed", + None)) + if timestamp is None: + return None + + published = calendar.timegm(timestamp) read = True if read_until is not None: diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py new file mode 100644 index 000000000..4a260a9de --- /dev/null +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -0,0 +1,371 @@ +# coding=utf-8 +from __future__ import absolute_import + +import flask +import threading +import os +import yaml +import codecs +import time +from binascii import hexlify +from collections import defaultdict +from flask_babel import gettext + +import octoprint.plugin +from octoprint.settings import valid_boolean_trues +from octoprint.server.util.flask import restricted_access, no_firstrun_access +from octoprint.server import NO_CONTENT, current_user, admin_permission +from octoprint.util import atomic_write, monotonic_time + + +CUTOFF_TIME = 10 * 60 # 10min + + +class AppAlreadyExists(Exception): + pass + + +class PendingDecision(object): + def __init__(self, app_id, app_token, user_id, user_token): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + self.user_token = user_token + self.created = monotonic_time() + + def external(self): + return dict(app_id=self.app_id, + user_id=self.user_id, + user_token=self.user_token) + + +class ReadyDecision(object): + def __init__(self, app_id, app_token, user_id): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + + @classmethod + def for_pending(cls, pending, user_id): + return cls(pending.app_id, pending.app_token, user_id) + + +class ActiveKey(object): + def __init__(self, app_id, api_key, user_id): + self.app_id = app_id + self.api_key = api_key + self.user_id = user_id + + def external(self): + return dict(app_id=self.app_id, + api_key=self.api_key, + user_id=self.user_id) + + def internal(self): + return dict(app_id=self.app_id, + api_key=self.api_key) + + @classmethod + def for_internal(cls, internal, user_id): + return cls(internal["app_id"], internal["api_key"], user_id) + + +class AppKeysPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin): + + def __init__(self): + self._pending_decisions = [] + self._pending_lock = threading.RLock() + + self._ready_decisions = [] + self._ready_lock = threading.RLock() + + self._keys = defaultdict(list) + self._keys_lock = threading.RLock() + + self._key_path = None + + def initialize(self): + self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") + self._load_keys() + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="usersettings", name=gettext("Application Keys")), + dict(type="settings", name=gettext("Application Keys"))] + + ##~~ AssetPlugin + + def get_assets(self): + return dict(js=["js/appkeys.js"], + clientjs=["clientjs/appkeys.js"], + less=["less/appkeys.less"], + css=["css/appkeys.css"]) + + ##~~ BlueprintPlugin mixin + + @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) + @no_firstrun_access + def handle_request(self): + data = flask.request.json + if not "app" in data: + return flask.make_response("No app name provided", 400) + + app_name = data["app"] + user_id = None + if "user" in data: + user_id = data["user"] + + app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) + + self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access", + app_name=app_name, + user_token=user_token, + user_id=user_id)) + response = flask.jsonify(app_token=app_token) + response.status_code = 202 + response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True) + return response + + @octoprint.plugin.BlueprintPlugin.route("/request/") + @no_firstrun_access + def handle_decision_poll(self, app_token): + if self._is_pending(app_token): + response = flask.jsonify(message="Awaiting decision") + response.status_code = 202 + return response + + result = self._get_decision(app_token) + if result: + return flask.jsonify(api_key=result) + + return flask.abort(404) + + @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) + @restricted_access + def handle_decision(self, user_token): + data = flask.request.json + if not "decision" in data: + return flask.make_response("No decision provided", 400) + decision = data["decision"] in valid_boolean_trues + user_id = current_user.get_name() + + result = self._set_decision(user_token, decision, user_id) + if not result: + return flask.abort(404) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False # No API key required to request API access + + ##~~ SimpleApiPlugin mixin + + def get_api_commands(self): + return dict(generate=["app"], + revoke=["key"]) + + def on_api_get(self, request): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if request.values.get("all") in valid_boolean_trues and admin_permission.can(): + keys = self._all_api_keys() + else: + keys = self._api_keys_for_user(user_id) + + return flask.jsonify(keys=map(lambda x: x.external(), keys), + pending=dict((x.user_token, x.external()) for x in self._get_pending(user_id))) + + def on_api_command(self, command, data): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if command == "revoke": + api_key = data.get("key") + if not api_key: + return flask.abort(400) + + if not admin_permission.can(): + user_for_key = self._user_for_api_key(api_key) + if user_for_key is None or user_for_key.user_id != user_id: + return flask.abort(403) + + self._delete_api_key(api_key) + + elif command == "generate": + # manual generateKey + app_name = data.get("app") + if not app_name: + return flask.abort(400) + + self._add_api_key(user_id, app_name.strip()) + + return NO_CONTENT + + ##~~ key validator hook + + def validate_api_key(self, api_key, *args, **kwargs): + return self._user_for_api_key(api_key) + + ##~~ Helpers + + def _add_pending_decision(self, app_name, user_id=None): + app_token = self._generate_key() + user_token = self._generate_key() + + with self._pending_lock: + self._remove_stale_pending() + self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token)) + + return app_token, user_token + + def _is_pending(self, app_token): + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.app_token == app_token: + return True + + return False + + def _get_pending(self, user_id): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_id == user_id or data.user_id is None: + result.append(data) + return result + + def _remove_stale_pending(self): + with self._pending_lock: + cutoff = monotonic_time() - CUTOFF_TIME + len_before = len(self._pending_decisions) + self._pending_decisions = filter(lambda x: x.created >= cutoff, + self._pending_decisions) + len_after = len(self._pending_decisions) + if len_after < len_before: + self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after)) + + def _set_decision(self, user_token, decision, user_id): + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_token == user_token and (data.user_id == user_id or data.user_id is None): + pending = data + break + else: + return False # not found + + if decision: + with self._ready_lock: + self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) + + with self._pending_lock: + self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions) + + return True + + def _get_decision(self, app_token): + self._remove_stale_pending() + + with self._ready_lock: + for data in self._ready_decisions: + if data.app_token == app_token: + decision = data + break + else: + return False # not found + + api_key = self._add_api_key(decision.user_id, decision.app_id) + + with self._ready_lock: + self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions) + + return api_key + + def _add_api_key(self, user_id, app_name): + with self._keys_lock: + for key in self._keys[user_id]: + if key.app_id.lower() == app_name.lower(): + return key.api_key + + key = ActiveKey(app_name, self._generate_key(), user_id) + self._keys[user_id].append(key) + self._save_keys() + return key.api_key + + def _delete_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + self._keys[user_id] = filter(lambda x: x.api_key != api_key, data) + self._save_keys() + + def _user_for_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + if filter(lambda x: x.api_key == api_key, data): + return self._user_manager.findUser(userid=user_id) + return None + + def _api_keys_for_user(self, user_id): + with self._keys_lock: + return self._keys[user_id] + + def _all_api_keys(self): + with self._keys_lock: + result = [] + for user_id, keys in self._keys.items(): + result += keys + return result + + def _generate_key(self): + return hexlify(os.urandom(16)) + + def _load_keys(self): + with self._keys_lock: + if not os.path.exists(self._key_path): + return + + try: + with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f: + persisted = yaml.safe_load(f) + except: + self._logger.exception("Could not load application keys from {}".format(self._key_path)) + return + + if not isinstance(persisted, dict): + return + + keys = defaultdict(list) + for user_id, persisted_keys in persisted.items(): + keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys] + self._keys = keys + + def _save_keys(self): + with self._keys_lock: + to_persist = dict() + for user_id, keys in self._keys.items(): + to_persist[user_id] = [x.internal() for x in keys] + + try: + with atomic_write(self._key_path) as f: + yaml.safe_dump(to_persist, f) + except: + self._logger.exception("Could not write application keys to {}".format(self._key_path)) + +__plugin_name__ = u"Application Keys Plugin" +__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys" +__plugin_author__ = u"Gina Häußge, Aldo Hoeben" +__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to " + u"obtain an API key without you manually copy-pasting it.") +__plugin_implementation__ = AppKeysPlugin() +__plugin_hooks__ = { + "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key +} diff --git a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js new file mode 100644 index 000000000..580ad1364 --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js @@ -0,0 +1,87 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintAppKeysClient = function(base) { + this.base = base; + }; + + OctoPrintAppKeysClient.prototype.getKeys = function(opts) { + return this.base.simpleApiGet("appkeys", opts); + }; + + OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) { + return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts); + }; + + OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) { + return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts); + }; + + OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) { + return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts); + }; + + OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts); + }; + + OctoPrintAppKeysClient.prototype.request = function(app, opts) { + return this.requestForUser(app, undefined, opts); + }; + + OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts); + }; + + OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) { + return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts); + }; + + OctoPrintAppKeysClient.prototype.authenticate = function(app, user) { + var deferred = $.Deferred(); + var client = this; + + client.requestForUser(app, user) + .done(function(response) { + var token = response.app_token; + if (!token) { + // no token received, something went wrong + deferred.reject(); + return; + } + + var interval = 1000; + var poll = function() { + client.checkDecision(token) + .done(function(response) { + if (response.api_key) { + // got a decision, resolve the promise + deferred.resolve(response.api_key); + } else { + // no decision yet, poll a bit more + deferred.notify(); + window.setTimeout(poll, interval); + } + }) + .fail(function() { + // something went wrong + deferred.reject(); + }); + }; + window.setTimeout(poll, interval); + }) + .fail(function() { + // something went wrong + deferred.reject(); + }); + + return deferred.promise(); + }; + + OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient); + return OctoPrintAppKeysClient; +}); diff --git a/src/octoprint/plugins/appkeys/static/css/appkeys.css b/src/octoprint/plugins/appkeys/static/css/appkeys.css new file mode 100644 index 000000000..6240d21d7 --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/css/appkeys.css @@ -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} \ No newline at end of file diff --git a/src/octoprint/plugins/appkeys/static/js/appkeys.js b/src/octoprint/plugins/appkeys/static/js/appkeys.js new file mode 100644 index 000000000..bdd72e97b --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/js/appkeys.js @@ -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("\"%(app)s\" has requested access to control OctoPrint through the API."); + message = _.sprintf(message, {app: app}); + message = "

" + message + "

" + gettext("Do you want to allow access to this application with your user account?") + "

"; + 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"] + ]) +}); diff --git a/src/octoprint/plugins/appkeys/static/less/appkeys.less b/src/octoprint/plugins/appkeys/static/less/appkeys.less new file mode 100644 index 000000000..0e7d3f1c8 --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/less/appkeys.less @@ -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; + } + } +} diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 new file mode 100644 index 000000000..700fb8f2b --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 @@ -0,0 +1,59 @@ +
+

{{ _('There are no application keys registered yet.') }}

+
+
+ + + + + + + + + + + + + + + + + + +
{{ _('User') }}{{ _('Application identifier') }}{{ _('Action') }}

{{ _('API Key') }}:
+ +
diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 new file mode 100644 index 000000000..2499b2330 --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 @@ -0,0 +1,49 @@ +{{ _('Registered application keys') }} + +
+

{{ _('There are no application keys registered yet.') }}

+
+
+ + + + + + + + + + + + + +
{{ _('Application identifier') }}{{ _('Action') }}

{{ _('API Key') }}:
+ +
+ +{{ _('Manually generate an application key') }} + +
+
+ +
+ +
+
+ +
+
+ +
+
+
diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py new file mode 100644 index 000000000..cf75a073a --- /dev/null +++ b/src/octoprint/plugins/backup/__init__.py @@ -0,0 +1,866 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from octoprint.settings import default_settings +from octoprint.plugin.core import FolderOrigin +from octoprint.server import admin_permission, NO_CONTENT +from octoprint.server.util.flask import restricted_access +from octoprint.util import is_hidden_path +from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version +from octoprint.util.pip import LocalPipCaller + +try: + from os import scandir +except ImportError: + from scandir import scandir + +try: + import zlib # check if zlib is available +except ImportError: + zlib = None + + +from flask_babel import gettext + +import codecs +import flask +import logging +import os +import requests +import sarge +import shutil +import tempfile +import threading +import time +import zipfile +import json +import sys +import traceback + + +UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json" + + +class BackupPlugin(octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.StartupPlugin): + + _pip_caller = None + + # noinspection PyMissingConstructor + def __init__(self): + self._in_progress = [] + self._in_progress_lock = threading.RLock() + + ##~~ StarupPlugin + + def on_after_startup(self): + self._clean_dir_backup(self._settings._basedir, + on_log_progress=self._logger.info) + + ##~~ AssetPlugin + + def get_assets(self): + return dict(js=["js/backup.js"], + clientjs=["clientjs/backup.js"], + css=["css/backup.css"], + less=["less/backup.less"]) + + ##~~ BlueprintPlugin + + @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) + @admin_permission.require(403) + @restricted_access + def get_state(self): + backups = self._get_backups() + unknown_plugins = self._get_unknown_plugins() + return flask.jsonify(backups=backups, + backup_in_progress=len(self._in_progress) > 0, + unknown_plugins=unknown_plugins) + + @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"]) + @admin_permission.require(403) + @restricted_access + def get_unknown_plugins(self): + # TODO add caching + unknown_plugins = self._get_unknown_plugins() + return flask.jsonify(unknown_plugins=unknown_plugins) + + @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"]) + @admin_permission.require(403) + @restricted_access + def delete_unknown_plugins(self): + data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) + try: + os.remove(data_file) + except: + pass + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"]) + @admin_permission.require(403) + @restricted_access + def get_backups(self): + backups = self._get_backups() + return flask.jsonify(backups=backups) + + @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"]) + @admin_permission.require(403) + @restricted_access + def create_backup(self): + backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S")) + + data = flask.request.json + exclude = data.get("exclude", []) + + def on_backup_start(name, temporary_path, exclude): + self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path, + u",".join(exclude) if len(exclude) else "-")) + + with self._in_progress_lock: + self._in_progress.append(name) + self._send_client_message("backup_started", payload=dict(name=name)) + + def on_backup_done(name, final_path, exclude): + with self._in_progress_lock: + self._in_progress.remove(name) + self._send_client_message("backup_done", payload=dict(name=name)) + + self._logger.info(u"... done creating backup zip.") + + + thread = threading.Thread(target=self._create_backup, + args=(backup_file,), + kwargs=dict(exclude=exclude, + settings=self._settings, + plugin_manager=self._plugin_manager, + datafolder=self.get_plugin_data_folder(), + on_backup_start=on_backup_start, + on_backup_done=on_backup_done)) + thread.daemon = True + thread.start() + + response = flask.jsonify(started=True, + name=backup_file) + response.status_code = 201 + return response + + @octoprint.plugin.BlueprintPlugin.route("/backup/", methods=["DELETE"]) + @admin_permission.require(403) + @restricted_access + def delete_backup(self, filename): + backup_folder = self.get_plugin_data_folder() + full_path = os.path.realpath(os.path.join(backup_folder, filename)) + if full_path.startswith(backup_folder) \ + and os.path.exists(full_path) \ + and not is_hidden_path(full_path): + try: + os.remove(full_path) + except: + self._logger.exception(u"Could not delete {}".format(filename)) + raise + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) + @admin_permission.require(403) + @restricted_access + def perform_restore(self): + input_name = "file" + input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) + + if input_upload_path in flask.request.values: + # file to restore was uploaded + path = flask.request.values[input_upload_path] + + elif flask.request.json and "path" in flask.request.json: + # existing backup is supposed to be restored + backup_folder = self.get_plugin_data_folder() + path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"])) + if not path.startswith(backup_folder) \ + or not os.path.exists(path) \ + or is_hidden_path(path): + return flask.abort(404) + + else: + return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400) + + def on_install_plugins(plugins): + force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) + pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"]) + + def on_log(line): + self._logger.info(line) + self._send_client_message("logline", dict(line=line, type="stdout")) + + for plugin in plugins: + octoprint_compatible = plugin["compatibility"]["octoprint"] + os_compatible = plugin["compatibility"]["os"] + compatible = octoprint_compatible and os_compatible + if not compatible: + if not octoprint_compatible and not os_compatible: + self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version " + u"of OctoPrint and the underlying operating system".format(plugin["id"])) + elif not octoprint_compatible: + self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version " + u"of OctoPrint".format(plugin["id"])) + elif not os_compatible: + self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying " + u"operating system".format(plugin["id"])) + self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"], + octoprint_compatible=octoprint_compatible, + os_compatible=os_compatible)) + continue + + self._logger.info(u"Installing plugin {}".format(plugin["id"])) + self._send_client_message("installing_plugin", dict(plugin=plugin["id"])) + self.__class__._install_plugin(plugin, + force_user=force_user, + pip_args=pip_args, + on_log=on_log) + + def on_report_unknown_plugins(plugins): + self._send_client_message("unknown_plugins", payload=dict(plugins=plugins)) + + def on_log_progress(line): + self._logger.info(line) + self._send_client_message("logline", payload=dict(line=line, stream="stdout")) + + def on_log_error(line, exc_info=None): + self._logger.error(line, exc_info=exc_info) + self._send_client_message("logline", payload=dict(line=line, stream="stderr")) + + if exc_info is not None: + exc_type, exc_value, exc_tb = exc_info + output = traceback.format_exception(exc_type, exc_value, exc_tb) + for line in output: + self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr")) + + def on_restore_start(path): + self._send_client_message("restore_started") + + def on_restore_done(path): + self._send_client_message("restore_done") + + def on_restore_failed(path): + self._send_client_message("restore_failed") + + archive = tempfile.NamedTemporaryFile(delete=False) + archive.close() + shutil.copy(path, archive.name) + path = archive.name + + # noinspection PyTypeChecker + thread = threading.Thread(target=self._restore_backup, + args=(path,), + kwargs=dict(settings=self._settings, + plugin_manager=self._plugin_manager, + datafolder=self.get_plugin_data_folder(), + on_install_plugins=on_install_plugins, + on_report_unknown_plugins=on_report_unknown_plugins, + on_log_progress=on_log_progress, + on_log_error=on_log_error, + on_restore_start=on_restore_start, + on_restore_done=on_restore_done, + on_restore_failed=on_restore_failed)) + thread.daemon = True + thread.start() + + return flask.jsonify(started=True) + + ##~~ tornado hook + + def route_hook(self, *args, **kwargs): + from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory + from octoprint.util import is_hidden_path + from octoprint.server import app + from octoprint.server.util.tornado import access_validation_factory + from octoprint.server.util.flask import admin_validator + + return [ + (r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(), + as_attachment=True, + path_validation=path_validation_factory(lambda path: not is_hidden_path(path), + status_code=404), + access_validation=access_validation_factory(app, admin_validator))) + ] + + def bodysize_hook(self, current_max_body_sizes, *args, **kwargs): + # max upload size of 1GB for the restore endpoint + return [("POST", r"/restore", 1024 * 1024 * 1024)] + + ##~~ CLI hook + + def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): + import click + + @click.command("backup") + @click.option("--exclude", multiple=True, + help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or " + "'timelapse' to exclude timelapses.") + def backup_command(exclude): + """ + Creates a new backup. + """ + + backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S")) + settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) + + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + click.echo("Creating backup at {}, please wait...".format(backup_file)) + self._create_backup(backup_file, + exclude=exclude, + settings=settings, + plugin_manager=cli_group.plugin_manager, + datafolder=datafolder) + click.echo("Done.") + + @click.command("restore") + @click.argument("path") + def restore_command(path): + """ + Restores an existing backup from the backup zip provided as argument. + + OctoPrint does not need to run for this to proceed. + """ + settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) + plugin_manager = cli_group.plugin_manager + + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + # register plugin manager plugin setting overlays + plugin_info = plugin_manager.get_plugin_info("pluginmanager") + if plugin_info and plugin_info.implementation: + default_settings_overlay = dict(plugins=dict()) + default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults() + settings.add_overlay(default_settings_overlay, at_end=True) + + if not os.path.isabs(path): + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + path = os.path.join(datafolder, path) + + if not os.path.exists(path): + click.echo(u"Backup {} does not exist".format(path), err=True) + sys.exit(-1) + + archive = tempfile.NamedTemporaryFile(delete=False) + archive.close() + shutil.copy(path, archive.name) + path = archive.name + + def on_install_plugins(plugins): + if not plugins: + return + + force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) + pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) + + def log(line): + click.echo(u"\t{}".format(line)) + + for plugin in plugins: + octoprint_compatible = plugin["compatibility"]["octoprint"] + os_compatible = plugin["compatibility"]["os"] + compatible = octoprint_compatible and os_compatible + if not compatible: + if not octoprint_compatible and not os_compatible: + click.echo(u"Cannot install plugin {}, it is incompatible to this version of " + u"OctoPrint and the underlying operating system".format(plugin["id"])) + elif not octoprint_compatible: + click.echo(u"Cannot install plugin {}, it is incompatible to this version of " + u"OctoPrint".format(plugin["id"])) + elif not os_compatible: + click.echo(u"Cannot install plugin {}, it is incompatible to the underlying " + u"operating system".format(plugin["id"])) + continue + + click.echo(u"Installing plugin {}".format(plugin["id"])) + self.__class__._install_plugin(plugin, + force_user=force_user, + pip_args=pip_args, + on_log=log) + + def on_report_unknown_plugins(plugins): + if not plugins: + return + + click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.") + for plugin in plugins: + click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?")) + + def on_log_progress(line): + click.echo(line) + + def on_log_error(line, exc_info=None): + click.echo(line, err=True) + + if exc_info is not None: + exc_type, exc_value, exc_tb = exc_info + output = traceback.format_exception(exc_type, exc_value, exc_tb) + for line in output: + click.echo(line.rstrip(), err=True) + + if self._restore_backup(path, + settings=settings, + plugin_manager=plugin_manager, + datafolder=datafolder, + on_install_plugins=on_install_plugins, + on_report_unknown_plugins=on_report_unknown_plugins, + on_log_progress=on_log_progress, + on_log_error=on_log_error): + click.echo(u"Restored from {}".format(path)) + else: + click.echo(u"Restoring from {} failed".format(path), err=True) + + return [backup_command, restore_command] + + ##~~ helpers + + def _get_backups(self): + backups = [] + for entry in scandir(self.get_plugin_data_folder()): + if is_hidden_path(entry.path): + continue + if not entry.is_file(): + continue + if not entry.name.endswith(".zip"): + continue + + backups.append(dict(name=entry.name, + date=entry.stat().st_mtime, + size=entry.stat().st_size, + url=flask.url_for("index") + "plugin/backup/download/" + entry.name)) + return backups + + def _get_unknown_plugins(self): + data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) + if os.path.exists(data_file): + try: + with codecs.open(data_file, mode="r", encoding="utf-8") as f: + unknown_plugins = json.load(f) + + assert isinstance(unknown_plugins, list) + assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins)) + + installed_plugins = self._plugin_manager.plugins + unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins) + if not unknown_plugins: + # no plugins left uninstalled, delete data file + try: + os.remove(data_file) + except: + self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file)) + + return unknown_plugins + except: + self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file)) + try: + os.remove(data_file) + except: + self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file)) + + return [] + + @classmethod + def _clean_dir_backup(cls, basedir, + on_log_progress=None): + basedir_backup = basedir + ".bck" + + if os.path.exists(basedir_backup): + def remove_bck(): + if callable(on_log_progress): + on_log_progress(u"Found config folder backup from prior restore, deleting it...") + shutil.rmtree(basedir_backup) + if callable(on_log_progress): + on_log_progress(u"... deleted.") + + thread = threading.Thread(target=remove_bck) + thread.daemon = True + thread.start() + + @classmethod + def _get_disk_size(cls, path): + total = 0 + for entry in scandir(path): + if entry.is_dir(): + total += cls._get_disk_size(entry.path) + elif entry.is_file(): + total += entry.stat().st_size + return total + + @classmethod + def _free_space(cls, path, size): + from psutil import disk_usage + return disk_usage(path).free > size + + @classmethod + def _get_plugin_repository_data(cls, url, logger=None): + if logger is None: + logger = logging.getLogger(__name__) + + try: + r = requests.get(url, timeout=30) + r.raise_for_status() + except: + logger.exception(u"Error while fetching the plugin repository data from {}".format(url)) + return dict() + + from octoprint.plugins.pluginmanager import map_repository_entry + return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json())) + + @classmethod + def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None): + if pip_args is None: + pip_args = [] + + if on_log is None: + on_log = logging.getLogger(__name__).info + + # prepare pip caller + def log(prefix, *lines): + for line in lines: + on_log(u"{} {}".format(prefix, line.rstrip())) + + def log_call(*lines): + log(u">", *lines) + + def log_stdout(*lines): + log(u"<", *lines) + + def log_stderr(*lines): + log(u"!", *lines) + + if cls._pip_caller is None: + cls._pip_caller = LocalPipCaller(force_user=force_user) + + cls._pip_caller.on_log_call = log_call + cls._pip_caller.on_log_stdout = log_stdout + cls._pip_caller.on_log_stderr = log_stderr + + # install plugin + pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir'] + + if plugin.get("follow_dependency_links"): + pip.append("--process-dependency-links") + + if force_user: + pip.append("--user") + + if pip_args: + pip += pip_args + + cls._pip_caller.execute(*pip) + + @classmethod + def _create_backup(cls, name, + exclude=None, + settings=None, + plugin_manager=None, + datafolder=None, + on_backup_start=None, + on_backup_done=None): + if exclude is None: + exclude = [] + + configfile = settings._configfile + basedir = settings._basedir + + temporary_path = os.path.join(datafolder, ".{}".format(name)) + final_path = os.path.join(datafolder, name) + + size = cls._get_disk_size(basedir) + if not cls._free_space(os.path.dirname(temporary_path), size): + raise InsufficientSpace() + + own_folder = datafolder + defaults = [os.path.join(basedir, "config.yaml"),] + \ + [os.path.join(basedir, folder) for folder in default_settings["folder"].keys()] + + compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED + + if callable(on_backup_start): + on_backup_start(name, temporary_path, exclude) + + with zipfile.ZipFile(temporary_path, "w", compression) as zip: + def add_to_zip(source, target, ignored=None): + if ignored is None: + ignored = [] + + if source in ignored: + return + + if os.path.isdir(source): + for entry in scandir(source): + add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored) + elif os.path.isfile(source): + zip.write(source, arcname=target) + + # add metadata + metadata = dict(version=get_octoprint_version_string(), + excludes=exclude) + zip.writestr("metadata.json", json.dumps(metadata)) + + # backup current config file + add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,]) + + # backup configured folder paths + for folder in default_settings["folder"].keys(): + if folder in exclude: + continue + add_to_zip(settings.global_get_basefolder(folder), + "basedir/" + folder.replace("_", "/"), + ignored=[own_folder,]) + + # backup anything else that might be lying around in our basedir + add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ]) + + # add list of installed plugins + plugins = [] + plugin_folder = settings.global_get_basefolder("plugins") + for key, plugin in plugin_manager.plugins.items(): + if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder): + # ignore anything bundled or from the plugins folder we already include in the backup + continue + + plugins.append(dict(key=plugin.key, + name=plugin.name, + url=plugin.url)) + + if len(plugins): + zip.writestr("plugin_list.json", json.dumps(plugins)) + + os.rename(temporary_path, final_path) + + if callable(on_backup_done): + on_backup_done(name, final_path, exclude) + + @classmethod + def _restore_backup(cls, path, + settings=None, + plugin_manager=None, + datafolder=None, + on_install_plugins=None, + on_report_unknown_plugins=None, + on_invalid_backup=None, + on_log_progress=None, + on_log_error=None, + on_restore_start=None, + on_restore_done=None, + on_restore_failed=None): + restart_command = settings.global_get(["server", "commands", "serverRestartCommand"]) + + basedir = settings._basedir + cls._clean_dir_backup(basedir, + on_log_progress=on_log_progress) + + plugin_repo = dict() + repo_url = settings.global_get(["plugins", "pluginmanager", "repository"]) + if repo_url: + plugin_repo = cls._get_plugin_repository_data(repo_url) + + if callable(on_restore_start): + on_restore_start(path) + + try: + + with zipfile.ZipFile(path, "r") as zip: + # read metadata + try: + metadata_zipinfo = zip.getinfo("metadata.json") + except KeyError: + if callable(on_invalid_backup): + on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json") + return False + + metadata_bytes = zip.read(metadata_zipinfo) + metadata = json.loads(metadata_bytes) + + backup_version = get_comparable_version(metadata["version"]) + if backup_version > get_octoprint_version(): + if callable(on_invalid_backup): + on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied") + return False + + # unzip to temporary folder + temp = tempfile.mkdtemp() + try: + if callable(on_log_progress): + on_log_progress(u"Unpacking backup to {}...".format(temp)) + abstemp = os.path.abspath(temp) + for member in zip.infolist(): + abspath = os.path.abspath(os.path.join(temp, member.filename)) + if abspath.startswith(abstemp): + zip.extract(member, temp) + + # sanity check + configfile = os.path.join(temp, "basedir", "config.yaml") + if not os.path.exists(configfile): + if callable(on_invalid_backup): + on_invalid_backup(u"Backup lacks config.yaml") + return False + + import yaml + + with codecs.open(configfile) as f: + configdata = yaml.safe_load(f) + + if configdata.get("accessControl", dict()).get("enabled", True): + userfile = os.path.join(temp, "basedir", "users.yaml") + if not os.path.exists(userfile): + if callable(on_invalid_backup): + on_invalid_backup(u"Backup lacks users.yaml") + return False + + if callable(on_log_progress): + on_log_progress(u"Unpacked") + + # install available plugins + with codecs.open(os.path.join(temp, "plugin_list.json"), "r") as f: + plugins = json.load(f) + + known_plugins = [] + unknown_plugins = [] + if plugins: + if plugin_repo: + for plugin in plugins: + if plugin["key"] in plugin_manager.plugins: + # already installed + continue + + if plugin["key"] in plugin_repo: + # not installed, can be installed from repository url + known_plugins.append(plugin_repo[plugin["key"]]) + else: + # not installed, not installable + unknown_plugins.append(plugin) + + else: + # no repo, all plugins are not installable + unknown_plugins = plugins + + if callable(on_log_progress): + if known_plugins: + on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins)))) + if unknown_plugins: + on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins)))) + + if callable(on_install_plugins): + on_install_plugins(known_plugins) + + if callable(on_report_unknown_plugins): + on_report_unknown_plugins(unknown_plugins) + + # move config data + basedir_backup = basedir + ".bck" + basedir_extracted = os.path.join(temp, "basedir") + + if callable(on_log_progress): + on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup)) + os.rename(basedir, basedir_backup) + + try: + if callable(on_log_progress): + on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir)) + os.rename(basedir_extracted, basedir) + except: + if callable(on_log_error): + on_log_error(u"Error while restoring config data", exc_info=sys.exc_info()) + on_log_error(u"Rolling back old config data") + + os.rename(basedir_backup, basedir) + + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if unknown_plugins: + if callable(on_log_progress): + on_log_progress(u"Writing info file about unknown plugins") + + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE) + try: + with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f: + json.dump(unknown_plugins, f) + except: + if callable(on_log_error): + on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path), + exc_info = sys.exc_info()) + + finally: + if callable(on_log_progress): + on_log_progress(u"Removing temporary unpacked folder") + shutil.rmtree(temp) + + except: + if callable(on_log_error): + on_log_error(u"Error while running restore", exc_info=sys.exc_info()) + if callable(on_restore_failed): + on_restore_failed(path) + return False + + finally: + # remove zip + if callable(on_log_progress): + on_log_progress(u"Removing temporary zip") + os.remove(path) + + # restart server + if restart_command: + import sarge + + if callable(on_log_progress): + on_log_progress(u"Restarting...") + try: + sarge.run(restart_command, async_=True) + except: + if callable(on_log_error): + on_log_error(u"Error while restarting via command {}".format(restart_command), + exc_info=sys.exc_info()) + on_log_error(u"Please restart OctoPrint manually") + return False + + if callable(on_restore_done): + on_restore_done(path) + + return True + + + def _send_client_message(self, message, payload=None): + if payload is None: + payload = dict() + payload["type"] = message + self._plugin_manager.send_plugin_message(self._identifier, payload) + + + +class InsufficientSpace(Exception): + pass + +__plugin_name__ = gettext(u"Backup & Restore") +__plugin_author__ = u"Gina Häußge" +__plugin_description__ = u"Backup & restore your OctoPrint settings and data" +__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup " + u"& restore your OctoPrint settings and data.") +__plugin_license__ = u"AGPLv3" +__plugin_implementation__ = BackupPlugin() +__plugin_hooks__ = { + "octoprint.server.http.routes": __plugin_implementation__.route_hook, + "octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook, + "octoprint.cli.commands": __plugin_implementation__.cli_commands_hook +} diff --git a/src/octoprint/plugins/backup/static/clientjs/backup.js b/src/octoprint/plugins/backup/static/clientjs/backup.js new file mode 100644 index 000000000..5f2ee6e62 --- /dev/null +++ b/src/octoprint/plugins/backup/static/clientjs/backup.js @@ -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; +}); diff --git a/src/octoprint/plugins/backup/static/css/backup.css b/src/octoprint/plugins/backup/static/css/backup.css new file mode 100644 index 000000000..f3561ce93 --- /dev/null +++ b/src/octoprint/plugins/backup/static/css/backup.css @@ -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} \ No newline at end of file diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js new file mode 100644 index 000000000..dadd24c8c --- /dev/null +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -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"] + }); +}); diff --git a/src/octoprint/plugins/backup/static/less/backup.less b/src/octoprint/plugins/backup/static/less/backup.less new file mode 100644 index 000000000..6f90681ff --- /dev/null +++ b/src/octoprint/plugins/backup/static/less/backup.less @@ -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; + } +} diff --git a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 new file mode 100644 index 000000000..2d0e5e57f --- /dev/null +++ b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 @@ -0,0 +1,129 @@ +
+ {% 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 %} +
    +
  • :
  • +
+ {{ _('Delete record of unknown plugins') }} +
+ + +

{{ _('Existing backups') }}

+ +
+

{{ _('There are no backups. Maybe create one below?') }}

+
+
+

{{ _('These are the backups of your settings and files that already exist on this OctoPrint instance. You may delete, download or restore them.') }}

+ + + + + + + + + + + + + + + + + + + + + +
{{ _('Name') }}{{ _('Date') }}{{ _('Size') }}{{ _('Action') }}
 |  | 
+ +
+ +

{{ _('Create backup') }}

+ +

{{ _('Create a new backup of the current state.') }}

+ +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ +

{{ _('Restore from uploaded backup') }}

+ +

{{ _('Restore settings & files from an uploaded backup archive.') }}

+ +
+
+ +
+
+ + {{ _('Browse...') }} + + + +
+
+
+ +
+
+ +
+
+
+ + diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 index 58cd4bfa7..823e65212 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 @@ -1,14 +1,22 @@

{{ _('Access Control') }}

-{% trans %}

+{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}

Please read the following, it is very important for your printer's health!

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 prevent strangers - possibly with - malicious intent - to gain access to your printer via the internet or another untrustworthy network + malicious intent - to gain access to your printer via an untrustworthy network and using it in such a way that it is damaged or worse (i.e. causes a fire).

+

+ If you plan on accessing OctoPrint remotely over the internet, you should not only rely on the built-in + Access Control mechanisms however - + take additional precautions. + 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! An instance available publicly on the internet + will be found, and people will try to break it open. +

It looks like you haven't configured access control yet. Please set up a username and password for the initial administrator account who will have full access to both the printer and OctoPrint's settings, then click @@ -36,12 +44,12 @@ {% trans %}

- Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't + Note: 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.

- Do NOT underestimate the risk of an unsecured access from the internet to your printer! + Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!

{% endtrans %}
diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index 79bcd31c9..c78cfc0d0 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -312,7 +312,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, working_dir)) import sarge - p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture()) + p = sarge.run(args, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture()) p.wait_events() self._slicing_commands[machinecode_path] = p.commands[0] diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py index 7b74fcdde..ac60d7074 100644 --- a/src/octoprint/plugins/cura/profile.py +++ b/src/octoprint/plugins/cura/profile.py @@ -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 diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js index a435065cb..9909b3b0a 100644 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ b/src/octoprint/plugins/cura/static/js/cura.js @@ -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 octoprint.log for details"), + type: "error", + hide: false + }); } }); diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 604e6337e..d5fb2fb41 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -194,8 +194,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, params["txtRecord"] = pybonjour.TXTRecord(txt_record) key = (reg_type, port) - self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) - self._logger.info(u"Registered {name} for {reg_type}".format(**locals())) + + counter = 1 + while True: + try: + self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) + self._logger.info(u"Registered '{name}' for {regtype}".format(**params)) + return True + except pybonjour.BonjourError as be: + if be.errorCode == pybonjour.kDNSServiceErr_NameConflict: + # Name already registered by different service, let's try a counter postfix. See #2852 + counter += 1 + params["name"] = u"{} ({})".format(name, counter) + else: + raise def zeroconf_unregister(self, reg_type, port=None): """ @@ -601,8 +613,14 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, alive message """ - from BaseHTTPServer import BaseHTTPRequestHandler - from StringIO import StringIO + try: + # noinspection PyCompatibility + from http.server import BaseHTTPRequestHandler + except ImportError: + # noinspection PyCompatibility + from BaseHTTPServer import BaseHTTPRequestHandler + + from io import BytesIO import socket socket.setdefaulttimeout(timeout) @@ -617,8 +635,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, class Request(BaseHTTPRequestHandler): + # noinspection PyMissingConstructor def __init__(self, request_text): - self.rfile = StringIO(request_text) + self.rfile = BytesIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request() diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py new file mode 100644 index 000000000..1c5ce3f6b --- /dev/null +++ b/src/octoprint/plugins/forcelogin/__init__.py @@ -0,0 +1,142 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +import flask +import flask_login +from flask_babel import gettext + +class ForceLoginPlugin(octoprint.plugin.UiPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin): + + def get_assets(self): + return dict( + js=["js/viewmodel.js"] + ) + + def will_handle_ui(self, request): + if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): + # ACL hasn't been configured yet, make an exception + return False + + from octoprint.server.util.flask import passive_login + + result = passive_login() + if hasattr(result, "status_code") and result.status_code == 200: + # passive login successful, no need to handle that + return False + else: + return True + + def on_ui_render(self, now, request, render_kwargs): + from flask import render_template, make_response + + """ + Support theming of the login dialog, just in case the core UI is themed as well. + + Example usage by a plugin: + + def forcelogin_theming(): + from flask import url_for + return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")] + + __plugin_hooks__ = { + "octoprint.plugin.forcelogin.theming": forcelogin_theming + } + + Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use + url_for like in the example above to be prepared for any configured prefix URLs. + """ + additional_assets = [] + for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items(): + try: + assets = hook() + if isinstance(assets, (tuple, list)): + additional_assets += assets + except: + self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name)) + + render_kwargs.update(dict(forcelogin_theming=additional_assets)) + return make_response(render_template("forcelogin_index.jinja2", **render_kwargs)) + + def get_ui_custom_tracked_files(self): + from os.path import join as opj + + paths = [opj("static", "css", "forcelogin.css"), + opj("static", "js", "main.js"), + opj("static", "js", "viewmodel.js"), + opj("static", "less", "forcelogin.less"), + opj("templates", "parts", "forcelogin_css.jinja2"), + opj("templates", "parts", "forcelogin_javascripts.jinja2"), + opj("templates", "forcelogin_index.jinja2")] + + return [opj(self._basefolder, path) for path in paths] + + def get_ui_preemptive_caching_enabled(self): + return False + + def get_before_request_handlers(self): + def check_login_required(): + if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): + # ACL hasn't been configured yet, make an exception + return + + if flask.request.endpoint in ("api.login",): + return + + user = flask_login.current_user + if user is None or user.is_anonymous() or not user.is_active(): + return flask.make_response("Forbidden", 403) + + return [check_login_required] + + def access_validator(self, request): + if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): + # ACL hasn't been configured yet, make an exception + return + + import tornado.web + from octoprint.server.util.flask import get_flask_user_from_request + + user = get_flask_user_from_request(request) + if user is None or not user.is_authenticated(): + raise tornado.web.HTTPError(403) + + def socket_register_validator(self, socket, user): + if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): + # ACL hasn't been configured yet, make an exception + return True + + return user is not None and not user.is_anonymous() and user.is_active() + + def socket_emit_validator(self, socket, user, message, payload): + if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): + # ACL hasn't been configured yet, make an exception + return True + + if message in ("connected", "reauthRequired"): + return True + + return user is not None and not user.is_anonymous() and user.is_active() + + +__plugin_name__ = "Force Login" +__plugin_author__ = "Gina Häußge" +__plugin_description__ = "Forces users to login, disables read-only mode." +__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your " + "OctoPrint instance. Only disable this if you are comfortable with this, your " + "OctoPrint instance is not publicly reachable on the internet and you fully " + "trust everyone who has access to your local network!") + +__plugin_implementation__ = ForceLoginPlugin() +__plugin_hooks__ = { + "octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers, + "octoprint.server.http.access_validator": __plugin_implementation__.access_validator, + "octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator, + "octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator +} diff --git a/src/octoprint/plugins/forcelogin/static/css/forcelogin.css b/src/octoprint/plugins/forcelogin/static/css/forcelogin.css new file mode 100644 index 000000000..73e8fe2af --- /dev/null +++ b/src/octoprint/plugins/forcelogin/static/css/forcelogin.css @@ -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} \ No newline at end of file diff --git a/src/octoprint/plugins/forcelogin/static/js/main.js b/src/octoprint/plugins/forcelogin/static/js/main.js new file mode 100644 index 000000000..e46bdf840 --- /dev/null +++ b/src/octoprint/plugins/forcelogin/static/js/main.js @@ -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(); +}); diff --git a/src/octoprint/plugins/forcelogin/static/js/viewmodel.js b/src/octoprint/plugins/forcelogin/static/js/viewmodel.js new file mode 100644 index 000000000..9d33e09f3 --- /dev/null +++ b/src/octoprint/plugins/forcelogin/static/js/viewmodel.js @@ -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, [], []]); +}); diff --git a/src/octoprint/plugins/forcelogin/static/less/forcelogin.less b/src/octoprint/plugins/forcelogin/static/less/forcelogin.less new file mode 100644 index 000000000..615f51202 --- /dev/null +++ b/src/octoprint/plugins/forcelogin/static/less/forcelogin.less @@ -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; + } + } + } + } +} diff --git a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 new file mode 100644 index 000000000..3b8b36ce4 --- /dev/null +++ b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 @@ -0,0 +1,39 @@ + + + OctoPrint Login + + {% include "parts/forcelogin_css.jinja2" %} + + {% include "parts/forcelogin_javascripts.jinja2" %} + + +
+ +
+ +
+
+
+
+
+
+ +
+
+
+
+
+ + diff --git a/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_css.jinja2 b/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_css.jinja2 new file mode 100644 index 000000000..f0df93c78 --- /dev/null +++ b/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_css.jinja2 @@ -0,0 +1,10 @@ + + + + + + + +{% for url in forcelogin_theming %} + +{% endfor %} diff --git a/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_javascripts.jinja2 b/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_javascripts.jinja2 new file mode 100644 index 000000000..962955914 --- /dev/null +++ b/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_javascripts.jinja2 @@ -0,0 +1,15 @@ + + + + + + + + +{% assets "js_client" %} + +{% endassets %} + + diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index ed11c1c28..9b7c9bd74 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -195,6 +195,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, def get_assets(self): return dict(js=["js/logging.js"], + clientjs=["clientjs/logging.js"], less=["less/logging.less"], css=["css/logging.css"]) diff --git a/src/octoprint/plugins/logging/static/clientjs/logging.js b/src/octoprint/plugins/logging/static/clientjs/logging.js new file mode 100644 index 000000000..23b90f85d --- /dev/null +++ b/src/octoprint/plugins/logging/static/clientjs/logging.js @@ -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; +}); diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index c4131debb..2f0f16988 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -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; diff --git a/src/octoprint/plugins/octopi_support/__init__.py b/src/octoprint/plugins/octopi_support/__init__.py deleted file mode 100644 index 3885b6525..000000000 --- a/src/octoprint/plugins/octopi_support/__init__.py +++ /dev/null @@ -1,175 +0,0 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" - -import flask -import os - -from flask_babel import gettext - -import octoprint.plugin - -_OCTOPI_VERSION_PATH = "/etc/octopi_version" -_CPUINFO_PATH = "/proc/cpuinfo" - -# based on https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F -_RPI_REVISION_MAP = { - "Beta": "1B (Beta)", - "0002": "1B", - "0003": "1B", - "0004": "1B", - "0005": "1B", - "0006": "1B", - "0007": "1A", - "0008": "1A", - "0009": "1A", - "000d": "1B", - "000e": "1B", - "000f": "1B", - "0010": "B+", - "0011": "CM1", - "0012": "A+", - "0013": "B+", - "0014": "CM1", - "0015": "A+", - "a01040": "2B", - "a01041": "2B", - "a21041": "2B", - "a22042": "2B", - "900021": "A+", - "900032": "B+", - "900092": "Zero", - "900093": "Zero", - "920093": "Zero", - "9000c1": "Zero W", - "a02082": "3B", - "a020a0": "CM3", - "a22082": "3B", - "a32082": "3B", -} - - -def get_octopi_version(): - with open(_OCTOPI_VERSION_PATH, "r") as f: - version_line = f.readline() - return version_line.strip() - - -def get_pi_cpuinfo(): - fields = dict(revision="Revision", - hardware="Hardware", - serial="Serial") - - result = dict() - with open(_CPUINFO_PATH) as f: - for line in f: - if not line: - continue - - for key, prefix in fields.items(): - if line.startswith(prefix): - result[key] = line[line.index(":") + 1:].strip() - - return result - - -def get_pi_model(hardware, revision): - if hardware not in ("BCM2835",): - return "unknown" - - if revision.startswith("1000"): - # strip flag for over-volted (https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F) - revision = revision[4:] - - return _RPI_REVISION_MAP.get(revision.lower(), "unknown") - - -class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.TemplatePlugin): - - # noinspection PyMissingConstructor - def __init__(self): - self._version = None - self._cpuinfo = None - self._model = None - - #~~ EnvironmentDetectionPlugin - - def get_additional_environment(self): - return dict(version=self._get_version(), - revision=self._get_cpuinfo().get("revision", "unknown"), - model=self._get_model()) - - #~~ SimpleApiPlugin - - def on_api_get(self, request): - return flask.jsonify(version=self._get_version()) - - #~~ AssetPlugin - - def get_assets(self): - return dict( - js=["js/octopi_support.js"], - css=["css/octopi_support.css"] - ) - - #~~ TemplatePlugin - - def get_template_configs(self): - return [ - dict(type="about", name="About OctoPi", template="octopi_support_about.jinja2") - ] - - def get_template_vars(self): - return dict(version=self._get_version()) - - #~~ Helpers - - def _get_version(self): - if self._version is None: - try: - self._version = get_octopi_version() - except: - self._logger.exception("Error while reading OctoPi version from file {}".format(_OCTOPI_VERSION_PATH)) - self._version = "unknown" - return self._version - - def _get_model(self): - if self._model is None: - try: - cpuinfo = self._get_cpuinfo() - self._model = get_pi_model(cpuinfo.get("hardware", "unknown"), - cpuinfo.get("revision", "unknown")) - except: - self._logger.exception("Error while detecting RPi model") - self._model = "unknown" - return self._model - - def _get_cpuinfo(self): - if self._cpuinfo is None: - try: - self._cpuinfo = get_pi_cpuinfo() - except: - self._logger.exception("Error while fetching cpu info") - self._cpuinfo = dict() - return self._cpuinfo - -__plugin_name__ = "OctoPi Support Plugin" -__plugin_author__ = "Gina Häußge" -__plugin_description__ = "Provides additional information about your OctoPi instance in the UI." -__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to " - "provide additional information about your OctoPi instance," - "which will make it more tricky to help you if you need support.") -__plugin_license__ = "AGPLv3" - -def __plugin_check__(): - from octoprint.util.platform import get_os - return get_os() == "linux" and os.path.exists(_OCTOPI_VERSION_PATH) - -def __plugin_load__(): - global __plugin_implementation__ - __plugin_implementation__ = OctoPiSupportPlugin() diff --git a/src/octoprint/plugins/octopi_support/static/css/octopi_support.css b/src/octoprint/plugins/octopi_support/static/css/octopi_support.css deleted file mode 100644 index 61b3a10ef..000000000 --- a/src/octoprint/plugins/octopi_support/static/css/octopi_support.css +++ /dev/null @@ -1,3 +0,0 @@ -#octopi_support_footer { - white-space: nowrap; -} diff --git a/src/octoprint/plugins/octopi_support/static/js/octopi_support.js b/src/octoprint/plugins/octopi_support/static/js/octopi_support.js deleted file mode 100644 index b27e32c96..000000000 --- a/src/octoprint/plugins/octopi_support/static/js/octopi_support.js +++ /dev/null @@ -1,50 +0,0 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintOctoPiSupportClient = function(base) { - this.base = base; - }; - - OctoPrintOctoPiSupportClient.prototype.get = function(opts) { - return this.base.get(this.base.getSimpleApiUrl("octopi_support")); - }; - - OctoPrintClient.registerPluginComponent("octopi_support", OctoPrintOctoPiSupportClient); - return OctoPrintOctoPiSupportClient; -}); - -$(function() { - - function OctoPiSupportViewModel(parameters) { - var self = this; - - self.requestData = function() { - OctoPrint.plugins.octopi_support.get() - .done(function(response) { - $("#octopi_support_footer").remove(); - if (!response.version) return; - - var octoPrintVersion = $(".footer span.version"); - var octoPiVersion = $(" " + gettext("running on") + " " + gettext("OctoPi") - + " " + response.version + "") - $(octoPiVersion).insertAfter(octoPrintVersion); - }) - }; - - self.onStartup = function() { - self.requestData(); - }; - - self.onServerReconnect = function() { - self.requestData(); - }; - } - - OCTOPRINT_VIEWMODELS.push({ - construct: OctoPiSupportViewModel - }); -}); diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py new file mode 100644 index 000000000..28b4f3d03 --- /dev/null +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -0,0 +1,303 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import flask +import os +import sarge + +from flask_babel import gettext +from octoprint.util import RepeatedTimer + +import octoprint.plugin + +_PROC_DT_MODEL_PATH = "/proc/device-tree/model" +_OCTOPI_VERSION_PATH = "/etc/octopi_version" +_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled" + +### uncomment for local debugging +#import sys +#base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes")) +#_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt") +#_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt") +#_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py")) +#import itertools +#_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70000")) + + +# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790 +_FLAG_UNDERVOLTAGE = 1 << 0 +_FLAG_FREQ_CAPPED = 1 << 1 +_FLAG_THROTTLED = 1 << 2 +_FLAG_PAST_UNDERVOLTAGE = 1 << 16 +_FLAG_PAST_FREQ_CAPPED = 1 << 17 +_FLAG_PAST_THROTTLED = 1 << 18 + + +class ThrottleState(object): + @classmethod + def from_value(cls, value): + if value == 0: + return ThrottleState() + + kwargs = dict(undervoltage=_FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE, + freq_capped=_FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED, + throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED, + past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE, + past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED, + past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED) + return ThrottleState(**kwargs) + + def __init__(self, **kwargs): + self._undervoltage = False + self._freq_capped = False + self._throttled = False + self._past_undervoltage = False + self._past_freq_capped = False + self._past_throttled = False + + for key, value in kwargs.items(): + local_key = "_{}".format(key) + if hasattr(self, local_key) and isinstance(value, bool): + setattr(self, local_key, value) + + @property + def undervoltage(self): + return self.current_undervoltage or self.past_undervoltage + + @property + def current_undervoltage(self): + return self._undervoltage + + @property + def past_undervoltage(self): + return self._past_undervoltage + + @property + def overheat(self): + return self.current_overheat or self.past_overheat + + @property + def current_overheat(self): + return self._freq_capped + + @property + def past_overheat(self): + return self._past_freq_capped + + @property + def issue(self): + return self.current_issue or self.past_issue + + @property + def current_issue(self): + return self._undervoltage or self._freq_capped or self._throttled + + @property + def past_issue(self): + return self._past_undervoltage or self._past_freq_capped or self._past_throttled + + def __eq__(self, other): + if not isinstance(other, ThrottleState): + return False + + return self._undervoltage == other._undervoltage \ + and self._freq_capped == other._freq_capped \ + and self._throttled == other._throttled \ + and self._past_undervoltage == other._past_undervoltage \ + and self._past_freq_capped == other._past_freq_capped \ + and self._past_throttled == other._past_throttled + + def as_dict(self): + return dict(current_undervoltage=self.current_undervoltage, + past_undervoltage=self.past_undervoltage, + current_overheat=self.current_overheat, + past_overheat=self.past_overheat, + current_issue=self.current_issue, + past_issue=self.past_issue) + + +_proc_dt_model = None +def get_proc_dt_model(): + global _proc_dt_model + + if _proc_dt_model is None: + with open(_PROC_DT_MODEL_PATH, "r") as f: + _proc_dt_model = f.readline().strip(" \t\r\n\0") + + return _proc_dt_model + + +def get_vcgencmd_throttled_state(command): + output = sarge.get_stdout(command) + #output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging + if not "throttled=0x" in output: + raise ValueError("cannot parse \"{}\" output: {}".format(command, output)) + + value = output[len("throttled="):].strip(" \t\r\n\0") + value = int(value, 0) + return ThrottleState.from_value(value) + + +def is_octopi(): + return os.path.exists(_OCTOPI_VERSION_PATH) + + +_octopi_version = None +def get_octopi_version(): + global _octopi_version + + if _octopi_version is None: + with open(_OCTOPI_VERSION_PATH, "r") as f: + _octopi_version = f.readline().strip(" \t\r\n\0") + + return _octopi_version + + +class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.SettingsPlugin): + + # noinspection PyMissingConstructor + def __init__(self): + self._throttle_state = ThrottleState() + self._throttle_check = None + self._throttle_undervoltage = False + self._throttle_overheat = False + self._throttle_functional = True + + #~~ EnvironmentDetectionPlugin + + def get_additional_environment(self): + result = dict(model=get_proc_dt_model()) + + if is_octopi(): + result.update(dict(octopi_version=get_octopi_version())) + + return result + + #~~ SimpleApiPlugin + + def on_api_get(self, request): + result = dict(throttle_state=self._throttle_state.as_dict()) + result.update(self.get_additional_environment()) + return flask.jsonify(**result) + + #~~ AssetPlugin + + def get_assets(self): + return dict( + js=["js/pi_support.js"], + clientjs=["clientjs/pi_support.js"], + css=["css/pi_support.css"] + ) + + #~~ TemplatePlugin + + def get_template_configs(self): + configs = [dict(type="settings", name=gettext("Pi Support"), template="pi_support_settings.jinja2", custom_bindings=False)] + + if is_octopi(): + configs.append(dict(type="about", name="About OctoPi", template="pi_support_about_octopi.jinja2")) + + return configs + + def get_template_vars(self): + return self.get_additional_environment() + + #~~ StartupPlugin + + def on_startup(self, *args, **kwargs): + if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]): + self._check_throttled_state() + self._throttle_check = RepeatedTimer(self._check_throttled_state_interval, + self._check_throttled_state, + condition=self._check_throttled_state_condition) + self._throttle_check.start() + + #~~ SettingsPlugin + + def get_settings_defaults(self): + return dict(vcgencmd_throttle_check_enabled=True, + vcgencmd_throttle_check_command=_VCGENCMD_THROTTLE) + + def get_settings_restricted_paths(self): + return dict(admin=[["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]]) + + #~~ Helpers + + def _check_throttled_state_interval(self): + if self._throttle_state.current_issue: + # check state every 30s if something's currently amiss + return 30 + else: + # check state every 5min if nothing's currently amiss + return 300 + + def _check_throttled_state_condition(self): + return self._throttle_functional + + def _check_throttled_state(self): + command = self._settings.get(["vcgencmd_throttle_check_command"]) + + self._logger.debug("Retrieving throttle state via \"{}\"".format(command)) + try: + state = get_vcgencmd_throttled_state(command) + except: + self._logger.exception("Got an error while trying to fetch the current throttle state via \"{}\"".format(command)) + self._throttle_functional = False + return + + if self._throttle_state == state: + # no change + return + + self._throttle_state = state + + if (not self._throttle_undervoltage and self._throttle_state.undervoltage) \ + or (not self._throttle_overheat and self._throttle_state.overheat): + message = "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " \ + "by overheating or insufficient power." + + if self._throttle_state.undervoltage: + self._throttle_undervoltage = True + message += "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " \ + "capable of supplying enough voltage and current to your Pi." + + if self._throttle_state.overheat: + self._throttle_overheat = True + message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \ + "CPU and GPU." + + self._logger.warn(message) + + self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state", + state=self._throttle_state.as_dict())) + + +__plugin_name__ = "Pi Support Plugin" +__plugin_author__ = "Gina Häußge" +__plugin_description__ = "Provides additional information about your Pi in the UI." +__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to " + "provide additional information about your Pi," + "which will make it more tricky to help you if you need support.") +__plugin_license__ = "AGPLv3" + +def __plugin_check__(): + try: + proc_dt_model = get_proc_dt_model() + if proc_dt_model is None: + return False + except: + return False + + return "raspberry pi" in proc_dt_model.lower() + +def __plugin_load__(): + global __plugin_implementation__ + __plugin_implementation__ = PiSupportPlugin() diff --git a/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js new file mode 100644 index 000000000..7c216aa0f --- /dev/null +++ b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js @@ -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; +}); + diff --git a/src/octoprint/plugins/pi_support/static/css/pi_support.css b/src/octoprint/plugins/pi_support/static/css/pi_support.css new file mode 100644 index 000000000..c6065b7ed --- /dev/null +++ b/src/octoprint/plugins/pi_support/static/css/pi_support.css @@ -0,0 +1,8 @@ +#octopi_support_footer { + white-space: nowrap; +} + +.pi_support_state_pulsate { + animation: pulsate 1s ease-out; + animation-iteration-count: infinite; +} diff --git a/src/octoprint/plugins/pi_support/static/js/pi_support.js b/src/octoprint/plugins/pi_support/static/js/pi_support.js new file mode 100644 index 000000000..2516a4f77 --- /dev/null +++ b/src/octoprint/plugins/pi_support/static/js/pi_support.js @@ -0,0 +1,71 @@ +$(function() { + + function PiSupportViewModel(parameters) { + var self = this; + + self.model = ko.observable(); + + self.currentUndervoltage = ko.observable(false); + self.currentOverheat = ko.observable(false); + self.pastUndervoltage = ko.observable(false); + self.pastOverheat = ko.observable(false); + self.currentIssue = ko.observable(false); + self.pastIssue = ko.observable(false); + + self.requestData = function() { + OctoPrint.plugins.pi_support.get() + .done(function(response) { + // Raspberry Pi model + self.model(response.model); + + // Throttle state + self.fromThrottleState(response.throttle_state); + + // OctoPi version + $("#octopi_support_footer").remove(); + if (!response.octopi_version) return; + + var octoPrintVersion = $(".footer span.version"); + var octoPiVersion = $(" " + gettext("running on") + " " + gettext("OctoPi") + + " " + response.octopi_version + "") + $(octoPiVersion).insertAfter(octoPrintVersion); + }) + }; + + self.fromThrottleState = function(state) { + self.currentUndervoltage(state.current_undervoltage); + self.pastUndervoltage(state.past_undervoltage); + self.currentOverheat(state.current_overheat); + self.pastOverheat(state.past_overheat); + self.currentIssue(state.current_issue); + self.pastIssue(state.past_issue); + }; + + self.issuePopoverContent = function() { + return "

- " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "

" + + "

- " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "

" + + "

" + gettext("A blinking icon indicates an acute issue!") + "

" + }; + + self.onStartup = function() { + self.requestData(); + }; + + self.onServerReconnect = function() { + self.requestData(); + }; + + self.onDataUpdaterPluginMessage = function(plugin, data) { + if (plugin !== "pi_support") return; + if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return; + if (data.type !== "throttle_state") return; + + self.fromThrottleState(data.state); + } + } + + OCTOPRINT_VIEWMODELS.push({ + construct: PiSupportViewModel, + elements: ["#navbar_plugin_pi_support"] + }); +}); diff --git a/src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 similarity index 81% rename from src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 rename to src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 index 6dcb2d674..b3a43aaaa 100644 --- a/src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 +++ b/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 @@ -2,10 +2,10 @@

The ready-to-go Raspberry Pi image with OctoPrint

-

Version {{ plugin_octopi_support_version }}

+

Version {{ plugin_pi_support_octopi_version }}, running on {{ plugin_pi_support_model }}

diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 new file mode 100644 index 000000000..d74c76b54 --- /dev/null +++ b/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 @@ -0,0 +1,4 @@ + + + + diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 new file mode 100644 index 000000000..83cd07fea --- /dev/null +++ b/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 @@ -0,0 +1,31 @@ +

{{ _('Pi Support') }}

+ +

{{ _('Please restart OctoPrint after changing any of this plugin\'s settings.') }}

+ +
+
+
+ + {{ _('This will regularly check with the Pi if something is amiss either with power regulation or CPU/GPU temperature.') }} +
+
+ +
+ +
+ +
+ +
+ + {{ _('Defaults to /usr/bin/vcgencmd get_throttled. You usually shouldn\'t have to change this.') }} +
+
+ +
+
+ + + diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 06d4cfe80..c085c032e 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -15,7 +15,7 @@ from octoprint.server.util.flask import restricted_access, with_revalidation_che from octoprint.server import admin_permission from octoprint.util.pip import LocalPipCaller from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible -from octoprint.util.platform import get_os +from octoprint.util.platform import get_os, is_os_compatible from flask import jsonify, make_response from flask_babel import gettext @@ -33,6 +33,35 @@ import threading _DATA_FORMAT_VERSION = "v2" + +def map_repository_entry(entry): + result = copy.deepcopy(entry) + + if not "follow_dependency_links" in result: + result["follow_dependency_links"] = False + + result["is_compatible"] = dict( + octoprint=True, + os=True + ) + + if "compatibility" in entry: + if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance( + entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]): + result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"]) + + if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance( + entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]): + result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"]) + + return result + + +already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)" +success_string = "Successfully installed" +failure_string = "Could not install" + + class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.AssetPlugin, @@ -111,7 +140,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._console_logger.propagate = False # decouple repository fetching from server startup - self._fetch_all_data(async=True) + self._fetch_all_data(do_async=True) ##~~ SettingsPlugin @@ -139,6 +168,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def get_assets(self): return dict( js=["js/pluginmanager.js"], + clientjs=["clientjs/pluginmanager.js"], css=["css/pluginmanager.css"], less=["less/pluginmanager.less"] ) @@ -208,7 +238,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, from octoprint.events import Events if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False): return - self._fetch_all_data(async=True) + self._fetch_all_data(do_async=True) ##~~ SimpleApiPlugin @@ -340,10 +370,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, all_plugins_before = self._plugin_manager.find_plugins(existing=dict()) - already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)" - success_string = "Successfully installed" - failure_string = "Could not install" - try: returncode, stdout, stderr = self._call_pip(pip_args) @@ -459,6 +485,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.log_all_plugins() self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) + self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key, + version=new_plugin.version, + source=source, + source_type=source_type)) + result = dict(result=True, source=source, source_type=source_type, @@ -549,6 +580,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.reload_plugins() + self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key, + version=plugin.version)) + result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, @@ -667,7 +701,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if strip: lines = map(lambda x: x.strip(), lines) - self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines])) + self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", + loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: self._console_logger.debug(u"{prefix} {line}".format(**locals())) @@ -688,6 +723,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif not plugin.enabled and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) + self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key, + version=plugin.version)) + def _mark_plugin_disabled(self, plugin, needs_restart=False): disabled_list = list(self._settings.global_get(["plugins", "_disabled"], validator=lambda x: isinstance(x, list), @@ -705,12 +743,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) - def _fetch_all_data(self, async=False): + self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key, + version=plugin.version)) + + def _fetch_all_data(self, do_async=False): def run(): self._repository_available = self._fetch_repository_from_disk() self._notices_available = self._fetch_notices_from_disk() - if async: + if do_async: thread = threading.Thread(target=run) thread.daemon = True thread.start() @@ -764,30 +805,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if repo_data is None: return False - current_os = get_os() - octoprint_version = get_octoprint_version(base=True) - - def map_repository_entry(entry): - result = copy.deepcopy(entry) - - if not "follow_dependency_links" in result: - result["follow_dependency_links"] = False - - result["is_compatible"] = dict( - octoprint=True, - os=True - ) - - if "compatibility" in entry: - if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]): - result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"], - octoprint_version=octoprint_version) - - if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]): - result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"]) - - return result - self._repository_plugins = map(map_repository_entry, repo_data) return True @@ -859,30 +876,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._notices = notices return True - @staticmethod - def _is_os_compatible(current_os, compatibility_entries): - """ - Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries`` - """ - if len(compatibility_entries) == 0: - # shortcut - no compatibility info means we are compatible - return True - - negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries)) - positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries) - - negative_match = False - if negative_entries: - # check if we are blacklisted - negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries)) - - positive_match = True - if positive_entries: - # check if we are whitelisted - positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries)) - - return positive_match and not negative_match - @property def _reconnect_hooks(self): reconnect_hooks = self.__class__.RECONNECT_HOOKS diff --git a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js new file mode 100644 index 000000000..acaaf3590 --- /dev/null +++ b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js @@ -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; +}); diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 5bf20baef..403aae500 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -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; diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 182f61a3e..677bef7fd 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -90,6 +90,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, def get_assets(self): return dict(js=("js/printer_safety_check.js",), + clientjs=("clientjs/printer_safety_check.js",), css=("css/printer_safety_check.css",), less=("less/printer_safety_check.less",)) diff --git a/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js b/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js new file mode 100644 index 000000000..5a52fc4f9 --- /dev/null +++ b/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js @@ -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; +}); diff --git a/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js b/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js index c69bf8eb6..34e75aa97 100644 --- a/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js +++ b/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js @@ -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; diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index b395d0db4..fd17d0897 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import octoprint.plugin +import copy import flask import os import threading @@ -26,9 +27,16 @@ from flask_babel import gettext from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag from octoprint.server import admin_permission, VERSION, REVISION, BRANCH from octoprint.util import dict_merge, to_unicode +from octoprint.util.version import get_comparable_version +from octoprint.util.pip import LocalPipCaller import octoprint.settings +MINIMUM_PYTHON = "2.7.9" +MINIMUM_SETUPTOOLS = "5.5.1" +MINIMUM_PIP = "9.0.1" + + ##~~ Plugin @@ -42,7 +50,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") - DATA_FORMAT_VERSION = "v3" + DATA_FORMAT_VERSION = "v4" # noinspection PyMissingConstructor def __init__(self): @@ -61,6 +69,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._version_cache_dirty = False self._version_cache_timestamp = None + self._environment_supported = False + self._environment_versions = dict() + self._environment_ready = threading.Event() + self._console_logger = None def initialize(self): @@ -91,6 +103,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, # the server startup def fetch_data(): self.get_current_versions() + self._check_environment() thread = threading.Thread(target=fetch_data) thread.daemon = True @@ -164,6 +177,24 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return self._configured_checks + def _check_environment(self): + from platform import python_version + import pkg_resources + + local_pip = LocalPipCaller() + + # check python and setuptools version + versions = dict(python=python_version(), + setuptools=pkg_resources.get_distribution("setuptools").version, + pip=local_pip.version_string) + supported = get_comparable_version(versions["python"]) >= get_comparable_version(MINIMUM_PYTHON) \ + and get_comparable_version(versions["setuptools"]) >= get_comparable_version(MINIMUM_SETUPTOOLS) \ + and get_comparable_version(versions["pip"]) >= get_comparable_version(MINIMUM_PIP) + + self._environment_supported = supported + self._environment_versions = versions + self._environment_ready.set() + def _load_version_cache(self): if not os.path.isfile(self._version_cache_path): return @@ -482,11 +513,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, force = flask.request.values.get("force", "false") in octoprint.settings.valid_boolean_trues def view(): + self._environment_ready.wait() + try: information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force) - return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current", + return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible and self._environment_supported else "updateAvailable" if update_available else "current", information=information, - timestamp=self._version_cache_timestamp)) + timestamp=self._version_cache_timestamp, + environment=dict(supported=self._environment_supported, + versions=[dict(name=gettext("Python"), current=self._environment_versions.get("python", "unknown"), minimum=MINIMUM_PYTHON), + dict(name=gettext("pip"), current=self._environment_versions.get("pip", "unknown"), minimum=MINIMUM_PIP), + dict(name=gettext("setuptools"), current=self._environment_versions.get("setuptools", "unknown"), minimum=MINIMUM_SETUPTOOLS)]))) except exceptions.ConfigurationInvalid as e: return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500) @@ -513,6 +550,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, hash.update(str(data.get("online", None))) hash.update(",".join(targets)) + + hash.update(str(self._environment_supported)) hash.update(str(self._version_cache_timestamp)) hash.update(str(self._connectivity_checker.online)) hash.update(str(self._update_in_progress)) @@ -535,6 +574,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, # do not update while a print job is running return flask.make_response("Printer is currently printing or paused", 409) + if not self._environment_supported: + return flask.make_response("Direct updates are not supported in this Python environment", 409) + if not "application/json" in flask.request.headers["Content-Type"]: return flask.make_response("Expected content-type JSON", 400) @@ -559,6 +601,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return dict( css=["css/softwareupdate.css"], js=["js/softwareupdate.js"], + clientjs=["clientjs/softwareupdate.js"], less=["less/softwareupdate.less"] ) @@ -645,6 +688,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, continue target_information, target_update_available, target_update_possible, target_online, target_error = future.result() + target_update_possible = target_update_possible and self._environment_supported target_information = dict_merge(dict(local=dict(name="?", value="?"), remote=dict(name="?", value="?", @@ -778,6 +822,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, :param targets: an iterable defining the targets to update, if not supplied defaults to all targets """ + if not self._environment_supported: + self._logger.error("Direct updates are unsupported in this environment") + return [], dict() + targets = kwargs.get("targets", kwargs.get("check_targets", None)) checks = self._get_configured_checks() @@ -897,6 +945,20 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, # determine the target version to update to target_version = information["remote"]["value"] target_error = False + target_result = None + + def trigger_event(success, **additional_payload): + if success: + event = "update_succeeded" + else: + event = "update_failed" + + payload = copy.copy(additional_payload) + payload.update(dict(target=target, + from_version=information["local"]["value"], + to_version=target_version)) + + self._event_bus.fire("plugin_softwareupdate_{}".format(event), payload=payload) ### The actual update procedure starts here... @@ -911,6 +973,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online) target_result = ("success", update_result) self._logger.info("Update of %s to %s successful!" % (target, target_version)) + trigger_event(True) except exceptions.UnknownUpdateType: self._logger.warn("Update of %s can not be performed, unknown update type" % target) @@ -923,6 +986,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, except Exception as e: self._logger.exception("Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this" % target) + trigger_event(False) + if not "ignorable" in populated_check or not populated_check["ignorable"]: target_error = True @@ -960,7 +1025,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._logger.info("Restarting...") try: - util.execute(restart_command, evaluate_returncode=False, async=True) + util.execute(restart_command, evaluate_returncode=False, do_async=True) except exceptions.ScriptError as e: self._logger.exception("Error while restarting via command {}".format(restart_command)) self._logger.warn("Restart stdout:\n{}".format(e.stdout)) diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index 42e7629b9..fbb3e2618 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -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: diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index 14574f45b..2f143e4a6 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -59,7 +59,9 @@ def _execute(command, **kwargs): joined_command = command _log_call(joined_command) - kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture())) + kwargs.update(dict(async_=True, + stdout=sarge.Capture(), + stderr=sarge.Capture())) try: p = sarge.run(command, **kwargs) diff --git a/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js new file mode 100644 index 000000000..932dcf8ce --- /dev/null +++ b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js @@ -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; +}); diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index d0484a5b8..c3125ef82 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -1,88 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintSoftwareUpdateClient = function(base) { - this.base = base; - - var url = this.base.getBlueprintUrl("softwareupdate"); - this.checkUrl = url + "check"; - this.updateUrl = url + "update"; - }; - - OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) { - if (arguments.length == 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - entries = params.entries; - force = params.force; - opts = params.opts; - } - - entries = entries || []; - if (typeof entries == "string") { - entries = [entries]; - } - - var data = {}; - if (!!force) { - data.force = true; - } - if (entries && entries.length) { - data.check = entries.join(","); - } - return this.base.getWithQuery(this.checkUrl, data, opts); - }; - - OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - force = params.force; - opts = params.opts; - } - - return this.checkEntries({entries: [], force: force, opts: opts}); - }; - - OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - targets = params.targets; - force = params.force; - opts = params.opts; - } - - targets = targets || []; - if (typeof targets === "string") { - targets = [targets]; - } - - var data = { - targets: targets, - force: !!force - }; - return this.base.postJson(this.updateUrl, data, opts); - }; - - OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - force = params.force; - opts = params.opts; - } - - var data = { - force: !!force - }; - return this.base.postJson(this.updateUrl, data, opts); - }; - - OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient); - return OctoPrintSoftwareUpdateClient; -}); - $(function() { function SoftwareUpdateViewModel(parameters) { var self = this; @@ -116,6 +31,9 @@ $(function() { && !self.octoprintReleasedVersion(); }); + self.environmentSupported = ko.observable(true); + self.environmentVersions = ko.observableArray([]); + self.cacheTimestamp = ko.observable(); self.cacheTimestampText = ko.pureComputed(function() { return formatDate(self.cacheTimestamp()); @@ -132,6 +50,10 @@ $(function() { && (!self.config_checkoutFolder() || self.config_checkoutFolder().trim() === ''); }); + self.enableUpdate = ko.pureComputed(function() { + return !self.updateInProgress && self.environmentSupported(); + }); + self.enable_configSave = ko.pureComputed(function() { return self.config_checkType() === "github_release" || (self.config_checkType() === "git_commit" && !self.error_checkoutFolder()); @@ -300,6 +222,9 @@ $(function() { var octoprint = data.information["octoprint"]; self.octoprintReleasedVersion(!octoprint || octoprint.released_version); + self.environmentSupported(data.environment.supported); + self.environmentVersions(data.environment.versions); + if (data.status === "inProgress") { self._markWorking(gettext("Updating..."), gettext("Updating, please wait.")); return; @@ -314,7 +239,7 @@ $(function() { _.each(self.versions.items(), function(update_info) { if (update_info.updateAvailable) { text += "
  • " - + "" + + "" + "" + update_info.fullNameRemote + "" + (update_info.releaseNotes ? "" + gettext("Release Notes") + "" : "") + "
  • "; @@ -322,7 +247,11 @@ $(function() { }); text += ""; - text += "

    " + gettext("Those components marked with can be updated directly.") + "

    "; + if (!self.environmentSupported()) { + text += "

    " + gettext("This version of the Python environment is not supported for direct updates.") + "

    "; + } else { + text += "

    " + gettext("Those components marked with can be updated directly.") + "

    "; + } if (!self.loginState.isAdmin()) { text += "

    " + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "

    "; diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 106d64bc5..13b5c5313 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -15,6 +15,23 @@ Documentation.

    {% endtrans %}
    +
    {% trans %} +

    + This version of the Python environment is not supported for direct updates. +

    +

    + 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: +

    +{% endtrans %} +
      +
    • : ({{ _('you have') }}: )
    • +
    +{% trans %} +

    + Please take a look at this FAQ entry on how to proceed. +

    +{% endtrans %}
    @@ -29,7 +46,7 @@ - {{ _('Update') }} + {{ _('Update') }} :
    {{ _('Installed:') }} @@ -59,7 +76,7 @@
    - +
    diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py index 08dfed097..fb970144f 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -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 diff --git a/src/octoprint/plugins/softwareupdate/util.py b/src/octoprint/plugins/softwareupdate/util.py index 020fce3df..0adf55ba0 100644 --- a/src/octoprint/plugins/softwareupdate/util.py +++ b/src/octoprint/plugins/softwareupdate/util.py @@ -9,12 +9,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from .exceptions import ScriptError -def execute(command, cwd=None, evaluate_returncode=True, async=False): +def execute(command, cwd=None, evaluate_returncode=True, **kwargs): + do_async = kwargs.get("do_async", kwargs.get("async", False)) + import sarge p = None try: - p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async=async) + p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=do_async) except: returncode = p.returncode if p is not None else None stdout = p.stdout.text if p is not None and p.stdout is not None else "" diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py new file mode 100644 index 000000000..108b275e5 --- /dev/null +++ b/src/octoprint/plugins/tracking/__init__.py @@ -0,0 +1,269 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from flask_babel import gettext + +import requests +import hashlib +import logging + +try: + # noinspection PyCompatibility + from urllib.parse import urlencode +except ImportError: + from urllib import urlencode + +# noinspection PyCompatibility +import concurrent.futures + +from octoprint.util import RepeatedTimer +from octoprint.util.version import get_octoprint_version_string +from octoprint.events import Events + +TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/" + +# noinspection PyMissingConstructor +class TrackingPlugin(octoprint.plugin.SettingsPlugin, + octoprint.plugin.EnvironmentDetectionPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.ShutdownPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.WizardPlugin, + octoprint.plugin.EventHandlerPlugin): + + def __init__(self): + self._environment = None + self._printer_connection_parameters = None + self._url = None + self._ping_worker = None + self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + + self._record_next_firmware_info = False + + def initialize(self): + self._init_tracking() + + ##~~ SettingsPlugin + + def get_settings_defaults(self): + return dict(enabled=None, + unique_id=None, + server=TRACKING_URL, + ping=15*60, + events=dict(startup=True, + printjob=True, + plugin=True, + update=True, + printer=True)) + + def get_settings_restricted_paths(self): + return dict(admin=[["enabled"], ["unique_id"], ["events"]], + never=[["server"], ["ping"]]) + + def on_settings_save(self, data): + enabled = self._settings.get([b"enabled"]) + + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + + if enabled is None and self._settings.get([b"enabled"]): + # tracking was just enabled, let's init it and send a startup event + self._init_tracking() + self._track_startup() + + ##~~ EnvironmentDetectionPlugin + + def on_environment_detected(self, environment, *args, **kwargs): + self._environment = environment + + ##~~ StartupPlugin + + def on_after_startup(self): + self._track_startup() + + ping = self._settings.get_int(["ping"]) + if ping: + self._ping_worker = RepeatedTimer(ping, self._track_ping) + self._ping_worker.start() + + ##~~ ShutdownPlugin + + def on_shutdown(self): + self._track_shutdown() + + ##~~ EventHandlerPlugin + + def on_event(self, event, payload): + if event.startswith("plugin_pluginmanager_"): + self._track_plugin_event(event, payload) + if event.startswith("plugin_softwareupdate_"): + self._track_update_event(event, payload) + elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): + self._track_printjob_event(event, payload) + elif event in (Events.CONNECTED,): + self._printer_connection_parameters = dict(port=payload["port"], + baudrate=payload["baudrate"]) + self._record_next_firmware_info = True + elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info: + self._record_next_firmware_info = False + self._track_printer_event(event, payload) + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + dict(type="settings", name=gettext("Anonymous Usage Tracking"), template="tracking_settings.jinja2", custom_bindings=False), + dict(type="wizard", name=gettext("Anonymous Usage Tracking"), template="tracking_wizard.jinja2", custom_bindings=True, mandatory=True) + ] + + ##~~ AssetPlugin + + def get_assets(self): + return dict(js=["js/tracking.js"]) + + ##~~ WizardPlugin + + def is_wizard_required(self): + return self._settings.get([b"enabled"]) is None + + ##~~ helpers + + def _init_tracking(self): + if not self._settings.get_boolean([b"enabled"]): + return + self._init_id() + self._logger.info("Initialized anonymous tracking") + + def _init_id(self): + if self._settings.get_boolean([b"enabled"]) and not self._settings.get([b"unique_id"]): + import uuid + self._settings.set([b"unique_id"], str(uuid.uuid4())) + self._settings.save() + + def _track_ping(self): + self._track("ping") + + def _track_startup(self): + if not self._settings.get_boolean(["events", "startup"]): + return + + payload = dict(version=get_octoprint_version_string(), + os=self._environment[b"os"][b"id"], + python=self._environment[b"python"][b"version"], + pip=self._environment[b"python"][b"pip"], + cores=self._environment[b"hardware"][b"cores"], + freq=self._environment[b"hardware"][b"freq"], + ram=self._environment[b"hardware"][b"ram"]) + + if b"plugins" in self._environment and b"pi_support" in self._environment[b"plugins"]: + payload[b"pi_model"] = self._environment[b"plugins"][b"pi_support"][b"model"] + if b"octopi_version" in self._environment[b"plugins"][b"pi_support"]: + payload[b"octopi_version"] = self._environment[b"plugins"][b"pi_support"][b"octopi_version"] + + self._track("startup", **payload) + + def _track_shutdown(self): + if not self._settings.get_boolean(["events", "startup"]): + return + + self._track("shutdown") + + def _track_plugin_event(self, event, payload): + if not self._settings.get_boolean(["events", "plugin"]): + return + + if event.endswith("_installplugin"): + self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_uninstallplugin"): + self._track("uninstall_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_enableplugin"): + self._track("enable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_disableplugin"): + self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + + def _track_update_event(self, event, payload): + if not self._settings.get_boolean(["events", "update"]): + return + + if event.endswith("_update_succeeded"): + self._track("update_successful", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version")) + elif event.endswith("_update_failed"): + self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version")) + + def _track_printjob_event(self, event, payload): + if not self._settings.get_boolean(["events", "printjob"]): + return + + sha = hashlib.sha1() + sha.update(payload.get("name")) + sha.update(self._settings.get([b"unique_id"])) + + track_event = None + args = dict(origin=payload.get(b"origin"), file=sha.hexdigest()) + + if event == Events.PRINT_STARTED: + track_event = "print_started" + elif event == Events.PRINT_DONE: + try: + elapsed = int(payload.get(b"time")) + except ValueError: + elapsed = "unknown" + args[b"elapsed"] = elapsed + track_event = "print_done" + elif event == Events.PRINT_FAILED: + track_event = "print_failed" + elif event == Events.PRINT_CANCELLED: + track_event = "print_cancelled" + + if track_event is not None: + self._track(track_event, **args) + + def _track_printer_event(self, event, payload): + if not self._settings.get_boolean(["events", "printer"]): + return + + if event in (Events.FIRMWARE_DATA,): + args = dict(firmware_name=payload["name"]) + if self._printer_connection_parameters: + args["printer_port"] = self._printer_connection_parameters["port"] + args["printer_baudrate"] = self._printer_connection_parameters["baudrate"] + self._track("printer_connected", **args) + + def _track(self, event, **kwargs): + if not self._settings.get_boolean([b"enabled"]): + return + + self._executor.submit(self._do_track, event, **kwargs) + + def _do_track(self, event, **kwargs): + if not self._connectivity_checker.online: + return + + server = self._settings.get([b"server"]) + url = server.format(id=self._settings.get([b"unique_id"]), event=event) + + headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())} + try: + params = urlencode(kwargs, doseq=True).replace("+", "%20") + requests.get(url, + params=params, + timeout=3.1, + headers=headers) + self._logger.debug("Sent tracking event to {}".format(url)) + except: + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.exception("Error while sending event to anonymous usage tracking".format(url)) + else: + pass + +__plugin_name__ = "Anonymous Usage Tracking" +__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked" +__plugin_homepage__ = "https://tracking.octoprint.org" +__plugin_author__ = "Gina Häußge" + +__plugin_implementation__ = TrackingPlugin() diff --git a/src/octoprint/plugins/tracking/static/js/tracking.js b/src/octoprint/plugins/tracking/static/js/tracking.js new file mode 100644 index 000000000..6855450b6 --- /dev/null +++ b/src/octoprint/plugins/tracking/static/js/tracking.js @@ -0,0 +1,85 @@ +$(function() { + function TrackingViewModel(parameters) { + var self = this; + + self.settingsViewModel = parameters[0]; + + self.setup = ko.observable(false); + + self.decision = ko.observable(); + self.required = false; + self.active = false; + + self.enableTracking = function() { + self.settingsViewModel.settings.plugins.tracking.enabled(true); + self.decision(true); + self._sendData(); + }; + + self.disableTracking = function() { + self.settingsViewModel.settings.plugins.tracking.enabled(false); + self.decision(false); + self._sendData(); + }; + + self.onBeforeWizardTabChange = function(next, current) { + if (!self.required) return true; + + if (!current || !_.startsWith(current, "wizard_plugin_tracking") || self.setup()) { + return true; + } + + self._showDecisionNeededDialog(); + return false; + }; + + self.onBeforeWizardFinish = function() { + if (!self.required) return true; + + if (self.setup()) { + return true; + } + + self._showDecisionNeededDialog(); + return false; + }; + + self.onWizardPreventSettingsRefreshDialog = function() { + return self.active; + }; + + self.onWizardDetails = function(response) { + self.required = response && response.tracking && response.tracking.required; + }; + + self._showDecisionNeededDialog = function() { + showMessageDialog({ + title: gettext("Please set up anonymous usage tracking"), + message: gettext("You haven't yet decided on whether to enable or disable anonymous usage tracking. You need to either enable or disable it before continuing.") + }); + }; + + self._sendData = function() { + var data = { + plugins: { + tracking: { + enabled: self.settingsViewModel.settings.plugins.tracking.enabled() + } + } + }; + + self.active = true; + self.settingsViewModel.saveData(data) + .done(function() { + self.setup(true); + self.active = false; + }); + }; + } + + OCTOPRINT_VIEWMODELS.push([ + TrackingViewModel, + ["settingsViewModel"], + "#wizard_plugin_tracking" + ]); +}); diff --git a/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 new file mode 100644 index 000000000..524a6f4f2 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 @@ -0,0 +1,10 @@ +{% trans %} +

    + Anonymous usage tracking provides valuable insights into how many instances running what versions of OctoPrint are out there, + whether they are successfully completing print jobs and various other metrics. +

    +

    + By enabling it you help to identify problems with new releases and release candidates early on, and to better + tailor OctoPrint's future development to actual use. +

    +{% endtrans %} diff --git a/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 new file mode 100644 index 000000000..d1fc0d990 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 @@ -0,0 +1,4 @@ +

    {% trans %} + For details on what gets tracked, please refer to tracking.octoprint.org + and also the Privacy Policy at tracking.octoprint.org. +{% endtrans %}

    diff --git a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 new file mode 100644 index 000000000..3a5fa8a08 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 @@ -0,0 +1,44 @@ +

    {{ _('Anonymous Usage Tracking') }}

    + +{% include "snippets/plugins/tracking/trackingDescription.jinja2" %} + +
    +
    +
    + +
    +
    +
    + +
    + +
    +
    +
    + +
    + + + + + + +
    +
    +
    + +{% include "snippets/plugins/tracking/trackingDetails.jinja2" %} diff --git a/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 new file mode 100644 index 000000000..ebc2896f0 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 @@ -0,0 +1,23 @@ +

    {{ _('Configure Anonymous Usage Tracking') }}

    + +{% include "snippets/plugins/tracking/trackingDescription.jinja2" %} + +{% include "snippets/plugins/tracking/trackingDetails.jinja2" %} + +

    + {{ _('Note: You can always change your decision and also access more granular controls via Settings > Anonymous Usage Tracking.') }} +

    + + + + diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 3d9ada889..bed0a65b7 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -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 @@ -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": diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 66bfeb0b5..9c7926bc9 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -242,6 +242,7 @@ class Server(object): # monkey patch a bunch of stuff util.tornado.fix_json_encode() + util.flask.fix_flask_jsonify() util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")]) # setup app @@ -473,6 +474,7 @@ class Server(object): self._setup_assets() # configure timelapse + octoprint.timelapse.valid_timelapse("test") octoprint.timelapse.configure_timelapse() # setup command triggers @@ -512,11 +514,24 @@ class Server(object): additional_mime_types=dict(mime_type_guesser=mime_type_guesser) - admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator)) - user_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator)) + access_validators_from_plugins = [] + for plugin, hook in pluginManager.get_hooks("octoprint.server.http.access_validator").items(): + try: + access_validators_from_plugins.append(util.tornado.access_validation_factory(app, hook)) + except: + self._logger.exception("Error while adding tornado access validator from plugin {}".format(plugin)) + + admin_validators = [util.tornado.access_validation_factory(app, util.flask.admin_validator),] + access_validators_from_plugins + user_validators = [util.tornado.access_validation_factory(app, util.flask.user_validator),] + access_validators_from_plugins + + admin_validator = dict(access_validation=util.tornado.validation_chain(*admin_validators)) + user_validator = dict(access_validation=util.tornado.validation_chain(*user_validators)) + access_validator = dict(access_validation=util.tornado.validation_chain(*access_validators_from_plugins)) no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404)) + timelapse_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path) and octoprint.timelapse.valid_timelapse(path), + status_code=404)) def joined_dict(*dicts): if not len(dicts): @@ -532,15 +547,17 @@ class Server(object): server_routes = self._router.urls + [ # various downloads # .mpg and .mp4 timelapses: - (r"/downloads/timelapse/([^/]*\.m(.*))", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")), - download_handler_kwargs, - no_hidden_files_validator)), + (r"/downloads/timelapse/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")), + download_handler_kwargs, + timelapse_validator, + access_validator)), (r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads"), as_attachment=True, name_generator=download_name_generator), download_handler_kwargs, no_hidden_files_validator, - additional_mime_types)), + additional_mime_types, + access_validator)), (r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("logs"), mime_type_guesser=lambda *args, **kwargs: "text/plain"), download_handler_kwargs, @@ -1076,16 +1093,25 @@ class Server(object): def _setup_blueprints(self): from octoprint.server.api import api from octoprint.server.apps import apps, clear_registered_app - import octoprint.server.views - app.register_blueprint(api, url_prefix="/api") - app.register_blueprint(apps, url_prefix="/apps") + import octoprint.server.views # do not remove or the index view won't be found + + blueprints = OrderedDict() + blueprints["/api"] = api + blueprints["/apps"] = apps # also register any blueprints defined in BlueprintPlugins - self._register_blueprint_plugins() + blueprints.update(self._prepare_blueprint_plugins()) # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves - self._register_asset_plugins() + blueprints.update(self._prepare_asset_plugins()) + + # make sure all before/after_request hook results are attached as well + self._add_plugin_request_handlers_to_blueprints(*blueprints.values()) + + # register everything with the system + for url_prefix, blueprint in blueprints.items(): + app.register_blueprint(blueprint, url_prefix=url_prefix) global pluginLifecycleManager def clear_apps(name, plugin): @@ -1093,27 +1119,37 @@ class Server(object): pluginLifecycleManager.add_callback("enabled", clear_apps) pluginLifecycleManager.add_callback("disabled", clear_apps) - def _register_blueprint_plugins(self): + def _prepare_blueprint_plugins(self): + blueprints = OrderedDict() + blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin) for plugin in blueprint_plugins: try: - self._register_blueprint_plugin(plugin) + blueprint, prefix = self._prepare_blueprint_plugin(plugin) + blueprints[prefix] = blueprint except: self._logger.exception("Error while registering blueprint of plugin {}, ignoring it".format(plugin._identifier)) continue - def _register_asset_plugins(self): + return blueprints + + def _prepare_asset_plugins(self): + blueprints = OrderedDict() + asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin) for plugin in asset_plugins: if isinstance(plugin, octoprint.plugin.BlueprintPlugin): continue try: - self._register_asset_plugin(plugin) + blueprint, prefix = self._prepare_asset_plugin(plugin) + blueprints[prefix] = blueprint except: self._logger.exception("Error while registering assets of plugin {}, ignoring it".format(plugin._identifier)) continue - def _register_blueprint_plugin(self, plugin): + return blueprints + + def _prepare_blueprint_plugin(self, plugin): name = plugin._identifier blueprint = plugin.get_blueprint() if blueprint is None: @@ -1135,7 +1171,9 @@ class Server(object): if self._logger: self._logger.debug("Registered API of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix)) - def _register_asset_plugin(self, plugin): + return blueprint, url_prefix + + def _prepare_asset_plugin(self, plugin): name = plugin._identifier url_prefix = "/plugin/{name}".format(name=name) @@ -1145,6 +1183,32 @@ class Server(object): if self._logger: self._logger.debug("Registered assets of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix)) + return blueprint, url_prefix + + def _add_plugin_request_handlers_to_blueprints(self, *blueprints): + before_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.before_request") + after_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.after_request") + + for plugin, hook in before_hooks.items(): + for blueprint in blueprints: + try: + result = hook() + if isinstance(result, (list, tuple)): + for h in result: + blueprint.before_request(h) + except: + self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin)) + + for plugin, hook in after_hooks.items(): + for blueprint in blueprints: + try: + result = hook() + if isinstance(result, (list, tuple)): + for h in result: + blueprint.after_request(h) + except: + self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin)) + def _setup_assets(self): global app global assets @@ -1285,25 +1349,6 @@ class Server(object): "js/lib/loglevel.min.js", "js/lib/sockjs.js" ] - js_client = [ - "js/app/client/base.js", - "js/app/client/socket.js", - "js/app/client/browser.js", - "js/app/client/connection.js", - "js/app/client/control.js", - "js/app/client/files.js", - "js/app/client/job.js", - "js/app/client/languages.js", - "js/app/client/printer.js", - "js/app/client/printerprofiles.js", - "js/app/client/settings.js", - "js/app/client/slicing.js", - "js/app/client/system.js", - "js/app/client/timelapse.js", - "js/app/client/users.js", - "js/app/client/util.js", - "js/app/client/wizard.js" - ] css_libs = [ "css/bootstrap.min.css", @@ -1356,13 +1401,15 @@ class Server(object): js_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["js"], filters="js_delimiter_bundler") + clientjs_core = dynamic_core_assets["clientjs"] + \ + all_assets_for_plugins(dynamic_plugin_assets["bundled"]["clientjs"]) + clientjs_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["clientjs"], + filters="js_delimiter_bundler") + js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters)) - js_client_bundle = Bundle(*js_client, - output="webassets/packed_client.js", - filters=",".join(js_filters)) js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters=",".join(js_filters)) @@ -1378,6 +1425,21 @@ class Server(object): output="webassets/packed_app.js", filters=",".join(js_filters)) + js_client_core_bundle = Bundle(*clientjs_core, + output="webassets/packed_client_core.js", + filters=",".join(js_filters)) + + if len(clientjs_plugins) == 0: + js_client_plugins_bundle = Bundle(*[]) + else: + js_client_plugins_bundle = Bundle(*clientjs_plugins.values(), + output="webassets/packed_client_plugins.js", + filters=",".join(js_plugin_filters)) + + js_client_bundle = Bundle(js_client_core_bundle, js_client_plugins_bundle, + output="webassets/packed_client.js", + filters=",".join(js_filters)) + # -- CSS ------------------------------------------------------------------------------------------------------- css_filters = ["cssrewrite"] @@ -1437,6 +1499,11 @@ class Server(object): # -- asset registration ---------------------------------------------------------------------------------------- assets.register("js_libs", js_libs_bundle) + assets.register("js_client_core", js_client_core_bundle) + for plugin, bundle in clientjs_plugins.items(): + # register our collected clientjs plugin bundles so that they are bound to the environment + assets.register("js_client_plugin_{}".format(plugin), bundle) + assets.register("js_client_plugins", js_client_plugins_bundle) assets.register("js_client", js_client_bundle) assets.register("js_core", js_core_bundle) for plugin, bundle in js_plugins.items(): diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 89945c661..ed4cc7cee 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -7,20 +7,20 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import netaddr -import sarge from flask import Blueprint, request, jsonify, abort, current_app, session, make_response, g from flask_login import login_user, logout_user, current_user from flask_principal import Identity, identity_changed, AnonymousIdentity import octoprint.util as util +import octoprint.util.net as util_net import octoprint.users import octoprint.server import octoprint.plugin from octoprint.server import admin_permission, NO_CONTENT from octoprint.settings import settings as s, valid_boolean_trues from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler -from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login +from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login, get_remote_address #~~ init api blueprint, including sub modules @@ -214,7 +214,16 @@ def login(): g.user = user login_user(user, remember=remember) identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) - return jsonify(user.asDict()) + + remote_addr = get_remote_address(request) + logging.getLogger(__name__).info("Actively logging in user {} from {}".format(user.get_id(), remote_addr)) + + response = user.asDict() + response["_is_external_client"] = s().getBoolean(["server", "ipCheck", "enabled"]) \ + and not util_net.is_lan_address(remote_addr, + additional_private=s().get(["server", "ipCheck", "trustedSubnets"])) + return jsonify(response) + return make_response(("User unknown or password incorrect", 401, [])) elif "passive" in data: diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 8338957b6..c3586e69c 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -18,6 +18,7 @@ import octoprint.filemanager.util import octoprint.filemanager.storage import octoprint.slicing +import os import psutil import hashlib import logging @@ -132,7 +133,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: diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 6cdcfe0be..4da866326 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -90,6 +90,7 @@ def getSettings(): "name": s.get(["appearance", "name"]), "color": s.get(["appearance", "color"]), "colorTransparent": s.getBoolean(["appearance", "colorTransparent"]), + "colorIcon": s.getBoolean(["appearance", "colorIcon"]), "defaultLanguage": s.get(["appearance", "defaultLanguage"]), "showFahrenheitAlso": s.getBoolean(["appearance", "showFahrenheitAlso"]) }, @@ -153,6 +154,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"]), @@ -170,7 +172,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"), @@ -371,6 +374,7 @@ def _saveSettings(data): if "name" in data["appearance"]: s.set(["appearance", "name"], data["appearance"]["name"]) if "color" in data["appearance"]: s.set(["appearance", "color"], data["appearance"]["color"]) if "colorTransparent" in data["appearance"]: s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"]) + if "colorIcon" in data["appearance"]: s.setBoolean(["appearance", "colorIcon"], data["appearance"]["colorIcon"]) if "defaultLanguage" in data["appearance"]: s.set(["appearance", "defaultLanguage"], data["appearance"]["defaultLanguage"]) if "showFahrenheitAlso" in data["appearance"]: s.setBoolean(["appearance", "showFahrenheitAlso"], data["appearance"]["showFahrenheitAlso"]) @@ -409,17 +413,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"]) @@ -446,12 +450,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"]) diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 2c54a5c86..98fa5dc43 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -127,15 +127,17 @@ def downloadTimelapse(filename): @api.route("/timelapse/", methods=["DELETE"]) @restricted_access def deleteTimelapse(filename): - if util.is_allowed_file(filename, ["mpg", "mpeg", "mp4", "m4v", "mkv"]): - timelapse_folder = settings().getBaseFolder("timelapse") - full_path = os.path.realpath(os.path.join(timelapse_folder, filename)) - if full_path.startswith(timelapse_folder) and os.path.exists(full_path): - try: - os.remove(full_path) - except Exception as ex: - logging.getLogger(__file__).exception("Error deleting timelapse file {}".format(full_path)) - return make_response("Unexpected error: {}".format(ex), 500) + timelapse_folder = settings().getBaseFolder("timelapse") + full_path = os.path.realpath(os.path.join(timelapse_folder, filename)) + if octoprint.timelapse.valid_timelapse(full_path) \ + and full_path.startswith(timelapse_folder) \ + and os.path.exists(full_path) \ + and not util.is_hidden_path(full_path): + try: + os.remove(full_path) + except Exception as ex: + logging.getLogger(__file__).exception("Error deleting timelapse file {}".format(full_path)) + return make_response("Unexpected error: {}".format(ex), 500) return getTimelapseData() diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 5770bc0c9..c2df7ea30 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -43,7 +43,7 @@ def enforceApiKeyRequestHandler(): apikey = get_api_key(_flask.request) - if apikey is None: + if not apikey: return _flask.make_response("No API key provided", 403) if apikey != octoprint.server.UI_API_KEY and not settings().getBoolean(["api", "enabled"]): diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 2ab536e36..b53bf4fb6 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -31,6 +31,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.contrib.cache import BaseCache @@ -250,6 +251,32 @@ def fix_flask_login_remote_address(): flask_login._get_remote_addr = fixed_get_remote_addr +def fix_flask_jsonify(): + def fixed_jsonify(*args, **kwargs): + """Backported from https://github.com/pallets/flask/blob/7e714bd28b6e96d82b2848b48cf8ff48b517b09b/flask/json/__init__.py#L257""" + from flask.json import current_app, dumps + + indent = None + separators = (',', ':') + + if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug: + indent = 2 + separators = (', ', ': ') + + if args and kwargs: + raise TypeError('jsonify() behavior undefined when passed both args and kwargs') + elif len(args) == 1: # single args are passed directly to dumps() + data = args[0] + else: + data = args or kwargs + + return current_app.response_class( + dumps(data, indent=indent, separators=separators) + '\n', + mimetype='application/json' + ) + + flask.jsonify = fixed_jsonify + #~~ WSGI environment wrapper for reverse proxying class ReverseProxiedEnvironment(object): @@ -514,13 +541,24 @@ def passive_login(): else: user = flask_login.current_user + remoteAddr = get_remote_address(flask.request) + ipCheckEnabled = settings().getBoolean(["server", "ipCheck", "enabled"]) + ipCheckTrusted = settings().get(["server", "ipCheck", "trustedSubnets"]) + if user is not None and not user.is_anonymous() and user.is_active(): flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) if hasattr(user, "session"): flask.session["usersession.id"] = user.session flask.g.user = user - return flask.jsonify(user.asDict()) + + logging.getLogger(__name__).info("Passively logging in user {} from {}".format(user.get_id(), remoteAddr)) + + response = user.asDict() + response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr, + additional_private=ipCheckTrusted) + return flask.jsonify(response) + elif settings().getBoolean(["accessControl", "autologinLocal"]) \ and settings().get(["accessControl", "autologinAs"]) is not None \ and settings().get(["accessControl", "localNetworks"]) is not None: @@ -531,7 +569,6 @@ def passive_login(): localNetworks.add(ip) try: - remoteAddr = get_remote_address(flask.request) if netaddr.IPAddress(remoteAddr) in localNetworks: user = octoprint.server.userManager.findUser(autologinAs) if user is not None and user.is_active(): @@ -541,7 +578,14 @@ def passive_login(): flask_login.login_user(user) flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) - return flask.jsonify(user.asDict()) + + logging.getLogger(__name__).info("Passively logging in user {} from {} via autologin".format(user.get_id(), + remoteAddr)) + + response = user.asDict() + response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr, + additional_private=ipCheckTrusted) + return flask.jsonify(response) except: logger = logging.getLogger(__name__) logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks)) @@ -1056,7 +1100,7 @@ def admin_validator(request): :param request: The Flask request object """ - 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.is_admin(): raise tornado.web.HTTPError(403) @@ -1071,12 +1115,12 @@ def user_validator(request): :param request: The Flask request object """ - user = _get_flask_user_from_request(request) + user = get_flask_user_from_request(request) if user is None or not user.is_authenticated(): raise tornado.web.HTTPError(403) -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. @@ -1120,28 +1164,34 @@ def redirect_to_tornado(request, target, code=302): def restricted_access(func): + """ + This combines :py:func:`no_firstrun_access` and ``login_required``. + """ + @functools.wraps(func) + def decorated_view(*args, **kwargs): + return no_firstrun_access(flask_login.login_required(func))(*args, **kwargs) + return decorated_view + +def no_firstrun_access(func): """ If you decorate a view with this, it will ensure that first setup has been - done for OctoPrint's Access Control plus that any conditions of the - login_required decorator are met (possibly through a session already created - by octoprint.server.util.apiKeyRequestHandler earlier in the request processing). + done for OctoPrint's Access Control. If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun" flag from the settings being set to True and the userManager not indicating that it's user database has been customized from default), the decorator will cause a HTTP 403 status code to be returned by the decorated resource. """ + @functools.wraps(func) def decorated_view(*args, **kwargs): # if OctoPrint hasn't been set up yet, abort if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()): return flask.make_response("OctoPrint isn't setup yet", 403) - - return flask_login.login_required(func)(*args, **kwargs) + return func(*args, **kwargs) return decorated_view - def firstrun_only_access(func): """ If you decorate a view with this, it will ensure that first setup has _not_ been @@ -1321,6 +1371,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater): def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): assets = dict( js=[], + clientjs=[], css=[], less=[] ) @@ -1362,6 +1413,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": @@ -1376,9 +1447,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))) @@ -1408,6 +1481,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): diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index 7debafa0e..656c32613 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -88,11 +88,17 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o self._pluginManager = pluginManager self._remoteAddress = None + self._user = None self._throttleFactor = 1 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 + def _getRemoteAddress(self, info): forwardedFor = info.headers.get("X-Forwarded-For") if forwardedFor is not None: @@ -132,39 +138,14 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o safe_mode=octoprint.server.safe_mode )) - self._printer.register_callback(self) - self._fileManager.register_slicingprogress_callback(self) - octoprint.timelapse.register_callback(self) - self._pluginManager.register_message_receiver(self.on_plugin_message) - - self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress}) - for event in octoprint.events.all_events(): - self._eventManager.subscribe(event, self._onEvent) - - octoprint.timelapse.notify_callbacks(octoprint.timelapse.current) - - # This is a horrible hack for now to allow displaying a notification that a render job is still - # active in the backend on a fresh connect of a client. This needs to be substituted with a proper - # job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints - # start and so on. - # - # For now this is the easiest way though to at least inform the user that a timelapse is still ongoing. - # - # TODO remove when central job management becomes available and takes care of this for us - if octoprint.timelapse.current_render_job is not None: - self._emit("event", {"type": Events.MOVIE_RENDERING, "payload": octoprint.timelapse.current_render_job}) + self._register() def on_close(self): - self._printer.unregister_callback(self) - self._fileManager.unregister_slicingprogress_callback(self) - octoprint.timelapse.unregister_callback(self) - self._pluginManager.unregister_message_receiver(self.on_plugin_message) - - self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress}) - for event in octoprint.events.all_events(): - self._eventManager.unsubscribe(event, self._onEvent) + self._unregister() self._logger.info("Client connection closed: %s" % self._remoteAddress) + + self._user = None self._remoteAddress = None def on_message(self, message): @@ -175,7 +156,29 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o self._logger.warn("Invalid JSON received from client {}, ignoring: {!r}".format(self._remoteAddress, message)) return - if "throttle" in message: + if "auth" in message: + try: + parts = message["auth"].split(":") + 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"])) + else: + user_id, user_session = parts + user = self._userManager.findUser(userid=user_id, session=user_session) + + if user is not None: + self._user = user + self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(), + self._remoteAddress)) + else: + self._user = None + self._logger.warn("Unknown user/session combo: {}:{}".format(user_id, user_session)) + + self._register() + + elif "throttle" in message: try: throttle = int(message["throttle"]) if throttle < 1: @@ -257,6 +260,16 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o self.sendEvent(event, payload) def _emit(self, type, payload): + 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 + try: self.send({type: payload}) except Exception as e: @@ -264,3 +277,54 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o self._logger.exception("Could not send message to client {}".format(self._remoteAddress)) else: self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e)) + + def _register(self): + 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 + + self._printer.register_callback(self) + self._fileManager.register_slicingprogress_callback(self) + octoprint.timelapse.register_callback(self) + self._pluginManager.register_message_receiver(self.on_plugin_message) + + self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress}) + for event in octoprint.events.all_events(): + self._eventManager.subscribe(event, self._onEvent) + + octoprint.timelapse.notify_callbacks(octoprint.timelapse.current) + + # This is a horrible hack for now to allow displaying a notification that a render job is still + # active in the backend on a fresh connect of a client. This needs to be substituted with a proper + # job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints + # start and so on. + # + # For now this is the easiest way though to at least inform the user that a timelapse is still ongoing. + # + # TODO remove when central job management becomes available and takes care of this for us + if octoprint.timelapse.current_render_job is not None: + self._emit("event", {"type": Events.MOVIE_RENDERING, "payload": octoprint.timelapse.current_render_job}) + + self._registered = True + + def _unregister(self): + self._printer.unregister_callback(self) + self._fileManager.unregister_slicingprogress_callback(self) + octoprint.timelapse.unregister_callback(self) + self._pluginManager.unregister_message_receiver(self.on_plugin_message) + + self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress}) + for event in octoprint.events.all_events(): + self._eventManager.unsubscribe(event, self._onEvent) + + self._registered = False + diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 3ec1624a2..e40fbb2b9 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -1127,13 +1127,19 @@ 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): +def access_validation_factory(app, validator, *args): """ Creates an access validation wrapper using the supplied validator. :param validator: the access validator to use inside the validation wrapper :return: an access validator taking a request as parameter and performing the request validation """ + + # TODO remove in 1.4.0 + if len(args): + # old parameters incl. login_manager + validator = args[0] + def f(request): """ Creates a custom wsgi and Flask request context in order to be able to process user information @@ -1146,7 +1152,7 @@ def access_validation_factory(app, login_manager, validator): wsgi_environ = WsgiInputContainer.environ(request) with app.request_context(wsgi_environ): app.session_interface.open_session(app, flask.request) - login_manager.reload_user() + app.login_manager.reload_user() validator(flask.request) return f @@ -1162,3 +1168,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 diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 7f99d617a..b60a79f99 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -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": { @@ -278,21 +284,23 @@ default_settings = { "name": "", "color": "default", "colorTransparent": False, + "colorIcon": True, "defaultLanguage": "_default", "showFahrenheitAlso": False, "components": { "order": { - "navbar": ["settings", "systemmenu", "plugin_announcements", "login"], + "navbar": ["settings", "systemmenu", "plugin_announcements", "plugin_pi_support", "login"], "sidebar": ["plugin_printer_safety_check", "connection", "state", "files"], "tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"], "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"], - "about": ["about", "plugin_octopi_support", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"], + "about": ["about", "plugin_pi_support", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"], "generic": [] }, "disabled": { @@ -336,7 +344,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"} ], @@ -405,10 +413,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, @@ -595,6 +604,8 @@ class Settings(object): self._basedir = None + assert(isinstance(default_settings, dict)) + self._map = HierarchicalChainMap(dict(), default_settings) self._config = None @@ -865,6 +876,7 @@ class Settings(object): try: self._config = yaml.safe_load(f) self._mtime = self.last_modified + except yaml.YAMLError as e: details = e.message @@ -879,10 +891,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: @@ -1581,7 +1595,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() diff --git a/src/octoprint/static/gcodeviewer/js/renderer.js b/src/octoprint/static/gcodeviewer/js/renderer.js index 24d104ee6..f63412b42 100644 --- a/src/octoprint/static/gcodeviewer/js/renderer.js +++ b/src/octoprint/static/gcodeviewer/js/renderer.js @@ -10,7 +10,11 @@ GCODE.renderer = (function(){ // ***** PRIVATE ****** var canvas; var ctx; - var zoomFactor= 2.8, zoomFactorDelta = 0.4; + + var viewportChanged = true; + var lineWidthFactor = 1 / 2.8; + + var zoomFactorDelta = 0.4; var gridStep=10; var ctxHeight, ctxWidth; var prevX=0, prevY=0; @@ -18,7 +22,7 @@ GCODE.renderer = (function(){ var layerNumStore, progressStore={from: 0, to: -1}; var lastX, lastY; - var dragStart, dragged; + var dragStart; var scaleFactor = 1.1; var model = undefined; var modelInfo = undefined; @@ -56,7 +60,12 @@ GCODE.renderer = (function(){ bed: {x: 200, y: 200}, container: undefined, - onInternalOptionChange: undefined + onInternalOptionChange: undefined, + + onViewportChange: undefined, + onDragStart: undefined, // Cancellable (return false) + onDrag: undefined, // Cancellable (return false) + onDragStop: undefined }; var offsetModelX = 0, offsetModelY = 0; @@ -66,19 +75,37 @@ GCODE.renderer = (function(){ var speedsByLayer = {}; var currentInvertX = false, currentInvertY = false; + function notifyIfViewportChanged() { + if (viewportChanged) { + if (renderOptions["onViewportChange"]) { + renderOptions["onViewportChange"](ctx.getTransform()); + } + viewportChanged = false; + } + } + var reRender = function(){ + notifyIfViewportChanged(); + var p1 = ctx.transformedPoint(0,0); var p2 = ctx.transformedPoint(canvas.width,canvas.height); ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y); + drawGrid(); drawBoundingBox(); - if (renderOptions['showNextLayer'] && model && model.length && layerNumStore < model.length - 1) { - drawLayer(layerNumStore + 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore + 1), true); + if (model && model.length) { + if (layerNumStore < model.length) { + if (renderOptions['showNextLayer'] && layerNumStore < model.length - 1) { + drawLayer(layerNumStore + 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore + 1), true); + } + if (renderOptions['showPreviousLayer'] && layerNumStore > 0) { + drawLayer(layerNumStore - 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore - 1), true); + } + drawLayer(layerNumStore, progressStore.from, progressStore.to); + } else { + console.log("Got request to render non-existent layer"); + } } - if (renderOptions['showPreviousLayer'] && layerNumStore > 0) { - drawLayer(layerNumStore - 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore - 1), true); - } - drawLayer(layerNumStore, progressStore.from, progressStore.to); }; function trackTransforms(ctx){ @@ -95,22 +122,26 @@ GCODE.renderer = (function(){ var restore = ctx.restore; ctx.restore = function(){ xform = savedTransforms.pop(); + viewportChanged = true; return restore.call(ctx); }; var scale = ctx.scale; ctx.scale = function(sx,sy){ xform = xform.scaleNonUniform(sx,sy); + viewportChanged = true; return scale.call(ctx,sx,sy); }; var rotate = ctx.rotate; ctx.rotate = function(radians){ xform = xform.rotate(radians*180/Math.PI); + viewportChanged = true; return rotate.call(ctx,radians); }; var translate = ctx.translate; ctx.translate = function(dx,dy){ xform = xform.translate(dx,dy); + viewportChanged = true; return translate.call(ctx,dx,dy); }; var transform = ctx.transform; @@ -118,6 +149,7 @@ GCODE.renderer = (function(){ var m2 = svg.createSVGMatrix(); m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f; xform = xform.multiply(m2); + viewportChanged = true; return transform.call(ctx,a,b,c,d,e,f); }; var setTransform = ctx.setTransform; @@ -128,6 +160,7 @@ GCODE.renderer = (function(){ xform.d = d; xform.e = e; xform.f = f; + viewportChanged = true; return setTransform.call(ctx,a,b,c,d,e,f); }; var pt = svg.createSVGPoint(); @@ -152,10 +185,12 @@ GCODE.renderer = (function(){ ctxWidth = canvas.width; lastX = ctxWidth/2; lastY = ctxHeight/2; - ctx.lineWidth = 2; + ctx.lineWidth = 2 * lineWidthFactor; ctx.lineCap = 'round'; trackTransforms(ctx); + ctx.scale(1,-1); // Invert y-axis + // dragging => translating canvas.addEventListener('mousedown', function(event){ document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none'; @@ -163,10 +198,10 @@ GCODE.renderer = (function(){ // remember starting point of dragging gesture lastX = (event.offsetX || (event.pageX - canvas.offsetLeft)) * pixelRatio; lastY = (event.offsetY || (event.pageY - canvas.offsetTop)) * pixelRatio; - dragStart = ctx.transformedPoint(lastX, lastY); - // not yet dragged anything - dragged = false; + var pt = ctx.transformedPoint(lastX, lastY); + if (!renderOptions["onDragStart"] || (renderOptions["onDragStart"](pt) !== false)) + dragStart = pt; }, false); canvas.addEventListener('mousemove', function(event){ @@ -175,11 +210,13 @@ GCODE.renderer = (function(){ lastY = (event.offsetY || (event.pageY - canvas.offsetTop)) * pixelRatio; // mouse movement => dragged - dragged = true; - - if (dragStart !== undefined){ + if (dragStart !== undefined) { // translate var pt = ctx.transformedPoint(lastX,lastY); + + if (renderOptions["onDrag"] && (renderOptions["onDrag"](pt) === false)) + return; + ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y); reRender(); @@ -207,6 +244,12 @@ GCODE.renderer = (function(){ canvas.addEventListener('mouseup', function(event){ // reset dragStart dragStart = undefined; + + if (renderOptions["onDragStop"]) { + var x = (event.offsetX || (event.pageX - canvas.offsetLeft)) * pixelRatio; + var y = (event.offsetY || (event.pageY - canvas.offsetTop)) * pixelRatio; + renderOptions["onDragStop"](ctx.transformedPoint(x,y)); + } }, false); // mouse wheel => zooming @@ -294,45 +337,45 @@ GCODE.renderer = (function(){ ctx.beginPath(); ctx.strokeStyle = renderOptions["colorGrid"]; ctx.fillStyle = "#ffffff"; - ctx.lineWidth = 2; + ctx.lineWidth = 2 * lineWidthFactor; // outline - ctx.rect(minX * zoomFactor, -1 * minY * zoomFactor, width * zoomFactor, -1 * height * zoomFactor); + ctx.rect(minX, minY, width, height); // origin - ctx.moveTo(minX * zoomFactor, 0); - ctx.lineTo(maxX * zoomFactor, 0); - ctx.moveTo(0, -1 * minY * zoomFactor); - ctx.lineTo(0, -1 * maxY * zoomFactor); + ctx.moveTo(minX, 0); + ctx.lineTo(maxX, 0); + ctx.moveTo(0, minY); + ctx.lineTo(0, maxY); // draw ctx.fill(); ctx.stroke(); ctx.strokeStyle = renderOptions["colorGrid"]; - ctx.lineWidth = 1; + ctx.lineWidth = lineWidthFactor; //~~ grid starting from origin ctx.beginPath(); for (x = 0; x <= maxX; x += gridStep) { - ctx.moveTo(x * zoomFactor, -1 * minY * zoomFactor); - ctx.lineTo(x * zoomFactor, -1 * maxY * zoomFactor); + ctx.moveTo(x, minY); + ctx.lineTo(x, maxY); if (renderOptions["bed"]["centeredOrigin"]) { - ctx.moveTo(-1 * x * zoomFactor, -1 * minY * zoomFactor); - ctx.lineTo(-1 * x * zoomFactor, -1 * maxY * zoomFactor); + ctx.moveTo(-1 * x, minY); + ctx.lineTo(-1 * x, maxY); } } ctx.stroke(); ctx.beginPath(); for (y = 0; y <= maxY; y += gridStep) { - ctx.moveTo(minX * zoomFactor, -1 * y * zoomFactor); - ctx.lineTo(maxX * zoomFactor, -1 * y * zoomFactor); + ctx.moveTo(minX, y); + ctx.lineTo(maxX, y); if (renderOptions["bed"]["centeredOrigin"]) { - ctx.moveTo(minX * zoomFactor, y * zoomFactor); - ctx.lineTo(maxX * zoomFactor, y * zoomFactor); + ctx.moveTo(minX, -1 * y); + ctx.lineTo(maxX, -1 * y); } } ctx.stroke(); @@ -343,44 +386,45 @@ GCODE.renderer = (function(){ ctx.strokeStyle = renderOptions["colorGrid"]; ctx.fillStyle = "#ffffff"; - ctx.lineWidth = 2; + ctx.lineWidth = 2 * lineWidthFactor; //~~ bed outline & origin ctx.beginPath(); // outline - ctx.arc(0, 0, renderOptions["bed"]["r"] * zoomFactor, 0, Math.PI * 2, true); + var r = renderOptions["bed"]["r"]; + ctx.arc(0, 0, r, 0, Math.PI * 2, true); // origin - ctx.moveTo(-1 * renderOptions["bed"]["r"] * zoomFactor, 0); - ctx.lineTo(renderOptions["bed"]["r"] * zoomFactor, 0); - ctx.moveTo(0, -1 * renderOptions["bed"]["r"] * zoomFactor); - ctx.lineTo(0, renderOptions["bed"]["r"] * zoomFactor); + ctx.moveTo(-1 * r, 0); + ctx.lineTo(r, 0); + ctx.moveTo(0, r); + ctx.lineTo(0, -1 * r); // draw ctx.fill(); ctx.stroke(); ctx.strokeStyle = renderOptions["colorGrid"]; - ctx.lineWidth = 1; + ctx.lineWidth = lineWidthFactor; //~~ grid starting from origin ctx.beginPath(); - for (i = 0; i <= renderOptions["bed"]["r"]; i += gridStep) { + for (i = 0; i <= r; i += gridStep) { var x = i; - var y = Math.sqrt(Math.pow(renderOptions["bed"]["r"], 2) - Math.pow(x, 2)); + var y = Math.sqrt(r*r - x*x); - ctx.moveTo(x * zoomFactor, y * zoomFactor); - ctx.lineTo(x * zoomFactor, -1 * y * zoomFactor); + ctx.moveTo(x, -1 * y); + ctx.lineTo(x, y); - ctx.moveTo(y * zoomFactor, x * zoomFactor); - ctx.lineTo(-1 * y * zoomFactor, x * zoomFactor); + ctx.moveTo(y, -1 * x); + ctx.lineTo(-1 * y, -1 * x); - ctx.moveTo(-1 * x * zoomFactor, y * zoomFactor); - ctx.lineTo(-1 * x * zoomFactor, -1 * y * zoomFactor); + ctx.moveTo(-1 * x, -1 * y); + ctx.lineTo(-1 * x, y); - ctx.moveTo(y * zoomFactor, -1 * x * zoomFactor); - ctx.lineTo(-1 * y * zoomFactor, -1 * x * zoomFactor); + ctx.moveTo(y, x); + ctx.lineTo(-1 * y, x); } ctx.stroke(); }; @@ -391,31 +435,31 @@ GCODE.renderer = (function(){ var minX, minY, width, height; if (renderOptions["showFullSize"]) { - minX = modelInfo.min.x * zoomFactor; - minY = modelInfo.min.y * zoomFactor; - width = modelInfo.modelSize.x * zoomFactor; - height = modelInfo.modelSize.y * zoomFactor; + minX = modelInfo.min.x; + minY = modelInfo.min.y; + width = modelInfo.modelSize.x; + height = modelInfo.modelSize.y; ctx.beginPath(); ctx.strokeStyle = "#0000ff"; ctx.setLineDash([2, 5]); - ctx.rect(minX, minY * -1, width, height * -1); + ctx.rect(minX, minY, width, height); ctx.stroke(); } if (renderOptions["showBoundingBox"]) { - minX = modelInfo.boundingBox.minX * zoomFactor; - minY = modelInfo.boundingBox.minY * zoomFactor; - width = modelInfo.boundingBox.maxX * zoomFactor - minX; - height = modelInfo.boundingBox.maxY * zoomFactor - minY; + minX = modelInfo.boundingBox.minX; + minY = modelInfo.boundingBox.minY; + width = modelInfo.boundingBox.maxX - minX; + height = modelInfo.boundingBox.maxY - minY; ctx.beginPath(); ctx.strokeStyle = "#ff0000"; ctx.setLineDash([2, 5]); - ctx.rect(minX, minY * -1, width, height * -1); + ctx.rect(minX, minY, width, height); ctx.stroke(); } @@ -439,29 +483,35 @@ GCODE.renderer = (function(){ */ var ax, bx, cx, ay, by, cy; - var h = Math.sqrt(0.75 * length * length); + var h = Math.sqrt(0.75 * length * length) / 2; ax = centerX - length / 2; - bx = centerX + length / 2; + bx = ax + length; cx = centerX; if (up) { - ay = centerY + h / 2; - by = centerY + h / 2; - cy = centerY - h / 2; + ay = centerY - h; + by = centerY - h; + cy = centerY + h; } else { - ay = centerY - h / 2; - by = centerY - h / 2; - cy = centerY + h / 2; + ay = centerY + h; + by = centerY + h; + cy = centerY - h; } + var origLineJoin = ctx.lineJoin; + ctx.lineJoin = "miter"; + ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx, by); + ctx.moveTo(bx, by); ctx.lineTo(cx, cy); ctx.lineTo(ax, ay); ctx.stroke(); ctx.fill(); + + ctx.lineJoin = origLineJoin; }; var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){ @@ -472,11 +522,6 @@ GCODE.renderer = (function(){ //~~ store current layer values isNotCurrentLayer = isNotCurrentLayer !== undefined ? isNotCurrentLayer : false; - if (!isNotCurrentLayer) { - // not not current layer == current layer => store layer number and from/to progress - layerNumStore = layerNum; - progressStore = {from: fromProgress, to: toProgress}; - } if (!model || !model[layerNum]) return; @@ -487,19 +532,28 @@ GCODE.renderer = (function(){ if (cmds[0].prevX !== undefined && cmds[0].prevY !== undefined) { // command contains prevX/prevY values, use those - prevX = cmds[0].prevX * zoomFactor; - prevY = -1 * cmds[0].prevY * zoomFactor; + prevX = cmds[0].prevX; + prevY = cmds[0].prevY; } else if (fromProgress > 0) { // previous command in same layer exists, use x/y as prevX/prevY - prevX = cmds[fromProgress - 1].x * zoomFactor; - prevY = -cmds[fromProgress - 1].y * zoomFactor; + prevX = cmds[fromProgress - 1].x; + prevY = cmds[fromProgress - 1].y; } else if (model[layerNum - 1]) { // previous layer exists, use last x/y as prevX/prevY prevX = undefined; prevY = undefined; - for (i = model[layerNum-1].length-1; i >= 0; i--) { - if (prevX === undefined && model[layerNum - 1][i].x !== undefined) prevX = model[layerNum - 1][i].x * zoomFactor; - if (prevY === undefined && model[layerNum - 1][i].y !== undefined) prevY =- model[layerNum - 1][i].y * zoomFactor; + var prevModelLayer = model[layerNum-1]; + for (i = prevModelLayer.length-1; i >= 0; i--) { + if (prevX === undefined && prevModelLayer[i].x !== undefined) { + prevX = prevModelLayer[i].x; + if (prevY !== undefined) + break; + } + if (prevY === undefined && prevModelLayer[i].y !== undefined) { + prevY = prevModelLayer[i].y; + if (prevX !== undefined) + break; + } } } @@ -510,106 +564,160 @@ GCODE.renderer = (function(){ //~~ render this layer's commands + var sizeRetractSpot = renderOptions["sizeRetractSpot"] * lineWidthFactor * 2; + + // alpha value (100% if current layer is being rendered, 30% otherwise) + var alpha = (renderOptions['showNextLayer'] || renderOptions['showPreviousLayer']) && isNotCurrentLayer ? 0.3 : 1.0; + + var colorLine = {}; + var colorMove = {}; + var colorRetract = {}; + var colorRestart = {}; + + function getColorLineForTool(tool) { + var rv = colorLine[tool]; + if (rv === undefined) { + var lineColor = renderOptions["colorLine"][tool]; + if (lineColor === undefined) lineColor = renderOptions["colorLine"][0]; + var shade = tool * 0.15; + rv = colorLine[tool] = pusher.color(lineColor).shade(shade).alpha(alpha).html(); + } + return rv; + } + + function getColorMoveForTool(tool) { + var rv = colorMove[tool]; + if (rv === undefined) { + var shade = tool * 0.15; + rv = colorMove[tool] = pusher.color(renderOptions["colorMove"]).shade(shade).alpha(alpha).html(); + } + return rv; + } + + function getColorRetractForTool(tool) { + var rv = colorRetract[tool]; + if (rv === undefined) { + var shade = tool * 0.15; + rv = colorRetract[tool] = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html(); + } + return rv; + } + + function getColorRestartForTool(tool) { + var rv = colorRestart[tool]; + if (rv === undefined) { + var shade = tool * 0.15; + rv = colorRestart[tool] = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html(); + } + return rv; + } + + var prevPathType = "fill"; + function strokePathIfNeeded(newPathType, strokeStyle) { + if ((newPathType != prevPathType) || (newPathType == "fill")) { + if (prevPathType != "fill") { + ctx.stroke(); + } + prevPathType = newPathType; + + ctx.beginPath(); + if (newPathType != "fill") { + ctx.strokeStyle = strokeStyle; + ctx.moveTo(prevX, prevY); + } + } + } + + ctx.lineJoin = "round"; + for (i = fromProgress; i <= toProgress; i++) { - ctx.lineWidth = 1; - if (typeof(cmds[i]) === 'undefined') continue; + var cmd = cmds[i]; - if (typeof(cmds[i].prevX) !== 'undefined' && typeof(cmds[i].prevY) !== 'undefined') { + if (cmd.prevX !== undefined && cmd.prevY !== undefined) { // override new (prevX, prevY) - prevX = cmds[i].prevX * zoomFactor; - prevY = -1 * cmds[i].prevY * zoomFactor; + prevX = cmd.prevX; + prevY = cmd.prevY; } // new x - if (typeof(cmds[i].x) === 'undefined' || isNaN(cmds[i].x)) { - x = prevX / zoomFactor; + if (cmd.x === undefined || isNaN(cmd.x)) { + x = prevX; } else { - x = cmds[i].x; + x = cmd.x; } // new y - if (typeof(cmds[i].y) === 'undefined' || isNaN(cmds[i].y)) { - y = prevY / zoomFactor; + if (cmd.y === undefined || isNaN(cmd.y)) { + y = prevY; } else { - y = -cmds[i].y; + y = cmd.y; } // current tool - var tool = cmds[i].tool; - if (tool === undefined) tool = 0; + var tool = cmd.tool || 0; - // line color based on tool - var lineColor = renderOptions["colorLine"][tool]; - if (lineColor === undefined) lineColor = renderOptions["colorLine"][0]; - - // alpha value (100% if current layer is being rendered, 30% otherwise) - var alpha = (renderOptions['showNextLayer'] || renderOptions['showPreviousLayer']) && isNotCurrentLayer ? 0.3 : 1.0; - var shade = tool * 0.15; - - if (!cmds[i].extrude && !cmds[i].noMove) { + if (!cmd.extrude && !cmd.noMove) { // neither extrusion nor move - if (cmds[i].retract === -1) { + if (cmd.retract == -1) { // retract => draw dot if configured to do so if (renderOptions["showRetracts"]) { - ctx.strokeStyle = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html(); - ctx.fillStyle = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html(); - drawTriangle(prevX, prevY, renderOptions["sizeRetractSpot"] * 2, true); + strokePathIfNeeded("fill"); + ctx.fillStyle = getColorRetractForTool(tool); + ctx.strokeStyle = ctx.fillStyle; + drawTriangle(prevX, prevY, sizeRetractSpot, true); } } + strokePathIfNeeded("move", getColorMoveForTool(tool)); if(renderOptions["showMoves"]){ // move => draw line from (prevX, prevY) to (x, y) in move color - ctx.strokeStyle = pusher.color(renderOptions["colorMove"]).shade(shade).alpha(alpha).html(); - ctx.beginPath(); - ctx.moveTo(prevX, prevY); - ctx.lineTo(x*zoomFactor,y*zoomFactor); - ctx.stroke(); + ctx.lineWidth = lineWidthFactor; + ctx.lineTo(x,y); } - } else if(cmds[i].extrude) { - if (cmds[i].retract === 0) { + } else if(cmd.extrude) { + if (cmd.retract == 0) { // no retraction => real extrusion move, use tool color to draw line - ctx.strokeStyle = pusher.color(renderOptions["colorLine"][tool]).shade(shade).alpha(alpha).html(); - ctx.lineWidth = renderOptions['extrusionWidth']; - ctx.beginPath(); - ctx.moveTo(prevX, prevY); - if (cmds[i].direction !== undefined && cmds[i].direction !== 0){ - var cmd = cmds[i]; - var di = cmd.i*zoomFactor; - var dj = -1*cmd.j*zoomFactor; // Y-coordinate is inverted + strokePathIfNeeded("extrude", getColorLineForTool(tool)); + ctx.lineWidth = renderOptions['extrusionWidth'] * lineWidthFactor; + if (cmd.direction !== undefined && cmd.direction != 0){ + var di = cmd.i; + var dj = cmd.j; var centerX = prevX+di; var centerY = prevY+dj; var startAngle = Math.atan2(prevY-centerY, prevX - centerX); - var endAngle = Math.atan2(y*zoomFactor-centerY, x*zoomFactor - centerX); + var endAngle = Math.atan2(y - centerY, x - centerX); var radius=Math.sqrt(di*di+dj*dj); - ctx.arc(centerX,centerY,radius,startAngle,endAngle,cmd.direction<0); // Y-coordinate is inverted so direction is also inverted + ctx.arc(centerX,centerY,radius,startAngle,endAngle,cmd.direction<0); // Y-axis is inverted so direction is also inverted } else { - ctx.lineTo(x*zoomFactor,y*zoomFactor); + ctx.lineTo(x,y); } - ctx.stroke(); } else { // we were previously retracting, now we are restarting => draw dot if configured to do so if (renderOptions["showRetracts"]) { - ctx.strokeStyle = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html(); - ctx.fillStyle = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html(); - drawTriangle(prevX, prevY, renderOptions["sizeRetractSpot"] * 2, false); + strokePathIfNeeded("fill"); + ctx.fillStyle = getColorRestartForTool(tool); + ctx.strokeStyle = ctx.fillStyle; + drawTriangle(prevX, prevY, sizeRetractSpot, false); } } } // set new (prevX, prevY) - prevX = x * zoomFactor; - prevY = y * zoomFactor; + prevX = x; + prevY = y; + } + + if (prevPathType != "fill") { + ctx.stroke(); } - ctx.stroke(); - if (renderOptions["showHead"]) { - ctx.strokeStyle = pusher.color(renderOptions["colorHead"]).shade(shade).alpha(alpha).html(); + var sizeHeadSpot = renderOptions["sizeHeadSpot"] * lineWidthFactor + lineWidthFactor / 2; + var shade = tool * 0.15; ctx.fillStyle = pusher.color(renderOptions["colorHead"]).shade(shade).alpha(alpha).html(); ctx.beginPath(); - ctx.arc(prevX, prevY, renderOptions["sizeHeadSpot"], 0, Math.PI*2, true); - ctx.stroke(); + ctx.arc(prevX, prevY, sizeHeadSpot, 0, Math.PI*2, true); ctx.fill(); } }; @@ -622,8 +730,8 @@ GCODE.renderer = (function(){ if (renderOptions["centerViewport"] || renderOptions["zoomInOnModel"]) { canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2); if (modelInfo) { - offsetModelX = canvasCenter.x - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) * zoomFactor / 2; - offsetModelY = canvasCenter.y + (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) * zoomFactor / 2; + offsetModelX = canvasCenter.x - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2; + offsetModelY = canvasCenter.y - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2; } else { offsetModelX = 0; offsetModelY = 0; @@ -631,10 +739,10 @@ GCODE.renderer = (function(){ offsetBedX = 0; offsetBedY = 0; } else if (modelInfo && renderOptions["moveModel"]) { - offsetModelX = (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2) * zoomFactor; - offsetModelY = -1 * (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2) * zoomFactor; - offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2) * zoomFactor; - offsetBedY = (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2) * zoomFactor; + offsetModelX = (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2); + offsetModelY = (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2); + offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2); + offsetBedY = -1 * (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2); } else if (renderOptions["bed"]["circular"] || renderOptions["bed"]["centeredOrigin"]) { canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2); offsetModelX = canvasCenter.x; @@ -671,10 +779,9 @@ GCODE.renderer = (function(){ var length = modelInfo.boundingBox.maxY - modelInfo.boundingBox.minY; var scaleF = width > length ? (canvas.width - 10) / width : (canvas.height - 10) / length; - scaleF /= zoomFactor; if (transform.a && transform.d) { scaleX = scaleF / transform.a * (renderOptions["invertAxes"]["x"] ? -1 : 1); - scaleY = scaleF / transform.d * (renderOptions["invertAxes"]["y"] ? -1 : 1); + scaleY = scaleF / transform.d * (renderOptions["invertAxes"]["y"] ? 1 : -1); ctx.translate(pt.x,pt.y); ctx.scale(scaleX, scaleY); ctx.translate(-pt.x, -pt.y); @@ -721,22 +828,30 @@ GCODE.renderer = (function(){ if(renderOptions["bed"]["circular"]) { bedWidth = bedHeight = renderOptions["bed"]["r"] * 2; } - zoomFactor = Math.min((canvas.width - 10) / bedWidth, (canvas.height - 10) / bedHeight); + // Ratio of bed to canvas viewport + var viewportRatio = Math.min((canvas.width - 10) / bedWidth, (canvas.height - 10) / bedHeight); + + // Apply initial translation to center the bed in the viewport var translationX, translationY; if (renderOptions["bed"]["circular"]) { translationX = canvas.width / 2; translationY = canvas.height / 2; } else { - translationX = (canvas.width - bedWidth * zoomFactor) / 2; - translationY = bedHeight * zoomFactor + (canvas.height - bedHeight * zoomFactor) / 2; + translationX = (canvas.width - bedWidth * viewportRatio) / 2; + translationY = bedHeight * viewportRatio + (canvas.height - bedHeight * viewportRatio) / 2; } - ctx.translate(translationX, translationY); + ctx.translate(translationX, -translationY); + ctx.scale(viewportRatio, viewportRatio); + offsetModelX = 0; offsetModelY = 0; offsetBedX = 0; offsetBedY = 0; + + // Scaling to apply to move lines and extrusion/retraction markers + lineWidthFactor = 1 / viewportRatio; }, setOption: function(options){ var mustRefresh = false; @@ -748,7 +863,7 @@ GCODE.renderer = (function(){ dirty = true; renderOptions[opt] = options[opt]; - if ($.inArray(opt, ["moveModel", "centerViewport", "zoomInOnModel", "bed", "invertAxes"]) > -1) { + if ($.inArray(opt, ["moveModel", "centerViewport", "zoomInOnModel", "bed", "invertAxes", "onViewportChange"]) > -1) { mustRefresh = true; } } @@ -770,25 +885,12 @@ GCODE.renderer = (function(){ }, render: function(layerNum, fromProgress, toProgress){ if (!initialized) this.init(); + + layerNumStore = layerNum; + progressStore.from = fromProgress; + progressStore.to = toProgress; - var p1 = ctx.transformedPoint(0, 0); - var p2 = ctx.transformedPoint(canvas.width, canvas.height); - ctx.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y); - drawGrid(); - drawBoundingBox(); - if (model && model.length) { - if (layerNum < model.length) { - if (renderOptions['showNextLayer'] && layerNum < model.length - 1) { - drawLayer(layerNum + 1, 0, this.getLayerNumSegments(layerNum + 1), true); - } - if (renderOptions['showPreviousLayer'] && layerNum > 0) { - drawLayer(layerNum - 1, 0, this.getLayerNumSegments(layerNum - 1), true); - } - drawLayer(layerNum, fromProgress, toProgress); - } else { - console.log("Got request to render non-existent layer"); - } - } + reRender(); }, getModelNumLayers: function(){ return model ? model.length : 1; @@ -838,7 +940,7 @@ GCODE.renderer = (function(){ this.render(layerNum, 0, toProgress); }, refresh: function(layerNum) { - if (!layerNum) layerNum = layerNumStore; + if (layerNum === undefined) layerNum = layerNumStore; this.doRender(model, layerNum); }, getZ: function(layerNum){ diff --git a/src/octoprint/static/img/mask-theme.svg b/src/octoprint/static/img/mask-theme.svg new file mode 100644 index 000000000..1d09f4d45 --- /dev/null +++ b/src/octoprint/static/img/mask-theme.svg @@ -0,0 +1,30 @@ + + + + +mask-theme + + + + + + + + + diff --git a/src/octoprint/static/img/favicon.svg b/src/octoprint/static/img/mask.svg similarity index 100% rename from src/octoprint/static/img/favicon.svg rename to src/octoprint/static/img/mask.svg diff --git a/src/octoprint/static/js/app/client/base.js b/src/octoprint/static/js/app/client/base.js index 2eb51d4d9..f8e6b3ae0 100644 --- a/src/octoprint/static/js/app/client/base.js +++ b/src/octoprint/static/js/app/client/base.js @@ -111,7 +111,9 @@ additional = additional || {}; var headers = $.extend({}, additional); - headers["X-Api-Key"] = this.options.apikey; + if (this.options.apikey) { + headers["X-Api-Key"] = this.options.apikey; + } if (this.options.locale !== undefined) { headers["X-Locale"] = this.options.locale; diff --git a/src/octoprint/static/js/app/client/socket.js b/src/octoprint/static/js/app/client/socket.js index b1d70b7a4..9562ed017 100644 --- a/src/octoprint/static/js/app/client/socket.js +++ b/src/octoprint/static/js/app/client/socket.js @@ -85,6 +85,10 @@ this.sendMessage("throttle", this.rateThrottleFactor); }; + OctoPrintSocketClient.prototype.sendAuth = function(userId, session) { + this.sendMessage("auth", userId + ":" + session); + }; + OctoPrintSocketClient.prototype.sendMessage = function(type, payload) { var data = {}; data[type] = payload; diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index e33367740..098eb0aa7 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -342,6 +342,12 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { }) }; + self._onReauthMessage = function(event) { + self._ifInitialized(function() { + callViewModels(self.allViewModels, "onDataUpdaterReauthRequired", [event.data.reason]); + }) + }; + self._onIncreaseRate = function(measurement, minimum) { log.debug("We are fast (" + measurement + " < " + minimum + "), increasing refresh rate"); OctoPrint.socket.increaseRate(); @@ -372,5 +378,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { .onMessage("slicingProgress", self._onSlicingProgress) .onMessage("event", self._onEvent) .onMessage("timelapse", self._onTimelapse) - .onMessage("plugin", self._onPluginMessage); + .onMessage("plugin", self._onPluginMessage) + .onMessage("reauthRequired", self._onReauthMessage); } diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 1eb161d05..7df9e46af 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -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 = $('

    ' + title + '

    '); + } else { + modalHeader = $('

    ' + title + '

    '); + } - var modalHeader = $('

    ' + title + '

    '); 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; } diff --git a/src/octoprint/static/js/app/viewmodels/appearance.js b/src/octoprint/static/js/app/viewmodels/appearance.js index 75c1c527a..81282ba78 100644 --- a/src/octoprint/static/js/app/viewmodels/appearance.js +++ b/src/octoprint/static/js/app/viewmodels/appearance.js @@ -1,10 +1,96 @@ $(function() { + var save = {}; + + // Using the theme color (for the top bar), also recolor the favicon tentacle. + function themeFavicon(colorname) { + save.colorName = colorname; + + // the following is from an Apache licensed snippet: + // http://blog.roomanna.com/09-24-2011/dynamically-coloring-a-favicon + var link = document.querySelector("link[rel='shortcut icon']"); + if (!link) { + link = document.createElement("link"); + link.setAttribute("rel", "shortcut icon"); + document.head.appendChild(link); + } + + // try to get the best quality ico possible; prefer svg, the apple-touch pngs are more difficult, + // but all three of the others give a high-quality ico. + var faviconUrl = document.querySelector("link[rel~='mask-icon-theme']").href + || link.href + || window.location.origin + "/favicon.ico"; + + function onImageLoaded() { + var icosize = 256; + + var canvas = document.createElement("canvas"); + canvas.width = icosize; + canvas.height = icosize; + + var context = canvas.getContext("2d"); + + function grayscale() { + var imageData = context.getImageData(0, 0, canvas.width, canvas.height), + pixels = imageData.data, + i, l, r, g, b, a, luma; + + for (i = 0, l = pixels.length; i < l; i += 4) { + a = pixels[i + 3]; + if (a === 0) { continue; } + + r = pixels[i]; + g = pixels[i + 1]; + b = pixels[i + 2]; + + luma = r * 0.2126 + g * 0.7152 + b * 0.0722; + + pixels[i] = pixels[i + 1] = pixels[i + 2] = luma; + } + + context.putImageData(imageData, 0, 0); + } + + function colorize(color, alpha) { + context.globalCompositeOperation = "source-atop"; + context.globalAlpha = alpha; + context.fillStyle = color; + context.fillRect(0, 0, canvas.width, canvas.height); + context.globalCompositeOperation = "source-over"; + context.globalAlpha = 1.0; + } + + context.drawImage(img, 0, 0, canvas.width, canvas.height); + if (save.colorName !== "default") { + grayscale(); + colorize(save.colorName, .3); + } + link.type = "image/x-icon"; + link.href = canvas.toDataURL(); + } + + var img = document.createElement("img"); + img.addEventListener("load", onImageLoaded); + img.src = faviconUrl; + } + function AppearanceViewModel(parameters) { var self = this; self.name = parameters[0].appearance_name; self.color = parameters[0].appearance_color; self.colorTransparent = parameters[0].appearance_colorTransparent; + self.colorIcon = parameters[0].appearance_colorIcon; + + function updateIcon() { + if (self.colorIcon()) { + themeFavicon(self.color()); + } else { + themeFavicon("default"); + } + } + self.color.subscribe(updateIcon); + self.colorIcon.subscribe(updateIcon); + updateIcon(); self.brand = ko.pureComputed(function() { if (self.name()) diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index 1110b6c28..63615747b 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -56,6 +56,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; @@ -64,12 +67,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); }; @@ -153,7 +171,11 @@ $(function() { self.onEventSettingsUpdated = function() { self.requestData(); - } + }; + + self.onEventConnected = function() { + self.requestData(); + }; self.onStartup = function() { var connectionTab = $("#connection"); diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index d2a77e8cc..522659f97 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -197,7 +197,7 @@ $(function() { }); self._retrieveBedDimensions = function(currentProfileData) { - if (currentProfileData == undefined) { + if (currentProfileData === undefined) { currentProfileData = self.settings.printerProfiles.currentProfileData(); } @@ -205,7 +205,7 @@ $(function() { var x = undefined, y = undefined, r = undefined, circular = false, centeredOrigin = false; var formFactor = currentProfileData.volume.formFactor(); - if (formFactor == "circular") { + if (formFactor === "circular") { r = currentProfileData.volume.width() / 2; circular = true; centeredOrigin = true; @@ -213,7 +213,7 @@ $(function() { x = currentProfileData.volume.width(); y = currentProfileData.volume.depth(); if (currentProfileData.volume.origin) { - centeredOrigin = currentProfileData.volume.origin() == "center"; + centeredOrigin = currentProfileData.volume.origin() === "center"; } } @@ -384,7 +384,7 @@ $(function() { self.loadFile = function(path, date){ self.enableReload(false); self.needsLoad = false; - if (self.status == "idle" && self.errorCount < 3) { + if (self.status === "idle" && self.errorCount < 3) { self.status = "request"; OctoPrint.files.download("local", path) .done(function(response, rstatus) { @@ -412,10 +412,10 @@ $(function() { GCODE.renderer.clear(); GCODE.gCodeReader.loadFile(par); - if (self.layerSlider != undefined) { + if (self.layerSlider !== undefined) { self.layerSlider.slider("disable"); } - if (self.layerCommandSlider != undefined) { + if (self.layerCommandSlider !== undefined) { self.layerCommandSlider.slider("disable"); } }; @@ -440,10 +440,10 @@ $(function() { GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd); GCODE.ui.updateLayerInfo(cmdIndex.layer); - if (self.layerSlider != undefined) { + if (self.layerSlider !== undefined) { self.layerSlider.slider("setValue", cmdIndex.layer); } - if (self.layerCommandSlider != undefined) { + if (self.layerCommandSlider !== undefined) { self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]); } }; @@ -465,17 +465,17 @@ $(function() { self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused); if(self.loadedFilepath - && self.loadedFilepath == data.job.file.path - && self.loadedFileDate == data.job.file.date) { + && self.loadedFilepath === data.job.file.path + && self.loadedFileDate === data.job.file.date) { if (OctoPrint.coreui.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) { self._renderPercentage(data.progress.completion); } self.errorCount = 0 } else { self.clear(); - if (data.job.file.path && data.job.file.origin != "sdcard" - && self.status != "request" - && (!self.waitForApproval() || self.selectedFile.path() != data.job.file.path || self.selectedFile.date() != data.job.file.date)) { + if (data.job.file.path && data.job.file.origin !== "sdcard" + && self.status !== "request" + && (!self.waitForApproval() || self.selectedFile.path() !== data.job.file.path || self.selectedFile.date() !== data.job.file.date)) { self.selectedFile.path(data.job.file.path); self.selectedFile.date(data.job.file.date); self.selectedFile.size(data.job.file.size); @@ -515,7 +515,7 @@ $(function() { self._onModelLoaded = function(model) { if (!model) { self.ui_modelInfo(""); - if (self.layerSlider != undefined) { + if (self.layerSlider !== undefined) { self.layerSlider.slider("disable"); self.layerSlider.slider("setMax", 1); self.layerSlider.slider("setValue", 0); @@ -528,14 +528,13 @@ $(function() { } else { var output = []; output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm"); - output.push(gettext("Estimated total print time") + ": " + formatFuzzyPrintTime(model.printTime)); output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm")); - output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited")); + output.push(gettext("Estimated total print time") + ": " + formatFuzzyPrintTime(model.printTime)); self.ui_modelInfo(output.join("
    ")); self.maxLayer = model.layersPrinted - 1; - if (self.layerSlider != undefined) { + if (self.layerSlider !== undefined) { self.layerSlider.slider("enable"); self.layerSlider.slider("setMax", self.maxLayer); self.layerSlider.slider("setValue", 0); @@ -549,7 +548,7 @@ $(function() { self._onLayerSelected = function(layer) { if (!layer) { self.ui_layerInfo(""); - if (self.layerCommandSlider != undefined) { + if (self.layerCommandSlider !== undefined) { self.layerCommandSlider.slider("disable"); self.layerCommandSlider.slider("setMax", 1); self.layerCommandSlider.slider("setValue", [0, 1]); @@ -563,8 +562,8 @@ $(function() { output.push(gettext("Layer number") + ": " + (layer.number + 1)); output.push(gettext("Layer height") + " (mm): " + layer.height); output.push(gettext("GCODE commands") + ": " + layer.commands); - if (layer.filament != undefined) { - if (layer.filament.length == 1) { + if (layer.filament !== undefined) { + if (layer.filament.length === 1) { output.push(gettext("Filament") + ": " + layer.filament[0].toFixed(2) + "mm"); } else { for (var i = 0; i < layer.filament.length; i++) { @@ -576,7 +575,7 @@ $(function() { self.ui_layerInfo(output.join("
    ")); - if (self.layerCommandSlider != undefined) { + if (self.layerCommandSlider !== undefined) { self.layerCommandSlider.slider("enable"); self.layerCommandSlider.slider("setMax", layer.commands - 1); self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]); @@ -591,11 +590,12 @@ $(function() { if (!options) return; for (var opt in options) { - if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) { + if (!options.hasOwnProperty(opt)) continue; + if (opt === "zoomInOnModel" && options[opt] !== self.renderer_zoomOnModel()) { self.renderer_zoomOnModel(false); - } else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) { + } else if (opt === "centerViewport" && options[opt] !== self.renderer_centerViewport()) { self.renderer_centerViewport(false); - } else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) { + } else if (opt === "moveModel" && options[opt] !== self.renderer_centerModel()) { self.renderer_centerModel(false); } } @@ -605,7 +605,7 @@ $(function() { if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false); var value = event.value; - if (self.currentLayer !== undefined && self.currentLayer == value) return; + if (self.currentLayer !== undefined && self.currentLayer === value) return; self.currentLayer = value; GCODE.ui.changeSelectedLayer(value); @@ -645,7 +645,7 @@ $(function() { if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false); var tuple = event.value; - if (self.currentCommand !== undefined && self.currentCommand[0] == tuple[0] && self.currentCommand[1] == tuple[1]) return; + if (self.currentCommand !== undefined && self.currentCommand[0] === tuple[0] && self.currentCommand[1] === tuple[1]) return; self.currentCommand = tuple; GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]); @@ -660,14 +660,14 @@ $(function() { }; self.onTabChange = function(current, previous) { - self.tabActive = current == "#gcode"; + self.tabActive = current === "#gcode"; if (self.tabActive && self.needsLoad) { self.loadFile(self.selectedFile.path(), self.selectedFile.date()); } }; self.shiftLayer = function(value){ - if (value != self.currentLayer) { + if (value !== self.currentLayer) { self.layerSlider.slider('setValue', value); value = self.layerSlider.slider('getValue'); //This sets the scroll bar to the appropriate position. diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index 556bb8aa8..d00e7f804 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -20,6 +20,8 @@ $(function() { self.elementPasswordInput = undefined; self.elementLoginButton = undefined; + self.externalAddressNotification = undefined; + self.userMenuText = ko.pureComputed(function() { if (self.loggedIn()) { return self.username(); @@ -60,6 +62,62 @@ $(function() { callViewModels(self.allViewModels, "onUserLoggedIn", [response]); log.info("User " + response.name + " logged in") } + + if (response.session) { + OctoPrint.socket.sendAuth(response.name, response.session); + } + + // Show warning if connecting from what seems to be an external IP address, unless ignored + var ignorePublicAddressWarning = localStorage["loginState.ignorePublicAddressWarning"]; + if (ignorePublicAddressWarning === undefined) { + ignorePublicAddressWarning = false; + } else { + ignorePublicAddressWarning = JSON.parse(ignorePublicAddressWarning); + } + + if (response._is_external_client && !ignorePublicAddressWarning) { + var text = gettext("

    It seems that you are connecting to OctoPrint over the public internet.

    " + + "

    This is strongly discouraged unless you have taken proper network security precautions. " + + "Your printer is an appliance you really should not be giving access to " + + "everyone with an internet connection.

    Please see " + + "this blog post for " + + "ways to safely access your OctoPrint instance from remote.

    " + + "

    If you know what you are doing or you are sure this message is " + + "mistaken since you are in an isolated LAN, feel free to ignore it.

    "); + text = _.sprintf(text, {url: "https://octoprint.org/blog/2018/09/03/safe-remote-access/"}); + + if (self.externalAddressNotification !== undefined) { + self.externalAddressNotification.remove(); + } + + self.externalAddressNotification = new PNotify({ + title: gettext("Possible external access detected"), + text: text, + hide: false, + type: "error", + confirm: { + confirm: true, + buttons: [{ + text: gettext("Ignore"), + addClass: "btn btn-danger", + click: function(notice) { + notice.remove(); + localStorage["loginState.ignorePublicAddressWarning"] = JSON.stringify(true); + } + }, { + text: gettext("Later"), + addClass: "btn btn-primary", + click: function(notice) { + notice.remove(); + } + }] + }, + buttons: { + sticker: false + } + + }) + } } else { self.loggedIn(false); self.resetCurrentUserData(); @@ -141,7 +199,7 @@ $(function() { new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"}); self.fromResponse(response); }) - .error(function(error) { + .fail(function(error) { if (error && error.status === 401) { self.fromResponse(false); } @@ -155,6 +213,14 @@ $(function() { self.login(); }; + self.onDataUpdaterReauthRequired = function(reason) { + if (reason === "logout" || reason === "removed") { + self.logout(); + } else { + self.requestData(); + } + }; + self.onAllBound = function(allViewModels) { self.allViewModels = allViewModels; self.startupDeferred.resolve(); diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 9f45e6174..397c00a46 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -111,6 +111,7 @@ $(function() { self.appearance_name = ko.observable(undefined); self.appearance_color = ko.observable(undefined); self.appearance_colorTransparent = ko.observable(); + self.appearance_colorIcon = ko.observable(); self.appearance_defaultLanguage = ko.observable(); self.appearance_showFahrenheitAlso = ko.observable(undefined); @@ -182,12 +183,14 @@ $(function() { self.serial_supportResendsWithoutOk = ko.observable(undefined); self.serial_logPositionOnPause = ko.observable(undefined); self.serial_logPositionOnCancel = ko.observable(undefined); + self.serial_abortHeatupOnCancel = ko.observable(undefined); self.serial_maxTimeoutsIdle = ko.observable(undefined); self.serial_maxTimeoutsPrinting = ko.observable(undefined); self.serial_maxTimeoutsLong = ko.observable(undefined); self.serial_capAutoreportTemp = ko.observable(undefined); self.serial_capAutoreportSdStatus = ko.observable(undefined); self.serial_capBusyProtocol = ko.observable(undefined); + self.serial_capEmergencyParser = ko.observable(undefined); self.folder_uploads = ko.observable(undefined); self.folder_timelapse = ko.observable(undefined); @@ -298,7 +301,7 @@ $(function() { }; self.addTerminalFilter = function() { - self.terminalFilters.push({name: "New", regex: "(Send: M105)|(Recv: ok T:)"}) + self.terminalFilters.push({name: "New", regex: "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)"}) }; self.removeTerminalFilter = function(filter) { diff --git a/src/octoprint/static/js/app/viewmodels/terminal.js b/src/octoprint/static/js/app/viewmodels/terminal.js index 6d4dd3ea3..cd853fe25 100644 --- a/src/octoprint/static/js/app/viewmodels/terminal.js +++ b/src/octoprint/static/js/app/viewmodels/terminal.js @@ -6,6 +6,7 @@ $(function() { self.settings = parameters[1]; self.tabActive = false; + self.previousScroll = undefined; self.log = ko.observableArray([]); self.log.extend({ throttle: 500 }); @@ -278,14 +279,19 @@ $(function() { }; self.terminalScrollEvent = _.throttle(function () { - if (self.autoscrollEnabled()) { - var container = self.fancyFunctionality() ? $("#terminal-output") : $("#terminal-output-lowfi"); + var container = self.fancyFunctionality() ? $("#terminal-output") : $("#terminal-output-lowfi"); + var pos = container.scrollTop(); + var scrollingUp = self.previousScroll !== undefined && pos < self.previousScroll; + + if (self.autoscrollEnabled() && scrollingUp) { var maxScroll = container[0].scrollHeight - container[0].offsetHeight; - if (container.scrollTop() <= maxScroll ) { + if (pos <= maxScroll ) { self.autoscrollEnabled(false); } } + + self.previousScroll = pos; }, 250); self.gotoTerminalCommand = function() { @@ -414,6 +420,10 @@ $(function() { self.updateOutput(); }; + self.onBrowserTabVisibilityChange = function(status) { + self.updateOutput(); + }; + } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/templates/dialogs/settings/appearance.jinja2 b/src/octoprint/templates/dialogs/settings/appearance.jinja2 index b50a93735..b20a91573 100644 --- a/src/octoprint/templates/dialogs/settings/appearance.jinja2 +++ b/src/octoprint/templates/dialogs/settings/appearance.jinja2 @@ -15,7 +15,14 @@
    +
    +
    +
    +
    +
    diff --git a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 index cdf39635d..2d7cca2a0 100644 --- a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 +++ b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 @@ -280,6 +280,13 @@
    +
    +
    + +
    +
    - {{ _('Event based position logging') }} + {{ _('Pausing') }}
    +
    +
    + {{ _('Cancelling') }}
    +
    + +
    diff --git a/src/octoprint/templates/dialogs/wizard/firstrun_end.jinja2 b/src/octoprint/templates/dialogs/wizard/firstrun_end.jinja2 index 53b71622a..33aeb89be 100644 --- a/src/octoprint/templates/dialogs/wizard/firstrun_end.jinja2 +++ b/src/octoprint/templates/dialogs/wizard/firstrun_end.jinja2 @@ -4,7 +4,7 @@ Your OctoPrint installation is now all set up and ready to go. {% endtrans %}

    -

    {{ _('On your printer\'s safety') }}

    +

    {{ _('For your printer\'s safety') }}

    {% trans %} @@ -13,12 +13,18 @@ sometimes sadly do catch fire, so stay or have someone else stay close enough to physically intervene in case of such catastrophic failure. {% endtrans %}

    +

    {% trans url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %} + You also should never make your OctoPrint instance available for everyone on the + public internet, even with Access Control enabled. Your instance will be found, and bad people + will try to abuse it. Don't put yourself at risk, + use a safe way to access your instance remotely. +{% endtrans %}

    {{ _('If you enjoy OctoPrint...') }}

    {% trans url='https://octoprint.org/support-octoprint/?utm_source=octoprint&utm_medium=first_run_wizard' %} - Please consider to support OctoPrint's ongoing development, + Please consider supporting OctoPrint's ongoing development, which can only continue with funding by users like you! You can also find this link in the "About" dialog.
    Thank you! {% endtrans %}

    diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index d25076b5e..d18a41fca 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -4,7 +4,8 @@ OctoPrint - + + diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 83be0bf9a..221c898f9 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -21,6 +21,7 @@ import octoprint.util as util from octoprint.settings import settings from octoprint.events import eventManager, Events +from octoprint.plugin import plugin_manager from octoprint.util import monotonic_time import sarge @@ -60,6 +61,30 @@ _cleanup_lock = threading.RLock() # lock for timelapse job _job_lock = threading.RLock() +# cached valid timelapse extensions +_extensions = None + +def valid_timelapse(path): + global _extensions + + if _extensions is None: + # create list of extensions + extensions = ["mpg", "mpeg", "mp4", "m4v", "mkv"] + + hooks = plugin_manager().get_hooks("octoprint.timelapse.extensions") + for name, hook in hooks.items(): + try: + result = hook() + if result is None or not isinstance(result, list): + continue + extensions += result + except: + logging.getLogger(__name__).exception("Exception while retrieving additional timelapse extensions from hook {name}".format(name=name)) + + _extensions = list(set(extensions)) + + return util.is_allowed_file(path, _extensions) + def _extract_prefix(filename): """ @@ -86,7 +111,7 @@ def get_finished_timelapses(): files = [] basedir = settings().getBaseFolder("timelapse", check_writable=False) for entry in scandir(basedir): - if not fnmatch.fnmatch(entry.name, "*.m*"): + if util.is_hidden_path(entry.path) or not valid_timelapse(entry.path): continue files.append({ "name": entry.name, diff --git a/src/octoprint/users.py b/src/octoprint/users.py index 30b7f1f46..e47df6d66 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -518,6 +518,11 @@ class SessionUser(wrapt.ObjectProxy): self._self_session = "".join(random.choice(chars) for _ in range(10)) self._self_created = time.time() + def asDict(self): + result = self.__wrapped__.asDict() + result.update(dict(session=self.session)) + return result + @property def session(self): return self._self_session diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 29f6a1bbb..b23681bc4 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -339,15 +339,15 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= u'test_123.gco' >>> find_collision_free_name("test1234", "g o", []) u'test1234.g_o' - >>> find_collision_free_name("test12345", "gco", ["test12~1.gco"]) + >>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) u'test12~2.gco' - >>> many_files = ["test12~{}.gco".format(x) for x in range(10)[1:]] + >>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]] >>> find_collision_free_name("test12345", "gco", many_files) u'test1~10.gco' - >>> many_more_files = many_files + ["test1~{}.gco".format(x) for x in range(10, 99)] + >>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)] >>> find_collision_free_name("test12345", "gco", many_more_files) u'test1~99.gco' - >>> many_more_files_plus_one = many_more_files + ["test1~99.gco"] + >>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"] >>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) Traceback (most recent call last): ... @@ -357,13 +357,15 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= """ - if not isinstance(filename, unicode): - filename = unicode(filename) - if not isinstance(extension, unicode): - extension = unicode(extension) + filename = to_unicode(filename) + extension = to_unicode(extension) + + if filename.startswith(u"/"): + filename = filename[1:] + existing_filenames = [to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames] def make_valid(text): - return re.sub(r"\s+", "_", text.translate({ord(i):None for i in ".\"/\\[]:;=,"})).lower() + return re.sub(u"\s+", u"_", text.translate({ord(i):None for i in ".\"/\\[]:;=,"})).lower() filename = make_valid(filename) extension = make_valid(extension) @@ -1268,8 +1270,9 @@ class ResettableTimer(threading.Thread): class CountedEvent(object): - def __init__(self, value=0, maximum=None, **kwargs): + def __init__(self, value=0, minimum=0, maximum=None, **kwargs): self._counter = 0 + self._min = minimum self._max = kwargs.get("max", maximum) self._mutex = threading.RLock() self._event = threading.Event() @@ -1300,7 +1303,7 @@ class CountedEvent(object): self._event.wait(timeout) def blocked(self): - return self.counter == 0 + return self.counter <= 0 def acquire(self, blocking=1): return self._mutex.acquire(blocking=blocking) @@ -1311,7 +1314,8 @@ class CountedEvent(object): def _internal_set(self, value): self._counter = value if self._counter <= 0: - self._counter = 0 + if self._min is not None and self._counter < self._min: + self._counter = self._min self._event.clear() else: if self._max is not None and self._counter > self._max: diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 6cc5a0fdf..cfbedd623 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -76,6 +76,9 @@ regexes_parameters = dict( regex_minMaxError = re.compile("Error:[0-9]\n") """Regex matching first line of min/max errors from the firmware.""" +regex_marlinKillError = re.compile("Heating failed|Thermal Runaway|MAXTEMP triggered|MINTEMP triggered|Invalid extruder number|Watchdog barked|KILL caused") +"""Regex matching first line of kill causing errors from Marlin.""" + regex_sdPrintingByte = re.compile("(?P[0-9]*)/(?P[0-9]*)") """Regex matching SD printing status reports. @@ -123,7 +126,7 @@ Groups will be as follows: * ``target``: new target temperature (float) """ -regex_position = re.compile("X:(?P{float})\s*Y:(?P{float})\s*Z:(?P{float})\s*((E:(?P{float}))|(?P(E\d+:{float}\s*)+))".format(float=regex_float_pattern)) +regex_position = re.compile("X:\s*(?P{float})\s*Y:\s*(?P{float})\s*Z:\s*(?P{float})\s*((E:\s*(?P{float}))|(?P(E\d+:\s*{float}\s*)+))".format(float=regex_float_pattern)) """Regex for matching position reporting. Groups will be as follows: @@ -135,7 +138,7 @@ Groups will be as follows: * ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions """ -regex_e_positions = re.compile("E(?P\d+):(?P{float})".format(float=regex_float_pattern)) +regex_e_positions = re.compile("E(?P\d+):\s*(?P{float})".format(float=regex_float_pattern)) """Regex for matching multiple E coordinates in a position report. Groups will be as follows: @@ -351,6 +354,7 @@ class MachineCom(object): CAPABILITY_AUTOREPORT_TEMP = "AUTOREPORT_TEMP" CAPABILITY_AUTOREPORT_SD_STATUS = "AUTOREPORT_SD_STATUS" CAPABILITY_BUSY_PROTOCOL = "BUSY_PROTOCOL" + CAPABILITY_EMERGENCY_PARSER = "EMERGENCY_PARSER" CAPABILITY_SUPPORT_ENABLED = "enabled" CAPABILITY_SUPPORT_DETECTED = "detected" @@ -438,7 +442,8 @@ class MachineCom(object): self._capability_support = { self.CAPABILITY_AUTOREPORT_TEMP: settings().getBoolean(["serial", "capabilities", "autoreport_temp"]), self.CAPABILITY_AUTOREPORT_SD_STATUS: settings().getBoolean(["serial", "capabilities", "autoreport_sdstatus"]), - self.CAPABILITY_BUSY_PROTOCOL: settings().getBoolean(["serial", "capabilities", "busy_protocol"]) + self.CAPABILITY_BUSY_PROTOCOL: settings().getBoolean(["serial", "capabilities", "busy_protocol"]), + self.CAPABILITY_EMERGENCY_PARSER: settings().getBoolean(["serial", "capabilities", "emergency_parser"]) } self._lastLines = deque([], 50) @@ -454,6 +459,7 @@ class MachineCom(object): self._temperature_autoreporting = False self._sdstatus_autoreporting = False self._busy_protocol_detected = False + self._busy_protocol_support = False self._trigger_ok_after_resend = settings().get(["serial", "supportResendsWithoutOk"]) self._resend_ok_timer = None @@ -476,7 +482,7 @@ class MachineCom(object): self._long_running_commands = settings().get(["serial", "longRunningCommands"]) self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"]) - self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send") + self._clear_to_send = CountedEvent(name="comm.clear_to_send", minimum=None) self._send_queue = SendQueue() self._temperature_timer = None self._sd_status_timer = None @@ -540,6 +546,7 @@ class MachineCom(object): self._log_position_on_pause = settings().getBoolean(["serial", "logPositionOnPause"]) self._log_position_on_cancel = settings().getBoolean(["serial", "logPositionOnCancel"]) + self._abort_heatup_on_cancel = settings().getBoolean(["serial", "abortHeatupOnCancel"]) # print job self._currentFile = None @@ -1018,11 +1025,6 @@ class MachineCom(object): self._callback.on_comm_print_job_started() if self.isSdFileSelected(): - interval = self._timeout_intervals.get("sdStatus", 1.0) - if interval <= 0: - interval = 1.0 - self._sd_status_timer = RepeatedTimer(interval, self._poll_sd_status, run_first=True) - if not external_sd: # make sure to ignore the "file selected" later on, otherwise we'll reset our progress data self._ignore_select = True @@ -1038,15 +1040,9 @@ class MachineCom(object): else: self._currentFile.pos = 0 - def start_polling(): - self._sd_status_timer.start() - self.sendCommand("M24", - on_sent=start_polling, part_of_job=True, tags=tags | {"trigger:comm.start_print",}) - else: - self._sd_status_timer.start() else: if pos is not None and isinstance(pos, int) and pos > 0: self._currentFile.seek(pos) @@ -1161,6 +1157,7 @@ class MachineCom(object): elif check_timer: return + self._currentFile.done = True self._recordFilePosition() self._callback.on_comm_print_job_cancelled() @@ -1206,16 +1203,18 @@ class MachineCom(object): with self._jobLock: self._changeState(self.STATE_CANCELLING) + if self._abort_heatup_on_cancel: + # abort any ongoing heatups immediately to get back control over the printer + self.sendCommand("M108", + part_of_job=False, + tags=tags | {"trigger:comm.cancel", "trigger:abort_heatup"}, + force=True) + if self.isSdFileSelected(): if not external_sd: self.sendCommand("M25", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # pause print self.sendCommand("M27", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # get current byte position in file self.sendCommand("M26 S0", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # reset position in file to byte 0 - if self._sd_status_timer is not None: - try: - self._sd_status_timer.cancel() - except: - pass if self._log_position_on_cancel and not disable_log_position: self.sendCommand("M400", @@ -1500,8 +1499,8 @@ class MachineCom(object): self._changeState(self.STATE_CONNECTING) #Start monitoring the serial port. - self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals) - self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals) + self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) + self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) startSeen = False supportRepetierTargetTemp = settings().getBoolean(["serial", "repetierTargetTemp"]) @@ -1521,7 +1520,7 @@ class MachineCom(object): if line.strip() is not "": self._consecutive_timeouts = 0 - self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals) + self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) if self._dwelling_until and now > self._dwelling_until: self._dwelling_until = False @@ -1535,23 +1534,27 @@ class MachineCom(object): ##~~ busy protocol handling if line.startswith("echo:busy:") or line.startswith("busy:"): # reset the ok timeout, the regular comm timeout has already been reset - self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals) + self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) # make sure the printer sends busy in a small enough interval to match our timeout if not self._busy_protocol_detected and self._capability_support.get(self.CAPABILITY_BUSY_PROTOCOL, False): - self._log("Printer seems to support the busy protocol, adjusting timeouts and setting busy " - "interval accordingly") - self._busy_protocol_detected = True + to_log = "Printer seems to support the busy protocol, will adjust timeouts and set busy " \ + "interval accordingly" + self._log(to_log) + self._logger.info(to_log) + self._busy_protocol_detected = True new_communication_timeout = self._timeout_intervals.get("communicationBusy", 2) - self._serial.timeout = new_communication_timeout busy_interval = max(int(new_communication_timeout) - 1, 1) - self._logger.info("Printer seems to support the busy protocol, telling it to set the busy " - "interval to our \"communicationBusy\" timeout - 1s = {}s".format(busy_interval)) + def busyIntervalSet(): + self._logger.info("Telling the printer to set the busy interval to our " + "\"communicationBusy\" timeout - 1s = {}s".format(busy_interval)) + self._busy_protocol_support = True + self._serial.timeout = new_communication_timeout - self._set_busy_protocol_interval(interval=busy_interval) + self._set_busy_protocol_interval(interval=busy_interval, callback=busyIntervalSet) if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE): continue @@ -1665,7 +1668,7 @@ class MachineCom(object): # Both variants can only happen if we are not currently blocked by a dwelling command self._handle_timeout() - self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals) + self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) # timeout only considered handled if the printer is printing and it was a comm timeout, not an ok # timeout @@ -1810,6 +1813,11 @@ class MachineCom(object): if not sd_always_available and not self._sdAvailable: self.initSdCard() + elif "teacup" in firmware_name.lower(): + self._logger.info("Detected Teacup firmware, enabling relevant features for issue free communication") + + disable_external_heatup_detection = True # see #2854 + self._firmware_info_received = True self._firmware_info = data self._firmware_name = firmware_name @@ -1835,6 +1843,8 @@ class MachineCom(object): elif capability == self.CAPABILITY_AUTOREPORT_SD_STATUS and enabled: self._logger.info("Firmware states that it supports sd status autoreporting") self._set_autoreport_sdstatus_interval() + elif capability == self.CAPABILITY_EMERGENCY_PARSER and enabled: + self._logger.info("Firmware states that it supports emergency GCODEs M108 and M410 to be sent without waiting for an acknowledgement first") # notify plugins for name, hook in self._firmware_info_hooks["capabilities"].items(): @@ -1893,17 +1903,19 @@ class MachineCom(object): total = int(match.group("total")) if self.isSdPrinting() and current == total == 0: - # apparently not SD printing - newer Marlin reports it like that for some reason + # apparently not SD printing - some Marlin versions report it like that for some reason self.cancelPrint(external_sd=True) elif self.isSdFileSelected(): - if not self.isSdPrinting() and current != total: + if not self.isSdPrinting() and current != total and current > 0: self.startPrint(external_sd=True) self._currentFile.pos = current if self._currentFile.size == 0: self._currentFile.size = total - self._callback.on_comm_progress() + + if not self._currentFile.done: + self._callback.on_comm_progress() elif 'Not SD printing' in line and self.isSdFileSelected() and self.isPrinting() and not self.isFinishing(): # something went wrong, printer is reporting that we actually are not printing right now... @@ -1919,9 +1931,7 @@ class MachineCom(object): size = 0 user = None - expected = False if self._sdFileToSelect: - expected = True name = self._sdFileToSelect user = self._sdFileToSelectUser @@ -1929,12 +1939,6 @@ class MachineCom(object): self._sdFileToSelectUser = None self._currentFile = PrintingSdFileInformation(name, size, user=user) - - if not expected: - # It doesn't look like we expected this, so it might be that someone just started a print - # job from SD via the printer's controller. Let's query the printing status and see if that's - # indeed the case and if so switch states accordingly - self.sendCommand("M27", tags={"trigger:unexpected_file_open"}) elif 'File selected' in line: if self._ignore_select: self._ignore_select = False @@ -1953,12 +1957,6 @@ class MachineCom(object): self._currentFile.done = True self._currentFile.pos = 0 - if self._sd_status_timer is not None: - try: - self._sd_status_timer.cancel() - except: - pass - self.sendCommand("M400", part_of_job=True) self._callback.on_comm_print_job_done() def finalize(): @@ -2062,7 +2060,7 @@ class MachineCom(object): self._resend_ok_timer.cancel() self._resend_ok_timer = None - self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals) + self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) self._clear_to_send.set() # reset long running commands, persisted current tools and heatup counters on ok @@ -2270,7 +2268,7 @@ class MachineCom(object): command or heating, no poll will be done. """ - if self.isOperational() and not self._sdstatus_autoreporting and not self._connection_closing and self.isSdPrinting() and not self._long_running_command and not self._dwelling_until and not self._heating: + if self.isOperational() and not self._sdstatus_autoreporting and not self._connection_closing and self.isSdFileSelected() and not self._long_running_command and not self._dwelling_until and not self._heating: self.sendCommand("M27", cmd_type="sd_status_poll", tags={"trigger:comm.poll_sd_status"}) def _set_autoreport_temperature_interval(self, interval=None): @@ -2289,19 +2287,24 @@ class MachineCom(object): interval = 1 self.sendCommand("M27 S{}".format(interval), tags={"trigger:comm.set_autoreport_sdstatus_interval"}) - def _set_busy_protocol_interval(self, interval=None): + def _set_busy_protocol_interval(self, interval=None, callback=None): if interval is None: try: interval = max(int(self._timeout_intervals.get("communicationBusy", 3)) - 1, 1) except: interval = 2 - self.sendCommand("M113 S{}".format(interval), tags={"trigger:comm.set_busy_protocol_interval"}) + self.sendCommand("M113 S{}".format(interval), + tags={"trigger:comm.set_busy_protocol_interval"}, + on_sent=callback) def _onConnected(self): self._serial.timeout = settings().getFloat(["serial", "timeout", "communication"]) - self._temperature_timer = RepeatedTimer(self._getTemperatureTimerInterval, self._poll_temperature, run_first=True) + self._temperature_timer = RepeatedTimer(self._get_temperature_timer_interval, self._poll_temperature, run_first=True) self._temperature_timer.start() + self._sd_status_timer = RepeatedTimer(self._get_sd_status_timer_interval, self._poll_sd_status, run_first=True) + self._sd_status_timer.start() + self._changeState(self.STATE_OPERATIONAL) self.resetLineNumbers(tags={"trigger:comm.on_connected",}) @@ -2335,10 +2338,10 @@ class MachineCom(object): self._set_autoreport_temperature_interval() if self._sdstatus_autoreporting: self._set_autoreport_sdstatus_interval() - if self._busy_protocol_detected: + if self._busy_protocol_support: self._set_busy_protocol_interval() - def _getTemperatureTimerInterval(self): + def _get_temperature_timer_interval(self): busy_default = 4.0 target_default = 2.0 @@ -2362,6 +2365,12 @@ class MachineCom(object): return get("temperature", busy_default) + def _get_sd_status_timer_interval(self): + interval = self._timeout_intervals.get("sdStatus", 1.0) + if interval <= 0: + interval = 1.0 + return interval + def _send_from_command_queue(self): # We loop here to make sure that if we do NOT send the first command # from the queue, we'll send the second (if there is one). We do not @@ -2506,17 +2515,31 @@ class MachineCom(object): "cannot open", "open failed", "cannot enter") + _fatal_errors = ("kill() called", + "fatal:") def _handle_errors(self, line): if line is None: return lower_line = line.lower() + if lower_line.startswith("fatal:"): + # hello Repetier firmware -_- + line = "Error:" + line + lower_line = line.lower() + if lower_line.startswith('error:') or line.startswith('!!'): if regex_minMaxError.match(line): # special delivery for firmware that goes "Error:x\n: Extruder switched off. MAXTEMP triggered !\n" line = line.rstrip() + self._readline() lower_line = line.lower() + elif regex_marlinKillError.search(line): + # special delivery for marlin kill errors that are split across multiple error lines + next_line = self._readline().strip() + if next_line.lower().startswith("error:"): + next_line = next_line[6:].strip() + line = line.rstrip() + " - " + next_line + lower_line = line.lower() stripped_error = (line[6:] if lower_line.startswith("error:") else line[2:]).strip() @@ -2553,11 +2576,12 @@ class MachineCom(object): level=logging.WARN) if not self._ignore_errors: - if self._disconnect_on_errors: + if self._disconnect_on_errors or any(map(lambda x: x in lower_line, self._fatal_errors)): self._trigger_error(stripped_error, "firmware") elif self.isPrinting(): self.cancelPrint(firmware_error=stripped_error) self._clear_to_send.set() + else: self._log("WARNING! Received an error from the printer's firmware, ignoring that as configured " "but you might want to investigate what happened here! Error: {}".format(stripped_error)) @@ -2612,7 +2636,14 @@ class MachineCom(object): if self._currentFile is None: return None, None, None - line, pos, lineno = self._currentFile.getNext() + try: + line, pos, lineno = self._currentFile.getNext() + except EnvironmentError: + self._log("There was an error reading from the file that's being printed, cancelling the print. Please " + "consult octoprint.log for details on the error.") + self.cancelPrint() + return None, None, None + if line is None: if isinstance(self._currentFile, StreamingGcodeFileInformation): self._finishFileTransfer() @@ -2986,17 +3017,7 @@ class MachineCom(object): continue # now comes the part where we increase line numbers and send stuff - no turning back now - command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands - command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands - checksum_enabled = not self._neverSendChecksum and ((self.isPrinting() and self._currentFile and self._currentFile.checksum) or - self._alwaysSendChecksum or - not self._firmware_info_received) - - command_to_send = command.encode("ascii", errors="replace") - if command_requiring_checksum or (command_allowing_checksum and checksum_enabled): - self._do_increment_and_send_with_checksum(command_to_send) - else: - self._do_send_without_checksum(command_to_send) + self._do_send(command, gcode=gcode) # trigger "sent" phase and use up one "ok" if on_sent is not None and callable(on_sent): @@ -3156,6 +3177,24 @@ class MachineCom(object): ##~~ actual sending via serial + def _needs_checksum(self, gcode=None): + command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands + command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands + return command_requiring_checksum or (command_allowing_checksum and self._checksum_enabled) + + @property + def _checksum_enabled(self): + return not self._neverSendChecksum and ((self.isPrinting() and self._currentFile and self._currentFile.checksum) or + self._alwaysSendChecksum or + not self._firmware_info_received) + + def _do_send(self, command, gcode=None): + command_to_send = command.encode("ascii", errors="replace") + if self._needs_checksum(gcode): + self._do_increment_and_send_with_checksum(command_to_send) + else: + self._do_send_without_checksum(command_to_send) + def _do_increment_and_send_with_checksum(self, cmd): with self._line_mutex: linenumber = self._currentLine @@ -3424,7 +3463,12 @@ class MachineCom(object): self._resendDelta = None def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): - # emergency stop, jump the queue with the M112 + self._logger.info("Force-sending M112 to the printer") + + # emergency stop, jump the queue with the M112, regardless of whether the EMERGENCY_PARSER capability is + # available or not + # + # send the M112 once without and with checksum self._do_send_without_checksum("M112") self._do_increment_and_send_with_checksum("M112") @@ -3452,6 +3496,32 @@ class MachineCom(object): # I hope it got it the first time because as far as I can tell, there is no way to know return None, + def _gcode_M108_queuing(self, cmd, gcode=None, *args, **kwargs): + # only jump the queue with M108 if the EMERGENCY_PARSER capability is available + if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False): + return + + self._logger.info("Force-sending M108 to the printer") + self._do_send(cmd, gcode=gcode) + + # use up an ok since we will get one back for this command and don't want to get out of sync + self._clear_to_send.clear() + + return None, + + def _gcode_M410_queuing(self, cmd, gcode=None, *args, **kwargs): + # only jump the queue with M410 if the EMERGENCY_PARSER capability is available + if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False): + return + + self._logger.info("Force-sending M410 to the printer") + self._do_send(cmd, gcode=gcode) + + # use up an ok since we will get one back for this command and don't want to get out of sync + self._clear_to_send.clear() + + return None, + def _gcode_M114_queued(self, *args, **kwargs): self._reset_position_timers() _gcode_M114_sent = _gcode_M114_queued @@ -3467,7 +3537,7 @@ class MachineCom(object): elif s_match: _timeout = float(s_match.group("value")) - self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals) + _timeout + self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) + _timeout self._dwelling_until = time.time() + _timeout def _validate_tool(self, tool): @@ -3646,6 +3716,10 @@ class PrintingFileInformation(object): def done(self): return self._done + @done.setter + def done(self, value): + self._done = value + class PrintingSdFileInformation(PrintingFileInformation): """ Encapsulates information regarding an ongoing print from SD. @@ -3660,14 +3734,6 @@ class PrintingSdFileInformation(PrintingFileInformation): def getFileLocation(self): return FileDestinations.SDCARD - @property - def done(self): - return self._done - - @done.setter - def done(self, value): - self._done = value - @property def size(self): return self._size diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index 97678d608..b01236caf 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -78,7 +78,7 @@ class CommandlineCaller(object): self._logger.debug(u"Calling: {}".format(joined_command)) self.on_log_call(joined_command) - kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture())) + kwargs.update(dict(async_=True, stdout=sarge.Capture(), stderr=sarge.Capture())) p = sarge.run(command, **kwargs) while len(p.commands) == 0: diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index 061564ce0..2fa5ddb0d 100644 --- a/src/octoprint/util/gcodeInterpreter.py +++ b/src/octoprint/util/gcodeInterpreter.py @@ -43,15 +43,9 @@ class Vector3D(object): True """ - def __init__(self, *args, **kwargs): - self.x = kwargs.get("x", 0.0) - self.y = kwargs.get("y", 0.0) - self.z = kwargs.get("z", 0.0) - + def __init__(self, *args): if len(args) == 3: - self.x = args[0] - self.y = args[1] - self.z = args[2] + (self.x, self.y, self.z) = args elif len(args) == 1: # copy constructor @@ -134,30 +128,25 @@ class MinMax3D(object): >>> empty = MinMax3D() >>> empty.size == Vector3D(0.0, 0.0, 0.0) True - >>> partial = MinMax3D() - >>> partial.record(Vector3D(2.0, None, 2.0)) - >>> partial.min.x == 2.0 == partial.max.x and partial.min.y == None == partial.max.y and partial.min.z == 2.0 == partial.max.z - True - >>> partial.record(Vector3D(1.0, None, 3.0)) - >>> partial.min.x == 1.0 and partial.min.y == None and partial.min.z == 2.0 - True - >>> partial.max.x == 2.0 and partial.max.y == None and partial.max.z == 3.0 - True - >>> partial.size == Vector3D(1.0, 0.0, 1.0) - True """ def __init__(self): - self.min = Vector3D(None, None, None) - self.max = Vector3D(None, None, None) + self.min = Vector3D(float("inf"), float("inf"), float("inf")) + self.max = Vector3D(-float("inf"), -float("inf"), -float("inf")) def record(self, coordinate): - for c in "xyz": - current_min = getattr(self.min, c) - current_max = getattr(self.max, c) - value = getattr(coordinate, c) - setattr(self.min, c, value if current_min is None or value < current_min else current_min) - setattr(self.max, c, value if current_max is None or value > current_max else current_max) + """ + Records the coordinate, storing the min and max values. + + The input vector components must not be None. + """ + self.min.x = min(self.min.x, coordinate.x) + self.min.y = min(self.min.y, coordinate.y) + self.min.z = min(self.min.z, coordinate.z) + self.max.x = max(self.max.x, coordinate.x) + self.max.y = max(self.max.y, coordinate.y) + self.max.z = max(self.max.z, coordinate.z) + @property def size(self): @@ -165,7 +154,7 @@ class MinMax3D(object): for c in "xyz": min = getattr(self.min, c) max = getattr(self.max, c) - value = abs(max - min) if min is not None and max is not None else 0.0 + value = abs(max - min) if max >= min else 0.0 setattr(result, c, value) return result @@ -199,12 +188,12 @@ class gcode(object): @property def printing_area(self): - return dict(minX=self._minMax.min.x, - minY=self._minMax.min.y, - minZ=self._minMax.min.z, - maxX=self._minMax.max.x, - maxY=self._minMax.max.y, - maxZ=self._minMax.max.z) + return dict(minX=None if math.isinf(self._minMax.min.x) else self._minMax.min.x, + minY=None if math.isinf(self._minMax.min.y) else self._minMax.min.y, + minZ=None if math.isinf(self._minMax.min.z) else self._minMax.min.z, + maxX=None if math.isinf(self._minMax.max.x) else self._minMax.max.x, + maxY=None if math.isinf(self._minMax.max.y) else self._minMax.max.y, + maxZ=None if math.isinf(self._minMax.max.z) else self._minMax.max.z) def load(self, filename, throttle=None, speedx=6000, speedy=6000, offsets=None, max_extruders=10, g90_extruder=False): if os.path.isfile(filename): @@ -498,17 +487,13 @@ def getCodeInt(line, code): def getCodeFloat(line, code): - import math n = line.find(code) + 1 if n < 1: return None m = line.find(' ', n) try: if m < 0: - val = float(line[n:]) - else: - val = float(line[n:m]) - return val if not (math.isnan(val) or math.isinf(val)) else None + return float(line[n:]) + return float(line[n:m]) except: return None - diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py index 50e536584..2ca5cfea3 100644 --- a/src/octoprint/util/net.py +++ b/src/octoprint/util/net.py @@ -6,6 +6,8 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms import socket import sys +import netaddr +import netifaces HAS_V6 = socket.has_ipv6 @@ -21,3 +23,51 @@ else: else: # Whatever we are running on here, it we don't want to use V6 on here due to lack of dual stack support HAS_V6 = False + +def is_lan_address(address, additional_private=None): + if address.lower().startswith("::ffff:") and "." in address: + # ipv6 mapped ipv4 address, unmap + address = address[len("::ffff:"):] + + ip = netaddr.IPAddress(address) + if ip.is_private() or ip.is_loopback(): + return True + + if additional_private is None or not isinstance(additional_private, (list, tuple)): + additional_private = [] + + subnets = netaddr.IPSet() + for additional in additional_private: + try: + subnets.add(netaddr.IPNetwork(additional)) + except: + pass + + def to_ipnetwork(address): + try: + prefix = address["netmask"] + if "/" in prefix: + # v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64" + _, prefix = prefix.split("/") + + addr = address["addr"] + if "%" in addr: + # interface comment in netifaces output, e.g. "fe80::457f:bbee:d579:1063%wlan0" + addr = addr[:addr.find("%")] + return netaddr.IPNetwork("{}/{}".format(addr, prefix)) + except: + pass + + for interface in netifaces.interfaces(): + addrs = netifaces.ifaddresses(interface) + for v4 in addrs.get(socket.AF_INET, ()): + subnets.add(to_ipnetwork(v4)) + + if HAS_V6: + for v6 in addrs.get(socket.AF_INET6, ()): + subnets.add(to_ipnetwork(v6)) + + if ip in subnets: + return True + + return False diff --git a/src/octoprint/util/platform/__init__.py b/src/octoprint/util/platform/__init__.py index 084a76b43..cd21be30f 100644 --- a/src/octoprint/util/platform/__init__.py +++ b/src/octoprint/util/platform/__init__.py @@ -49,9 +49,38 @@ _OPERATING_SYSTEMS = dict(windows=["win32"], freebsd=lambda x: x.startswith("freebsd")) OPERATING_SYSTEM_UNMAPPED = "unmapped" + def get_os(): for identifier, platforms in _OPERATING_SYSTEMS.items(): if (callable(platforms) and platforms(sys.platform)) or (isinstance(platforms, list) and sys.platform in platforms): return identifier else: return OPERATING_SYSTEM_UNMAPPED + + +def is_os_compatible(compatibility_entries, current_os=None): + """ + 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 + + if current_os is None: + current_os = get_os() + + 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 + diff --git a/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py b/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py index d5dd6efc7..00e494b6d 100644 --- a/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py +++ b/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py @@ -10,6 +10,7 @@ import socket from octoprint.vendor.sockjs.tornado import websocket, session from octoprint.vendor.sockjs.tornado.transports import base +from tornado.ioloop import IOLoop LOG = logging.getLogger("tornado.general") @@ -74,11 +75,16 @@ class RawWebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransport session.close() def send_pack(self, message, binary=False): - # Send message - try: - self.write_message(message, binary) - except IOError: - self.server.io_loop.add_callback(self.on_close) + if IOLoop.current(False) == self.server.io_loop: + # Running in Main Thread + # Send message + try: + self.write_message(message, binary) + except IOError: + self.server.io_loop.add_callback(self.on_close) + else: + # Not running in Main Thread so use proper thread to send message + self.server.io_loop.add_callback(lambda: self.send_pack(message, binary)) def session_closed(self): try: diff --git a/src/octoprint/vendor/sockjs/tornado/transports/websocket.py b/src/octoprint/vendor/sockjs/tornado/transports/websocket.py index 8df3a2901..644b14543 100644 --- a/src/octoprint/vendor/sockjs/tornado/transports/websocket.py +++ b/src/octoprint/vendor/sockjs/tornado/transports/websocket.py @@ -11,6 +11,7 @@ import socket from octoprint.vendor.sockjs.tornado import proto, websocket from octoprint.vendor.sockjs.tornado.transports import base from octoprint.vendor.sockjs.tornado.util import bytes_to_str +from tornado.ioloop import IOLoop LOG = logging.getLogger("tornado.general") @@ -81,11 +82,16 @@ class WebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMix session.close() def send_pack(self, message, binary=False): - # Send message - try: - self.write_message(message, binary) - except IOError: - self.server.io_loop.add_callback(self.on_close) + if IOLoop.current(False) == self.server.io_loop: + # Running in Main Thread + # Send message + try: + self.write_message(message, binary) + except IOError: + self.server.io_loop.add_callback(self.on_close) + else: + # Not running in Main Thread so use proper thread to send message + self.server.io_loop.add_callback(lambda: self.send_pack(message, binary)) def session_closed(self): # If session was closed by the application, terminate websocket diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py index 328be4558..158408a53 100644 --- a/src/octoprint_setuptools/__init__.py +++ b/src/octoprint_setuptools/__init__.py @@ -524,8 +524,7 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1" translation_dir = os.path.join(source_folder, "translations") pot_file = os.path.join(translation_dir, "messages.pot") bundled_dir = os.path.join(source_folder, package, "translations") - if os.path.isdir(translation_dir) and os.path.isfile(pot_file): - cmdclass.update(get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, bundled_dir=bundled_dir, pack_name_prefix="{name}-i18n-".format(**locals()), pack_path_prefix="_plugins/{identifier}/".format(**locals()))) + cmdclass.update(get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, bundled_dir=bundled_dir, pack_name_prefix="{name}-i18n-".format(**locals()), pack_path_prefix="_plugins/{identifier}/".format(**locals()))) from setuptools import find_packages packages = list(set([package] + filter(lambda x: x.startswith("{package}.".format(package=package)), find_packages(where=source_folder, exclude=ignored_packages)) + additional_packages)) diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index 278578151..b0215911c 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -300,29 +300,9 @@ class FileManagerTest(unittest.TestCase): date=now) - mock_atomic_write.assert_called_with(recovery_file) + mock_atomic_write.assert_called_with(recovery_file, max_permissions=438) mock_yaml_safe_dump.assert_called_with(expected, stream=mock_atomic_write_handle, default_flow_style=False, indent=" ", allow_unicode=True) - @mock.patch("octoprint.util.atomic_write", create=True) - @mock.patch("yaml.safe_dump", create=True) - @mock.patch("time.time") - def test_save_recovery_data(self, mock_time, mock_yaml_safe_dump, mock_atomic_write): - import os - - now = 123456789 - path = "some_file.gco" - pos = 1234 - recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml") - - mock_atomic_write.return_value = mock.MagicMock(spec=file) - mock_atomic_write_handle = mock_atomic_write.return_value.__enter__.return_value - mock_time.return_value = now - self.local_storage.path_in_storage.return_value = path - - mock_yaml_safe_dump.side_effect = RuntimeError - - self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos) - @mock.patch("os.path.isfile") @mock.patch("os.remove") def test_delete_recovery_data(self, mock_remove, mock_isfile): @@ -352,29 +332,26 @@ class FileManagerTest(unittest.TestCase): self.file_manager.delete_recovery_data() - @mock.patch("os.path.isfile") - @mock.patch("yaml.safe_load") - def test_get_recovery_data(self, mock_yaml_safe_load, mock_isfile): - import os - recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml") + @mock.patch("os.path.isfile", return_value=True) + def test_get_recovery_data(self, mock_isfile): + import os + import yaml + recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml") - mock_isfile.return_value = True + data = dict(path="some_path.gco", + origin="local", + pos=1234, + date=123456789) + text_data = yaml.dump(data) - data = dict(path="some_path.gco", - origin="local", - pos=1234, - date=123456789) - mock_yaml_safe_load.return_value = data + with mock.patch("__builtin__.open", mock.mock_open(read_data=text_data)) as m: + # moved safe_load to here so we could mock up the return value properly + with mock.patch("yaml.safe_load", return_value=data) as n: + result = self.file_manager.get_recovery_data() - with mock.patch("__builtin__.open", mock.mock_open(read_data=data), create=True) as m: - result = self.file_manager.get_recovery_data() - - self.assertDictEqual(data, result) - - m.assert_called_with(recovery_file) - - mock_handle = m() - mock_yaml_safe_load.assert_called_with(mock_handle) + self.assertDictEqual(data, result) + n.assert_called_with(m()) + mock_isfile.assert_called_with(recovery_file) @mock.patch("os.path.isfile") def test_get_recovery_data_no_file(self, mock_isfile): diff --git a/tests/plugins/pi_support/__init__.py b/tests/plugins/pi_support/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/plugins/pi_support/fakes/fake_model.txt b/tests/plugins/pi_support/fakes/fake_model.txt new file mode 100644 index 000000000..686e67ebc --- /dev/null +++ b/tests/plugins/pi_support/fakes/fake_model.txt @@ -0,0 +1 @@ +Raspberry Pi Model F Rev 1.1 diff --git a/tests/plugins/pi_support/fakes/fake_octopi.txt b/tests/plugins/pi_support/fakes/fake_octopi.txt new file mode 100644 index 000000000..e815b861f --- /dev/null +++ b/tests/plugins/pi_support/fakes/fake_octopi.txt @@ -0,0 +1 @@ +0.15.1 diff --git a/tests/plugins/pi_support/fakes/fake_vcgencmd.py b/tests/plugins/pi_support/fakes/fake_vcgencmd.py new file mode 100644 index 000000000..3dc7084cf --- /dev/null +++ b/tests/plugins/pi_support/fakes/fake_vcgencmd.py @@ -0,0 +1,2 @@ +#!/usr/bin/env python2 +print("throttled=0x50005") diff --git a/tests/plugins/pi_support/test_pi_support.py b/tests/plugins/pi_support/test_pi_support.py new file mode 100644 index 000000000..be33f8c71 --- /dev/null +++ b/tests/plugins/pi_support/test_pi_support.py @@ -0,0 +1,153 @@ + +import unittest +import ddt +import mock + +OCTOPI_VERSION = "0.14.0" + +DT_MODEL = "Raspberry Pi Model F Rev 1.1" + +VCGENCMD = "/usr/bin/vcgencmd get_throttled" + +class PiSupportTestCase(unittest.TestCase): + + def test_get_octopi_version(self): + from octoprint.plugins.pi_support import get_octopi_version + + with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: + m.return_value.readline.return_value = OCTOPI_VERSION + version = get_octopi_version() + + m.assert_called_once_with("/etc/octopi_version", "r") + self.assertEqual(version, OCTOPI_VERSION) + + def test_get_proc_dt_model(self): + from octoprint.plugins.pi_support import get_proc_dt_model + + with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: + m.return_value.readline.return_value = DT_MODEL + model = get_proc_dt_model() + + m.assert_called_once_with("/proc/device-tree/model", "r") + self.assertEqual(model, DT_MODEL) + + def test_get_vcgencmd_throttle_state(self): + from octoprint.plugins.pi_support import get_vcgencmd_throttled_state + + with mock.patch("sarge.get_stdout", mock.MagicMock()) as m: + m.return_value = "throttled=0x70005" + state = get_vcgencmd_throttled_state(VCGENCMD) + + m.assert_called_once_with(VCGENCMD) + self.assertTrue(state.current_undervoltage) + self.assertFalse(state.current_overheat) + self.assertTrue(state.current_issue) + self.assertTrue(state.past_undervoltage) + self.assertTrue(state.past_overheat) + self.assertTrue(state.past_issue) + + def test_get_vcgencmd_throttle_state_unparseable1(self): + from octoprint.plugins.pi_support import get_vcgencmd_throttled_state + + with mock.patch("sarge.get_stdout", mock.MagicMock()) as m: + m.return_value = "invalid" + + try: + get_vcgencmd_throttled_state(VCGENCMD) + except ValueError: + # expected + pass + else: + self.fail("Expected ValueError") + + def test_get_vcgencmd_throttle_state_unparseable2(self): + from octoprint.plugins.pi_support import get_vcgencmd_throttled_state + + with mock.patch("sarge.get_stdout", mock.MagicMock()) as m: + m.return_value = "throttled=0xinvalid" + + try: + get_vcgencmd_throttled_state(VCGENCMD) + except ValueError: + # expected + pass + else: + self.fail("Expected ValueError") + + +@ddt.ddt +class ThrottleStateTestCase(unittest.TestCase): + + @ddt.data( + (0x00000, dict(_undervoltage=False, + _freq_capped=False, + _throttled=False, + _past_undervoltage=False, + _past_freq_capped=False, + _past_throttled=False, + current_undervoltage=False, + past_undervoltage=False, + current_overheat=False, + past_overheat=False, + current_issue=False, + past_issue=False)), + + (0x50005, dict(_undervoltage=True, + _freq_capped=False, + _throttled=True, + _past_undervoltage=True, + _past_freq_capped=False, + _past_throttled=True, + current_undervoltage=True, + past_undervoltage=True, + current_overheat=False, + past_overheat=False, + current_issue=True, + past_issue=True)), + + (0x50000, dict(_undervoltage=False, + _freq_capped=False, + _throttled=False, + _past_undervoltage=True, + _past_freq_capped=False, + _past_throttled=True, + current_undervoltage=False, + past_undervoltage=True, + current_overheat=False, + past_overheat=False, + current_issue=False, + past_issue=True)), + + (0x00006, dict(_undervoltage=False, + _freq_capped=True, + _throttled=True, + _past_undervoltage=False, + _past_freq_capped=False, + _past_throttled=False, + current_undervoltage=False, + past_undervoltage=False, + current_overheat=True, + past_overheat=False, + current_issue=True, + past_issue=False)), + ) + @ddt.unpack + def test_conversion(self, input, expected_flags): + from octoprint.plugins.pi_support import ThrottleState + + output = ThrottleState.from_value(input) + + for key, value in expected_flags.items(): + self.assertEqual(getattr(output, key), value) + + def test_as_dict(self): + from octoprint.plugins.pi_support import ThrottleState + + state = ThrottleState(undervoltage=True, throttled=True, past_undervoltage=True, past_freq_capped=True, past_throttled=True) + + self.assertDictEqual(state.as_dict(), dict(current_undervoltage=True, + past_undervoltage=True, + current_overheat=False, + past_overheat=True, + current_issue=True, + past_issue=True)) diff --git a/tests/plugins/test_octopi_support.py b/tests/plugins/test_octopi_support.py deleted file mode 100644 index ad6140a34..000000000 --- a/tests/plugins/test_octopi_support.py +++ /dev/null @@ -1,89 +0,0 @@ - -import unittest -import ddt -import mock - -OCTOPI_VERSION = "0.14.0" - -CPUINFO = """ -processor : 0 -model name : ARMv7 Processor rev 4 (v7l) -BogoMIPS : 38.40 -Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0xd03 -CPU revision : 4 - -processor : 1 -model name : ARMv7 Processor rev 4 (v7l) -BogoMIPS : 38.40 -Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0xd03 -CPU revision : 4 - -processor : 2 -model name : ARMv7 Processor rev 4 (v7l) -BogoMIPS : 38.40 -Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0xd03 -CPU revision : 4 - -processor : 3 -model name : ARMv7 Processor rev 4 (v7l) -BogoMIPS : 38.40 -Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0xd03 -CPU revision : 4 - -Hardware : BCM2835 -Revision : a02082 -Serial : 000000000abcdef1 -""" - -@ddt.ddt -class OctoPiSupportTestCase(unittest.TestCase): - - def test_get_octopi_version(self): - from octoprint.plugins.octopi_support import get_octopi_version - - with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: - m.return_value.readline.return_value = OCTOPI_VERSION - version = get_octopi_version() - - m.assert_called_once_with("/etc/octopi_version", "r") - self.assertEqual(version, "0.14.0") - - def test_get_pi_cpuinfo(self): - from octoprint.plugins.octopi_support import get_pi_cpuinfo - - with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: - m.return_value.__iter__.return_value = CPUINFO.splitlines() - cpuinfo = get_pi_cpuinfo() - - m.assert_called_once_with("/proc/cpuinfo") - self.assertDictEqual(cpuinfo, dict(hardware="BCM2835", revision="a02082", serial="000000000abcdef1")) - - @ddt.data( - ("BCM2835", "a02082", "3B"), - ("BCM2835", "1000a02082", "3B"), - - # failures - ("something else", "a02082", "unknown"), - ("BCM2835", "aabbccdd", "unknown") - ) - @ddt.unpack - def test_get_pi_model(self, hardware, revision, expected): - from octoprint.plugins.octopi_support import get_pi_model - actual = get_pi_model(hardware, revision) - self.assertEqual(actual, expected) diff --git a/tests/plugins/test_pluginmanager.py b/tests/plugins/test_pluginmanager.py deleted file mode 100644 index 47ed9c040..000000000 --- a/tests/plugins/test_pluginmanager.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -""" -Unit tests for bundled plugin "PluginManager". -""" - -from __future__ import absolute_import - -__author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" - -import unittest -import mock -import ddt - -from octoprint.plugins.pluginmanager import PluginManagerPlugin - -@ddt.ddt -class PluginManagerPluginTests(unittest.TestCase): - - @ddt.data( - ("linux", "linux2", [], True), - ("linux", "linux2", ["linux", "freebsd"], True), - ("windows", "win32", ["linux", "freebsd"], False), - ("linux", "linux2", ["!windows"], True), - ("windows", "win32", ["!windows"], False), - ("unmapped", "os2", [], True), - ("unmapped", "os2", ["linux", "freebsd"], False), - ("unmapped", "os2", ["!os2"], False), - ("unmapped", "sunos5", ["linux", "freebsd", "sunos"], True), - ("unmapped", "sunos5", ["!sunos", "!os2"], False), - - # both black and white listing at the same time usually doesn't - # make a whole lot of sense, but let's test it anyhow - ("linux", "linux2", ["!windows", "linux", "freebsd"], True), - ("linux", "linux2", ["!windows", "freebsd"], False), - ("windows", "win32", ["!windows", "linux", "freebsd"], False), - ("unmapped", "sunos5", ["!windows", "linux", "freebsd"], False) - ) - @ddt.unpack - def test_is_os_compatible(self, current_os, sys_platform, entries, expected): - with mock.patch("sys.platform", sys_platform): - actual = PluginManagerPlugin._is_os_compatible(current_os, entries) - self.assertEqual(actual, expected) diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index 9c8ab966e..a0b17f218 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -18,6 +18,7 @@ import yaml import hashlib import ddt import time +import re import octoprint.settings @@ -115,6 +116,67 @@ class TestSettings(unittest.TestCase): except: self.fail("Could not remove temporary custom basedir") + ##~~ regexes + def test_should_have_regex_filters(self): + # we don't want the mocked_config, because we're testing the actual value. + #with self.mocked_config(): + + filters = octoprint.settings.Settings().get(["terminalFilters"]) + + # we *should* have at least three, but we'll ensure there's at least one as a sanity check. + self.assertGreater(len(filters), 0) + + def test_should_have_suppress_temperature_regex(self): + # we don't want the mocked_config, because we're testing the actual value. + #with self.mocked_config(): + + filters = octoprint.settings.Settings().get(["terminalFilters"]) + temperature_regex_filters = [x for x in filters if x.get('name') == 'Suppress temperature messages'] + self.assertEqual(len(temperature_regex_filters), 1) + + # we know there's a 'name' by now, so just ensure we have the regex key + temperature_regex_filter = temperature_regex_filters[0] + self.assertIn('regex', temperature_regex_filter.keys()) + + def test_temperature_regex_should_not_match(self): + '''random entries that aren't temperature regex entries''' + # we don't want the mocked_config, because we're testing the actual value. + #with self.mocked_config(): + bad_terminal_entries = [ + 'Send: N71667 G1 X163.151 Y35.424 E0.02043*83', + 'Send: N85343 G1 Z29.880 F10800.000*15', + 'Recv: ok', + ] + + filters = octoprint.settings.Settings().get(["terminalFilters"]) + temperature_pattern = [x for x in filters if x.get('name') == 'Suppress temperature messages'][0]['regex'] + + matcher = re.compile(temperature_pattern) + for terminal_string in bad_terminal_entries: + match_result = matcher.match(terminal_string) + # can switch to assertIsNone after 3.x upgrade. + self.assertFalse(match_result, "string matched and it shouldn't have.") + + + def test_temperature_regex_matches(self): + # we don't want the mocked_config, because we're testing the actual value. + #with self.mocked_config(): + + common_terminal_entries = [ + 'Recv: ok N5993 P15 B15 T:59.2 /0.0 B:31.8 /0.0 T0:59.2 /0.0 @:0 B@:100:', # monoprice mini delta + 'Recv: ok T:210.3 /210.0 B:60.3 /60.0 T0:210.3 /210.0 @:79 B@:0 P:35.9 A:40.0', # Prusa mk3 + ] + + filters = octoprint.settings.Settings().get(["terminalFilters"]) + temperature_pattern = [x for x in filters if x.get('name') == 'Suppress temperature messages'][0]['regex'] + + matcher = re.compile(temperature_pattern) + for terminal_string in common_terminal_entries: + match_result = matcher.match(terminal_string) + # can switch to assertIsNotNone after 3.x upgrade. + self.assertTrue(match_result, "string did not match and it should have.") + + ##~~ test getters def test_get(self): diff --git a/tests/timelapse/test_timelapse_helpers.py b/tests/timelapse/test_timelapse_helpers.py index 26f05c307..2ae7099a6 100644 --- a/tests/timelapse/test_timelapse_helpers.py +++ b/tests/timelapse/test_timelapse_helpers.py @@ -6,6 +6,7 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms import unittest import mock +import ddt import os import time @@ -14,9 +15,11 @@ from collections import namedtuple, OrderedDict _stat = namedtuple("StatResult", "st_size, st_ctime, st_mtime") _entry = namedtuple("DirEntry", "name, path, is_file, is_dir, stat") +import octoprint.plugin import octoprint.settings import octoprint.timelapse +@ddt.ddt class TimelapseTest(unittest.TestCase): def setUp(self): @@ -27,10 +30,35 @@ class TimelapseTest(unittest.TestCase): self.settings = mock.create_autospec(octoprint.settings.Settings) self.settings_getter.return_value = self.settings + self.plugin_manager_patcher = mock.patch("octoprint.timelapse.plugin_manager") + self.plugin_manager_getter = self.plugin_manager_patcher.start() + + self.plugin_manager = mock.create_autospec(octoprint.plugin.PluginManager) + self.plugin_manager_getter.return_value = self.plugin_manager + + def extension_factory(*args, **kwargs): + return ["gif"] + hooks = dict(test=extension_factory) + self.plugin_manager.get_hooks.return_value = hooks + self.now = time.time() def cleanUp(self): self.settings_patcher.stop() + self.plugin_manager_patcher.stop() + + @ddt.data( + ("test.mpg", True), + ("test.dat", False), + ("test.gif", True) + ) + @ddt.unpack + def test_valid_timelapse(self, input, expected): + ## test + actual = octoprint.timelapse.valid_timelapse(input) + + ## verify + self.assertEqual(expected, actual) @mock.patch("os.remove") @mock.patch("octoprint.timelapse.scandir") diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py index 119ff406d..dc3adae14 100644 --- a/tests/util/test_comm_helpers.py +++ b/tests/util/test_comm_helpers.py @@ -267,11 +267,11 @@ class TestCommHelpers(unittest.TestCase): ("NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01", dict(NAME="Malyan", VER="3.7", MODEL="M300", HW="HG01")), ("FIRMWARE_NAME:Marlin 1.1.0 From Archive SOURCE_CODE_URL:http:// ... PROTOCOL_VERSION:1.0 MACHINE_TYPE:www.cxsw3d.com EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000", - dict(FIRMWARE_NAME="Marlin 1.1.0 From Archive", - SOURCE_CODE_URL="http:// ...", - PROTOCOL_VERSION="1.0", - MACHINE_TYPE="www.cxsw3d.com", - EXTRUDER_COUNT="1", + dict(FIRMWARE_NAME="Marlin 1.1.0 From Archive", + SOURCE_CODE_URL="http:// ...", + PROTOCOL_VERSION="1.0", + MACHINE_TYPE="www.cxsw3d.com", + EXTRUDER_COUNT="1", UUID="00000000-0000-0000-0000-000000000000")) ) @unpack @@ -333,6 +333,12 @@ class TestCommHelpers(unittest.TestCase): e4=0.0, e5=0.0)), + # whitespace after the :, e.g. AlfaWise U20, see #2839 + ("X:150.0 Y:150.0 Z: 0.7 E: 0.0", dict(x=150.0, + y=150.0, + z=0.7, + e=0.0)), + # invalid ("", None), ("X:62.417 Y:64.781 Z:0.2", None) diff --git a/tests/util/test_counted_event.py b/tests/util/test_counted_event.py index 87c2f7baa..703e9078d 100644 --- a/tests/util/test_counted_event.py +++ b/tests/util/test_counted_event.py @@ -88,6 +88,24 @@ class CountedEventTest(unittest.TestCase): self.assertEqual(0, event._counter) self.assertFalse(event._event.is_set()) + def test_clear_more_than_available_without_minimum(self): + """The counter may sink below zero if initialized without a minimum.""" + + event = CountedEvent(1, minimum=None) + + self.assertEqual(1, event._counter) + self.assertTrue(event._event.is_set()) + + event.clear() + + self.assertEqual(0, event._counter) + self.assertFalse(event._event.is_set()) + + event.clear() + + self.assertEqual(-1, event._counter) + self.assertFalse(event._event.is_set()) + def test_blocked(self): """Blocked should only be true if the counter is 0.""" diff --git a/tests/util/test_net.py b/tests/util/test_net.py new file mode 100644 index 000000000..a1a33cec0 --- /dev/null +++ b/tests/util/test_net.py @@ -0,0 +1,54 @@ +# coding=utf-8 +from __future__ import absolute_import + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import unittest +import ddt +import mock + +import socket + +import octoprint.util.net + + +def patched_interfaces(): + return ["eth0"] + + +def patched_ifaddresses(addr): + if addr == "eth0": + return { + socket.AF_INET: [dict(addr="192.168.123.10", netmask="255.255.255.0"), + dict(addr="12.1.1.10", netmask="255.0.0.0")], + socket.AF_INET6: [dict(addr="2a01:4f8:1c0c:6958::1", netmask="ffff:ffff:ffff:ffff::/64")] + } + + return dict() + + +@ddt.ddt +class UtilNetTest(unittest.TestCase): + + @ddt.data( + ("127.0.0.1", [], True), + ("192.168.123.234", [], True), + ("172.24.0.1", [], True), + ("10.1.2.3", [], True), + ("fc00::1", [], True), + ("::1", [], True), + ("::ffff:192.168.1.1", [], True), + ("::ffff:8.8.8.8", [], False), + ("11.1.2.3", [], False), + ("11.1.2.3", ["11/8"], True), + ("12.1.1.123", [], True), + ("2a01:4f8:1c0c:6958::1:23", [], True) + ) + @ddt.unpack + @mock.patch("netifaces.interfaces", side_effect=patched_interfaces) + @mock.patch("netifaces.ifaddresses", side_effect=patched_ifaddresses) + @mock.patch.object(octoprint.util.net, "HAS_V6", True) + def test_is_lan_address(self, input_address, input_additional, expected, nifa, nifs): + actual = octoprint.util.net.is_lan_address(input_address, additional_private=input_additional) + self.assertEqual(expected, actual) diff --git a/tests/util/test_platform.py b/tests/util/test_platform.py index 49f27d0a5..2fd03e097 100644 --- a/tests/util/test_platform.py +++ b/tests/util/test_platform.py @@ -28,3 +28,29 @@ class PlatformUtilTest(unittest.TestCase): from octoprint.util.platform import get_os actual = get_os() self.assertEqual(actual, expected) + + @ddt.data( + ("linux", "linux2", [], True), + ("linux", "linux2", ["linux", "freebsd"], True), + ("windows", "win32", ["linux", "freebsd"], False), + ("linux", "linux2", ["!windows"], True), + ("windows", "win32", ["!windows"], False), + ("unmapped", "os2", [], True), + ("unmapped", "os2", ["linux", "freebsd"], False), + ("unmapped", "os2", ["!os2"], False), + ("unmapped", "sunos5", ["linux", "freebsd", "sunos"], True), + ("unmapped", "sunos5", ["!sunos", "!os2"], False), + + # both black and white listing at the same time usually doesn't + # make a whole lot of sense, but let's test it anyhow + ("linux", "linux2", ["!windows", "linux", "freebsd"], True), + ("linux", "linux2", ["!windows", "freebsd"], False), + ("windows", "win32", ["!windows", "linux", "freebsd"], False), + ("unmapped", "sunos5", ["!windows", "linux", "freebsd"], False) + ) + @ddt.unpack + def test_is_os_compatible(self, current_os, sys_platform, entries, expected): + with mock.patch("sys.platform", sys_platform): + from octoprint.util.platform import is_os_compatible + actual = is_os_compatible(entries, current_os=current_os) + self.assertEqual(actual, expected)