diff --git a/docs/api/general.rst b/docs/api/general.rst index 624bc935c..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. 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/forcelogin.rst b/docs/bundledplugins/forcelogin.rst index bb69c35c9..e5214f79f 100644 --- a/docs/bundledplugins/forcelogin.rst +++ b/docs/bundledplugins/forcelogin.rst @@ -1,9 +1,9 @@ .. _sec-bundledplugins-forcelogin: -Forcelogin Plugin +ForceLogin Plugin ================= -The Forcelogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous +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. @@ -24,12 +24,12 @@ instead forces users to log in if they want to get any kind of information from .. 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. + the ForceLogin Plugin in OctoPrint's plugin manager. .. _sec-bundledplugins-forcelogin-sourcecode: Source code ----------- -The source of the Backup plugin is bundled with OctoPrint and can be found in +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 a1683a800..8bf1d5d35 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -9,6 +9,7 @@ Bundled Plugins action_command_prompt.rst announcements.rst + appkeys.rst backup.rst cura.rst discovery.rst diff --git a/docs/images/bundledplugins-appkeys-confirmation_prompt.png b/docs/images/bundledplugins-appkeys-confirmation_prompt.png new file mode 100644 index 000000000..a1bbadec5 Binary files /dev/null and b/docs/images/bundledplugins-appkeys-confirmation_prompt.png differ diff --git a/docs/images/bundledplugins-appkeys-settings.png b/docs/images/bundledplugins-appkeys-settings.png new file mode 100644 index 000000000..61b185dac Binary files /dev/null and b/docs/images/bundledplugins-appkeys-settings.png differ diff --git a/docs/images/bundledplugins-appkeys-user_settings.png b/docs/images/bundledplugins-appkeys-user_settings.png new file mode 100644 index 000000000..96fd18ebc Binary files /dev/null and b/docs/images/bundledplugins-appkeys-user_settings.png differ diff --git a/docs/jsclientlib/index.rst b/docs/jsclientlib/index.rst index cf4f20376..43b734769 100644 --- a/docs/jsclientlib/index.rst +++ b/docs/jsclientlib/index.rst @@ -80,9 +80,13 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s .. seealso:: - `OctoPrint-ForceLogin `_ - A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the - client library's :ref:`browser component ` 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/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index b34a78dfa..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'] ) 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/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 index ad117cb0b..cf75a073a 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -69,6 +69,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, def get_assets(self): return dict(js=["js/backup.js"], + clientjs=["clientjs/backup.js"], css=["css/backup.css"], less=["less/backup.less"]) 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/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 61eedb240..dadd24c8c 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -1,56 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintBackupClient = function(base) { - this.base = base; - this.url = this.base.getBlueprintUrl("backup"); - }; - - OctoPrintBackupClient.prototype.get = function(refresh, opts) { - return this.base.get(this.url, opts); - }; - - OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) { - exclude = exclude || []; - - var data = { - exclude: exclude - }; - - return this.base.postJson(this.url + "backup", data, opts); - }; - - OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) { - return this.base.delete(this.url + "backup/" + backup, opts); - }; - - OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) { - var data = { - path: backup - }; - - return this.base.postJson(this.url + "restore", data, opts); - }; - - OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) { - data = data || {}; - - var filename = data.filename || undefined; - return this.base.upload(this.url + "restore", file, filename, data); - }; - - OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) { - return this.base.delete(this.url + "unknown_plugins", opts); - }; - - OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient); - return OctoPrintBackupClient; -}); - $(function() { function BackupViewModel(parameters) { var self = this; 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/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index e0bd9ac10..28b4f3d03 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -193,6 +193,7 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, def get_assets(self): return dict( js=["js/pi_support.js"], + clientjs=["clientjs/pi_support.js"], css=["css/pi_support.css"] ) 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/js/pi_support.js b/src/octoprint/plugins/pi_support/static/js/pi_support.js index ced2a55e4..2516a4f77 100644 --- a/src/octoprint/plugins/pi_support/static/js/pi_support.js +++ b/src/octoprint/plugins/pi_support/static/js/pi_support.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 OctoPrintPiSupportClient = function(base) { - this.base = base; - }; - - OctoPrintPiSupportClient.prototype.get = function(opts) { - return this.base.get(this.base.getSimpleApiUrl("pi_support")); - }; - - OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient); - return OctoPrintPiSupportClient; -}); - $(function() { function PiSupportViewModel(parameters) { diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index df4def7e6..c085c032e 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -168,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"] ) 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 c6a08208e..fd17d0897 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -601,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"] ) 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 b9aee68cc..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; diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 71e676e4d..c751b59dd 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1348,25 +1348,6 @@ class Server(object): "js/lib/loglevel.min.js", "js/lib/sockjs.js" ] - js_client = [ - "js/app/client/base.js", - "js/app/client/socket.js", - "js/app/client/browser.js", - "js/app/client/connection.js", - "js/app/client/control.js", - "js/app/client/files.js", - "js/app/client/job.js", - "js/app/client/languages.js", - "js/app/client/printer.js", - "js/app/client/printerprofiles.js", - "js/app/client/settings.js", - "js/app/client/slicing.js", - "js/app/client/system.js", - "js/app/client/timelapse.js", - "js/app/client/users.js", - "js/app/client/util.js", - "js/app/client/wizard.js" - ] css_libs = [ "css/bootstrap.min.css", @@ -1419,13 +1400,15 @@ class Server(object): js_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["js"], filters="js_delimiter_bundler") + clientjs_core = dynamic_core_assets["clientjs"] + \ + all_assets_for_plugins(dynamic_plugin_assets["bundled"]["clientjs"]) + clientjs_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["clientjs"], + filters="js_delimiter_bundler") + js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters)) - js_client_bundle = Bundle(*js_client, - output="webassets/packed_client.js", - filters=",".join(js_filters)) js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters=",".join(js_filters)) @@ -1441,6 +1424,21 @@ class Server(object): output="webassets/packed_app.js", filters=",".join(js_filters)) + js_client_core_bundle = Bundle(*clientjs_core, + output="webassets/packed_client_core.js", + filters=",".join(js_filters)) + + if len(clientjs_plugins) == 0: + js_client_plugins_bundle = Bundle(*[]) + else: + js_client_plugins_bundle = Bundle(*clientjs_plugins.values(), + output="webassets/packed_client_plugins.js", + filters=",".join(js_plugin_filters)) + + js_client_bundle = Bundle(js_client_core_bundle, js_client_plugins_bundle, + output="webassets/packed_client.js", + filters=",".join(js_filters)) + # -- CSS ------------------------------------------------------------------------------------------------------- css_filters = ["cssrewrite"] @@ -1500,6 +1498,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/util/flask.py b/src/octoprint/server/util/flask.py index b3d8b82c4..fc3b148f0 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1345,6 +1345,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater): def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): assets = dict( js=[], + clientjs=[], css=[], less=[] ) @@ -1386,6 +1387,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": @@ -1400,9 +1421,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))) @@ -1432,6 +1455,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/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/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; }