Merge branch 'maintenance' into devel

This commit is contained in:
Gina Häußge committed 2017-02-17 13:49:56 +01:00
commit 4f6f829dc3
70 files changed
+1876 -1395

No files matched your search

+3
View File
@@ -67,10 +67,13 @@ All GCODE scripts have access to the following template variables through the te
There are a couple of additional template variables available for the following specific scripts:
* ``afterPrintPaused`` and ``beforePrintResumed``
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
``t`` taken from commands sent through OctoPrint.
* ``afterPrintCancelled``
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
current tool ``t`` taken from commands sent through OctoPrint.
+99 -41
View File
@@ -1,29 +1,45 @@
.. sec-jsclientlib-base:
.. _sec-jsclientlib-base:
:mod:`OctoPrint`
----------------
:mod:`OctoPrintClient`
----------------------
.. js:data:: OctoPrint.options
.. js:class:: OctoPrintClient([options])
The client library's options.
Instantiates a new instance of the client library. Note that by default there's always an instance registered
globally called ``OctoPrint``.
``OctoPrint.options.apikey``
:param object options: An optional object of options to set :js:attr:`OctoPrintClient.options` to.
.. js:attribute:: OctoPrintClient.options
The client library instance's options. The following keys are currently supported:
``apikey``
The API Key to use for requests against the OctoPrint API. Should usually be
the anonymous UI API Key provided on the socket.
``OctoPrint.options.baseurl``
``baseurl``
The base URL of the OctoPrint API
``OctoPrint.options.locale``
``locale``
The locale to set in ``X-Locale`` headers on API requests. Useful for API
endpoints that might return localized content.
.. js:data:: OctoPrint.plugins
.. js:attribute:: OctoPrintClient.plugins
Registration of client library components provided by plugins.
OctoPrint plugins should always register their library exports
in this object, using their plugin identifier as key.
OctoPrint plugins should always register their client classes here using their plugin identifier as key via
:js:func:`OctoPrintClient.registerPluginComponent`.
.. note::
The registration mechanism has changed slightly with OctoPrint 1.3.2 due to an otherwise unsolvable issue with
allowing multiple clients to exist concurrently and still keeping the existing architecture intact.
The old mechanism works fine as long as you are only planning to offer your plugin client implementation on the
default client instance ``OctoPrint``, however if you also want to support additional clients you'll need to
use the implementation and registration approach as described below.
**Example:**
@@ -31,19 +47,26 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(window.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
var exports = {};
})(window || this, function(OctoPrintClient) {
var MyPluginClient = function(base) {
this.base = base;
};
// fill exports
MyPluginClient.prototype.someFunction = function() {
// do something
};
OctoPrint.plugins.myplugin = exports
// further define API
OctoPrintClient.registerPluginComponent("myplugin", MyPluginClient);
return MyPluginClient;
});
.. js:function:: OctoPrint.getBaseUrl()
.. js:function:: OctoPrintClient.getBaseUrl()
Returns the canonical base URL to use for OctoPrint's API. Uses the current value of
:js:data:`OctoPrint.options.baseurl <OctoPrint.options>`. If that doesn't end in a ``/``,
@@ -51,7 +74,7 @@
:returns string: The base url to use to access OctoPrint's API.
.. js:function:: OctoPrint.getRequestHeaders(additional)
.. js:function:: OctoPrintClient.getRequestHeaders(additional)
Generates a dictionary of HTTP headers to use for API requests against OctoPrint with all
necessary headers and any additionally provided ones.
@@ -62,7 +85,7 @@
:param object additional: Additional headers to add to the request.
:returns object: HTTP headers to use for requests.
.. js:function:: OctoPrint.ajax(method, url, opts)
.. js:function:: OctoPrintClient.ajax(method, url, opts)
Performs an AJAX request against the OctoPrint API, utilizing `jQuery's own ajax function <http://api.jquery.com/jquery.ajax/>`_.
@@ -87,7 +110,7 @@
:param object opts: Additional options to use for the request, see above for details (optional)
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.ajaxWithData(method, url, data, opts)
.. js:function:: OctoPrintClient.ajaxWithData(method, url, data, opts)
Performs an AJAX request against the OctoPrint API, including the provided ``data`` in the body of the request.
@@ -99,7 +122,7 @@
:param object opts: Additonal options to use for the request (optional)
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.get(url, opts)
.. js:function:: OctoPrintClient.get(url, opts)
Performs a ``GET`` request against ``url``.
@@ -116,7 +139,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.getWithQuery(url, data, opts)
.. js:function:: OctoPrintClient.getWithQuery(url, data, opts)
Performs a ``GET`` request against ``url`` using the provided ``data`` as URL query.
@@ -132,7 +155,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.post(url, data, opts)
.. js:function:: OctoPrintClient.post(url, data, opts)
Performs a ``POST`` request against ``url`` using the provided ``data`` as request body.
@@ -152,7 +175,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.postJson(url, data, opts)
.. js:function:: OctoPrintClient.postJson(url, data, opts)
Performs a ``POST`` request against ``url`` using the provided ``data`` object as request body
after serializing it to JSON.
@@ -172,33 +195,33 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.put(url, data, opts)
.. js:function:: OctoPrintClient.put(url, data, opts)
Performs ``PUT`` request against ``url`` using the provided ``data`` as request body.
See :js:func:`OctoPrint.post` for details.
.. js:function:: OctoPrint.putJson(url, data, opts)
.. js:function:: OctoPrintClient.putJson(url, data, opts)
Performs ``PUT`` request against ``url`` using the provided ``data`` as request body after
serializing it to JSON.
See :js:func:`OctoPrint.postJson` for details.
.. js:function:: OctoPrint.patch(url, data, opts)
.. js:function:: OctoPrintClient.patch(url, data, opts)
Performs ``PATCH`` request against ``url`` using the provided ``data`` as request body.
See :js:func:`OctoPrint.post` for details.
.. js:function:: OctoPrint.patchJson(url, data, opts)
.. js:function:: OctoPrintClient.patchJson(url, data, opts)
Performs ``PATCH`` request against ``url`` using the provided ``data`` as request body after
serializing it to JSON.
See :js:func:`OctoPrint.postJson` for details.
.. js:function:: OctoPrint.delete(url, opts)
.. js:function:: OctoPrintClient.delete(url, opts)
Performs a ``DELETE`` request against ``url``.
@@ -206,7 +229,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.download(url, opts)
.. js:function:: OctoPrintClient.download(url, opts)
Downloads a file from ``url``, returning the response body as data type ``text``.
@@ -218,7 +241,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.upload(url, file, filename, additional)
.. js:function:: OctoPrintClient.upload(url, file, filename, additional)
Uploads a ``file`` to ``url`` using a ``multipart/form-data`` ``POST`` request.
@@ -286,7 +309,7 @@
:param string filename: An optional file name to use for the upload
:param object additional: An optional object of additional key/value pairs to set on the uploaded form data
.. js:function:: OctoPrint.issueCommand(url, command, payload, opts)
.. js:function:: OctoPrintClient.issueCommand(url, command, payload, opts)
Issues a command against an OctoPrint command API endpoint.
@@ -318,7 +341,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.getSimpleApiUrl(plugin)
.. js:function:: OctoPrintClient.getSimpleApiUrl(plugin)
Returns the proper URL for the endpoint of a :class:`~octoprint.plugin.SimpleApiPlugin`, based on the
plugin identifier.
@@ -333,7 +356,7 @@
:param string plugin: The identifier of the plugin for which to return the URL
:returns string: The URL to use as endpoint
.. js:function:: OctoPrint.simpleApiGet(plugin, opts)
.. js:function:: OctoPrintClient.simpleApiGet(plugin, opts)
Performs a ``GET`` request against the endpoint of a :class:`~octoprint.plugin.SimpleApiPlugin` with
identifier ``plugin``.
@@ -349,7 +372,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.simpleApiCommand(plugin, command, payload, opts)
.. js:function:: OctoPrintClient.simpleApiCommand(plugin, command, payload, opts)
Performs the API command ``command`` against the endpoint of a :class:`~octoprint.plugin.SimpleApiPlugin` with
identifier ``plugin``, including the optional ``payload``.
@@ -370,7 +393,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.getBlueprintUrl(plugin)
.. js:function:: OctoPrintClient.getBlueprintUrl(plugin)
Returns the proper base URL for blueprint endpoints of a :class:`~octoprint.plugin.BlueprintPlugin` with
identifier ``plugin``.
@@ -382,11 +405,15 @@
// prints "plugin/myplugin/"
console.log(OctoPrint.getBlueprintUrl("myplugin"));
.. js:function:: OctoPrint.createRejectedDeferred()
.. js:function:: OctoPrintClient.createRejectedDeferred()
Static method.
Shortcut for creating a rejected `jQuery Deferred <http://api.jquery.com/category/deferred-object/>`_.
.. js:function:: OctoPrint.createCustomException(name)
.. js:function:: OctoPrintClient.createCustomException(name)
Static method.
Creates a custom exception class. ``name`` may be either a function in which case it will be used
as constructor for the new exception class, or a string, in which case a constructor with proper
@@ -397,9 +424,40 @@
.. code-block:: javascript
MyCustomException = OctoPrint.createCustomException("MyCustomException");
MyCustomException = OctoPrintClient.createCustomException("MyCustomException");
throw new MyCustomException("Something went horribly wrong!");
.. js:class:: OctoPrint.InvalidArgumentError
.. js:function:: OctoPrintClient.registerPluginComponent(identifier, clientClass)
Static method.
Registers the plugin client component ``clientClass`` under the name ``identifier`` on the
:js:attr:`OctoPrintClient.plugins` registry.
``clientClass`` must have a constructor that follows the signature ``ClientClass(base)`` and in which it sets
the attribute ``base`` on the instance to:
.. code-block:: javascript
var MyPluginClient = function(base) {
this.base = base;
}
Each :js:class:`OctoPrintClient` will create its own instance of registered plugin classes and make them available
under :js:attr:`OctoPrintClient.plugins`. It will inject itself into those instances in order to allow plugin
clients to access its functionality via ``this.base``:
.. code-block:: javascript
MyPluginClient.prototype.doSomething = function(data, opts) {
return this.base.simpleApiCommand("myplugin", "doSomething", data, opts);
};
:param string identifier: The identifier of the plugin for which ``clientClass`` is the client
:param class clientClass: The client class to register. Constructor must follow the signature ``ClientClass(base)``
where ``base`` will be assigned to the instance as ``this.base`` and be the :js:class:`OctoPrintClient`
instance to use for API calls etc via ``this.base``.
.. js:class:: OctoPrintClient.InvalidArgumentError
Exception to use when functions are called with invalid arguments.
+6 -6
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-browser:
.. _sec-jsclientlib-browser:
:mod:`OctoPrint.browser`
------------------------
:mod:`OctoPrintClient.browser`
------------------------------
.. js:function:: OctoPrint.browser.login(username, password, remember, opts)
.. js:function:: OctoPrintClient.browser.login(username, password, remember, opts)
Logs the browser into OctoPrint, using the provided ``username`` and
``password`` as credentials. If ``remember`` is set to ``true``, the session
@@ -24,7 +24,7 @@
:param object opts: Additional request options
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.browser.passiveLogin(opts)
.. js:function:: OctoPrintClient.browser.passiveLogin(opts)
Tries to perform a passive login into OctoPrint, using existing session data
stored in the browser's cookies.
@@ -32,7 +32,7 @@
:param object opts: Additional request options
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.browser.logout(opts)
.. js:function:: OctoPrintClient.browser.logout(opts)
Logs the browser out of OctoPrint.
+7 -7
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-connection:
.. _sec-jsclientlib-connection:
:mod:`OctoPrint.connection`
---------------------------
:mod:`OctoPrintClient.connection`
---------------------------------
.. js:function:: OctoPrint.connection.getSettings(opts)
.. js:function:: OctoPrintClient.connection.getSettings(opts)
Retrieves the available connection options for connection to a printer.
@@ -12,7 +12,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.connection.connect(data, opts)
.. js:function:: OctoPrintClient.connection.connect(data, opts)
Connects to the printer, optionally using the provided connection ``data`` as parameters.
@@ -30,7 +30,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.connection.disconnect(opts)
.. js:function:: OctoPrintClient.connection.disconnect(opts)
Disconnects from the printer.
@@ -39,7 +39,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.connection.fakeAck(opts)
.. js:function:: OctoPrintClient.connection.fakeAck(opts)
Triggers a fake acknowledgement (``ok``) on the printer.
+8 -8
View File
@@ -1,16 +1,16 @@
.. sec-jsclientlib-control:
.. _sec-jsclientlib-control:
:mod:`OctoPrint.control`
------------------------
:mod:`OctoPrintClient.control`
------------------------------
.. js:function:: OctoPrint.control.getCustomControls(opts)
.. js:function:: OctoPrintClient.control.getCustomControls(opts)
Retrieves the defined custom controls from the server.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.control.sendGcode(commands, opts)
.. js:function:: OctoPrintClient.control.sendGcode(commands, opts)
Sends the provided ``commands`` to the printer.
@@ -21,7 +21,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.control.sendGcodeWithParameters(commands, parameters, opts)
.. js:function:: OctoPrintClient.control.sendGcodeWithParameters(commands, parameters, opts)
Sends the provided ``commands`` to the printer, replacing contained placeholders with
the provided ``parameters`` first.
@@ -34,7 +34,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.control.sendGcodeScript(script, context, opts)
.. js:function:: OctoPrintClient.control.sendGcodeScript(script, context, opts)
Sends the provided ``script`` to the printer, enhancing the template with the
specified ``context``.
@@ -44,7 +44,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.control.sendGcodeScriptWithParameters(script, context, parameters, opts)
.. js:function:: OctoPrintClient.control.sendGcodeScriptWithParameters(script, context, parameters, opts)
Sends the provided ``script`` to the printer, enhancing the template with the
specified ``context`` and ``parameters``.
+16 -16
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-files:
.. _sec-jsclientlib-files:
:mod:`OctoPrint.files`
----------------------
:mod:`OctoPrintClient.files`
----------------------------
.. js:function:: OctoPrint.files.get(location, filename, opts)
.. js:function:: OctoPrintClient.files.get(location, filename, opts)
Retrieves information about the file ``filename`` at ``location``.
@@ -14,7 +14,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.list(recursively, opts)
.. js:function:: OctoPrintClient.files.list(recursively, opts)
Retrieves a list of all files from the server.
@@ -56,7 +56,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.listForLocation(location, recursively, opts)
.. js:function:: OctoPrintClient.files.listForLocation(location, recursively, opts)
Retrieves a list of all files stored at the specified ``location`` from the server.
@@ -73,7 +73,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.select(location, path, print, opts)
.. js:function:: OctoPrintClient.files.select(location, path, print, opts)
Selects a file at ``location`` named ``filename`` for printing. If ``print`` is supplied and
truthy, also starts printing the file immediately.
@@ -86,7 +86,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.slice(location, path, parameters, opts)
.. js:function:: OctoPrintClient.files.slice(location, path, parameters, opts)
Slices a file at ``location`` called ``filename``, using the supplied slice command ``parameters``.
@@ -98,7 +98,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.delete(location, path, opts)
.. js:function:: OctoPrintClient.files.delete(location, path, opts)
Deletes the file or folder at ``location`` and ``path``.
@@ -109,7 +109,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.copy(location, path, destination, opts)
.. js:function:: OctoPrintClient.files.copy(location, path, destination, opts)
Copies file or folder ``path`` on ``location`` to new parent folder ``destination`` on ``location``.
@@ -129,7 +129,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.move(location, filename, destination, opts)
.. js:function:: OctoPrintClient.files.move(location, filename, destination, opts)
Moves file or folder ``path`` on ``location`` to new parent folder ``destination`` on ``location``.
@@ -149,7 +149,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.createFolder(location, name, path, opts)
.. js:function:: OctoPrintClient.files.createFolder(location, name, path, opts)
Creates a new folder ``name`` on ``location``. If ``path`` is provided and not empty the folder
will be created as a new child of it.
@@ -173,7 +173,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.upload(location, file, data)
.. js:function:: OctoPrintClient.files.upload(location, file, data)
Uploads a ``file`` to the specified ``location``.
@@ -200,7 +200,7 @@
:param object or string file: The file to upload, see :js:func:`OctoPrint.upload` for more details
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.download(location, path, opts)
.. js:function:: OctoPrintClient.files.download(location, path, opts)
Downloads the file at ``path`` in ``location``.
@@ -222,7 +222,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.pathForEntry(entry)
.. js:function:: OctoPrintClient.files.pathForEntry(entry)
Utility function to retrieve the path within its location for a given ``entry``.
@@ -242,7 +242,7 @@
:param object entry: The entry object for which to retrieve the path
:returns string: The path of the entry within its location
.. js:function:: OctoPrint.files.entryForPath(path, root)
.. js:function:: OctoPrintClient.files.entryForPath(path, root)
Utility function to retrieve an entry by its ``path`` based on an entry tree provided by its
``root``.
+35
View File
@@ -43,6 +43,41 @@ because the library depends on those to be available (as ``$`` and ``_``). You c
Note that all components depend on the ``base`` component to be present, so if you are only including a select
number of components, make sure to at the very least include that one to be able to utilize the client.
When you import the client library as described above, a global variable ``OctoPrint`` will become available, which is
a prepared instance of the ``OctoPrintClient`` class the library assembles from registered components. You can directly
used that singular ``OctoPrint`` instance if you only need to talk to one OctoPrint server:
.. code-block:: javascript
OctoPrint.options.baseurl = "http://example.com/octoprint/"
OctoPrint.options.apikey = "apikey";
OctoPrint.files.list()
.done(function(response) {
// do something with the response
});
If you want to access multiple servers, you should however instead instantiate your own clients. You can provide the
connection options (``baseurl`` and ``apikey``) directly in the constructor or set them later:
.. code-block:: javascript
var client1 = new OctoPrintClient({baseurl: "http://example.com/octoprint1/", apikey: "apikey1"});
var client2 = new OctoPrintClient();
client2.options.baseurl = "http://example.com/octoprint2/";
client2.options.apikey = "apikey2";
client1.files.list()
.done(function(response) {
// do something with the response for server 1
});
client2.files.list()
.done(function(response) {
// do something with the response for server 2
});
.. seealso::
`OctoPrint-ForceLogin <https://github.com/OctoPrint/OctoPrint-ForceLogin>`_
+10 -10
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-job:
.. _sec-jsclientlib-job:
:mod:`OctoPrint.job`
--------------------
:mod:`OctoPrintClient.job`
--------------------------
.. js:function:: OctoPrint.job.get(opts)
.. js:function:: OctoPrintClient.job.get(opts)
Retrieves information about the current job.
@@ -12,7 +12,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.start(opts)
.. js:function:: OctoPrintClient.job.start(opts)
Starts the current job.
@@ -21,7 +21,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.cancel(opts)
.. js:function:: OctoPrintClient.job.cancel(opts)
Cancels the current job.
@@ -30,7 +30,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.restart(opts)
.. js:function:: OctoPrintClient.job.restart(opts)
Restarts the current job. This is equivalent to cancelling and immediately restarting
the job.
@@ -53,7 +53,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.pause(opts)
.. js:function:: OctoPrintClient.job.pause(opts)
Pauses the current job if it's running, does nothing if it's already paused.
@@ -62,7 +62,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.resume(opts)
.. js:function:: OctoPrintClient.job.resume(opts)
Resumes the current job if it's currently pause, does nothing if it's running.
@@ -71,7 +71,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.togglePause(opts)
.. js:function:: OctoPrintClient.job.togglePause(opts)
Resumes a paused and pauses a running job.
+6 -6
View File
@@ -1,28 +1,28 @@
.. sec-jsclientlib-languages:
.. _sec-jsclientlib-languages:
:mod:`OctoPrint.languages`
--------------------------
:mod:`OctoPrintClient.languages`
--------------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.languages.list(opts)
.. js:function:: OctoPrintClient.languages.list(opts)
Retrieves a list of available language packs.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.languages.upload(file)
.. js:function:: OctoPrintClient.languages.upload(file)
Uploads a language pack.
:param object or string file: The file to upload, see :js:func:`OctoPrint.upload` for more details
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.languages.delete(locale, pack, opts)
.. js:function:: OctoPrintClient.languages.delete(locale, pack, opts)
Deletes the language pack ``pack`` for the specified locale ``locale``.
+6 -6
View File
@@ -1,14 +1,14 @@
.. sec-jsclientlib-logs:
.. _sec-jsclientlib-logs:
:mod:`OctoPrint.logs`
---------------------
:mod:`OctoPrintClient.logs`
---------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.logs.list(opts)
.. js:function:: OctoPrintClient.logs.list(opts)
Retrieves a list of log files.
@@ -17,7 +17,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.logs.delete(path, opts)
.. js:function:: OctoPrintClient.logs.delete(path, opts)
Deletes the specified log ``path``.
@@ -27,7 +27,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.logs.download(path, opts)
.. js:function:: OctoPrintClient.logs.download(path, opts)
Downloads the specified log ``file``.
+20 -20
View File
@@ -1,7 +1,7 @@
.. sec-jsclientlib-printer:
.. _sec-jsclientlib-printer:
:mod:`OctoPrint.printer`
------------------------
:mod:`OctoPrintClient.printer`
------------------------------
.. note::
@@ -15,7 +15,7 @@
.. contents::
:local:
.. js:function:: OctoPrint.printer.getFullState(flags, opts)
.. js:function:: OctoPrintClient.printer.getFullState(flags, opts)
Retrieves the full printer state, including temperature information, sd state and general
printer state.
@@ -34,7 +34,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.getToolState(flags, opts)
.. js:function:: OctoPrintClient.printer.getToolState(flags, opts)
Retrieves the current printer extruder state/temperature information, and optionally also the temperature
history.
@@ -52,7 +52,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setToolTargetTemperatures(targets, opts)
.. js:function:: OctoPrintClient.printer.setToolTargetTemperatures(targets, opts)
Sets the given temperatures on the printer's extruders.
@@ -72,7 +72,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setToolTemperatureOffsets(offsets, opts)
.. js:function:: OctoPrintClient.printer.setToolTemperatureOffsets(offsets, opts)
Sets the given temperature offsets for the printer's extruders.
@@ -93,7 +93,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.selectTool(tool, opts)
.. js:function:: OctoPrintClient.printer.selectTool(tool, opts)
Selects the printer's current extruder.
@@ -119,7 +119,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.extrude(amount, opts)
.. js:function:: OctoPrintClient.printer.extrude(amount, opts)
Extrudes or retracts ``amount`` mm of filament on the currently selected extruder.
@@ -140,7 +140,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setFlowrate(factor, opts)
.. js:function:: OctoPrintClient.printer.setFlowrate(factor, opts)
Sets the current flowrate multiplier.
@@ -152,7 +152,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.getBedState(data, opts)
.. js:function:: OctoPrintClient.printer.getBedState(data, opts)
Retrieves the current printer bed state/temperature information, and optionally also the temperature
history.
@@ -170,7 +170,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setBedTargetTemperature(target, opts)
.. js:function:: OctoPrintClient.printer.setBedTargetTemperature(target, opts)
Sets the given temperature on the printer's heated bed (if available).
@@ -190,7 +190,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setBedTemperatureOffset(offset, opts)
.. js:function:: OctoPrintClient.printer.setBedTemperatureOffset(offset, opts)
Sets the given temperature offset for the printer's heated bed (if available).
@@ -210,7 +210,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.jog(amounts, opts)
.. js:function:: OctoPrintClient.printer.jog(amounts, opts)
Jogs the specified axes by the specified ``amounts``.
@@ -237,7 +237,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.home(axes, opts)
.. js:function:: OctoPrintClient.printer.home(axes, opts)
Homes the specified ``axes``.
@@ -263,7 +263,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setFeedrate(factor, opts)
.. js:function:: OctoPrintClient.printer.setFeedrate(factor, opts)
Sets the feedrate multiplier to use.
@@ -275,7 +275,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.getSdState(opts)
.. js:function:: OctoPrintClient.printer.getSdState(opts)
Retrieves the current ready state of the printer's SD card.
@@ -284,7 +284,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.initSd(opts)
.. js:function:: OctoPrintClient.printer.initSd(opts)
Instructs the printer to initialize its SD card (if present).
@@ -293,7 +293,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.refreshSd(opts)
.. js:function:: OctoPrintClient.printer.refreshSd(opts)
Instructs the printer to refresh the list of files on the SD card (if present).
@@ -302,7 +302,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.releaseSd(opts)
.. js:function:: OctoPrintClient.printer.releaseSd(opts)
Instructs the printer to release its SD card (if present).
+8 -8
View File
@@ -1,22 +1,22 @@
.. sec-jsclientlib-printerprofiles:
.. _sec-jsclientlib-printerprofiles:
:mod:`OctoPrint.printerprofiles`
--------------------------------
:mod:`OctoPrintClient.printerprofiles`
--------------------------------------
.. js:function:: OctoPrint.printerprofiles.list(opts)
.. js:function:: OctoPrintClient.printerprofiles.list(opts)
Retrieves a list of all configured printer profiles.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printerprofiles.get(id, opts)
.. js:function:: OctoPrintClient.printerprofiles.get(id, opts)
:param string id: The identifier of the profile to retrieve
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printerprofiles.add(profile, additional, opts)
.. js:function:: OctoPrintClient.printerprofiles.add(profile, additional, opts)
Adds a new profile to OctoPrint.
@@ -25,7 +25,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printerprofiles.update(id, profile, opts)
.. js:function:: OctoPrintClient.printerprofiles.update(id, profile, opts)
Updates an existing profile in OctoPrint.
@@ -34,7 +34,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printerprofiles.delete(id, opts)
.. js:function:: OctoPrintClient.printerprofiles.delete(id, opts)
Deletes a profile in OctoPrint.
+7 -7
View File
@@ -1,16 +1,16 @@
.. sec-jsclientlib-settings:
.. _sec-jsclientlib-settings:
:mod:`OctoPrint.settings`
-------------------------
:mod:`OctoPrintClient.settings`
-------------------------------
.. js:function:: OctoPrint.settings.get(opts)
.. js:function:: OctoPrintClient.settings.get(opts)
Retrieves the current settings.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.settings.save(settings, opts)
.. js:function:: OctoPrintClient.settings.save(settings, opts)
Saves the provided ``settings``.
@@ -18,7 +18,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.settings.getPluginSettings(plugin, opts)
.. js:function:: OctoPrintClient.settings.getPluginSettings(plugin, opts)
Retrieves the settings of the specified ``plugin``.
@@ -26,7 +26,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.settings.savePluginSettings(plugin, settings, opts)
.. js:function:: OctoPrintClient.settings.savePluginSettings(plugin, settings, opts)
Saves the ``settings`` for the specified ``plugin``.
+9 -9
View File
@@ -1,16 +1,16 @@
.. sec-jsclientlib-slicing:
.. _sec-jsclientlib-slicing:
:mod:`OctoPrint.slicing`
------------------------
:mod:`OctoPrintClient.slicing`
------------------------------
.. js:function:: OctoPrint.slicing.listAllSlicersAndProfiles(opts)
.. js:function:: OctoPrintClient.slicing.listAllSlicersAndProfiles(opts)
Retrieves a list of all slicers and their available slicing profiles.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.listProfilesForSlicer(slicer, opts)
.. js:function:: OctoPrintClient.slicing.listProfilesForSlicer(slicer, opts)
Retrieves of all slicing profiles for the specified ``slicer``.
@@ -18,7 +18,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.getProfileForSlicer(slicer, profileId, opts)
.. js:function:: OctoPrintClient.slicing.getProfileForSlicer(slicer, profileId, opts)
Retrieves the slicing profile with ``profileId`` for the specified ``slicer``.
@@ -27,7 +27,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.addProfileForSlicer(slicer, profileId, profile, opts)
.. js:function:: OctoPrintClient.slicing.addProfileForSlicer(slicer, profileId, profile, opts)
Adds the profile with identifier ``profileId`` to the specified ``slicer``, using the provided ``profile`` data.
@@ -37,7 +37,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.updateProfileForSlicer(slicer, profileId, profile, opts)
.. js:function:: OctoPrintClient.slicing.updateProfileForSlicer(slicer, profileId, profile, opts)
Updates the profile ``profileId`` for ``slicer`` with the provided ``profile`` data.
@@ -47,7 +47,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.deleteProfileForSlicer(slicer, profileId, opts)
.. js:function:: OctoPrintClient.slicing.deleteProfileForSlicer(slicer, profileId, opts)
Deletes the profile ``profileId`` for ``slicer``.
+15 -15
View File
@@ -1,24 +1,24 @@
.. sec-jsclientlib-socket:
.. _sec-jsclientlib-socket:
:mod:`OctoPrint.socket`
-----------------------
:mod:`OctoPrintClient.socket`
-----------------------------
.. js:data:: OctoPrint.socket.options
.. js:attribute:: OctoPrintClient.socket.options
The socket client's options.
``OctoPrint.socket.options.timeouts``
``OctoPrintClient.socket.options.timeouts``
A list of consecutive timeouts after which to attempt reconnecting to a
disconnected sockets, in seconds. Defaults to ``[1, 1, 2, 3, 5, 8, 13, 20, 40, 100]``.
The default setting here makes the client slowly back off after the first couple of very
fast connection attempts don't succeed, and give up after 10 tries.
``OctoPrint.socket.options.rateSlidingWindowSize``
``OctoPrintClient.socket.options.rateSlidingWindowSize``
Number of last rate measurements to take into account for timing analysis and
communication throttling. See :ref:`Communication Throttling <sec-jsclient-socket-throttling>`
below.
.. js:function:: OctoPrint.socket.connect(opts)
.. js:function:: OctoPrintClient.socket.connect(opts)
Connects the socket client to OctoPrint's `SockJS <http://sockjs.org/>`_ socket.
@@ -27,15 +27,15 @@
:param object opts: Additional options for the SockJS constructor.
.. js:function:: OctoPrint.socket.reconnect()
.. js:function:: OctoPrintClient.socket.reconnect()
Reconnects the socket client. If the socket is currently connected it will be disconnected first.
.. js:function:: OctoPrint.socket.disconnect()
.. js:function:: OctoPrintClient.socket.disconnect()
Disconnects the socket client.
.. js:function:: OctoPrint.socket.onMessage(message, handler)
.. js:function:: OctoPrintClient.socket.onMessage(message, handler)
Registers the ``handler`` for messages of type ``message``.
@@ -60,7 +60,7 @@
:param string message: The type of message for which to register
:param function handler: The handler function
.. js:function:: OctoPrint.socket.sendMessage(type, payload)
.. js:function:: OctoPrintClient.socket.sendMessage(type, payload)
Sends a message of type ``type`` with the provided ``payload`` to the server.
@@ -70,7 +70,7 @@
:param string type: Type of message to send
:param object payload: Payload to send
.. js:function:: OctoPrint.socket.onRateTooLow(measured, minimum)
.. js:function:: OctoPrintClient.socket.onRateTooLow(measured, minimum)
Called by the socket client when the measured message round trip times have been lower than
the current lower processing limit over the full sliding window, indicating that messages
@@ -82,7 +82,7 @@
:param Number measured: Maximal measured message round trip time
:param Number minimum: Lower round trip time limit for keeping the rate
.. js:function:: OctoPrint.socket.onRateTooHigh(measured, maximum)
.. js:function:: OctoPrintClient.socket.onRateTooHigh(measured, maximum)
Called by the socket client when the last measured round trip time was higher than the
current upper procesisng limit, indicating that the messages are now processed slower than
@@ -94,11 +94,11 @@
:param Number measured: Measured message round trip time
:param Number minimum: Upper round trip time limit for keeping the rate
.. js:function:: OctoPrint.socket.increaseRate()
.. js:function:: OctoPrintClient.socket.increaseRate()
Instructs the server to increase the message rate by 500ms.
.. js:function:: OctoPrint.socket.decreaseRate()
.. js:function:: OctoPrintClient.socket.decreaseRate()
Instructs the server to decrease the message rate by 500ms.
+5 -5
View File
@@ -1,21 +1,21 @@
.. sec-jsclientlib-system:
:mod:`OctoPrint.system`
-----------------------
:mod:`OctoPrintClient.system`
-----------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.system.getCommands(opts)
.. js:function:: OctoPrintClient.system.getCommands(opts)
Retrieves a list of configured system commands for both ``core`` and ``custom`` sources.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.system.getCommandsForSource(source, opts)
.. js:function:: OctoPrintClient.system.getCommandsForSource(source, opts)
Retrieves a list of system commands, limiting it to the specified ``source``, which might be
either ``core`` or ``custom``.
@@ -23,7 +23,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.system.executeCommand(source, action, opts)
.. js:function:: OctoPrintClient.system.executeCommand(source, action, opts)
Executes command ``action`` on ``source``.
+13 -13
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-timelapse:
.. _sec-jsclientlib-timelapse:
:mod:`OctoPrint.timelapse`
--------------------------
:mod:`OctoPrintClient.timelapse`
--------------------------------
.. js:function:: OctoPrint.timelapse.get(unrendered, opts)
.. js:function:: OctoPrintClient.timelapse.get(unrendered, opts)
Get a list of all timelapses and the current timelapse config.
@@ -13,7 +13,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.list(opts)
.. js:function:: OctoPrintClient.timelapse.list(opts)
Get the lists of rendered and unrendered timelapses. The returned promis
will be resolved with an object containing the properties ``rendered``
@@ -23,21 +23,21 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.listRendered(opts)
.. js:function:: OctoPrintClient.timelapse.listRendered(opts)
Get the list of rendered timelapses.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.listUnrendered(opts)
.. js:function:: OctoPrintClient.timelapse.listUnrendered(opts)
Get the list of unrendered timelapses.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.download(filename, opts)
.. js:function:: OctoPrintClient.timelapse.download(filename, opts)
Download the rendered timelapse ``filename``.
@@ -45,7 +45,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.delete(filename, opts)
.. js:function:: OctoPrintClient.timelapse.delete(filename, opts)
Delete the rendered timelapse ``filename``.
@@ -53,7 +53,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.deleteUnrendered(name, opts)
.. js:function:: OctoPrintClient.timelapse.deleteUnrendered(name, opts)
Delete the unrendered timelapse ``name``.
@@ -61,7 +61,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.renderUnrendered(name, opts)
.. js:function:: OctoPrintClient.timelapse.renderUnrendered(name, opts)
Render the unrendered timelapse ``name``.
@@ -69,14 +69,14 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.getConfig(opts)
.. js:function:: OctoPrintClient.timelapse.getConfig(opts)
Get the current timelapse configuration.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.saveConfig(config, opts)
.. js:function:: OctoPrintClient.timelapse.saveConfig(config, opts)
Save the timelapse configuration.
+13 -13
View File
@@ -1,7 +1,7 @@
.. sec-jsclientlib-users:
.. _sec-jsclientlib-users:
:mod:`OctoPrint.users`
----------------------
:mod:`OctoPrintClient.users`
----------------------------
.. note::
@@ -9,7 +9,7 @@
has admin rights *or* corresponds to the user to be modified. Some methods
definitely require admin rights.
.. js:function:: OctoPrint.users.list(opts)
.. js:function:: OctoPrintClient.users.list(opts)
Get a list of all registered users.
@@ -18,7 +18,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.get(name, opts)
.. js:function:: OctoPrintClient.users.get(name, opts)
Get information about a specific user.
@@ -26,7 +26,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.add(user, opts)
.. js:function:: OctoPrintClient.users.add(user, opts)
Add a new user.
@@ -36,7 +36,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.update(name, active, admin, opts)
.. js:function:: OctoPrintClient.users.update(name, active, admin, opts)
Update an existing user.
@@ -48,7 +48,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.delete(name, opts)
.. js:function:: OctoPrintClient.users.delete(name, opts)
Delete an existing user.
@@ -58,7 +58,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.changePassword(name, password, opts)
.. js:function:: OctoPrintClient.users.changePassword(name, password, opts)
Change the password for a user.
@@ -67,7 +67,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.generateApiKey(name, opts)
.. js:function:: OctoPrintClient.users.generateApiKey(name, opts)
Generate a new API key for a user.
@@ -75,7 +75,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.resetApiKey(name, opts)
.. js:function:: OctoPrintClient.users.resetApiKey(name, opts)
Reset the API key for a user to being unset.
@@ -83,7 +83,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.getSettings(name, opts)
.. js:function:: OctoPrintClient.users.getSettings(name, opts)
Get the settings for a user.
@@ -91,7 +91,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.saveSettings(name, settings, opts)
.. js:function:: OctoPrintClient.users.saveSettings(name, settings, opts)
Save the settings for a user.
+7 -7
View File
@@ -1,14 +1,14 @@
.. sec-jsclientlib-util:
.. _sec-jsclientlib-util:
:mod:`OctoPrint.util`
---------------------
:mod:`OctoPrintClient.util`
---------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.util.test(command, parameters, opts)
.. js:function:: OctoPrintClient.util.test(command, parameters, opts)
Execute a :ref:`test command <sec-api-util-test>`.
@@ -19,7 +19,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.util.testPath(path, additional, opts)
.. js:function:: OctoPrintClient.util.testPath(path, additional, opts)
Test the provided ``path`` for existance. More test criteria supported by the :ref:`path test command <sec-api-util-test-path>`
can be provided via the ``additional`` object.
@@ -59,7 +59,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.util.testExecutable(path, opts)
.. js:function:: OctoPrintClient.util.testExecutable(path, opts)
Shortcut to test if a provided ``path`` exists and is executable by OctoPrint.
@@ -95,7 +95,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.util.testUrl(url, additional, opts)
.. js:function:: OctoPrintClient.util.testUrl(url, additional, opts)
Test if a URL can be accessed. More test criteria supported by the :ref:`URL test command <sec-api-util-test-url>`
can be provided via the ``additional`` object.
+5 -5
View File
@@ -1,21 +1,21 @@
.. sec-jsclientlib-wizard:
.. _sec-jsclientlib-wizard:
:mod:`OctoPrint.wizard`
-----------------------
:mod:`OctoPrintClient.wizard`
-----------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.wizard.get(opts)
.. js:function:: OctoPrintClient.wizard.get(opts)
Retrieve additional data about registered wizards.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.wizard.finish(handled, opts)
.. js:function:: OctoPrintClient.wizard.finish(handled, opts)
Inform wizards that the wizard dialog has been finished.
+32 -6
View File
@@ -205,17 +205,26 @@ class FileManager(object):
# callback was not registered
pass
def _determine_analysis_backlog(self, storage_type, storage_manager):
def _determine_analysis_backlog(self, storage_type, storage_manager, root=None, high_priority=False):
counter = 0
for entry, path, printer_profile in storage_manager.analysis_backlog:
backlog_generator = storage_manager.analysis_backlog
if root is not None:
backlog_generator = storage_manager.analysis_backlog_for_path(path=root)
for entry, path, printer_profile in backlog_generator:
file_type = get_file_type(path)[-1]
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())
if self._analysis_queue.enqueue(queue_entry, high_priority=False):
if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority):
counter += 1
self._logger.info("Added {counter} items from storage type \"{storage_type}\" to analysis queue".format(**locals()))
if root:
self._logger.info("Added {counter} items from storage type \"{storage_type}\" and root \"{root}\" to analysis queue".format(**locals()))
else:
self._logger.info("Added {counter} items from storage type \"{storage_type}\" to analysis queue".format(**locals()))
def add_storage(self, storage_type, storage_manager):
self._storage_managers[storage_type] = storage_manager
@@ -396,6 +405,10 @@ class FileManager(object):
if hook_file_object is not None:
file_object = hook_file_object
queue_entry = self._analysis_queue_entry(destination, path)
self._analysis_queue.dequeue(queue_entry)
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
if analysis is None:
@@ -415,13 +428,21 @@ class FileManager(object):
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def copy_file(self, destination, source, dst):
self._storage(destination).copy_file(source, dst)
path = self._storage(destination).copy_file(source, dst)
if not self.has_analysis(destination, path):
queue_entry = self._analysis_queue_entry(destination, path)
if queue_entry:
self._analysis_queue.enqueue(queue_entry)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_file(self, destination, source, dst):
queue_entry = self._analysis_queue_entry(destination, source)
self._analysis_queue.dequeue(queue_entry)
self._storage(destination).move_file(source, dst)
path = self._storage(destination).move_file(source, dst)
if not self.has_analysis(destination, path):
queue_entry = self._analysis_queue_entry(destination, path)
if queue_entry:
self._analysis_queue.enqueue(queue_entry)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def add_folder(self, destination, path, ignore_existing=True):
@@ -438,15 +459,20 @@ class FileManager(object):
def copy_folder(self, destination, source, dst):
self._storage(destination).copy_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_folder(self, destination, source, dst):
self._analysis_queue.dequeue_folder(destination, source)
self._analysis_queue.pause()
self._storage(destination).move_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
self._analysis_queue.resume()
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def has_analysis(self, destination, path):
return self._storage(destination).has_analysis(path)
def get_metadata(self, destination, path):
return self._storage(destination).get_metadata(path)
+37 -1
View File
@@ -44,6 +44,11 @@ class StorageInterface(object):
return
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
@@ -174,6 +179,8 @@ class StorageInterface(object):
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
@@ -183,6 +190,8 @@ class StorageInterface(object):
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
@@ -216,6 +225,8 @@ class StorageInterface(object):
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
@@ -225,6 +236,16 @@ class StorageInterface(object):
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
@@ -462,7 +483,10 @@ class LocalFileStorage(StorageInterface):
@property
def analysis_backlog(self):
for entry in self._analysis_backlog_generator():
return self.analysis_backlog_for_path()
def analysis_backlog_for_path(self, path=None):
for entry in self._analysis_backlog_generator(path):
yield entry
def _analysis_backlog_generator(self, path=None):
@@ -604,6 +628,8 @@ class LocalFileStorage(StorageInterface):
except Exception as e:
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
return self.path_in_storage(destination_data["fullpath"])
def move_folder(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
@@ -614,6 +640,8 @@ class LocalFileStorage(StorageInterface):
self._delete_metadata(source_data["fullpath"])
return self.path_in_storage(destination_data["fullpath"])
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
path, name = self.sanitize(path)
if not octoprint.filemanager.valid_file_type(name):
@@ -687,6 +715,8 @@ class LocalFileStorage(StorageInterface):
self._copy_metadata_entry(source_data["path"], source_data["name"],
destination_data["path"], destination_data["name"])
return self.path_in_storage(destination_data["fullpath"])
def move_file(self, source, destination, allow_overwrite=False):
source_data, destination_data = self._get_source_destination_data(source, destination)
@@ -699,6 +729,12 @@ class LocalFileStorage(StorageInterface):
destination_data["path"], destination_data["name"],
delete_source=True)
return self.path_in_storage(destination_data["fullpath"])
def has_analysis(self, path):
metadata = self.get_metadata(path)
return "analysis" in metadata
def get_metadata(self, path):
path, name = self.sanitize(path)
return self._get_metadata_entry(path, name)
@@ -1,68 +1,71 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
var exports = {};
exports.get = function(refresh, opts) {
return OctoPrint.get(OctoPrint.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts);
})(this, function(OctoPrintClient) {
var OctoPrintPluginManagerClient = function(base) {
this.base = base;
};
exports.getWithRefresh = function(opts) {
return exports.get(true, opts);
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts);
};
exports.getWithoutRefresh = function(opts) {
return exports.get(false, opts);
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
return this.get(true, opts);
};
exports.install = function(pluginUrl, dependencyLinks, 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 OctoPrint.simpleApiCommand("pluginmanager", "install", data, opts);
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
exports.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks,
reinstall: plugin,
force: true
};
return OctoPrint.simpleApiCommand("pluginmanager", "install", data, opts);
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
exports.uninstall = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "uninstall", data, opts);
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
};
exports.enable = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "enable", data, opts);
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
};
exports.disable = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "disable", data, opts);
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
};
exports.upload = function(file) {
return OctoPrint.upload(OctoPrint.getBlueprintUrl("pluginmanager") + "upload_archive", file);
OctoPrintPluginManagerClient.prototype.upload = function(file) {
return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
};
OctoPrint.plugins.pluginmanager = exports;
OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
return OctoPrintPluginManagerClient;
});
$(function() {
@@ -75,8 +75,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if self._refresh_configured_checks or self._configured_checks is None:
self._refresh_configured_checks = False
self._configured_checks = self._settings.get(["checks"], merged=True)
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
check_providers = self._settings.get(["check_providers"], merged=True)
effective_configs = dict()
for name, hook in update_check_hooks.items():
try:
hook_checks = hook()
@@ -84,6 +87,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
else:
for key, default_config in hook_checks.items():
if key in effective_configs or key == "octoprint":
if key == name:
self._logger.warn("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook")))
else:
self._logger.warn("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key))
continue
check_providers[key] = name
yaml_config = dict()
@@ -103,8 +113,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
deletables = []
self._clean_settings_check(key, yaml_config, default_config, delete=deletables, save=False)
# finally set our internal representation to our processed result
self._configured_checks[key] = effective_config
if effective_config:
effective_configs[key] = effective_config
else:
self._logger.warn("Update for {} is empty or None, ignoring it".format(key))
# finally set all our internal representations to our processed results
for key, config in effective_configs.items():
self._configured_checks[key] = config
self._settings.set(["check_providers"], check_providers)
self._settings.save()
@@ -379,6 +395,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
if not data:
# nothing to do
return data
if delete is None:
delete = []
@@ -537,6 +557,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if not target in check_targets:
continue
if not check:
continue
try:
populated_check = self._populated_check(target, check)
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
@@ -820,8 +843,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if target == "octoprint":
from flask.ext.babel import gettext
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
result["displayName"] = check.get("displayName")
if result["displayName"] is None:
# displayName missing or set to None
result["displayName"] = gettext("OctoPrint")
result["displayVersion"] = check.get("displayVersion")
if result["displayVersion"] is None:
# displayVersion missing or set to None
result["displayVersion"] = "{octoprint_version}"
stable_branch = "master"
release_branches = []
@@ -876,8 +907,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
result["release_compare"] = "python_unequal"
else:
result["displayName"] = check.get("displayName", target)
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
result["displayName"] = check.get("displayName")
if result["displayName"] is None:
# displayName missing or None
result["displayName"] = target
result["displayVersion"] = check.get("displayVersion", check.get("current"))
if result["displayVersion"] is None:
# displayVersion AND current missing or None
result["displayVersion"] = "unknown"
if check["type"] in ("github_commit",):
result["current"] = check.get("current", None)
else:
@@ -1,17 +1,19 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
var exports = {};
})(this, function(OctoPrintClient) {
var OctoPrintSoftwareUpdateClient = function(base) {
this.base = base;
var url = OctoPrint.getBlueprintUrl("softwareupdate");
var checkUrl = url + "check";
var updateUrl = url + "update";
var url = this.base.getBlueprintUrl("softwareupdate");
this.checkUrl = url + "check";
this.updateUrl = url + "update";
};
exports.checkEntries = function(entries, force, opts) {
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
@@ -31,20 +33,20 @@
if (entries && entries.length) {
data.check = entries.join(",");
}
return OctoPrint.getWithQuery(checkUrl, data, opts);
return this.base.getWithQuery(this.checkUrl, data, opts);
};
exports.check = function(force, 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 exports.checkEntries({entries: [], force: force, opts: opts});
return this.checkEntries({entries: [], force: force, opts: opts});
};
exports.update = function(entries, force, opts) {
OctoPrintSoftwareUpdateClient.prototype.update = function(entries, force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
@@ -61,10 +63,10 @@
entries: entries,
force: !!force
};
return OctoPrint.postJson(updateUrl, data, opts);
return this.base.postJson(this.updateUrl, data, opts);
};
exports.updateAll = function(force, opts) {
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
@@ -74,10 +76,11 @@
var data = {
force: !!force
};
return OctoPrint.postJson(updateUrl, data, opts);
return this.base.postJson(this.updateUrl, data, opts);
};
OctoPrint.plugins.softwareupdate = exports;
OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient);
return OctoPrintSoftwareUpdateClient;
});
$(function() {
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
def can_perform_update(target, check):
return "python_updater" in check and check["python_updater"] is not None
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update")
def perform_update(target, check, target_version, log_cb=None):
@@ -12,10 +12,11 @@ from ..exceptions import ConfigurationInvalid
from ..util import execute
def get_latest(target, check):
if not "command" in check:
raise ConfigurationInvalid("Update configuration for %s of type commandline needs command defined" % target)
command = check.get("command")
if command is None:
raise ConfigurationInvalid("Update configuration for {} of type commandline needs command set and not None".format(target))
returncode, stdout, stderr = execute(check["command"], evaluate_returncode=False)
returncode, stdout, stderr = execute(command, evaluate_returncode=False)
# We expect command line check commands to
#
@@ -48,10 +48,9 @@ def _git(args, cwd, hide_stderr=False):
def get_latest(target, check):
if not "checkout_folder" in check:
raise ConfigurationInvalid("Update configuration for %s needs checkout_folder" % target)
checkout_folder = check["checkout_folder"]
checkout_folder = check.get("checkout_folder")
if checkout_folder is None:
raise ConfigurationInvalid("Update configuration for {} of type git_commit needs checkout_folder set and not None".format(target))
returncode, _ = _git(["fetch"], checkout_folder)
if returncode != 0:
@@ -85,4 +84,4 @@ def get_latest(target, check):
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit")
logger.debug("Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit))
return information, is_current
return information, is_current
@@ -31,11 +31,14 @@ def _get_latest_commit(user, repo, branch):
def get_latest(target, check):
if "user" not in check or "repo" not in check:
raise ConfigurationInvalid("Update configuration for %s of type github_commit needs all of user and repo" % target)
user = check.get("user")
repo = check.get("repo")
if user is None or repo is None:
raise ConfigurationInvalid("Update configuration for {} of type github_commit needs user and repo set and not None".format(target))
branch = "master"
if "branch" in check:
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
current = None
@@ -115,12 +115,14 @@ def _get_sanitized_version(version_string):
Removes "-..." prefix from version strings.
Tests:
>>> _get_sanitized_version(None)
>>> _get_sanitized_version("1.2.15")
'1.2.15'
>>> _get_sanitized_version("1.2.15-dev12")
'1.2.15'
"""
if "-" in version_string:
if version_string is not None and "-" in version_string:
version_string = version_string[:version_string.find("-")]
return version_string
@@ -247,10 +249,12 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
def get_latest(target, check, custom_compare=None):
from ..exceptions import ConfigurationInvalid
if not "user" in check or not "repo" in check:
raise ConfigurationInvalid("github_release update configuration for %s needs user and repo set" % target)
user = check.get("user", None)
repo = check.get("repo", None)
current = check.get("current", None)
if user is None or repo is None or current is None:
raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target))
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
force_base = check.get("force_base", True)
@@ -8,7 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from ..exceptions import ConfigurationInvalid
def get_latest(target, check, full_data=False):
if not "python_checker" in check:
raise ConfigurationInvalid("Update configuration for %s of type commandline needs command defined" % target)
python_checker = check.get("python_checker")
if python_checker is None or not hasattr(python_checker, "get_latest"):
raise ConfigurationInvalid("Update configuration for {} of type python_checker needs python_checker defined and have an attribute \"get_latest\"".format(target))
return check["python_checker"].get_latest(target, check, full_data=full_data)
@@ -54,8 +54,12 @@ class VirtualPrinter(object):
self._send(item)
self.currentExtruder = 0
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.targetTemp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.sharedNozzle = settings().getBoolean(["devel", "virtualPrinter", "sharedNozzle"])
self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount)
self.temp = [0.0] * self.temperatureCount
self.targetTemp = [0.0] * self.temperatureCount
self.lastTempAt = time.time()
self.bedTemp = 1.0
self.bedTargetTemp = 1.0
@@ -301,8 +305,10 @@ class VirtualPrinter(object):
##~~ command implementations
def _gcode_T(self, code, data):
self.currentExtruder = int(code)
self._send("Active Extruder: %d" % self.currentExtruder)
t = int(code)
if 0 <= t <= self.extruderCount:
self.currentExtruder = t
self._send("Active Extruder: %d" % self.currentExtruder)
def _gcode_F(self, code, data):
if self._supportF:
@@ -628,7 +634,7 @@ class VirtualPrinter(object):
includeOk = not self._okBeforeCommandOutput
# send simulated temperature data
if settings().getInt(["devel", "virtualPrinter", "numExtruders"]) > 1:
if self.temperatureCount > 1:
allTemps = []
for i in range(len(self.temp)):
allTemps.append((i, self.temp[i], self.targetTemp[i]))
@@ -672,7 +678,7 @@ class VirtualPrinter(object):
except:
pass
if tool >= settings().getInt(["devel", "virtualPrinter", "numExtruders"]):
if tool >= self.temperatureCount:
return
try:
+59
View File
@@ -25,6 +25,7 @@ import re
from octoprint.settings import settings
from octoprint.util import deprecated
from octoprint.filemanager import FileDestinations
@deprecated(message="get_connection_options has been replaced by PrinterInterface.get_connection_options",
@@ -227,6 +228,64 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def can_modify_file(self, path, sd):
"""
Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted)
or not.
A file that is currently being printed is not allowed to be modified. Any other file or the current file
when it is not being printed is fine though.
.. since:: 1.3.2
.. warning::
This was introduced in 1.3.2 to work around an issue when updating a file that is already selected.
I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide
to depend on this particular method in this interface, be advised that it might vanish in future
versions!
Arguments:
path (str): path in storage of the file to check
sd (bool): True if to check against SD storage, False otherwise
Returns:
(bool) True if the file may be modified, False otherwise
"""
return not (self.is_current_file(path, sd) and (self.is_printing() or self.is_paused()))
def is_current_file(self, path, sd):
"""
Returns whether the provided ``path`` (on the printer's SD if ``sd`` is True) is the currently selected
file for printing.
.. since:: 1.3.2
.. warning::
This was introduced in 1.3.2 to work around an issue when updating a file that is already selected.
I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide
to depend on this particular method in this interface, be advised that it might vanish in future
versions!
Arguments:
path (str): path in storage of the file to check
sd (bool): True if to check against SD storage, False otherwise
Returns:
(bool) True if the file is currently selected, False otherwise
"""
current_job = self.get_current_job()
if current_job is not None and "file" in current_job:
current_job_file = current_job["file"]
if "path" in current_job_file and "origin" in current_job_file:
current_file_path = current_job_file["path"]
current_file_origin = current_job_file["origin"]
return path == current_file_path and sd == (current_file_origin == FileDestinations.SDCARD)
return False
def select_file(self, path, sd, printAfterSelect=False, pos=None):
"""
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
+22 -3
View File
@@ -124,7 +124,10 @@ class PrinterProfileManager(object):
- Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0)
* - ``extruder.nozzleDiameter``
- ``float``
- Diameter of the printer nozzle
- Diameter of the printer nozzle(s)
* - ``extruder.sharedNozzle``
- ``boolean``
- Whether there's only one nozzle shared among all extruders (true) or one nozzle per extruder (false).
* - ``axes``
- ``dict``
- Information about the printer axes
@@ -185,7 +188,8 @@ class PrinterProfileManager(object):
offsets = [
(0, 0)
],
nozzleDiameter = 0.4
nozzleDiameter = 0.4,
sharedNozzle = False
),
axes=dict(
x = dict(speed=6000, inverted=False),
@@ -390,6 +394,13 @@ class PrinterProfileManager(object):
def _load_default(self):
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
if self._migrate_profile(default_overrides):
try:
settings().set(["printerProfiles", "defaultProfile"], default_overrides)
settings().save()
except:
self._logger.exception("Tried to save default profile after migrating it while loading, ran into exception")
profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides))
if not profile:
self._logger.warn("Invalid default profile after applying overrides")
@@ -424,6 +435,14 @@ class PrinterProfileManager(object):
profile["volume"]["custom_box"] = False
modified = True
if "extruder" in profile and not "sharedNozzle" in profile["extruder"]:
profile["extruder"]["sharedNozzle"] = False
modified = True
if "extruder" in profile and "sharedNozzle" in profile["extruder"] and profile["extruder"]["sharedNozzle"]:
profile["extruder"]["offsets"] = [(0.0, 0.0)]
modified = True
return modified
def _ensure_valid_profile(self, profile):
@@ -462,7 +481,7 @@ class PrinterProfileManager(object):
return False
# convert booleans
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted"), ("extruder", "sharedNozzle")):
try:
convert_value(profile, path, bool)
except Exception as e:
+18 -6
View File
@@ -66,6 +66,8 @@ import octoprint.util
import octoprint.filemanager.storage
import octoprint.filemanager.analysis
import octoprint.slicing
from octoprint.server.util import enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, \
corsResponseHandler
from octoprint.server.util.flask import PreemptiveCache
from . import util
@@ -365,9 +367,14 @@ class Server(object):
as_attachment=True,
allow_client_caching=False
)
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))
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))
user_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path),
status_code=404))
def joined_dict(*dicts):
if not len(dicts):
@@ -392,9 +399,9 @@ class Server(object):
download_handler_kwargs,
admin_validator)),
# camera snapshot
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=self._settings.get(["webcam", "snapshot"]),
as_attachment=True,
access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, joined_dict(dict(url=self._settings.get(["webcam", "snapshot"]),
as_attachment=True),
user_validator)),
# generated webassets
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"))),
@@ -894,8 +901,13 @@ class Server(object):
return
if plugin.is_blueprint_protected():
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
blueprint.before_request(apiKeyRequestHandler)
blueprint.before_request(corsRequestHandler)
blueprint.before_request(enforceApiKeyRequestHandler)
blueprint.before_request(loginFromApiKeyRequestHandler)
blueprint.after_request(corsResponseHandler)
else:
blueprint.before_request(corsRequestHandler)
blueprint.before_request(loginFromApiKeyRequestHandler)
blueprint.after_request(corsResponseHandler)
url_prefix = "/plugin/{name}".format(name=name)
+5 -3
View File
@@ -19,7 +19,7 @@ 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, apiKeyRequestHandler, corsResponseHandler
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, corsResponseHandler
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
@@ -45,7 +45,9 @@ VERSION = "0.1"
api.after_request(noCachingExceptGetResponseHandler)
api.before_request(apiKeyRequestHandler)
api.before_request(corsRequestHandler)
api.before_request(enforceApiKeyRequestHandler)
api.before_request(loginFromApiKeyRequestHandler)
api.after_request(corsResponseHandler)
#~~ data from plugins
@@ -153,7 +155,7 @@ def wizardFinish():
if name in handled:
seen_wizards[name] = implementation.get_wizard_version()
except:
logging.getLogger(__name__).exceptino("There was an error finishing the wizard for {}, ignoring".format(name))
logging.getLogger(__name__).exception("There was an error finishing the wizard for {}, ignoring".format(name))
s().set(["server", "seenWizards"], seen_wizards)
s().save()
+9 -17
View File
@@ -289,17 +289,6 @@ def uploadGcodeFile(target):
if not printer.is_sd_ready():
return make_response("Can not upload to SD card, not yet initialized", 409)
# determine current job
currentPath = None
currentFilename = None
currentOrigin = None
currentJob = printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if currentJobFile is not None and "name" in currentJobFile.keys() and "origin" in currentJobFile.keys() and currentJobFile["name"] is not None and currentJobFile["origin"] is not None:
currentPath, currentFilename = fileManager.sanitize(FileDestinations.LOCAL, currentJobFile["name"])
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
# FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet
@@ -316,8 +305,13 @@ def uploadGcodeFile(target):
futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"])
# prohibit overwriting currently selected file while it's being printed
if futurePath == currentPath and futureFilename == currentFilename and target == currentOrigin and (printer.is_printing() or printer.is_paused()):
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409)
futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename)
futureFullPathInStorage = fileManager.path_in_storage(FileDestinations.LOCAL, futureFullPath)
if not printer.can_modify_file(futureFullPathInStorage, sd):
return make_response("Trying to overwrite file that is currently being printed: %s" % futureFullPath, 409)
reselect = printer.is_current_file(futureFullPathInStorage, sd)
def fileProcessingFinished(filename, absFilename, destination):
"""
@@ -342,13 +336,11 @@ def uploadGcodeFile(target):
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
exact file is already selected, such reloading it.
"""
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or reselect):
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename)
try:
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPath, upload, allow_overwrite=True)
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True)
except octoprint.filemanager.storage.StorageError as e:
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
return make_response("Could not upload the file \"{}\", invalid type".format(upload.filename), 400)
+36 -27
View File
@@ -10,6 +10,8 @@ import octoprint.timelapse
import octoprint.server
from octoprint.users import ApiUser
from octoprint.util import deprecated
import flask as _flask
from . import flask
@@ -18,51 +20,58 @@ from . import tornado
from . import watchdog
def apiKeyRequestHandler():
def enforceApiKeyRequestHandler():
"""
``before_request`` handler for blueprints for which all requests need to be made supplying an API key.
This may be the UI_API_KEY, in which case the underlying request processing will directly take place, or it may be
the global, an app specific or a user specific one. In any case it has to be present and must be valid, so anything
other than the above types will result in the application denying the request.
``before_request`` handler for blueprints which makes sure an API key is provided
"""
import octoprint.server
if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]):
return optionsAllowOrigin(_flask.request)
if _flask.request.method == 'OPTIONS':
# we ignore OPTIONS requests here
return
if _flask.request.endpoint == "static" or _flask.request.endpoint.endswith(".static"):
if _flask.request.endpoint and (_flask.request.endpoint == "static" or _flask.request.endpoint.endswith(".static")):
# no further handling for static resources
return
apikey = get_api_key(_flask.request)
if apikey is None:
# no api key => 401
return _flask.make_response("No API key provided", 401)
if apikey == octoprint.server.UI_API_KEY:
# ui api key => continue regular request processing
return
if not settings().getBoolean(["api", "enabled"]):
if apikey != octoprint.server.UI_API_KEY and not settings().getBoolean(["api", "enabled"]):
# api disabled => 401
return _flask.make_response("API disabled", 401)
if apikey == settings().get(["api", "key"]):
# global api key => continue regular request processing
return
apiKeyRequestHandler = deprecated("apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler")(enforceApiKeyRequestHandler)
if octoprint.server.appSessionManager.validate(apikey):
# app session key => continue regular request processing
return
user = get_user_for_apikey(apikey)
if user is not None:
# user specific api key => continue regular request processing
return
def loginFromApiKeyRequestHandler():
"""
``before_request`` handler for blueprints which creates a login session for the provided api key (if available)
# invalid api key => 401
return _flask.make_response("Invalid API key", 401)
UI_API_KEY and app session keys are handled as anonymous keys here and ignored.
"""
apikey = get_api_key(_flask.request)
if apikey and apikey != octoprint.server.UI_API_KEY and not octoprint.server.appSessionManager.validate(apikey):
user = get_user_for_apikey(apikey)
if user is not None and _flask.ext.login.login_user(user, remember=False):
_flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(),
identity=_flask.ext.principal.Identity(user.get_id()))
else:
return _flask.make_response("Invalid API key", 401)
def corsRequestHandler():
"""
``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled
"""
if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]):
# reply to OPTIONS request for CORS headers
return optionsAllowOrigin(_flask.request)
def corsResponseHandler(resp):
+15 -32
View File
@@ -62,12 +62,18 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
continue
if filter(lambda x: x.name.endswith('.mo'), scandir(locale_dir)):
result.append(Locale.parse(entry.name))
if not result:
result.append(Locale.parse(self._default_locale))
return result
dirs = additional_folders + [os.path.join(self.app.root_path, 'translations')]
# translations from plugins
plugins = octoprint.plugin.plugin_manager().enabled_plugins
for name, plugin in plugins.items():
plugin_translation_dir = os.path.join(plugin.location, 'translations')
if not os.path.isdir(plugin_translation_dir):
continue
dirs.append(plugin_translation_dir)
result = [Locale.parse(default_locale)]
for dir in dirs:
@@ -104,20 +110,20 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
else:
if isinstance(plugin_translations, support.Translations):
translations = translations.merge(plugin_translations)
logger.debug("Using translation folder {dirname} for locale {locale} of plugin {name}".format(**locals()))
logger.debug("Using translation plugin folder {dirname} from plugin {name} for locale {locale}".format(**locals()))
break
else:
logger.debug("No translations for locale {locale} for plugin {name}".format(**locals()))
logger.debug("No translations for locale {locale} from plugin {name}".format(**locals()))
# core translations
dirs = additional_folders + [os.path.join(ctx.app.root_path, 'translations')]
for dirname in dirs:
core_translations = support.Translations.load(dirname, [locale])
if isinstance(core_translations, support.Translations):
logger.debug("Using translation folder {dirname} for locale {locale} of core translations".format(**locals()))
logger.debug("Using translation core folder {dirname} for locale {locale}".format(**locals()))
break
else:
logger.debug("No core translations for locale {locale}")
logger.debug("No translations for locale {} in core folders".format(locale))
translations = translations.merge(core_translations)
ctx.babel_translations = translations
@@ -1083,20 +1089,13 @@ def restricted_access(func):
"""
If you decorate a view with this, it will ensure that first setup has been
done for OctoPrint's Access Control plus that any conditions of the
login_required decorator are met. It also allows to login using the masterkey or any
of the user's apikeys if API access is enabled globally and for the decorated view.
login_required decorator are met (possibly through a session already created
by octoprint.server.util.apiKeyRequestHandler earlier in the request processing).
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
flag from the settings being set to True and the userManager not indicating
that it's user database has been customized from default), the decorator
will cause a HTTP 403 status code to be returned by the decorated resource.
If the API key matches the UI API key, the result of calling login_required for the
view will be returned (browser session mode).
Otherwise the API key will be attempted to be resolved to a user. If that is
successful the user will be logged in and the view will be called directly.
Otherwise a HTTP 401 status code will be returned.
"""
@functools.wraps(func)
def decorated_view(*args, **kwargs):
@@ -1104,23 +1103,7 @@ def restricted_access(func):
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)
apikey = octoprint.server.util.get_api_key(flask.request)
if apikey == octoprint.server.UI_API_KEY:
# UI API key => call regular login_required decorator, we are using browser sessions here
return flask.ext.login.login_required(func)(*args, **kwargs)
# try to determine user for key
user = octoprint.server.util.get_user_for_apikey(apikey)
if user is None:
# no user or no key => go away
return flask.make_response("Invalid API key", 401)
if not flask.ext.login.login_user(user, remember=False):
# user for API key could not be logged in => go away
return flask.make_response("Invalid API key", 401)
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
return func(*args, **kwargs)
return flask.ext.login.login_required(func)(*args, **kwargs)
return decorated_view
+45 -18
View File
@@ -7,6 +7,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import os
import time
import threading
import watchdog.events
import octoprint.filemanager
@@ -32,39 +34,64 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
try:
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
# determine current job
currentFilename = None
currentOrigin = None
currentJob = self._printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
currentFilename = currentJobFile["name"]
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
futurePath, futureFilename = self._file_manager.sanitize(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
except:
futurePath = None
futureFilename = None
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
return
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
futureFullPath = self._file_manager.join_path(octoprint.filemanager.FileDestinations.LOCAL, futurePath, futureFilename)
futureFullPathInStorage = self._file_manager.path_in_storage(octoprint.filemanager.FileDestinations.LOCAL, futureFullPath)
if not self._printer.can_modify_file(futureFullPathInStorage, False):
return
self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
file_wrapper.filename,
file_wrapper,
allow_overwrite=True)
reselect = self._printer.is_current_file(futureFullPathInStorage, False)
added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
file_wrapper.filename,
file_wrapper,
allow_overwrite=True)
if os.path.exists(path):
try:
os.remove(path)
except:
self._logger.exception("Error while trying to clear a file from the watched folder")
pass
if reselect:
self._printer.select_file(self._file_manager.path_on_disk(octoprint.filemanager.FileDestinations.LOCAL,
added_file),
False)
except:
self._logger.exception("There was an error while processing the file {} in the watched folder".format(path))
def on_created(self, event):
self._upload(event.src_path)
thread = threading.Thread(target=self._repeatedly_check, args=(event.src_path,))
thread.daemon = True
thread.start()
def _repeatedly_check(self, path, interval=1, stable=5):
last_size = os.stat(path).st_size
countdown = stable
while True:
new_size = os.stat(path).st_size
if new_size == last_size:
self._logger.debug("File at {} is no longer growing, counting down: {}".format(path, countdown))
countdown -= 1
if countdown <= 0:
break
else:
self._logger.debug("File at {} is still growing (last: {}, new: {}), waiting...".format(path, last_size, new_size))
countdown = stable
last_size = new_size
time.sleep(interval)
self._logger.debug("File at {} is stable, moving it".format(path))
self._upload(path)
+4 -2
View File
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import os
import datetime
import codecs
from collections import defaultdict
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
@@ -924,14 +925,15 @@ def _get_translations(locale, domain):
def messages_from_po(path, locale, domain):
messages = dict()
with file(path) as f:
with codecs.open(path, encoding="utf-8") as f:
catalog = read_po(f, locale=locale, domain=domain)
for message in catalog:
message_id = message.id
if isinstance(message_id, (list, tuple)):
message_id = message_id[0]
messages[message_id] = message.string
if message.string:
messages[message_id] = message.string
return messages, catalog.plural_expr
+2 -1
View File
@@ -356,7 +356,8 @@ default_settings = {
"echoOnM117": True,
"brokenM29": True,
"supportF": False,
"firmwareName": "Virtual Marlin 1.0"
"firmwareName": "Virtual Marlin 1.0",
"sharedNozzle": False
}
}
}
+99 -60
View File
@@ -1,11 +1,58 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define("OctoPrint", ["jquery", "lodash"], factory);
define("OctoPrintClient", ["jquery", "lodash"], factory);
} else {
global.OctoPrint = factory(window.$, window._);
global.OctoPrintClient = factory(global.$, global._);
global.OctoPrint = new global.OctoPrintClient();
}
})(window || this, function($, _) {
var OctoPrint = {};
})(this, function($, _) {
var PluginRegistry = function(base) {
this.base = base;
this.components = {};
};
var OctoPrintClient = function(options) {
this.options = options || {
"baseurl": undefined,
"apikey": undefined,
"locale": undefined
};
this.components = {};
this.plugins = new PluginRegistry(this);
};
OctoPrintClient.registerComponent = function(name, component) {
Object.defineProperty(OctoPrintClient.prototype, name, {
get: function() {
if (this.components[name] !== undefined) {
return this.components[name];
}
var instance = new component(this);
this.components[name] = instance;
return instance;
},
enumerable: false,
configurable: false
});
};
OctoPrintClient.registerPluginComponent = function(name, component) {
Object.defineProperty(PluginRegistry.prototype, name, {
get: function() {
if (this.components[name] !== undefined) {
return this.components[name];
}
var instance = new component(this.base);
this.components[name] = instance;
return instance;
},
enumerable: false,
configurable: false
});
};
var noCache = function(opts) {
opts = opts || {};
@@ -44,36 +91,28 @@
return params;
};
OctoPrint.options = {
"baseurl": undefined,
"apikey": undefined,
"locale": undefined
};
OctoPrint.plugins = {};
OctoPrint.getBaseUrl = function() {
var url = OctoPrint.options.baseurl;
OctoPrintClient.prototype.getBaseUrl = function() {
var url = this.options.baseurl;
if (!_.endsWith(url, "/")) {
url = url + "/";
}
return url;
};
OctoPrint.getRequestHeaders = function(additional) {
OctoPrintClient.prototype.getRequestHeaders = function(additional) {
additional = additional || {};
var headers = $.extend({}, additional);
headers["X-Api-Key"] = OctoPrint.options.apikey;
headers["X-Api-Key"] = this.options.apikey;
if (OctoPrint.options.locale !== undefined) {
headers["X-Locale"] = OctoPrint.options.locale;
if (this.options.locale !== undefined) {
headers["X-Locale"] = this.options.locale;
}
return headers;
};
OctoPrint.ajax = function(method, url, opts) {
OctoPrintClient.prototype.ajax = function(method, url, opts) {
opts = opts || {};
method = opts.method || method || "GET";
@@ -81,11 +120,11 @@
var urlToCall = url;
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
urlToCall = OctoPrint.getBaseUrl() + url;
urlToCall = this.getBaseUrl() + url;
opts.url = urlToCall;
}
var headers = OctoPrint.getRequestHeaders(opts.headers);
var headers = this.getRequestHeaders(opts.headers);
var params = $.extend({}, opts);
params.type = method;
@@ -95,67 +134,67 @@
return $.ajax(urlToCall, params);
};
OctoPrint.ajaxWithData = function(method, url, data, opts) {
OctoPrintClient.prototype.ajaxWithData = function(method, url, data, opts) {
opts = opts || {};
var params = $.extend({}, opts);
params.data = data;
return OctoPrint.ajax(method, url, params);
return this.ajax(method, url, params);
};
OctoPrint.get = function(url, opts) {
return OctoPrint.ajax("GET", url, opts);
OctoPrintClient.prototype.get = function(url, opts) {
return this.ajax("GET", url, opts);
};
OctoPrint.getWithQuery = function(url, data, opts) {
return OctoPrint.ajaxWithData("GET", url, data, opts);
OctoPrintClient.prototype.getWithQuery = function(url, data, opts) {
return this.ajaxWithData("GET", url, data, opts);
};
OctoPrint.post = function(url, data, opts) {
return OctoPrint.ajaxWithData("POST", url, data, noCache(opts));
OctoPrintClient.prototype.post = function(url, data, opts) {
return this.ajaxWithData("POST", url, data, noCache(opts));
};
OctoPrint.postForm = function(url, data, opts) {
OctoPrintClient.prototype.postForm = function(url, data, opts) {
var form = new FormData();
_.each(data, function(value, key) {
form.append(key, value);
});
return OctoPrint.post(url, form, contentTypeFalse(noProcessData(opts)));
return this.post(url, form, contentTypeFalse(noProcessData(opts)));
};
OctoPrint.postJson = function(url, data, opts) {
return OctoPrint.post(url, JSON.stringify(data), contentTypeJson(opts));
OctoPrintClient.prototype.postJson = function(url, data, opts) {
return this.post(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.put = function(url, data, opts) {
return OctoPrint.ajaxWithData("PUT", url, data, noCache(opts));
OctoPrintClient.prototype.put = function(url, data, opts) {
return this.ajaxWithData("PUT", url, data, noCache(opts));
};
OctoPrint.putJson = function(url, data, opts) {
return OctoPrint.put(url, JSON.stringify(data), contentTypeJson(opts));
OctoPrintClient.prototype.putJson = function(url, data, opts) {
return this.put(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.patch = function(url, data, opts) {
return OctoPrint.ajaxWithData("PATCH", url, data, noCache(opts));
OctoPrintClient.prototype.patch = function(url, data, opts) {
return this.ajaxWithData("PATCH", url, data, noCache(opts));
};
OctoPrint.patchJson = function(url, data, opts) {
return OctoPrint.patch(url, JSON.stringify(data), contentTypeJson(opts));
OctoPrintClient.prototype.patchJson = function(url, data, opts) {
return this.patch(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.delete = function(url, opts) {
return OctoPrint.ajax("DELETE", url, opts);
OctoPrintClient.prototype.delete = function(url, opts) {
return this.ajax("DELETE", url, opts);
};
OctoPrint.download = function(url, opts) {
OctoPrintClient.prototype.download = function(url, opts) {
var params = $.extend({}, opts || {});
params.dataType = "text";
return OctoPrint.get(url, params);
return this.get(url, params);
};
OctoPrint.upload = function(url, file, filename, additional) {
OctoPrintClient.prototype.upload = function(url, file, filename, additional) {
additional = additional || {};
var fileData;
@@ -220,11 +259,11 @@
deferred.notify({loaded: e.loaded, total: e.total});
});
var headers = OctoPrint.getRequestHeaders();
var headers = this.getRequestHeaders();
var urlToCall = url;
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
urlToCall = OctoPrint.getBaseUrl() + url;
urlToCall = this.getBaseUrl() + url;
}
request.open("POST", urlToCall);
@@ -236,38 +275,38 @@
return deferred.promise();
};
OctoPrint.issueCommand = function(url, command, payload, opts) {
OctoPrintClient.prototype.issueCommand = function(url, command, payload, opts) {
payload = payload || {};
var data = $.extend({}, payload);
data.command = command;
return OctoPrint.postJson(url, data, opts);
return this.postJson(url, data, opts);
};
OctoPrint.getSimpleApiUrl = function(plugin) {
OctoPrintClient.prototype.getSimpleApiUrl = function(plugin) {
return "api/plugin/" + plugin;
};
OctoPrint.simpleApiGet = function(plugin, opts) {
return OctoPrint.get(OctoPrint.getSimpleApiUrl(plugin), opts);
OctoPrintClient.prototype.simpleApiGet = function(plugin, opts) {
return this.get(OctoPrintClient.prototype.getSimpleApiUrl(plugin), opts);
};
OctoPrint.simpleApiCommand = function(plugin, command, payload, opts) {
return OctoPrint.issueCommand(OctoPrint.getSimpleApiUrl(plugin), command, payload, opts);
OctoPrintClient.prototype.simpleApiCommand = function(plugin, command, payload, opts) {
return this.issueCommand(OctoPrintClient.prototype.getSimpleApiUrl(plugin), command, payload, opts);
};
OctoPrint.getBlueprintUrl = function(plugin) {
OctoPrintClient.prototype.getBlueprintUrl = function(plugin) {
return "plugin/" + plugin + "/";
};
OctoPrint.createRejectedDeferred = function() {
OctoPrintClient.createRejectedDeferred = function() {
var deferred = $.Deferred();
deferred.reject(arguments);
return deferred;
};
OctoPrint.createCustomException = function(name) {
OctoPrintClient.createCustomException = function(name) {
var constructor;
if (_.isFunction(name)) {
@@ -286,7 +325,7 @@
return constructor;
};
OctoPrint.InvalidArgumentError = OctoPrint.createCustomException("InvalidArgumentError");
OctoPrintClient.InvalidArgumentError = OctoPrintClient.createCustomException("InvalidArgumentError");
return OctoPrint;
return OctoPrintClient;
});
+25 -20
View File
@@ -1,29 +1,34 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var loginUrl = "api/login";
var logoutUrl = "api/logout";
OctoPrint.browser = {
login: function(username, password, remember, opts) {
var data = {
user: username,
pass: password,
remember: !!remember
};
return OctoPrint.postJson(loginUrl, data, opts);
},
passiveLogin: function(opts) {
return OctoPrint.postJson(loginUrl, {passive: true}, opts);
},
logout: function(opts) {
return OctoPrint.postJson(logoutUrl, {}, opts);
}
var OctoPrintBrowserClient = function(base) {
this.base = base;
};
OctoPrintBrowserClient.prototype.login = function(username, password, remember, opts) {
var data = {
user: username,
pass: password,
remember: !!remember
};
return this.base.postJson(loginUrl, data, opts);
};
OctoPrintBrowserClient.prototype.passiveLogin = function(opts) {
return this.base.postJson(loginUrl, {passive: true}, opts);
};
OctoPrintBrowserClient.prototype.logout = function(opts) {
return this.base.postJson(logoutUrl, {}, opts);
};
OctoPrintClient.registerComponent("browser", OctoPrintBrowserClient);
return OctoPrintBrowserClient;
});
@@ -1,27 +1,32 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/connection";
OctoPrint.connection = {
getSettings: function(opts) {
return OctoPrint.get(url, opts);
},
var OctoPrintConnectionClient = function(base) {
this.base = base;
};
connect: function(data, opts) {
return OctoPrint.issueCommand(url, "connect", data || {}, opts);
},
OctoPrintConnectionClient.prototype.getSettings = function(opts) {
return this.base.get(url, opts);
};
disconnect: function(opts) {
return OctoPrint.issueCommand(url, "disconnect", {}, opts);
},
OctoPrintConnectionClient.prototype.connect = function(data, opts) {
return this.base.issueCommand(url, "connect", data || {}, opts);
};
fakeAck: function(opts) {
return OctoPrint.issueCommand(url, "fake_ack", {}, opts);
}
}
OctoPrintConnectionClient.prototype.disconnect = function(opts) {
return this.base.issueCommand(url, "disconnect", {}, opts);
};
OctoPrintConnectionClient.prototype.fakeAck = function(opts) {
return this.base.issueCommand(url, "fake_ack", {}, opts);
};
OctoPrintClient.registerComponent("connection", OctoPrintConnectionClient);
return OctoPrintConnectionClient;
});
+23 -21
View File
@@ -1,14 +1,22 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var customUrl = "api/printer/command/custom";
var commandUrl = "api/printer/command";
var sendGcodeWithParameters = function(commands, parameters, opts) {
var OctoPrintControlClient = function(base) {
this.base = base;
};
OctoPrintControlClient.prototype.getCustomControls = function (opts) {
return this.base.get(customUrl, opts);
};
OctoPrintControlClient.prototype.sendGcodeWithParameters = function(commands, parameters, opts) {
commands = commands || [];
parameters = parameters || {};
@@ -16,38 +24,32 @@
commands = [commands];
}
return OctoPrint.postJson(commandUrl, {
return this.base.postJson(commandUrl, {
commands: commands,
parameters: parameters
}, opts);
};
var sendGcodeScriptWithParameters = function(script, context, parameters, opts) {
OctoPrintControlClient.prototype.sendGcodeScriptWithParameters = function(script, context, parameters, opts) {
script = script || "";
context = context || {};
parameters = parameters || {};
return OctoPrint.postJson(commandUrl, {
return this.base.postJson(commandUrl, {
script: script,
context: context,
parameters: parameters
}, opts);
};
OctoPrint.control = {
sendGcodeWithParameters: sendGcodeWithParameters,
sendGcodeScriptWithParameters: sendGcodeScriptWithParameters,
OctoPrintControlClient.prototype.sendGcode = function (commands, opts) {
return this.sendGcodeWithParameters(commands, undefined, opts);
};
getCustomControls: function (opts) {
return OctoPrint.get(customUrl, opts);
},
OctoPrintControlClient.prototype.sendGcodeScript = function (script, context, opts) {
return this.sendGcodeScriptWithParameters(script, context, undefined, opts);
};
sendGcode: function (commands, opts) {
return sendGcodeWithParameters(commands, undefined, opts);
},
sendGcodeScript: function (script, context, opts) {
return sendGcodeScriptWithParameters(script, context, undefined, opts);
}
}
OctoPrintClient.registerComponent("control", OctoPrintControlClient);
return OctoPrintControlClient;
});
+103 -106
View File
@@ -1,16 +1,17 @@
(function (factory) {
'use strict';
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(["OctoPrint", "jquery", "lodash"], factory);
define(["OctoPrintClient", "jquery", "lodash"], factory);
} else {
// Browser globals:
factory(window.OctoPrint, window.jQuery, window._);
factory(global.OctoPrintClient, global.$, global._);
}
})(function(OctoPrint, $, _) {
})(this, function(OctoPrintClient, $, _) {
var url = "api/files";
var downloadUrl = "downloads/files";
var OctoPrintFilesClient = function(base) {
this.base = base;
};
var resourceForLocation = function(location) {
return url + "/" + location;
};
@@ -27,15 +28,6 @@
return resourceForLocation(location) + "/" + filename;
};
var issueEntryCommand = function(location, entryname, command, data, opts) {
var url = resourceForEntry(location, entryname);
return OctoPrint.issueCommand(url, command, data, opts);
};
var getEntry = function(location, entryname, opts) {
return OctoPrint.get(resourceForEntry(location, entryname), opts);
};
var preProcessList = function(response) {
var recursiveCheck = function(element, index, list) {
if (!element.hasOwnProperty("parent")) element.parent = { children: list, parent: undefined };
@@ -56,7 +48,88 @@
_.each(response.files, recursiveCheck);
};
var pathForEntry = function(entry) {
OctoPrintFilesClient.prototype.get = function(location, entryname, opts) {
return this.base.get(resourceForEntry(location, entryname), opts);
};
OctoPrintFilesClient.prototype.list = function (recursively, force, opts) {
recursively = recursively || false;
force = force || false;
var query = {};
if (recursively) {
query.recursive = recursively;
}
if (force) {
query.force = force;
}
return this.base.getWithQuery(url, query, opts)
.done(preProcessList);
};
OctoPrintFilesClient.prototype.listForLocation = function (location, recursively, opts) {
recursively = recursively || false;
return this.base.getWithQuery(resourceForLocation(location), {recursive: recursively}, opts)
.done(preProcessList);
};
OctoPrintFilesClient.prototype.issueEntryCommand = function(location, entryname, command, data, opts) {
var url = resourceForEntry(location, entryname);
return this.base.issueCommand(url, command, data, opts);
};
OctoPrintFilesClient.prototype.select = function (location, path, print, opts) {
print = print || false;
var data = {
print: print
};
return this.issueEntryCommand(location, path, "select", data, opts);
};
OctoPrintFilesClient.prototype.slice = function (location, path, parameters, opts) {
return this.issueEntryCommand(location, path, "slice",
parameters || {}, opts);
};
OctoPrintFilesClient.prototype.delete = function (location, path, opts) {
return this.base.delete(resourceForEntry(location, path), opts);
};
OctoPrintFilesClient.prototype.copy = function(location, path, destination, opts) {
return this.issueEntryCommand(location, path, "copy", { destination: destination }, opts);
};
OctoPrintFilesClient.prototype.move = function(location, path, destination, opts) {
return this.issueEntryCommand(location, path, "move", { destination: destination }, opts);
};
OctoPrintFilesClient.prototype.createFolder = function (location, name, path, opts) {
var data = {foldername: name};
if (path !== undefined && path !== "") {
data.path = path;
}
return this.base.postForm(resourceForLocation(location), data, opts);
};
OctoPrintFilesClient.prototype.upload = function (location, file, data) {
data = data || {};
var filename = data.filename || undefined;
if (data.userdata && typeof data.userdata === "object") {
data.userdata = JSON.stringify(userdata);
}
return this.base.upload(resourceForLocation(location), file, filename, data);
};
OctoPrintFilesClient.prototype.download = function(location, path, opts) {
return this.base.download(downloadForEntry(location, path), opts);
};
OctoPrintFilesClient.prototype.pathForEntry = function(entry) {
if (!entry || !entry.hasOwnProperty("parent") || entry.parent == undefined) {
return "";
}
@@ -72,7 +145,7 @@
return recursivePath(entry.parent, entry.name);
};
var entryForPath = function(path, root) {
OctoPrintFilesClient.prototype.entryForPath = function(path, root) {
if (_.isArray(root)) {
root = {children: root};
}
@@ -99,94 +172,18 @@
return recursiveSearch(path.split("/"), root);
};
OctoPrint.files = {
get: getEntry,
OctoPrintFilesClient.prototype.pathForElement = function(element) {
// TODO Remove in 1.4.x
log.warn("pathForElement has been renamed to pathForEntry, please use that instead");
return this.pathForEntry(element);
};
list: function (recursively, force, opts) {
recursively = recursively || false;
force = force || false;
OctoPrintFilesClient.prototype.elementByPath = function(location, startElement) {
// TODO Remove in 1.4.x
log.warn("elementByPath has been renamed to entryForPath, please use that instead");
return this.entryForPath(location, startElement);
};
var query = {};
if (recursively) {
query.recursive = recursively;
}
if (force) {
query.force = force;
}
return OctoPrint.getWithQuery(url, query, opts)
.done(preProcessList);
},
listForLocation: function (location, recursively, opts) {
recursively = recursively || false;
return OctoPrint.getWithQuery(resourceForLocation(location), {recursive: recursively}, opts)
.done(preProcessList);
},
select: function (location, path, print, opts) {
print = print || false;
var data = {
print: print
};
return issueEntryCommand(location, path, "select", data, opts);
},
slice: function (location, path, parameters, opts) {
return issueEntryCommand(location, path, "slice",
parameters || {}, opts);
},
delete: function (location, path, opts) {
return OctoPrint.delete(resourceForEntry(location, path), opts);
},
copy: function(location, path, destination, opts) {
return issueEntryCommand(location, path, "copy", { destination: destination }, opts);
},
move: function(location, path, destination, opts) {
return issueEntryCommand(location, path, "move", { destination: destination }, opts);
},
createFolder: function (location, name, path, opts) {
var data = {foldername: name};
if (path !== undefined && path !== "") {
data.path = path;
}
return OctoPrint.postForm(resourceForLocation(location), data, opts);
},
upload: function (location, file, data) {
data = data || {};
var filename = data.filename || undefined;
if (data.userdata && typeof data.userdata === "object") {
data.userdata = JSON.stringify(userdata);
}
return OctoPrint.upload(resourceForLocation(location), file, filename, data);
},
download: function (location, path, opts) {
return OctoPrint.download(downloadForEntry(location, path), opts);
},
pathForEntry: pathForEntry,
entryForPath: entryForPath,
pathForElement: function(element) {
// TODO Remove in 1.4.x
log.warn("OctoPrint.files.pathForElement has been renamed to OctoPrint.files.pathForEntry, please use that instead");
return pathForEntry(element);
},
elementByPath: function(location, startElement) {
// TODO Remove in 1.4.x
log.warn("OctoPrint.files.elementByPath has been renamed to OctoPrint.files.entryForPath, please use that instead");
return entryForPath(location, startElement);
}
}
OctoPrintClient.registerComponent("files", OctoPrintFilesClient);
return OctoPrintFilesClient;
});
+39 -28
View File
@@ -1,42 +1,53 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/job";
var issueCommand = function(command, payload, opts) {
var OctoPrintJobClient = function(base) {
this.base = base;
};
OctoPrintJobClient.prototype.issueCommand = function(command, payload, opts) {
if (arguments.length == 2) {
opts = payload;
payload = {};
}
return OctoPrint.issueCommand(url, command, payload, opts);
return this.base.issueCommand(url, command, payload, opts);
};
OctoPrint.job = {
get: function(opts) {
return OctoPrint.get(url, opts);
},
start: function(opts) {
return issueCommand("start", opts);
},
restart: function(opts) {
return issueCommand("restart", opts);
},
pause: function(opts) {
return issueCommand("pause", {"action": "pause"}, opts);
},
resume: function(opts) {
return issueCommand("pause", {"action": "resume"}, opts)
},
togglePause: function(opts) {
return issueCommand("pause", {"action": "toggle"}, opts);
},
cancel: function(opts) {
return issueCommand("cancel", opts);
}
}
OctoPrintJobClient.prototype.get = function(opts) {
return OctoPrint.get(url, opts);
};
OctoPrintJobClient.prototype.start = function(opts) {
return this.issueCommand("start", opts);
};
OctoPrintJobClient.prototype.restart = function(opts) {
return this.issueCommand("restart", opts);
};
OctoPrintJobClient.prototype.pause = function(opts) {
return this.issueCommand("pause", {"action": "pause"}, opts);
};
OctoPrintJobClient.prototype.resume = function(opts) {
return this.issueCommand("pause", {"action": "resume"}, opts)
};
OctoPrintJobClient.prototype.togglePause = function(opts) {
return this.issueCommand("pause", {"action": "toggle"}, opts);
};
OctoPrintJobClient.prototype.cancel = function(opts) {
return this.issueCommand("cancel", opts);
};
OctoPrintClient.registerComponent("job", OctoPrintJobClient);
return OctoPrintJobClient;
});
+21 -14
View File
@@ -1,22 +1,29 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/languages";
OctoPrint.languages = {
list: function(opts) {
return OctoPrint.get(url, opts);
},
upload: function(file) {
return OctoPrint.upload(url, file);
},
delete: function(locale, pack, opts) {
var packUrl = url + "/" + locale + "/" + pack;
return OctoPrint.delete(packUrl, opts);
}
var OctoPrintLanguagesClient = function(base) {
this.base = base;
};
OctoPrintLanguagesClient.prototype.list = function(opts) {
return this.base.get(url, opts);
};
OctoPrintLanguagesClient.prototype.upload = function(file) {
return this.base.upload(url, file);
};
OctoPrintLanguagesClient.prototype.delete = function(locale, pack, opts) {
var packUrl = url + "/" + locale + "/" + pack;
return this.base.delete(packUrl, opts);
};
OctoPrintClient.registerComponent("languages", OctoPrintLanguagesClient);
return OctoPrintLanguagesClient;
});
+21 -16
View File
@@ -1,25 +1,30 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/logs";
OctoPrint.logs = {
list: function(opts) {
return OctoPrint.get(url, opts);
},
var OctoPrintLogsClient = function(base) {
this.base = base;
};
delete: function(file, opts) {
var fileUrl = url + "/" + file;
return OctoPrint.delete(fileUrl, opts);
},
OctoPrintLogsClient.prototype.list = function(opts) {
return this.base.get(url, opts);
};
download: function(file, opts) {
var fileUrl = url + "/" + file;
return OctoPrint.download(fileUrl, opts);
}
}
OctoPrintLogsClient.prototype.delete = function(file, opts) {
var fileUrl = url + "/" + file;
return this.base.delete(fileUrl, opts);
};
OctoPrintLogsClient.prototype.download = function(file, opts) {
var fileUrl = url + "/" + file;
return this.base.download(fileUrl, opts);
};
OctoPrintClient.registerComponent("logs", OctoPrintLogsClient);
return OctoPrintLogsClient;
});
+186 -181
View File
@@ -1,210 +1,215 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/printer";
var printheadUrl = url + "/printhead";
var toolUrl = url + "/tool";
var bedUrl = url + "/bed";
var sdUrl = url + "/sd";
var issuePrintheadCommand = function (command, payload, opts) {
return OctoPrint.issueCommand(printheadUrl, command, payload, opts);
var OctoPrintPrinterClient = function(base) {
this.base = base;
};
var issueToolCommand = function (command, payload, opts) {
return OctoPrint.issueCommand(toolUrl, command, payload, opts);
OctoPrintPrinterClient.prototype.issuePrintheadCommand = function (command, payload, opts) {
return this.base.issueCommand(printheadUrl, command, payload, opts);
};
var issueBedCommand = function (command, payload, opts) {
return OctoPrint.issueCommand(bedUrl, command, payload, opts);
OctoPrintPrinterClient.prototype.issueToolCommand = function (command, payload, opts) {
return this.base.issueCommand(toolUrl, command, payload, opts);
};
var issueSdCommand = function (command, payload, opts) {
return OctoPrint.issueCommand(sdUrl, command, payload, opts);
OctoPrintPrinterClient.prototype.issueBedCommand = function (command, payload, opts) {
return this.base.issueCommand(bedUrl, command, payload, opts);
};
OctoPrint.printer = {
getFullState: function (flags, opts) {
flags = flags || {};
OctoPrintPrinterClient.prototype.issueSdCommand = function (command, payload, opts) {
return this.base.issueCommand(sdUrl, command, payload, opts);
};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var exclude = flags.exclude || undefined;
OctoPrintPrinterClient.prototype.getFullState = function (flags, opts) {
flags = flags || {};
var getUrl = url;
if (history || exclude) {
getUrl += "?";
if (history) {
getUrl += "history=true&";
if (limit) {
getUrl += "limit=" + limit + "&";
}
}
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var exclude = flags.exclude || undefined;
if (exclude) {
getUrl += "exclude=" + exclude.join(",") + "&";
}
}
return OctoPrint.get(getUrl, opts);
},
getToolState: function (flags, opts) {
flags = flags || {};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var getUrl = toolUrl;
var getUrl = url;
if (history || exclude) {
getUrl += "?";
if (history) {
getUrl += "?history=true";
getUrl += "history=true&";
if (limit) {
getUrl += "&limit=" + limit;
getUrl += "limit=" + limit + "&";
}
}
return OctoPrint.get(getUrl, opts);
},
getBedState: function (flags, opts) {
flags = flags || {};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var getUrl = bedUrl;
if (history) {
getUrl += "?history=true";
if (limit) {
getUrl += "&limit=" + limit;
}
if (exclude) {
getUrl += "exclude=" + exclude.join(",") + "&";
}
return OctoPrint.get(getUrl, opts);
},
getSdState: function (opts) {
return OctoPrint.get(sdUrl, opts);
},
jog: function (params, opts) {
params = params || {};
var absolute = params.absolute || false;
var payload = {absolute: absolute};
if (params.x) payload.x = params.x;
if (params.y) payload.y = params.y;
if (params.z) payload.z = params.z;
if (params.speed !== undefined) payload.speed = params.speed;
return issuePrintheadCommand("jog", payload, opts);
},
home: function (axes, opts) {
axes = axes || [];
var payload = {
axes: axes
};
return issuePrintheadCommand("home", payload, opts);
},
setFeedrate: function (factor, opts) {
factor = factor || 100;
var payload = {
factor: factor
};
return issuePrintheadCommand("feedrate", payload, opts);
},
setToolTargetTemperatures: function (targets, opts) {
targets = targets || {};
var payload = {
targets: targets
};
return issueToolCommand("target", payload, opts);
},
setToolTemperatureOffsets: function (offsets, opts) {
offsets = offsets || {};
var payload = {
offsets: offsets
};
return issueToolCommand("offset", payload, opts);
},
selectTool: function (tool, opts) {
tool = tool || undefined;
var payload = {
tool: tool
};
return issueToolCommand("select", payload, opts);
},
extrude: function (amount, opts) {
amount = amount || undefined;
var payload = {
amount: amount
};
return issueToolCommand("extrude", payload, opts);
},
setFlowrate: function (factor, opts) {
factor = factor || 100;
var payload = {
factor: factor
};
return issueToolCommand("flowrate", payload, opts);
},
setBedTargetTemperature: function (target, opts) {
target = target || 0;
var payload = {
target: target
};
return issueBedCommand("target", payload, opts);
},
setBedTemperatureOffset: function (offset, opts) {
offset = offset || 0;
var payload = {
offset: offset
};
return issueBedCommand("offset", payload, opts);
},
initSd: function (opts) {
return issueSdCommand("init", {}, opts);
},
refreshSd: function (opts) {
return issueSdCommand("refresh", {}, opts);
},
releaseSd: function (opts) {
return issueSdCommand("release", {}, opts);
}
}
return this.base.get(getUrl, opts);
};
OctoPrintPrinterClient.prototype.getToolState = function (flags, opts) {
flags = flags || {};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var getUrl = toolUrl;
if (history) {
getUrl += "?history=true";
if (limit) {
getUrl += "&limit=" + limit;
}
}
return this.base.get(getUrl, opts);
};
OctoPrintPrinterClient.prototype.getBedState = function (flags, opts) {
flags = flags || {};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var getUrl = bedUrl;
if (history) {
getUrl += "?history=true";
if (limit) {
getUrl += "&limit=" + limit;
}
}
return this.base.get(getUrl, opts);
};
OctoPrintPrinterClient.prototype.getSdState = function (opts) {
return this.base.get(sdUrl, opts);
};
OctoPrintPrinterClient.prototype.jog = function (params, opts) {
params = params || {};
var absolute = params.absolute || false;
var payload = {absolute: absolute};
if (params.x) payload.x = params.x;
if (params.y) payload.y = params.y;
if (params.z) payload.z = params.z;
if (params.speed !== undefined) payload.speed = params.speed;
return this.issuePrintheadCommand("jog", payload, opts);
};
OctoPrintPrinterClient.prototype.home = function (axes, opts) {
axes = axes || [];
var payload = {
axes: axes
};
return this.issuePrintheadCommand("home", payload, opts);
};
OctoPrintPrinterClient.prototype.setFeedrate = function (factor, opts) {
factor = factor || 100;
var payload = {
factor: factor
};
return this.issuePrintheadCommand("feedrate", payload, opts);
};
OctoPrintPrinterClient.prototype.setToolTargetTemperatures = function (targets, opts) {
targets = targets || {};
var payload = {
targets: targets
};
return this.issueToolCommand("target", payload, opts);
};
OctoPrintPrinterClient.prototype.setToolTemperatureOffsets = function (offsets, opts) {
offsets = offsets || {};
var payload = {
offsets: offsets
};
return this.issueToolCommand("offset", payload, opts);
};
OctoPrintPrinterClient.prototype.selectTool = function (tool, opts) {
tool = tool || undefined;
var payload = {
tool: tool
};
return this.issueToolCommand("select", payload, opts);
};
OctoPrintPrinterClient.prototype.extrude = function (amount, opts) {
amount = amount || undefined;
var payload = {
amount: amount
};
return this.issueToolCommand("extrude", payload, opts);
};
OctoPrintPrinterClient.prototype.setFlowrate = function (factor, opts) {
factor = factor || 100;
var payload = {
factor: factor
};
return this.issueToolCommand("flowrate", payload, opts);
};
OctoPrintPrinterClient.prototype.setBedTargetTemperature = function (target, opts) {
target = target || 0;
var payload = {
target: target
};
return this.issueBedCommand("target", payload, opts);
};
OctoPrintPrinterClient.prototype.setBedTemperatureOffset = function (offset, opts) {
offset = offset || 0;
var payload = {
offset: offset
};
return this.issueBedCommand("offset", payload, opts);
};
OctoPrintPrinterClient.prototype.initSd = function (opts) {
return this.issueSdCommand("init", {}, opts);
};
OctoPrintPrinterClient.prototype.refreshSd = function (opts) {
return this.issueSdCommand("refresh", {}, opts);
};
OctoPrintPrinterClient.prototype.releaseSd = function (opts) {
return this.issueSdCommand("release", {}, opts);
};
OctoPrintClient.registerComponent("printer", OctoPrintPrinterClient);
return OctoPrintPrinterClient;
});
@@ -1,46 +1,51 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery"], factory);
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(window.OctoPrint, window.$);
factory(global.OctoPrintClient, global.$);
}
})(window || this, function(OctoPrint, $) {
})(this, function(OctoPrintClient, $) {
var url = "api/printerprofiles";
var profileUrl = function(profile) {
return url + "/" + profile;
};
OctoPrint.printerprofiles = {
list: function (opts) {
return OctoPrint.get(url, opts);
},
var OctoPrintPrinterProfileClient = function(base) {
this.base = base;
};
add: function (profile, basedOn, opts) {
profile = profile || {};
OctoPrintPrinterProfileClient.prototype.list = function (opts) {
return this.base.get(url, opts);
};
var data = {profile: profile};
if (basedOn) {
data.basedOn = basedOn;
}
OctoPrintPrinterProfileClient.prototype.add = function (profile, basedOn, opts) {
profile = profile || {};
return OctoPrint.postJson(url, data, opts);
},
get: function (id, opts) {
return OctoPrint.get(profileUrl(id), opts);
},
update: function (id, profile, opts) {
profile = profile || {};
var data = {profile: profile};
return OctoPrint.patchJson(profileUrl(id), data, opts);
},
delete: function (id, opts) {
return OctoPrint.delete(profileUrl(id), opts);
var data = {profile: profile};
if (basedOn) {
data.basedOn = basedOn;
}
}
return this.base.postJson(url, data, opts);
};
OctoPrintPrinterProfileClient.prototype.get = function (id, opts) {
return this.base.get(profileUrl(id), opts);
};
OctoPrintPrinterProfileClient.prototype. update = function (id, profile, opts) {
profile = profile || {};
var data = {profile: profile};
return this.base.patchJson(profileUrl(id), data, opts);
};
OctoPrintPrinterProfileClient.prototype.delete = function (id, opts) {
return this.base.delete(profileUrl(id), opts);
};
OctoPrintClient.registerComponent("printerprofiles", OctoPrintPrinterProfileClient);
return OctoPrintPrinterProfileClient;
});
+31 -29
View File
@@ -1,43 +1,45 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery"], factory);
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(window.OctoPrint, window.$);
factory(global.OctoPrintClient, global.$);
}
})(window || this, function(OctoPrint, $) {
})(this, function(OctoPrintClient, $) {
var url = "api/settings";
var get = function(opts) {
return OctoPrint.get(url, opts);
var OctoPrintSettingsClient = function(base) {
this.base = base;
};
var save = function(settings, opts) {
OctoPrintSettingsClient.prototype.get = function(opts) {
return this.base.get(url, opts);
};
OctoPrintSettingsClient.prototype.save = function(settings, opts) {
settings = settings || {};
return OctoPrint.postJson(url, settings, opts);
return this.base.postJson(url, settings, opts);
};
OctoPrint.settings = {
get: get,
save: save,
OctoPrintSettingsClient.prototype.getPluginSettings = function (plugin, opts) {
return this.get(opts)
.then(function (settings, statusText, request) {
if (!settings.plugins || !settings.plugins[plugin]) {
return $.Deferred()
.reject(request, "dataerror", "No settings for plugin " + plugin)
.promise();
} else {
return settings.plugins[plugin];
}
});
};
getPluginSettings: function (plugin, opts) {
return get(opts)
.then(function (settings, statusText, request) {
if (!settings.plugins || !settings.plugins[plugin]) {
return $.Deferred()
.reject(request, "dataerror", "No settings for plugin " + plugin)
.promise();
} else {
return settings.plugins[plugin];
}
});
},
OctoPrintSettingsClient.prototype.savePluginSettings = function (plugin, settings, opts) {
var data = {};
data["plugins"] = {};
data["plugins"][plugin] = settings;
return this.save(data, opts);
};
savePluginSettings: function (plugin, settings, opts) {
var data = {};
data["plugins"] = {};
data["plugins"][plugin] = settings;
return save(data, opts);
}
}
OctoPrintClient.registerComponent("settings", OctoPrintSettingsClient);
return OctoPrintSettingsClient;
});
+30 -25
View File
@@ -1,10 +1,10 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/slicing";
var slicerUrl = function(slicer) {
@@ -15,31 +15,36 @@
return slicerUrl(slicer) + "/profiles/" + profileId;
};
OctoPrint.slicing = {
listAllSlicersAndProfiles: function(opts) {
return OctoPrint.get(url, opts);
},
var OctoPrintSlicingClient = function(base) {
this.base = base;
};
listProfilesForSlicer: function(slicer, opts) {
return OctoPrint.get(slicerUrl(slicer) + "/profiles", opts);
},
OctoPrintSlicingClient.prototype.listAllSlicersAndProfiles = function(opts) {
return this.base.get(url, opts);
};
getProfileForSlicer: function(slicer, profileId, opts) {
return OctoPrint.get(profileUrl(slicer, profileId), opts);
},
OctoPrintSlicingClient.prototype.listProfilesForSlicer = function(slicer, opts) {
return this.base.get(slicerUrl(slicer) + "/profiles", opts);
};
addProfileForSlicer: function(slicer, profileId, profile, opts) {
profile = profile || {};
return OctoPrint.putJson(profileUrl(slicer, profileId), profile, opts);
},
OctoPrintSlicingClient.prototype.getProfileForSlicer = function(slicer, profileId, opts) {
return this.base.get(profileUrl(slicer, profileId), opts);
};
updateProfileForSlicer: function(slicer, profileId, profile, opts) {
profile = profile || {};
return OctoPrint.patchJson(profileUrl(slicer, profileId), profile, opts);
},
OctoPrintSlicingClient.prototype.addProfileForSlicer = function(slicer, profileId, profile, opts) {
profile = profile || {};
return this.base.putJson(profileUrl(slicer, profileId), profile, opts);
};
deleteProfileForSlicer: function(slicer, profileId, opts) {
return OctoPrint.delete(profileUrl(slicer, profileId), opts);
}
}
OctoPrintSlicingClient.prototype.updateProfileForSlicer = function(slicer, profileId, profile, opts) {
profile = profile || {};
return this.base.patchJson(profileUrl(slicer, profileId), profile, opts);
};
OctoPrintSlicingClient.prototype.deleteProfileForSlicer = function(slicer, profileId, opts) {
return this.base.delete(profileUrl(slicer, profileId), opts);
};
OctoPrintClient.registerComponent("slicing", OctoPrintSlicingClient);
return OctoPrintSlicingClient;
});
+102 -100
View File
@@ -1,59 +1,33 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery", "lodash", "sockjs"], factory);
define(["OctoPrintClient", "jquery", "lodash", "sockjs"], factory);
} else {
factory(window.OctoPrint, window.$, window._, window.SockJS);
factory(global.OctoPrintClient, global.$, global._, global.SockJS);
}
})(window || this, function(OctoPrint, $, _, SockJS) {
var exports = {};
exports.options = {
timeouts: [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100],
rateSlidingWindowSize: 20
};
})(this, function(OctoPrintClient, $, _, SockJS) {
var normalClose = 1000;
var socket = undefined;
var reconnecting = false;
var reconnectTrial = 0;
var registeredHandlers = {};
var OctoPrintSocketClient = function(base) {
this.base = base;
var rateThrottleFactor = 1;
var rateBase = 500;
var rateLastMeasurements = [];
this.options = {
timeouts: [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100],
rateSlidingWindowSize: 20
};
var onOpen = function() {
reconnecting = false;
reconnectTrial = 0;
this.socket = undefined;
this.reconnecting = false;
this.reconnectTrial = 0;
this.registeredHandlers = {};
this.rateThrottleFactor = 1;
this.rateBase = 500;
this.rateLastMeasurements = [];
};
var onClose = function(e) {
if (e.code == normalClose) {
return;
}
if (exports.onReconnectAttempt(reconnectTrial)) {
return;
}
if (reconnectTrial < exports.options.timeouts.length) {
var timeout = exports.options.timeouts[reconnectTrial];
setTimeout(exports.reconnect, timeout * 1000);
reconnectTrial++;
} else {
exports.onReconnectFailed();
}
};
var onMessage = function(msg) {
_.each(msg.data, function(data, key) {
propagateMessage(key, data);
});
};
var propagateMessage = function(event, data) {
if (!registeredHandlers.hasOwnProperty(event)) {
OctoPrintSocketClient.prototype.propagateMessage = function(event, data) {
if (!this.registeredHandlers.hasOwnProperty(event)) {
return;
}
@@ -61,14 +35,14 @@
var eventObj = {event: event, data: data};
var catchAllHandlers = registeredHandlers["*"];
var catchAllHandlers = this.registeredHandlers["*"];
if (catchAllHandlers && catchAllHandlers.length) {
_.each(catchAllHandlers, function(handler) {
handler(eventObj);
});
}
var handlers = registeredHandlers[event];
var handlers = this.registeredHandlers[event];
if (handlers && handlers.length) {
_.each(handlers, function(handler) {
handler(eventObj);
@@ -76,100 +50,128 @@
}
var end = new Date().getTime();
analyzeTiming(end - start);
this.analyzeTiming(end - start);
};
var analyzeTiming = function(measurement) {
while (rateLastMeasurements.length >= exports.options.rateSlidingWindowSize) {
rateLastMeasurements.shift();
OctoPrintSocketClient.prototype.analyzeTiming = function(measurement) {
while (this.rateLastMeasurements.length >= this.options.rateSlidingWindowSize) {
this.rateLastMeasurements.shift();
}
rateLastMeasurements.push(measurement);
this.rateLastMeasurements.push(measurement);
var processingLimit = rateThrottleFactor * rateBase;
var processingLimit = this.rateThrottleFactor * this.rateBase;
if (measurement > processingLimit) {
exports.onRateTooHigh(measurement, processingLimit);
} else if (rateThrottleFactor > 1) {
var maxProcessingTime = Math.max.apply(null, rateLastMeasurements);
var lowerProcessingLimit = (rateThrottleFactor - 1) * rateBase;
this.onRateTooHigh(measurement, processingLimit);
} else if (this.rateThrottleFactor > 1) {
var maxProcessingTime = Math.max.apply(null, this.rateLastMeasurements);
var lowerProcessingLimit = (this.rateThrottleFactor - 1) * this.rateBase;
if (maxProcessingTime < lowerProcessingLimit) {
exports.onRateTooLow(maxProcessingTime, lowerProcessingLimit);
this.onRateTooLow(maxProcessingTime, lowerProcessingLimit);
}
}
};
var increaseRate = function() {
if (rateThrottleFactor <= 1) {
rateThrottleFactor = 1;
OctoPrintSocketClient.prototype.increaseRate = function() {
if (this.rateThrottleFactor <= 1) {
this.rateThrottleFactor = 1;
return;
}
rateThrottleFactor--;
sendThrottleFactor();
this.rateThrottleFactor--;
this.sendThrottleFactor();
};
var decreaseRate = function() {
rateThrottleFactor++;
sendThrottleFactor();
OctoPrintSocketClient.prototype.decreaseRate = function() {
this.rateThrottleFactor++;
this.sendThrottleFactor();
};
var sendThrottleFactor = function() {
sendMessage("throttle", rateThrottleFactor);
OctoPrintSocketClient.prototype.sendThrottleFactor = function() {
this.sendMessage("throttle", this.rateThrottleFactor);
};
var sendMessage = function(type, payload) {
OctoPrintSocketClient.prototype.sendMessage = function(type, payload) {
var data = {};
data[type] = payload;
socket.send(JSON.stringify(data));
this.socket.send(JSON.stringify(data));
};
exports.connect = function(opts) {
OctoPrintSocketClient.prototype.connect = function(opts) {
opts = opts || {};
exports.disconnect();
this.disconnect();
var url = OctoPrint.options.baseurl;
var url = this.base.options.baseurl;
if (!_.endsWith(url, "/")) {
url += "/";
}
socket = new SockJS(url + "sockjs", undefined, opts);
socket.onopen = onOpen;
socket.onclose = onClose;
socket.onmessage = onMessage;
var self = this;
var onOpen = function() {
self.reconnecting = false;
self.reconnectTrial = 0;
};
var onClose = function(e) {
if (e.code == normalClose) {
return;
}
if (self.onReconnectAttempt(self.reconnectTrial)) {
return;
}
if (self.reconnectTrial < self.options.timeouts.length) {
var timeout = self.options.timeouts[self.reconnectTrial];
setTimeout(function() { self.reconnect() }, timeout * 1000);
self.reconnectTrial++;
} else {
self.onReconnectFailed();
}
};
var onMessage = function(msg) {
_.each(msg.data, function(data, key) {
self.propagateMessage(key, data);
});
};
this.socket = new SockJS(url + "sockjs", undefined, opts);
this.socket.onopen = onOpen;
this.socket.onclose = onClose;
this.socket.onmessage = onMessage;
};
exports.reconnect = function() {
exports.disconnect();
socket = undefined;
exports.connect();
OctoPrintSocketClient.prototype.reconnect = function() {
this.disconnect();
this.socket = undefined;
this.connect();
};
exports.disconnect = function() {
if (socket != undefined) {
socket.close();
OctoPrintSocketClient.prototype.disconnect = function() {
if (this.socket != undefined) {
this.socket.close();
}
};
exports.onMessage = function(message, handler) {
if (!registeredHandlers.hasOwnProperty(message)) {
registeredHandlers[message] = [];
OctoPrintSocketClient.prototype.onMessage = function(message, handler) {
if (!this.registeredHandlers.hasOwnProperty(message)) {
this.registeredHandlers[message] = [];
}
registeredHandlers[message].push(handler);
return exports;
this.registeredHandlers[message].push(handler);
return this;
};
exports.onReconnectAttempt = function(trial) {};
exports.onReconnectFailed = function() {};
OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {};
OctoPrintSocketClient.prototype.onReconnectFailed = function() {};
exports.onRateTooLow = function(measured, minimum) {
increaseRate();
OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) {
this.increaseRate();
};
exports.onRateTooHigh = function(measured, maximum) {
decreaseRate();
OctoPrintSocketClient.prototype.onRateTooHigh = function(measured, maximum) {
this.decreaseRate();
};
exports.increaseRate = increaseRate;
exports.decreaseRate = decreaseRate;
exports.sendMessage = sendMessage;
OctoPrint.socket = exports;
OctoPrintClient.registerComponent("socket", OctoPrintSocketClient);
return OctoPrintSocketClient;
});
+20 -15
View File
@@ -1,24 +1,29 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/system";
var commandUrl = "api/system/commands";
OctoPrint.system = {
getCommands: function (opts) {
return OctoPrint.get(commandUrl, opts);
},
getCommandsForSource: function (source, opts) {
return OctoPrint.get(commandUrl + "/" + source, opts);
},
executeCommand: function (source, action, opts) {
return OctoPrint.postJson(commandUrl + "/" + source + "/" + action, {}, opts);
}
var OctoPrintSystemClient = function(base) {
this.base = base;
};
OctoPrintSystemClient.prototype.getCommands = function (opts) {
return this.base.get(commandUrl, opts);
};
OctoPrintSystemClient.prototype.getCommandsForSource = function (source, opts) {
return this.base.get(commandUrl + "/" + source, opts);
};
OctoPrintSystemClient.prototype.executeCommand = function (source, action, opts) {
return this.base.postJson(commandUrl + "/" + source + "/" + action, {}, opts);
};
OctoPrintClient.registerComponent("system", OctoPrintSystemClient);
return OctoPrintSystemClient;
});
+74 -71
View File
@@ -1,10 +1,10 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery"], factory);
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(window.OctoPrint, window.$);
factory(global.OctoPrintClient, global.$);
}
})(window || this, function(OctoPrint, $) {
})(this, function(OctoPrintClient, $) {
var url = "api/timelapse";
var downloadUrl = "downloads/timelapse";
@@ -21,93 +21,96 @@
return url + "/unrendered/" + name;
};
var getTimelapseData = function (unrendered, opts) {
var OctoPrintTimelapseClient = function(base) {
this.base = base;
};
OctoPrintTimelapseClient.prototype.get = function (unrendered, opts) {
if (unrendered) {
opts = opts || {};
opts.data = {unrendered: unrendered};
}
return OctoPrint.get(url, opts);
return this.base.get(url, opts);
};
OctoPrint.timelapse = {
get: getTimelapseData,
OctoPrintTimelapseClient.prototype.list = function(opts) {
var deferred = $.Deferred();
list: function(opts) {
var deferred = $.Deferred();
this.get(true, opts)
.done(function (response, status, request) {
deferred.resolve({
rendered: response.files,
unrendered: response.unrendered
}, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
getTimelapseData(true, opts)
.done(function (response, status, request) {
deferred.resolve({
rendered: response.files,
unrendered: response.unrendered
}, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
};
return deferred.promise();
},
OctoPrintTimelapseClient.prototype.listRendered = function (opts) {
var deferred = $.Deferred();
listRendered: function (opts) {
var deferred = $.Deferred();
this.get(false, opts)
.done(function (response, status, request) {
deferred.resolve(response.files, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
getTimelapseData(false, opts)
.done(function (response, status, request) {
deferred.resolve(response.files, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
};
return deferred.promise();
},
OctoPrintTimelapseClient.prototype.listUnrendered = function (opts) {
var deferred = $.Deferred();
listUnrendered: function (opts) {
var deferred = $.Deferred();
this.get(true, opts)
.done(function (response, status, request) {
deferred.resolve(response.unrendered, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
getTimelapseData(true, opts)
.done(function (response, status, request) {
deferred.resolve(response.unrendered, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
};
return deferred.promise();
},
OctoPrintTimelapseClient.prototype.download = function (filename, opts) {
return this.base.download(timelapseDownloadUrl(filename), opts);
};
download: function (filename, opts) {
return OctoPrint.download(timelapseDownloadUrl(filename), opts);
},
OctoPrintTimelapseClient.prototype.delete = function (filename, opts) {
return this.base.delete(timelapseUrl(filename), opts);
};
delete: function (filename, opts) {
return OctoPrint.delete(timelapseUrl(filename), opts);
},
OctoPrintTimelapseClient.prototype.deleteUnrendered = function(name, opts) {
return this.base.delete(unrenderedTimelapseUrl(name), opts);
};
deleteUnrendered: function(name, opts) {
return OctoPrint.delete(unrenderedTimelapseUrl(name), opts);
},
OctoPrintTimelapseClient.prototype.renderUnrendered = function(name, opts) {
return this.base.issueCommand(unrenderedTimelapseUrl(name), "render");
};
renderUnrendered: function(name, opts) {
return OctoPrint.issueCommand(unrenderedTimelapseUrl(name), "render");
},
OctoPrintTimelapseClient.prototype.getConfig = function (opts) {
var deferred = $.Deferred();
this.get(false, opts)
.done(function (response, status, request) {
deferred.resolve(response.config, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
};
getConfig: function (opts) {
var deferred = $.Deferred();
getTimelapseData(false, opts)
.done(function (response, status, request) {
deferred.resolve(response.config, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
},
OctoPrintTimelapseClient.prototype.saveConfig = function (config, opts) {
config = config || {};
return OctoPrint.postJson(url, config, opts);
};
saveConfig: function (config, opts) {
config = config || {};
return OctoPrint.postJson(url, config, opts);
}
}
OctoPrintClient.registerComponent("timelapse", OctoPrintTimelapseClient);
return OctoPrintTimelapseClient;
});
+99 -94
View File
@@ -1,10 +1,10 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var baseUrl = "api/users";
var url = function() {
@@ -15,96 +15,101 @@
}
};
OctoPrint.users = {
list: function (opts) {
return OctoPrint.get(url(), opts);
},
add: function (user, opts) {
if (!user.name || !user.password) {
throw new OctoPrint.InvalidArgumentError("Both user's name and password need to be set");
}
var data = {
name: user.name,
password: user.password,
active: user.hasOwnProperty("active") ? !!user.active : true,
admin: user.hasOwnProperty("admin") ? !!user.admin : false
};
return OctoPrint.postJson(url(), data, opts);
},
get: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.get(url(name), opts);
},
update: function (name, active, admin, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
var data = {
active: !!active,
admin: !!admin
};
return OctoPrint.putJson(url(name), data, opts);
},
delete: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.delete(url(name), opts);
},
changePassword: function (name, password, opts) {
if (!name || !password) {
throw new OctoPrint.InvalidArgumentError("user name and password must be set");
}
var data = {
password: password
};
return OctoPrint.putJson(url(name, "password"), data, opts);
},
generateApiKey: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.postJson(url(name, "apikey"), opts);
},
resetApiKey: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.delete(url(name, "apikey"), opts);
},
getSettings: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.get(url(name, "settings"), opts);
},
saveSettings: function (name, settings, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
settings = settings || {};
return OctoPrint.patchJson(url(name, "settings"), settings, opts);
}
var OctoPrintUserClient = function(base) {
this.base = base;
};
OctoPrintUserClient.prototype.list = function (opts) {
return this.base.get(url(), opts);
};
OctoPrintUserClient.prototype.add = function (user, opts) {
if (!user.name || !user.password) {
throw new OctoPrintClient.InvalidArgumentError("Both user's name and password need to be set");
}
var data = {
name: user.name,
password: user.password,
active: user.hasOwnProperty("active") ? !!user.active : true,
admin: user.hasOwnProperty("admin") ? !!user.admin : false
};
return this.base.postJson(url(), data, opts);
};
OctoPrintUserClient.prototype.get = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.get(url(name), opts);
};
OctoPrintUserClient.prototype.update = function (name, active, admin, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
var data = {
active: !!active,
admin: !!admin
};
return this.base.putJson(url(name), data, opts);
};
OctoPrintUserClient.prototype.delete = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.delete(url(name), opts);
};
OctoPrintUserClient.prototype.changePassword = function (name, password, opts) {
if (!name || !password) {
throw new OctoPrintClient.InvalidArgumentError("user name and password must be set");
}
var data = {
password: password
};
return this.base.putJson(url(name, "password"), data, opts);
};
OctoPrintUserClient.prototype.generateApiKey = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.postJson(url(name, "apikey"), opts);
};
OctoPrintUserClient.prototype.resetApiKey = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.delete(url(name, "apikey"), opts);
};
OctoPrintUserClient.prototype.getSettings = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.get(url(name, "settings"), opts);
};
OctoPrintUserClient.prototype.saveSettings = function (name, settings, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
settings = settings || {};
return this.base.patchJson(url(name, "settings"), settings, opts);
};
OctoPrintClient.registerComponent("users", OctoPrintUserClient);
return OctoPrintUserClient;
});
+39 -36
View File
@@ -1,47 +1,50 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery"], factory);
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(window.OctoPrint, window.$);
factory(global.OctoPrintClient, global.$);
}
})(window || this, function(OctoPrint, $) {
})(this, function(OctoPrint, $) {
var url = "api/util";
var testUrl = url + "/test";
var test = function(command, parameters, opts) {
return OctoPrint.issueCommand(testUrl, command, parameters, opts);
var OctoPrintUtilClient = function(base) {
this.base = base;
};
OctoPrint.util = {
test: test,
testPath: function(path, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.path = path;
return test("path", data, opts);
},
testExecutable: function(path, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.path = path;
data.check_type = "file";
data.check_access = "x";
return test("path", data, opts);
},
testUrl: function(url, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.url = url;
return test("url", data, opts);
}
OctoPrintUtilClient.prototype.test = function(command, parameters, opts) {
return this.base.issueCommand(testUrl, command, parameters, opts);
};
OctoPrintUtilClient.prototype.testPath = function(path, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.path = path;
return this.test("path", data, opts);
};
OctoPrintUtilClient.prototype.testExecutable = function(path, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.path = path;
data.check_type = "file";
data.check_access = "x";
return this.test("path", data, opts);
};
OctoPrintUtilClient.prototype.testUrl = function(url, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.url = url;
return this.test("url", data, opts);
};
OctoPrintClient.registerComponent("util", OctoPrintUtilClient);
return OctoPrintUtilClient;
});
+16 -10
View File
@@ -1,18 +1,24 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/setup/wizard";
OctoPrint.wizard = {
get: function(opts) {
return OctoPrint.get(url, opts);
},
finish: function(handled, opts) {
return OctoPrint.postJson(url, {handled: handled || []}, opts);
}
var OctoPrintWizardClient = function(base) {
this.base = base;
};
OctoPrintWizardClient.prototype.get = function(opts) {
return this.base.get(url, opts);
};
OctoPrintWizardClient.prototype.finish = function(handled, opts) {
return this.base.postJson(url, {handled: handled || []}, opts);
};
OctoPrintClient.registerComponent("wizard", OctoPrintWizardClient);
return OctoPrintWizardClient;
});
@@ -174,7 +174,7 @@ $(function() {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets()) {
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
var offsets = [];
_.each(currentProfileData.extruder.offsets(), function(offset) {
offsets.push({x: offset[0], y: offset[1]})
@@ -25,7 +25,8 @@ $(function() {
offsets: [
[0,0]
],
nozzleDiameter: 0.4
nozzleDiameter: 0.4,
sharedNozzle: false
}
}
};
@@ -63,6 +64,7 @@ $(function() {
self.nozzleDiameter = ko.observable();
self.extruders = ko.observable();
self.extruderOffsets = ko.observableArray();
self.sharedNozzle = ko.observable();
self.axisXSpeed = ko.observable();
self.axisYSpeed = ko.observable();
@@ -209,6 +211,7 @@ $(function() {
self.heatedBed(data.heatedBed);
self.nozzleDiameter(data.extruder.nozzleDiameter);
self.sharedNozzle(data.extruder.sharedNozzle);
self.extruders(data.extruder.count);
var offsets = [];
if (data.extruder.count > 1) {
@@ -271,7 +274,8 @@ $(function() {
offsets: [
[0.0, 0.0]
],
nozzleDiameter: validFloat(self.nozzleDiameter(), defaultProfile.extruder.nozzleDiameter)
nozzleDiameter: validFloat(self.nozzleDiameter(), defaultProfile.extruder.nozzleDiameter),
sharedNozzle: self.sharedNozzle()
},
axes: {
x: {
@@ -49,7 +49,8 @@ $(function() {
// tools
var currentProfileData = self.settingsViewModel.printerProfiles.currentProfileData();
var numExtruders = (currentProfileData ? currentProfileData.extruder.count() : 0);
if (numExtruders && numExtruders > 1) {
var sharedNozzle = (currentProfileData ? currentProfileData.extruder.sharedNozzle() : false);
if (numExtruders && numExtruders > 1 && !sharedNozzle) {
// multiple extruders
for (var extruder = 0; extruder < numExtruders; extruder++) {
color = graphColors.shift();
@@ -62,7 +63,7 @@ $(function() {
tools[extruder]["name"](gettext("Tool") + " " + extruder);
tools[extruder]["key"]("tool" + extruder);
}
} else if (numExtruders == 1) {
} else if (numExtruders == 1 || sharedNozzle) {
// only one extruder, no need to add numbers
color = graphColors[0];
heaterOptions["tool0"] = {name: "T", color: color};
+7 -7
View File
@@ -1,8 +1,8 @@
/*!
* Less - Leaner CSS v2.7.1
* Less - Leaner CSS v2.7.2
* http://lesscss.org
*
* Copyright (c) 2009-2016, Alexis Sellier <self@cloudhead.net>
* Copyright (c) 2009-2017, Alexis Sellier <self@cloudhead.net>
* Licensed under the Apache-2.0 License.
*
*/
@@ -10,8 +10,8 @@
/** * @license Apache-2.0
*/
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.less=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;d.length>g;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./utils").addDataAttr,e=a("./browser");b.exports=function(a,b){d(b,e.currentScript(a)),void 0===b.isFileProtocol&&(b.isFileProtocol=/^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(a.location.protocol)),b.async=b.async||!1,b.fileAsync=b.fileAsync||!1,b.poll=b.poll||(b.isFileProtocol?1e3:1500),b.env=b.env||("127.0.0.1"==a.location.hostname||"0.0.0.0"==a.location.hostname||"localhost"==a.location.hostname||a.location.port&&a.location.port.length>0||b.isFileProtocol?"development":"production");var c=/!dumpLineNumbers:(comments|mediaquery|all)/.exec(a.location.hash);c&&(b.dumpLineNumbers=c[1]),void 0===b.useFileCache&&(b.useFileCache=!0),void 0===b.onReady&&(b.onReady=!0)}},{"./browser":3,"./utils":10}],2:[function(a,b,c){function d(a){a.filename&&console.warn(a),e.async||h.removeChild(i)}a("promise/polyfill.js");var e=window.less||{};a("./add-default-options")(window,e);var f=b.exports=a("./index")(window,e);window.less=f;var g,h,i;e.onReady&&(/!watch/.test(window.location.hash)&&f.watch(),e.async||(g="body { display: none !important }",h=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style"),i.type="text/css",i.styleSheet?i.styleSheet.cssText=g:i.appendChild(document.createTextNode(g)),h.appendChild(i)),f.registerStylesheetsImmediately(),f.pageLoadFinished=f.refresh("development"===f.env).then(d,d))},{"./add-default-options":1,"./index":8,"promise/polyfill.js":97}],3:[function(a,b,c){var d=a("./utils");b.exports={createCSS:function(a,b,c){var e=c.href||"",f="less:"+(c.title||d.extractId(e)),g=a.getElementById(f),h=!1,i=a.createElement("style");i.setAttribute("type","text/css"),c.media&&i.setAttribute("media",c.media),i.id=f,i.styleSheet||(i.appendChild(a.createTextNode(b)),h=null!==g&&g.childNodes.length>0&&i.childNodes.length>0&&g.firstChild.nodeValue===i.firstChild.nodeValue);var j=a.getElementsByTagName("head")[0];if(null===g||h===!1){var k=c&&c.nextSibling||null;k?k.parentNode.insertBefore(i,k):j.appendChild(i)}if(g&&h===!1&&g.parentNode.removeChild(g),i.styleSheet)try{i.styleSheet.cssText=b}catch(l){throw new Error("Couldn't reassign styleSheet.cssText.")}},currentScript:function(a){var b=a.document;return b.currentScript||function(){var a=b.getElementsByTagName("script");return a[a.length-1]}()}}},{"./utils":10}],4:[function(a,b,c){b.exports=function(a,b,c){var d=null;if("development"!==b.env)try{d="undefined"==typeof a.localStorage?null:a.localStorage}catch(e){}return{setCSS:function(a,b,e,f){if(d){c.info("saving "+a+" to cache.");try{d.setItem(a,f),d.setItem(a+":timestamp",b),e&&d.setItem(a+":vars",JSON.stringify(e))}catch(g){c.error('failed to save "'+a+'" to local storage for caching.')}}},getCSS:function(a,b,c){var e=d&&d.getItem(a),f=d&&d.getItem(a+":timestamp"),g=d&&d.getItem(a+":vars");return c=c||{},f&&b.lastModified&&new Date(b.lastModified).valueOf()===new Date(f).valueOf()&&(!c&&!g||JSON.stringify(c)===g)?e:void 0}}}},{}],5:[function(a,b,c){var d=a("./utils"),e=a("./browser");b.exports=function(a,b,c){function f(b,f){var g,h,i="less-error-message:"+d.extractId(f||""),j='<li><label>{line}</label><pre class="{class}">{content}</pre></li>',k=a.document.createElement("div"),l=[],m=b.filename||f,n=m.match(/([^\/]+(\?.*)?)$/)[1];k.id=i,k.className="less-error-message",h="<h3>"+(b.type||"Syntax")+"Error: "+(b.message||"There is an error in your .less file")+'</h3><p>in <a href="'+m+'">'+n+"</a> ";var o=function(a,b,c){void 0!==a.extract[b]&&l.push(j.replace(/\{line\}/,(parseInt(a.line,10)||0)+(b-1)).replace(/\{class\}/,c).replace(/\{content\}/,a.extract[b]))};b.extract&&(o(b,0,""),o(b,1,"line"),o(b,2,""),h+="on line "+b.line+", column "+(b.column+1)+":</p><ul>"+l.join("")+"</ul>"),b.stack&&(b.extract||c.logLevel>=4)&&(h+="<br/>Stack Trace</br />"+b.stack.split("\n").slice(1).join("<br/>")),k.innerHTML=h,e.createCSS(a.document,[".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-right: 15px;","padding: 4px 0;","margin: 0;","}",".less-error-message label {","font-size: 12px;","margin-right: 15px;","padding: 4px 0;","color: #cc7777;","}",".less-error-message pre {","color: #dd6666;","padding: 4px 0;","margin: 0;","display: inline-block;","}",".less-error-message pre.line {","cLine truncated
}})},{"../tree/anonymous":46,"../tree/javascript":63,"../tree/quoted":73,"./function-registry":22}],28:[function(a,b,c){b.exports=function(b){var c=a("../tree/dimension"),d=a("../tree/color"),e=a("../tree/expression"),f=a("../tree/quoted"),g=a("../tree/url"),h=a("./function-registry");h.add("svg-gradient",function(a){function b(){throw{type:"Argument",message:"svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position] or direction, color list"}}var h,i,j,k,l,m,n,o,p="linear",q='x="0" y="0" width="1" height="1"',r={compress:!1},s=a.toCSS(r);switch(2==arguments.length?(2>arguments[1].value.length&&b(),h=arguments[1].value):3>arguments.length?b():h=Array.prototype.slice.call(arguments,1),s){case"to bottom":i='x1="0%" y1="0%" x2="0%" y2="100%"';break;case"to right":i='x1="0%" y1="0%" x2="100%" y2="0%"';break;case"to bottom right":i='x1="0%" y1="0%" x2="100%" y2="100%"';break;case"to top right":i='x1="0%" y1="100%" x2="100%" y2="0%"';break;case"ellipse":case"ellipse at center":p="radial",i='cx="50%" cy="50%" r="75%"',q='x="-50" y="-50" width="101" height="101"';break;default:throw{type:"Argument",message:"svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'"}}for(j='<?xml version="1.0" ?><svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><'+p+'Gradient id="gradient" gradientUnits="userSpaceOnUse" '+i+">",k=0;h.length>k;k+=1)h[k]instanceof e?(l=h[k].value[0],m=h[k].value[1]):(l=h[k],m=void 0),l instanceof d&&((0===k||k+1===h.length)&&void 0===m||m instanceof c)||b(),n=m?m.toCSS(r):0===k?"0%":"100%",o=l.alpha,j+='<stop offset="'+n+'" stop-color="'+l.toRGB()+'"'+(1>o?' stop-opacity="'+o+'"':"")+"/>";return j+="</"+p+"Gradient><rect "+q+' fill="url(#gradient)" /></svg>',j=encodeURIComponent(j),j="data:image/svg+xml,"+j,new g(new f("'"+j+"'",j,!1,this.index,this.currentFileInfo),this.index,this.currentFileInfo)})}},{"../tree/color":50,"../tree/dimension":56,"../tree/expression":59,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],29:[function(a,b,c){var d=a("../tree/keyword"),e=a("../tree/detached-ruleset"),f=a("../tree/dimension"),g=a("../tree/color"),h=a("../tree/quoted"),i=a("../tree/anonymous"),j=a("../tree/url"),k=a("../tree/operation"),l=a("./function-registry"),m=function(a,b){return a instanceof b?d.True:d.False},n=function(a,b){if(void 0===b)throw{type:"Argument",message:"missing the required second argument to isunit."};if(b="string"==typeof b.value?b.value:b,"string"!=typeof b)throw{type:"Argument",message:"Second argument to isunit should be a unit or a string."};return a instanceof f&&a.unit.is(b)?d.True:d.False},o=function(a){var b=Array.isArray(a.value)?a.value:Array(a);return b};l.addMultiple({isruleset:function(a){return m(a,e)},iscolor:function(a){return m(a,g)},isnumber:function(a){return m(a,f)},isstring:function(a){return m(a,h)},iskeyword:function(a){return m(a,d)},isurl:function(a){return m(a,j)},ispixel:function(a){return n(a,"px")},ispercentage:function(a){return n(a,"%")},isem:function(a){return n(a,"em")},isunit:n,unit:function(a,b){if(!(a instanceof f))throw{type:"Argument",message:"the first argument to unit must be a number"+(a instanceof k?". Have you forgotten parenthesis?":"")};return b=b?b instanceof d?b.value:b.toCSS():"",new f(a.value,b)},"get-unit":function(a){return new i(a.unit)},extract:function(a,b){return b=b.value-1,o(a)[b]},length:function(a){return new f(o(a).length)}})},{"../tree/anonymous":46,"../tree/color":50,"../tree/detached-ruleset":55,"../tree/dimension":56,"../tree/keyword":65,"../tree/operation":71,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],30:[function(a,b,c){var d=a("./contexts"),e=a("./parser/parser"),f=a("./plugins/function-importer");b.exports=function(a){var b=function(a,b){this.rootFilename=b.filename,this.paths=a.paths||[],this.contents={},this.contentsIgnoredChars={},this.mime=a.mime,this.error=null,this.context=a,this.queue=[],this.files={}};return b.prototype.push=function(b,c,g,h,i){var j=this;this.queue.push(b);var k=function(a,c,d){j.queue.splice(j.queue.indexOf(b),1);var e=d===j.rootFilename;h.optional&&a?i(null,{rules:[]},!1,null):(j.files[d]=c,a&&!j.error&&(j.error=a),i(a,c,e,d))},l={relativeUrls:this.context.relativeUrls,entryPath:g.entryPath,rootpath:g.rootpath,rootFilename:g.rootFilename},m=a.getFileManager(b,g.currentDirectory,this.context,a);if(!m)return void k({message:"Could not find a file-manager for "+b});c&&(b=m.tryAppendExtension(b,h.plugin?".js":".less"));var n=function(a){var b=a.filename,c=a.contents.replace(/^\uFEFF/,"");l.currentDirectory=m.getPath(b),l.relativeUrls&&(l.rootpath=m.join(j.context.rootpath||"",m.pathDiff(l.currentDirectory,l.entryPath)),!m.isPathAbsolute(l.rootpath)&&m.alwaysMakePathsAbsolute()&&(l.rootpath=m.join(l.entryPath,l.rootpath))),l.filename=b;var i=new d.Parse(j.context);i.processImports=Line truncated
f={add:function(a,b){g[a]=b},addMultiple:function(a){Object.keys(a).forEach(function(b){g[b]=a[b]})}};try{c=new Function("functions","tree","fileInfo",a),c(f,e,this.fileInfo)}catch(h){b(new d({message:"Plugin evaluation error: '"+h.name+": "+h.message.replace(/["]/g,"'")+"'",filename:this.fileInfo.filename}),null)}b(null,{functions:g})}},{"../less-error":32,"../tree":62}],41:[function(a,b,c){var d;b.exports=function(b,c,e){var f=function(b,e,g){if("function"==typeof e&&(g=e,e={}),!g){d||(d="undefined"==typeof Promise?a("promise"):Promise);var h=this;return new d(function(a,c){f.call(h,b,e,function(b,d){b?c(b):a(d)})})}this.parse(b,e,function(a,b,d,e){if(a)return g(a);var f;try{var h=new c(b,d);f=h.toCSS(e)}catch(a){return g(a)}g(null,f)})};return f}},{promise:void 0}],42:[function(a,b,c){b.exports=function(a,b){var c=function(a){this.options=a};return c.prototype.toCSS=function(b,c,d){var e=new a({contentsIgnoredCharsMap:d.contentsIgnoredChars,rootNode:b,contentsMap:d.contents,sourceMapFilename:this.options.sourceMapFilename,sourceMapURL:this.options.sourceMapURL,outputFilename:this.options.sourceMapOutputFilename,sourceMapBasepath:this.options.sourceMapBasepath,sourceMapRootpath:this.options.sourceMapRootpath,outputSourceFiles:this.options.outputSourceFiles,sourceMapGenerator:this.options.sourceMapGenerator,sourceMapFileInline:this.options.sourceMapFileInline}),f=e.toCSS(c);return this.sourceMap=e.sourceMap,this.sourceMapURL=e.sourceMapURL,this.options.sourceMapInputFilename&&(this.sourceMapInputFilename=e.normalizeFilename(this.options.sourceMapInputFilename)),f+this.getCSSAppendage()},c.prototype.getCSSAppendage=function(){var a=this.sourceMapURL;if(this.options.sourceMapFileInline){if(void 0===this.sourceMap)return"";a="data:application/json;base64,"+b.encodeBase64(this.sourceMap)}return a?"/*# sourceMappingURL="+a+" */":""},c.prototype.getExternalSourceMap=function(){return this.sourceMap},c.prototype.setExternalSourceMap=function(a){this.sourceMap=a},c.prototype.isInline=function(){return this.options.sourceMapFileInline},c.prototype.getSourceMapURL=function(){return this.sourceMapURL},c.prototype.getOutputFilename=function(){return this.options.sourceMapOutputFilename},c.prototype.getInputFilename=function(){return this.sourceMapInputFilename},c}},{}],43:[function(a,b,c){b.exports=function(a){var b=function(b){this._css=[],this._rootNode=b.rootNode,this._contentsMap=b.contentsMap,this._contentsIgnoredCharsMap=b.contentsIgnoredCharsMap,b.sourceMapFilename&&(this._sourceMapFilename=b.sourceMapFilename.replace(/\\/g,"/")),this._outputFilename=b.outputFilename,this.sourceMapURL=b.sourceMapURL,b.sourceMapBasepath&&(this._sourceMapBasepath=b.sourceMapBasepath.replace(/\\/g,"/")),b.sourceMapRootpath?(this._sourceMapRootpath=b.sourceMapRootpath.replace(/\\/g,"/"),"/"!==this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1)&&(this._sourceMapRootpath+="/")):this._sourceMapRootpath="",this._outputSourceFiles=b.outputSourceFiles,this._sourceMapGeneratorConstructor=a.getSourceMapGenerator(),this._lineNumber=0,this._column=0};return b.prototype.normalizeFilename=function(a){return a=a.replace(/\\/g,"/"),this._sourceMapBasepath&&0===a.indexOf(this._sourceMapBasepath)&&(a=a.substring(this._sourceMapBasepath.length),"\\"!==a.charAt(0)&&"/"!==a.charAt(0)||(a=a.substring(1))),(this._sourceMapRootpath||"")+a},b.prototype.add=function(a,b,c,d){if(a){var e,f,g,h,i;if(b){var j=this._contentsMap[b.filename];this._contentsIgnoredCharsMap[b.filename]&&(c-=this._contentsIgnoredCharsMap[b.filename],0>c&&(c=0),j=j.slice(this._contentsIgnoredCharsMap[b.filename])),j=j.substring(0,c),f=j.split("\n"),h=f[f.length-1]}if(e=a.split("\n"),g=e[e.length-1],b)if(d)for(i=0;e.length>i;i++)this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+i+1,column:0===i?this._column:0},original:{line:f.length+i,column:0===i?h.length:0},source:this.normalizeFilename(b.filename)});else this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+1,column:this._column},original:{line:f.length,column:h.length},source:this.normalizeFilename(b.filename)});1===e.length?this._column+=g.length:(this._lineNumber+=e.length-1,this._column=g.length),this._css.push(a)}},b.prototype.isEmpty=function(){return 0===this._css.length},b.prototype.toCSS=function(a){if(this._sourceMapGenerator=new this._sourceMapGeneratorConstructor({file:this._outputFilename,sourceRoot:null}),this._outputSourceFiles)for(var b in this._contentsMap)if(this._contentsMap.hasOwnProperty(b)){var c=this._contentsMap[b];this._contentsIgnoredCharsMap[b]&&(c=c.slice(this._contentsIgnoredCharsMap[b])),this._sourceMapGenerator.setSourceContent(this.normalizeFilename(b),c)}if(this._rootNode.genCSS(a,this),this._css.length>0){var d,e=JSON.stringify(this._sourceMapGenerator.toJSON());this.sourceMapURL?d=this.sourceMapURL:this._sourceMapFilename&&(d=this._sourceMapFilename),this.sourceMapURL=d,this.sourceMap=e}return this._css.join("")},b}},{}],44:[function(a,b,c){var dLine truncated
this._setVisibilityToReplacement(C),Array.prototype.push.apply(u,C)}catch(D){throw{message:D.message,index:this.index,filename:this.currentFileInfo.filename,stack:D.stack}}if(v)return u}throw n?{type:"Runtime",message:"No matching definition was found for `"+this.format(t)+"`",index:this.index,filename:this.currentFileInfo.filename}:{type:"Name",message:this.selector.toCSS().trim()+" is undefined",index:this.index,filename:this.currentFileInfo.filename}},h.prototype._setVisibilityToReplacement=function(a){var b,c;if(this.blocksVisibility())for(b=0;a.length>b;b++)c=a[b],c.addVisibilityBlock()},h.prototype.format=function(a){return this.selector.toCSS().trim()+"("+(a?a.map(function(a){var b="";return a.name&&(b+=a.name+":"),b+=a.value.toCSS?a.value.toCSS():"???"}).join(", "):"")+")"},b.exports=h},{"../functions/default":20,"./mixin-definition":68,"./node":70,"./selector":77}],68:[function(a,b,c){var d=a("./selector"),e=a("./element"),f=a("./ruleset"),g=a("./rule"),h=a("./expression"),i=a("../contexts"),j=function(a,b,c,f,g,h,i){this.name=a,this.selectors=[new d([new e(null,a,this.index,this.currentFileInfo)])],this.params=b,this.condition=f,this.variadic=g,this.arity=b.length,this.rules=c,this._lookups={};var j=[];this.required=b.reduce(function(a,b){return!b.name||b.name&&!b.value?a+1:(j.push(b.name),a)},0),this.optionalParameters=j,this.frames=h,this.copyVisibilityInfo(i),this.allowRoot=!0};j.prototype=new f,j.prototype.type="MixinDefinition",j.prototype.evalFirst=!0,j.prototype.accept=function(a){this.params&&this.params.length&&(this.params=a.visitArray(this.params)),this.rules=a.visitArray(this.rules),this.condition&&(this.condition=a.visit(this.condition))},j.prototype.evalParams=function(a,b,c,d){var e,j,k,l,m,n,o,p,q=new f(null,null),r=this.params.slice(0),s=0;if(b.frames&&b.frames[0]&&b.frames[0].functionRegistry&&(q.functionRegistry=b.frames[0].functionRegistry.inherit()),b=new i.Eval(b,[q].concat(b.frames)),c)for(c=c.slice(0),s=c.length,k=0;s>k;k++)if(j=c[k],n=j&&j.name){for(o=!1,l=0;r.length>l;l++)if(!d[l]&&n===r[l].name){d[l]=j.value.eval(a),q.prependRule(new g(n,j.value.eval(a))),o=!0;break}if(o){c.splice(k,1),k--;continue}throw{type:"Runtime",message:"Named argument for "+this.name+" "+c[k].name+" not found"}}for(p=0,k=0;r.length>k;k++)if(!d[k]){if(j=c&&c[p],n=r[k].name)if(r[k].variadic){for(e=[],l=p;s>l;l++)e.push(c[l].value.eval(a));q.prependRule(new g(n,new h(e).eval(a)))}else{if(m=j&&j.value)m=m.eval(a);else{if(!r[k].value)throw{type:"Runtime",message:"wrong number of arguments for "+this.name+" ("+s+" for "+this.arity+")"};m=r[k].value.eval(b),q.resetCache()}q.prependRule(new g(n,m)),d[k]=m}if(r[k].variadic&&c)for(l=p;s>l;l++)d[l]=c[l].value.eval(a);p++}return q},j.prototype.makeImportant=function(){var a=this.rules?this.rules.map(function(a){return a.makeImportant?a.makeImportant(!0):a}):this.rules,b=new j(this.name,this.params,a,this.condition,this.variadic,this.frames);return b},j.prototype.eval=function(a){return new j(this.name,this.params,this.rules,this.condition,this.variadic,this.frames||a.frames.slice(0))},j.prototype.evalCall=function(a,b,c){var d,e,j=[],k=this.frames?this.frames.concat(a.frames):a.frames,l=this.evalParams(a,new i.Eval(a,k),b,j);return l.prependRule(new g("@arguments",new h(j).eval(a))),d=this.rules.slice(0),e=new f(null,d),e.originalRuleset=this,e=e.eval(new i.Eval(a,[this,l].concat(k))),c&&(e=e.makeImportant()),e},j.prototype.matchCondition=function(a,b){return!this.condition||this.condition.eval(new i.Eval(b,[this.evalParams(b,new i.Eval(b,this.frames?this.frames.concat(b.frames):b.frames),a,[])].concat(this.frames||[]).concat(b.frames)))},j.prototype.matchArgs=function(a,b){var c,d=a&&a.length||0,e=this.optionalParameters,f=a?a.reduce(function(a,b){return e.indexOf(b.name)<0?a+1:a},0):0;if(this.variadic){if(this.required-1>f)return!1}else{if(this.required>f)return!1;if(d>this.params.length)return!1}c=Math.min(f,this.arity);for(var g=0;c>g;g++)if(!this.params[g].name&&!this.params[g].variadic&&a[g].value.eval(b).toCSS()!=this.params[g].value.eval(b).toCSS())return!1;return!0},b.exports=j},{"../contexts":11,"./element":58,"./expression":59,"./rule":74,"./ruleset":76,"./selector":77}],69:[function(a,b,c){var d=a("./node"),e=a("./operation"),f=a("./dimension"),g=function(a){this.value=a};g.prototype=new d,g.prototype.type="Negative",g.prototype.genCSS=function(a,b){b.add("-"),this.value.genCSS(a,b)},g.prototype.eval=function(a){return a.isMathOn()?new e("*",[new f(-1),this.value]).eval(a):new g(this.value.eval(a))},b.exports=g},{"./dimension":56,"./node":70,"./operation":71}],70:[function(a,b,c){var d=function(){};d.prototype.toCSS=function(a){var b=[];return this.genCSS(a,{add:function(a,c,d){b.push(a)},isEmpty:function(){return 0===b.length}}),b.join("")},d.prototype.genCSS=function(a,b){b.add(this.value)},d.prototype.accept=function(a){this.value=a.visit(this.value)},d.prototype.eval=function(){return this},d.prototype._operate=function(a,b,c,d){switch(b){caLine truncated
this.variableImports.push(a)},d.prototype.tryRun=function(){this._currentDepth++;try{for(;;){for(;this.imports.length>0;){var a=this.imports[0];if(!a.isReady)return;this.imports=this.imports.slice(1),a.callback.apply(null,a.args)}if(0===this.variableImports.length)break;var b=this.variableImports[0];this.variableImports=this.variableImports.slice(1),b()}}finally{this._currentDepth--}0===this._currentDepth&&this._onSequencerEmpty&&this._onSequencerEmpty()},b.exports=d},{}],86:[function(a,b,c){var d=a("../contexts"),e=a("./visitor"),f=a("./import-sequencer"),g=function(a,b){this._visitor=new e(this),this._importer=a,this._finish=b,this.context=new d.Eval,this.importCount=0,this.onceFileDetectionMap={},this.recursionDetector={},this._sequencer=new f(this._onSequencerEmpty.bind(this))};g.prototype={isReplacing:!1,run:function(a){try{this._visitor.visit(a)}catch(b){this.error=b}this.isFinished=!0,this._sequencer.tryRun()},_onSequencerEmpty:function(){this.isFinished&&this._finish(this.error)},visitImport:function(a,b){var c=a.options.inline;if(!a.css||c){var e=new d.Eval(this.context,this.context.frames.slice(0)),f=e.frames[0];this.importCount++,a.isVariableImport()?this._sequencer.addVariableImport(this.processImportNode.bind(this,a,e,f)):this.processImportNode(a,e,f)}b.visitDeeper=!1},processImportNode:function(a,b,c){var d,e=a.options.inline;try{d=a.evalForImport(b)}catch(f){f.filename||(f.index=a.index,f.filename=a.currentFileInfo.filename),a.css=!0,a.error=f}if(!d||d.css&&!e)this.importCount--,this.isFinished&&this._sequencer.tryRun();else{d.options.multiple&&(b.importMultiple=!0);for(var g=void 0===d.css,h=0;c.rules.length>h;h++)if(c.rules[h]===a){c.rules[h]=d;break}var i=this.onImported.bind(this,d,b),j=this._sequencer.addImport(i);this._importer.push(d.getPath(),g,d.currentFileInfo,d.options,j)}},onImported:function(a,b,c,d,e,f){c&&(c.filename||(c.index=a.index,c.filename=a.currentFileInfo.filename),this.error=c);var g=this,h=a.options.inline,i=a.options.plugin,j=a.options.optional,k=e||f in g.recursionDetector;if(b.importMultiple||(a.skip=k?!0:function(){return f in g.onceFileDetectionMap?!0:(g.onceFileDetectionMap[f]=!0,!1)}),!f&&j&&(a.skip=!0),d&&(a.root=d,a.importedFilename=f,!h&&!i&&(b.importMultiple||!k))){g.recursionDetector[f]=!0;var l=this.context;this.context=b;try{this._visitor.visit(d)}catch(c){this.error=c}this.context=l}g.importCount--,g.isFinished&&g._sequencer.tryRun()},visitRule:function(a,b){"DetachedRuleset"===a.value.type?this.context.frames.unshift(a):b.visitDeeper=!1},visitRuleOut:function(a){"DetachedRuleset"===a.value.type&&this.context.frames.shift()},visitDirective:function(a,b){this.context.frames.unshift(a)},visitDirectiveOut:function(a){this.context.frames.shift()},visitMixinDefinition:function(a,b){this.context.frames.unshift(a)},visitMixinDefinitionOut:function(a){this.context.frames.shift()},visitRuleset:function(a,b){this.context.frames.unshift(a)},visitRulesetOut:function(a){this.context.frames.shift()},visitMedia:function(a,b){this.context.frames.unshift(a.rules[0])},visitMediaOut:function(a){this.context.frames.shift()}},b.exports=g},{"../contexts":11,"./import-sequencer":85,"./visitor":91}],87:[function(a,b,c){var d={Visitor:a("./visitor"),ImportVisitor:a("./import-visitor"),MarkVisibleSelectorsVisitor:a("./set-tree-visibility-visitor"),ExtendVisitor:a("./extend-visitor"),JoinSelectorVisitor:a("./join-selector-visitor"),ToCSSVisitor:a("./to-css-visitor")};b.exports=d},{"./extend-visitor":84,"./import-visitor":86,"./join-selector-visitor":88,"./set-tree-visibility-visitor":89,"./to-css-visitor":90,"./visitor":91}],88:[function(a,b,c){var d=a("./visitor"),e=function(){this.contexts=[[]],this._visitor=new d(this)};e.prototype={run:function(a){return this._visitor.visit(a)},visitRule:function(a,b){b.visitDeeper=!1},visitMixinDefinition:function(a,b){b.visitDeeper=!1},visitRuleset:function(a,b){var c,d=this.contexts[this.contexts.length-1],e=[];this.contexts.push(e),a.root||(c=a.selectors,c&&(c=c.filter(function(a){return a.getIsOutput()}),a.selectors=c.length?c:c=null,c&&a.joinSelectors(e,d,c)),c||(a.rules=null),a.paths=e)},visitRulesetOut:function(a){this.contexts.length=this.contexts.length-1},visitMedia:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules[0].root=0===c.length||c[0].multiMedia},visitDirective:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules&&a.rules.length&&(a.rules[0].root=a.isRooted||0===c.length||null)}},b.exports=e},{"./visitor":91}],89:[function(a,b,c){var d=function(a){this.visible=a};d.prototype.run=function(a){this.visit(a)},d.prototype.visitArray=function(a){if(!a)return a;var b,c=a.length;for(b=0;c>b;b++)this.visit(a[b]);return a},d.prototype.visit=function(a){return a?a.constructor===Array?this.visitArray(a):!a.blocksVisibility||a.blocksVisibility()?a:(this.visible?a.ensureVisibility():a.ensureInvisibility(),a.accept(this),a):a},b.exports=d},{}],90:[function(a,b,c){var d=a("../tree"),e=a("./visitor"),f=function(Line truncated
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.less=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./utils").addDataAttr,e=a("./browser");b.exports=function(a,b){d(b,e.currentScript(a)),void 0===b.isFileProtocol&&(b.isFileProtocol=/^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(a.location.protocol)),b.async=b.async||!1,b.fileAsync=b.fileAsync||!1,b.poll=b.poll||(b.isFileProtocol?1e3:1500),b.env=b.env||("127.0.0.1"==a.location.hostname||"0.0.0.0"==a.location.hostname||"localhost"==a.location.hostname||a.location.port&&a.location.port.length>0||b.isFileProtocol?"development":"production");var c=/!dumpLineNumbers:(comments|mediaquery|all)/.exec(a.location.hash);c&&(b.dumpLineNumbers=c[1]),void 0===b.useFileCache&&(b.useFileCache=!0),void 0===b.onReady&&(b.onReady=!0)}},{"./browser":3,"./utils":10}],2:[function(a,b,c){function d(a){a.filename&&console.warn(a),e.async||h.removeChild(i)}a("promise/polyfill.js");var e=window.less||{};a("./add-default-options")(window,e);var f=b.exports=a("./index")(window,e);window.less=f;var g,h,i;e.onReady&&(/!watch/.test(window.location.hash)&&f.watch(),e.async||(g="body { display: none !important }",h=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style"),i.type="text/css",i.styleSheet?i.styleSheet.cssText=g:i.appendChild(document.createTextNode(g)),h.appendChild(i)),f.registerStylesheetsImmediately(),f.pageLoadFinished=f.refresh("development"===f.env).then(d,d))},{"./add-default-options":1,"./index":8,"promise/polyfill.js":97}],3:[function(a,b,c){var d=a("./utils");b.exports={createCSS:function(a,b,c){var e=c.href||"",f="less:"+(c.title||d.extractId(e)),g=a.getElementById(f),h=!1,i=a.createElement("style");i.setAttribute("type","text/css"),c.media&&i.setAttribute("media",c.media),i.id=f,i.styleSheet||(i.appendChild(a.createTextNode(b)),h=null!==g&&g.childNodes.length>0&&i.childNodes.length>0&&g.firstChild.nodeValue===i.firstChild.nodeValue);var j=a.getElementsByTagName("head")[0];if(null===g||h===!1){var k=c&&c.nextSibling||null;k?k.parentNode.insertBefore(i,k):j.appendChild(i)}if(g&&h===!1&&g.parentNode.removeChild(g),i.styleSheet)try{i.styleSheet.cssText=b}catch(l){throw new Error("Couldn't reassign styleSheet.cssText.")}},currentScript:function(a){var b=a.document;return b.currentScript||function(){var a=b.getElementsByTagName("script");return a[a.length-1]}()}}},{"./utils":10}],4:[function(a,b,c){b.exports=function(a,b,c){var d=null;if("development"!==b.env)try{d="undefined"==typeof a.localStorage?null:a.localStorage}catch(e){}return{setCSS:function(a,b,e,f){if(d){c.info("saving "+a+" to cache.");try{d.setItem(a,f),d.setItem(a+":timestamp",b),e&&d.setItem(a+":vars",JSON.stringify(e))}catch(g){c.error('failed to save "'+a+'" to local storage for caching.')}}},getCSS:function(a,b,c){var e=d&&d.getItem(a),f=d&&d.getItem(a+":timestamp"),g=d&&d.getItem(a+":vars");if(c=c||{},f&&b.lastModified&&new Date(b.lastModified).valueOf()===new Date(f).valueOf()&&(!c&&!g||JSON.stringify(c)===g))return e}}}},{}],5:[function(a,b,c){var d=a("./utils"),e=a("./browser");b.exports=function(a,b,c){function f(b,f){var g,h,i="less-error-message:"+d.extractId(f||""),j='<li><label>{line}</label><pre class="{class}">{content}</pre></li>',k=a.document.createElement("div"),l=[],m=b.filename||f,n=m.match(/([^\/]+(\?.*)?)$/)[1];k.id=i,k.className="less-error-message",h="<h3>"+(b.type||"Syntax")+"Error: "+(b.message||"There is an error in your .less file")+'</h3><p>in <a href="'+m+'">'+n+"</a> ";var o=function(a,b,c){void 0!==a.extract[b]&&l.push(j.replace(/\{line\}/,(parseInt(a.line,10)||0)+(b-1)).replace(/\{class\}/,c).replace(/\{content\}/,a.extract[b]))};b.extract&&(o(b,0,""),o(b,1,"line"),o(b,2,""),h+="on line "+b.line+", column "+(b.column+1)+":</p><ul>"+l.join("")+"</ul>"),b.stack&&(b.extract||c.logLevel>=4)&&(h+="<br/>Stack Trace</br />"+b.stack.split("\n").slice(1).join("<br/>")),k.innerHTML=h,e.createCSS(a.document,[".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-right: 15px;","padding: 4px 0;","margin: 0;","}",".less-error-message label {","font-size: 12px;","margin-right: 15px;","padding: 4px 0;","color: #cc7777;","}",".less-error-message pre {","color: #dd6666;","padding: 4px 0;","margin: 0;","display: inline-block;","}",".less-error-message pre.line {","colorLine truncated
"../tree/quoted":73,"./function-registry":22}],28:[function(a,b,c){b.exports=function(b){var c=a("../tree/dimension"),d=a("../tree/color"),e=a("../tree/expression"),f=a("../tree/quoted"),g=a("../tree/url"),h=a("./function-registry");h.add("svg-gradient",function(a){function b(){throw{type:"Argument",message:"svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position] or direction, color list"}}var h,i,j,k,l,m,n,o,p="linear",q='x="0" y="0" width="1" height="1"',r={compress:!1},s=a.toCSS(r);switch(2==arguments.length?(arguments[1].value.length<2&&b(),h=arguments[1].value):arguments.length<3?b():h=Array.prototype.slice.call(arguments,1),s){case"to bottom":i='x1="0%" y1="0%" x2="0%" y2="100%"';break;case"to right":i='x1="0%" y1="0%" x2="100%" y2="0%"';break;case"to bottom right":i='x1="0%" y1="0%" x2="100%" y2="100%"';break;case"to top right":i='x1="0%" y1="100%" x2="100%" y2="0%"';break;case"ellipse":case"ellipse at center":p="radial",i='cx="50%" cy="50%" r="75%"',q='x="-50" y="-50" width="101" height="101"';break;default:throw{type:"Argument",message:"svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'"}}for(j='<?xml version="1.0" ?><svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><'+p+'Gradient id="gradient" gradientUnits="userSpaceOnUse" '+i+">",k=0;k<h.length;k+=1)h[k]instanceof e?(l=h[k].value[0],m=h[k].value[1]):(l=h[k],m=void 0),l instanceof d&&((0===k||k+1===h.length)&&void 0===m||m instanceof c)||b(),n=m?m.toCSS(r):0===k?"0%":"100%",o=l.alpha,j+='<stop offset="'+n+'" stop-color="'+l.toRGB()+'"'+(o<1?' stop-opacity="'+o+'"':"")+"/>";return j+="</"+p+"Gradient><rect "+q+' fill="url(#gradient)" /></svg>',j=encodeURIComponent(j),j="data:image/svg+xml,"+j,new g(new f("'"+j+"'",j,(!1),this.index,this.currentFileInfo),this.index,this.currentFileInfo)})}},{"../tree/color":50,"../tree/dimension":56,"../tree/expression":59,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],29:[function(a,b,c){var d=a("../tree/keyword"),e=a("../tree/detached-ruleset"),f=a("../tree/dimension"),g=a("../tree/color"),h=a("../tree/quoted"),i=a("../tree/anonymous"),j=a("../tree/url"),k=a("../tree/operation"),l=a("./function-registry"),m=function(a,b){return a instanceof b?d.True:d.False},n=function(a,b){if(void 0===b)throw{type:"Argument",message:"missing the required second argument to isunit."};if(b="string"==typeof b.value?b.value:b,"string"!=typeof b)throw{type:"Argument",message:"Second argument to isunit should be a unit or a string."};return a instanceof f&&a.unit.is(b)?d.True:d.False},o=function(a){var b=Array.isArray(a.value)?a.value:Array(a);return b};l.addMultiple({isruleset:function(a){return m(a,e)},iscolor:function(a){return m(a,g)},isnumber:function(a){return m(a,f)},isstring:function(a){return m(a,h)},iskeyword:function(a){return m(a,d)},isurl:function(a){return m(a,j)},ispixel:function(a){return n(a,"px")},ispercentage:function(a){return n(a,"%")},isem:function(a){return n(a,"em")},isunit:n,unit:function(a,b){if(!(a instanceof f))throw{type:"Argument",message:"the first argument to unit must be a number"+(a instanceof k?". Have you forgotten parenthesis?":"")};return b=b?b instanceof d?b.value:b.toCSS():"",new f(a.value,b)},"get-unit":function(a){return new i(a.unit)},extract:function(a,b){return b=b.value-1,o(a)[b]},length:function(a){return new f(o(a).length)}})},{"../tree/anonymous":46,"../tree/color":50,"../tree/detached-ruleset":55,"../tree/dimension":56,"../tree/keyword":65,"../tree/operation":71,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],30:[function(a,b,c){var d=a("./contexts"),e=a("./parser/parser"),f=a("./plugins/function-importer");b.exports=function(a){var b=function(a,b){this.rootFilename=b.filename,this.paths=a.paths||[],this.contents={},this.contentsIgnoredChars={},this.mime=a.mime,this.error=null,this.context=a,this.queue=[],this.files={}};return b.prototype.push=function(b,c,g,h,i){var j=this;this.queue.push(b);var k=function(a,c,d){j.queue.splice(j.queue.indexOf(b),1);var e=d===j.rootFilename;h.optional&&a?i(null,{rules:[]},!1,null):(j.files[d]=c,a&&!j.error&&(j.error=a),i(a,c,e,d))},l={relativeUrls:this.context.relativeUrls,entryPath:g.entryPath,rootpath:g.rootpath,rootFilename:g.rootFilename},m=a.getFileManager(b,g.currentDirectory,this.context,a);if(!m)return void k({message:"Could not find a file-manager for "+b});c&&(b=m.tryAppendExtension(b,h.plugin?".js":".less"));var n=function(a){var b=a.filename,c=a.contents.replace(/^\uFEFF/,"");l.currentDirectory=m.getPath(b),l.relativeUrls&&(l.rootpath=m.join(j.context.rootpath||"",m.pathDiff(l.currentDirectory,l.entryPath)),!m.isPathAbsolute(l.rootpath)&&m.alwaysMakePathsAbsolute()&&(l.rootpath=m.join(l.entryPath,l.rootpath))),l.filename=b;var i=new d.Parse(j.context);i.processImports=!1,j.contents[b]=c,(g.reference||h.reference)&&(l.rLine truncated
c(f,e,this.fileInfo)}catch(h){b(new d({message:"Plugin evaluation error: '"+h.name+": "+h.message.replace(/["]/g,"'")+"'",filename:this.fileInfo.filename}),null)}b(null,{functions:g})}},{"../less-error":32,"../tree":62}],41:[function(a,b,c){var d;b.exports=function(b,c,e){var f=function(b,e,g){if("function"==typeof e&&(g=e,e={}),!g){d||(d="undefined"==typeof Promise?a("promise"):Promise);var h=this;return new d(function(a,c){f.call(h,b,e,function(b,d){b?c(b):a(d)})})}this.parse(b,e,function(a,b,d,e){if(a)return g(a);var f;try{var h=new c(b,d);f=h.toCSS(e)}catch(a){return g(a)}g(null,f)})};return f}},{promise:void 0}],42:[function(a,b,c){b.exports=function(a,b){var c=function(a){this.options=a};return c.prototype.toCSS=function(b,c,d){var e=new a({contentsIgnoredCharsMap:d.contentsIgnoredChars,rootNode:b,contentsMap:d.contents,sourceMapFilename:this.options.sourceMapFilename,sourceMapURL:this.options.sourceMapURL,outputFilename:this.options.sourceMapOutputFilename,sourceMapBasepath:this.options.sourceMapBasepath,sourceMapRootpath:this.options.sourceMapRootpath,outputSourceFiles:this.options.outputSourceFiles,sourceMapGenerator:this.options.sourceMapGenerator,sourceMapFileInline:this.options.sourceMapFileInline}),f=e.toCSS(c);return this.sourceMap=e.sourceMap,this.sourceMapURL=e.sourceMapURL,this.options.sourceMapInputFilename&&(this.sourceMapInputFilename=e.normalizeFilename(this.options.sourceMapInputFilename)),f+this.getCSSAppendage()},c.prototype.getCSSAppendage=function(){var a=this.sourceMapURL;if(this.options.sourceMapFileInline){if(void 0===this.sourceMap)return"";a="data:application/json;base64,"+b.encodeBase64(this.sourceMap)}return a?"/*# sourceMappingURL="+a+" */":""},c.prototype.getExternalSourceMap=function(){return this.sourceMap},c.prototype.setExternalSourceMap=function(a){this.sourceMap=a},c.prototype.isInline=function(){return this.options.sourceMapFileInline},c.prototype.getSourceMapURL=function(){return this.sourceMapURL},c.prototype.getOutputFilename=function(){return this.options.sourceMapOutputFilename},c.prototype.getInputFilename=function(){return this.sourceMapInputFilename},c}},{}],43:[function(a,b,c){b.exports=function(a){var b=function(b){this._css=[],this._rootNode=b.rootNode,this._contentsMap=b.contentsMap,this._contentsIgnoredCharsMap=b.contentsIgnoredCharsMap,b.sourceMapFilename&&(this._sourceMapFilename=b.sourceMapFilename.replace(/\\/g,"/")),this._outputFilename=b.outputFilename,this.sourceMapURL=b.sourceMapURL,b.sourceMapBasepath&&(this._sourceMapBasepath=b.sourceMapBasepath.replace(/\\/g,"/")),b.sourceMapRootpath?(this._sourceMapRootpath=b.sourceMapRootpath.replace(/\\/g,"/"),"/"!==this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1)&&(this._sourceMapRootpath+="/")):this._sourceMapRootpath="",this._outputSourceFiles=b.outputSourceFiles,this._sourceMapGeneratorConstructor=a.getSourceMapGenerator(),this._lineNumber=0,this._column=0};return b.prototype.normalizeFilename=function(a){return a=a.replace(/\\/g,"/"),this._sourceMapBasepath&&0===a.indexOf(this._sourceMapBasepath)&&(a=a.substring(this._sourceMapBasepath.length),"\\"!==a.charAt(0)&&"/"!==a.charAt(0)||(a=a.substring(1))),(this._sourceMapRootpath||"")+a},b.prototype.add=function(a,b,c,d){if(a){var e,f,g,h,i;if(b){var j=this._contentsMap[b.filename];this._contentsIgnoredCharsMap[b.filename]&&(c-=this._contentsIgnoredCharsMap[b.filename],c<0&&(c=0),j=j.slice(this._contentsIgnoredCharsMap[b.filename])),j=j.substring(0,c),f=j.split("\n"),h=f[f.length-1]}if(e=a.split("\n"),g=e[e.length-1],b)if(d)for(i=0;i<e.length;i++)this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+i+1,column:0===i?this._column:0},original:{line:f.length+i,column:0===i?h.length:0},source:this.normalizeFilename(b.filename)});else this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+1,column:this._column},original:{line:f.length,column:h.length},source:this.normalizeFilename(b.filename)});1===e.length?this._column+=g.length:(this._lineNumber+=e.length-1,this._column=g.length),this._css.push(a)}},b.prototype.isEmpty=function(){return 0===this._css.length},b.prototype.toCSS=function(a){if(this._sourceMapGenerator=new this._sourceMapGeneratorConstructor({file:this._outputFilename,sourceRoot:null}),this._outputSourceFiles)for(var b in this._contentsMap)if(this._contentsMap.hasOwnProperty(b)){var c=this._contentsMap[b];this._contentsIgnoredCharsMap[b]&&(c=c.slice(this._contentsIgnoredCharsMap[b])),this._sourceMapGenerator.setSourceContent(this.normalizeFilename(b),c)}if(this._rootNode.genCSS(a,this),this._css.length>0){var d,e=JSON.stringify(this._sourceMapGenerator.toJSON());this.sourceMapURL?d=this.sourceMapURL:this._sourceMapFilename&&(d=this._sourceMapFilename),this.sourceMapURL=d,this.sourceMap=e}return this._css.join("")},b}},{}],44:[function(a,b,c){var d=a("./contexts"),e=a("./visitors"),f=a("./tree");b.exports=function(a,b){b=b||{};var c,g=b.variables,h=new d.Eval(b);"object"!=typeof g||Array.isArray(g)|Line truncated
stack:D.stack}}if(v)return u}throw n?{type:"Runtime",message:"No matching definition was found for `"+this.format(t)+"`",index:this.index,filename:this.currentFileInfo.filename}:{type:"Name",message:this.selector.toCSS().trim()+" is undefined",index:this.index,filename:this.currentFileInfo.filename}},h.prototype._setVisibilityToReplacement=function(a){var b,c;if(this.blocksVisibility())for(b=0;b<a.length;b++)c=a[b],c.addVisibilityBlock()},h.prototype.format=function(a){return this.selector.toCSS().trim()+"("+(a?a.map(function(a){var b="";return a.name&&(b+=a.name+":"),b+=a.value.toCSS?a.value.toCSS():"???"}).join(", "):"")+")"},b.exports=h},{"../functions/default":20,"./mixin-definition":68,"./node":70,"./selector":77}],68:[function(a,b,c){var d=a("./selector"),e=a("./element"),f=a("./ruleset"),g=a("./rule"),h=a("./expression"),i=a("../contexts"),j=function(a,b,c,f,g,h,i){this.name=a,this.selectors=[new d([new e(null,a,this.index,this.currentFileInfo)])],this.params=b,this.condition=f,this.variadic=g,this.arity=b.length,this.rules=c,this._lookups={};var j=[];this.required=b.reduce(function(a,b){return!b.name||b.name&&!b.value?a+1:(j.push(b.name),a)},0),this.optionalParameters=j,this.frames=h,this.copyVisibilityInfo(i),this.allowRoot=!0};j.prototype=new f,j.prototype.type="MixinDefinition",j.prototype.evalFirst=!0,j.prototype.accept=function(a){this.params&&this.params.length&&(this.params=a.visitArray(this.params)),this.rules=a.visitArray(this.rules),this.condition&&(this.condition=a.visit(this.condition))},j.prototype.evalParams=function(a,b,c,d){var e,j,k,l,m,n,o,p,q=new f(null,null),r=this.params.slice(0),s=0;if(b.frames&&b.frames[0]&&b.frames[0].functionRegistry&&(q.functionRegistry=b.frames[0].functionRegistry.inherit()),b=new i.Eval(b,[q].concat(b.frames)),c)for(c=c.slice(0),s=c.length,k=0;k<s;k++)if(j=c[k],n=j&&j.name){for(o=!1,l=0;l<r.length;l++)if(!d[l]&&n===r[l].name){d[l]=j.value.eval(a),q.prependRule(new g(n,j.value.eval(a))),o=!0;break}if(o){c.splice(k,1),k--;continue}throw{type:"Runtime",message:"Named argument for "+this.name+" "+c[k].name+" not found"}}for(p=0,k=0;k<r.length;k++)if(!d[k]){if(j=c&&c[p],n=r[k].name)if(r[k].variadic){for(e=[],l=p;l<s;l++)e.push(c[l].value.eval(a));q.prependRule(new g(n,new h(e).eval(a)))}else{if(m=j&&j.value)m=m.eval(a);else{if(!r[k].value)throw{type:"Runtime",message:"wrong number of arguments for "+this.name+" ("+s+" for "+this.arity+")"};m=r[k].value.eval(b),q.resetCache()}q.prependRule(new g(n,m)),d[k]=m}if(r[k].variadic&&c)for(l=p;l<s;l++)d[l]=c[l].value.eval(a);p++}return q},j.prototype.makeImportant=function(){var a=this.rules?this.rules.map(function(a){return a.makeImportant?a.makeImportant(!0):a}):this.rules,b=new j(this.name,this.params,a,this.condition,this.variadic,this.frames);return b},j.prototype.eval=function(a){return new j(this.name,this.params,this.rules,this.condition,this.variadic,this.frames||a.frames.slice(0))},j.prototype.evalCall=function(a,b,c){var d,e,j=[],k=this.frames?this.frames.concat(a.frames):a.frames,l=this.evalParams(a,new i.Eval(a,k),b,j);return l.prependRule(new g("@arguments",new h(j).eval(a))),d=this.rules.slice(0),e=new f(null,d),e.originalRuleset=this,e=e.eval(new i.Eval(a,[this,l].concat(k))),c&&(e=e.makeImportant()),e},j.prototype.matchCondition=function(a,b){return!(this.condition&&!this.condition.eval(new i.Eval(b,[this.evalParams(b,new i.Eval(b,this.frames?this.frames.concat(b.frames):b.frames),a,[])].concat(this.frames||[]).concat(b.frames))))},j.prototype.matchArgs=function(a,b){var c,d=a&&a.length||0,e=this.optionalParameters,f=a?a.reduce(function(a,b){return e.indexOf(b.name)<0?a+1:a},0):0;if(this.variadic){if(f<this.required-1)return!1}else{if(f<this.required)return!1;if(d>this.params.length)return!1}c=Math.min(f,this.arity);for(var g=0;g<c;g++)if(!this.params[g].name&&!this.params[g].variadic&&a[g].value.eval(b).toCSS()!=this.params[g].value.eval(b).toCSS())return!1;return!0},b.exports=j},{"../contexts":11,"./element":58,"./expression":59,"./rule":74,"./ruleset":76,"./selector":77}],69:[function(a,b,c){var d=a("./node"),e=a("./operation"),f=a("./dimension"),g=function(a){this.value=a};g.prototype=new d,g.prototype.type="Negative",g.prototype.genCSS=function(a,b){b.add("-"),this.value.genCSS(a,b)},g.prototype.eval=function(a){return a.isMathOn()?new e("*",[new f((-1)),this.value]).eval(a):new g(this.value.eval(a))},b.exports=g},{"./dimension":56,"./node":70,"./operation":71}],70:[function(a,b,c){var d=function(){};d.prototype.toCSS=function(a){var b=[];return this.genCSS(a,{add:function(a,c,d){b.push(a)},isEmpty:function(){return 0===b.length}}),b.join("")},d.prototype.genCSS=function(a,b){b.add(this.value)},d.prototype.accept=function(a){this.value=a.visit(this.value)},d.prototype.eval=function(){return this},d.prototype._operate=function(a,b,c,d){switch(b){case"+":return c+d;case"-":return c-d;case"*":return c*d;case"/":return c/d}},d.prototype.fround=function(a,b){var c=a&&a.numPrecision;return null==c?b:NuLine truncated
this.imports=this.imports.slice(1),a.callback.apply(null,a.args)}if(0===this.variableImports.length)break;var b=this.variableImports[0];this.variableImports=this.variableImports.slice(1),b()}}finally{this._currentDepth--}0===this._currentDepth&&this._onSequencerEmpty&&this._onSequencerEmpty()},b.exports=d},{}],86:[function(a,b,c){var d=a("../contexts"),e=a("./visitor"),f=a("./import-sequencer"),g=function(a,b){this._visitor=new e(this),this._importer=a,this._finish=b,this.context=new d.Eval,this.importCount=0,this.onceFileDetectionMap={},this.recursionDetector={},this._sequencer=new f(this._onSequencerEmpty.bind(this))};g.prototype={isReplacing:!1,run:function(a){try{this._visitor.visit(a)}catch(b){this.error=b}this.isFinished=!0,this._sequencer.tryRun()},_onSequencerEmpty:function(){this.isFinished&&this._finish(this.error)},visitImport:function(a,b){var c=a.options.inline;if(!a.css||c){var e=new d.Eval(this.context,this.context.frames.slice(0)),f=e.frames[0];this.importCount++,a.isVariableImport()?this._sequencer.addVariableImport(this.processImportNode.bind(this,a,e,f)):this.processImportNode(a,e,f)}b.visitDeeper=!1},processImportNode:function(a,b,c){var d,e=a.options.inline;try{d=a.evalForImport(b)}catch(f){f.filename||(f.index=a.index,f.filename=a.currentFileInfo.filename),a.css=!0,a.error=f}if(!d||d.css&&!e)this.importCount--,this.isFinished&&this._sequencer.tryRun();else{d.options.multiple&&(b.importMultiple=!0);for(var g=void 0===d.css,h=0;h<c.rules.length;h++)if(c.rules[h]===a){c.rules[h]=d;break}var i=this.onImported.bind(this,d,b),j=this._sequencer.addImport(i);this._importer.push(d.getPath(),g,d.currentFileInfo,d.options,j)}},onImported:function(a,b,c,d,e,f){c&&(c.filename||(c.index=a.index,c.filename=a.currentFileInfo.filename),this.error=c);var g=this,h=a.options.inline,i=a.options.plugin,j=a.options.optional,k=e||f in g.recursionDetector;if(b.importMultiple||(a.skip=!!k||function(){return f in g.onceFileDetectionMap||(g.onceFileDetectionMap[f]=!0,!1)}),!f&&j&&(a.skip=!0),d&&(a.root=d,a.importedFilename=f,!h&&!i&&(b.importMultiple||!k))){g.recursionDetector[f]=!0;var l=this.context;this.context=b;try{this._visitor.visit(d)}catch(c){this.error=c}this.context=l}g.importCount--,g.isFinished&&g._sequencer.tryRun()},visitRule:function(a,b){"DetachedRuleset"===a.value.type?this.context.frames.unshift(a):b.visitDeeper=!1},visitRuleOut:function(a){"DetachedRuleset"===a.value.type&&this.context.frames.shift()},visitDirective:function(a,b){this.context.frames.unshift(a)},visitDirectiveOut:function(a){this.context.frames.shift()},visitMixinDefinition:function(a,b){this.context.frames.unshift(a)},visitMixinDefinitionOut:function(a){this.context.frames.shift()},visitRuleset:function(a,b){this.context.frames.unshift(a)},visitRulesetOut:function(a){this.context.frames.shift()},visitMedia:function(a,b){this.context.frames.unshift(a.rules[0])},visitMediaOut:function(a){this.context.frames.shift()}},b.exports=g},{"../contexts":11,"./import-sequencer":85,"./visitor":91}],87:[function(a,b,c){var d={Visitor:a("./visitor"),ImportVisitor:a("./import-visitor"),MarkVisibleSelectorsVisitor:a("./set-tree-visibility-visitor"),ExtendVisitor:a("./extend-visitor"),JoinSelectorVisitor:a("./join-selector-visitor"),ToCSSVisitor:a("./to-css-visitor")};b.exports=d},{"./extend-visitor":84,"./import-visitor":86,"./join-selector-visitor":88,"./set-tree-visibility-visitor":89,"./to-css-visitor":90,"./visitor":91}],88:[function(a,b,c){var d=a("./visitor"),e=function(){this.contexts=[[]],this._visitor=new d(this)};e.prototype={run:function(a){return this._visitor.visit(a)},visitRule:function(a,b){b.visitDeeper=!1},visitMixinDefinition:function(a,b){b.visitDeeper=!1},visitRuleset:function(a,b){var c,d=this.contexts[this.contexts.length-1],e=[];this.contexts.push(e),a.root||(c=a.selectors,c&&(c=c.filter(function(a){return a.getIsOutput()}),a.selectors=c.length?c:c=null,c&&a.joinSelectors(e,d,c)),c||(a.rules=null),a.paths=e)},visitRulesetOut:function(a){this.contexts.length=this.contexts.length-1},visitMedia:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules[0].root=0===c.length||c[0].multiMedia},visitDirective:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules&&a.rules.length&&(a.rules[0].root=a.isRooted||0===c.length||null)}},b.exports=e},{"./visitor":91}],89:[function(a,b,c){var d=function(a){this.visible=a};d.prototype.run=function(a){this.visit(a)},d.prototype.visitArray=function(a){if(!a)return a;var b,c=a.length;for(b=0;b<c;b++)this.visit(a[b]);return a},d.prototype.visit=function(a){return a?a.constructor===Array?this.visitArray(a):!a.blocksVisibility||a.blocksVisibility()?a:(this.visible?a.ensureVisibility():a.ensureInvisibility(),a.accept(this),a):a},b.exports=d},{}],90:[function(a,b,c){var d=a("../tree"),e=a("./visitor"),f=function(a){this._visitor=new e(this),this._context=a};f.prototype={containsSilentNonBlockedChild:function(a){var b;if(null==a)return!1;for(var c=0;c<a.length;c++)if(b=a[c],b.iLine truncated
@@ -17,28 +17,38 @@
</div>
<div data-bind="visible: extruders() > 1" style="display: none">
<div class="control-group">
<label class="control-label">{{ _('Shared nozzle') }}</label>
<div class="controls">
{{ _('Please specify the nozzle offsets of the extruders relative to the first nozzle T0.') }}
<input type="checkbox" data-bind="checked: sharedNozzle">
<span class="help-block">{{ _('Check this if your printer has a single nozzle and heater shared among its extruders instead of one nozzle and heater per extruder') }}</span>
</div>
</div>
<!-- ko foreach: koExtruderOffsets -->
<div class="control-group">
<label class="control-label">{{ _('Offset') }} T<span data-bind="text: idx"></span></label>
<div class="controls form-inline">
<label>X</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: x" placeholder="0">
<span class="add-on">mm</span>
</div>
<label>Y</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: y" placeholder="0">
<span class="add-on">mm</span>
<div data-bind="visible: !sharedNozzle()" style="display: none">
<div class="control-group">
<div class="controls">
{{ _('Please specify the nozzle offsets of the extruders relative to the first nozzle T0.') }}
</div>
</div>
<!-- ko foreach: koExtruderOffsets -->
<div class="control-group">
<label class="control-label">{{ _('Offset') }} T<span data-bind="text: idx"></span></label>
<div class="controls form-inline">
<label>X</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: x" placeholder="0">
<span class="add-on">mm</span>
</div>
<label>Y</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: y" placeholder="0">
<span class="add-on">mm</span>
</div>
</div>
</div>
<!-- /ko -->
</div>
<!-- /ko -->
</div>
<p>
+1 -1
View File
@@ -329,7 +329,7 @@ class FilebasedUserManager(UserManager):
self._save()
def getAllUserSettings(self, username):
if not username in self._users.key():
if not username in self._users.keys():
raise UnknownUser(username)
user = self._users[username]
+11
View File
@@ -470,6 +470,12 @@ def dict_merge(a, b):
>>> expected = dict(foo="other foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
>>> dict_merge(a, b) == expected
True
>>> dict_merge(a, None) == a
True
>>> dict_merge(None, b) == b
True
>>> dict_merge(None, None) == dict()
True
Arguments:
a (dict): The dictionary to merge ``b`` into
@@ -481,6 +487,11 @@ def dict_merge(a, b):
from copy import deepcopy
if a is None:
a = dict()
if b is None:
b = dict()
if not isinstance(b, dict):
return b
result = deepcopy(a)
-105
View File
@@ -2,111 +2,6 @@
"""
Unit tests for octoprint.users
"""
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import ddt
import octoprint.users
from octoprint.util import dict_merge
default_settings = dict(key="value", sub=dict(subkey="subvalue"))
@ddt.ddt
class UserTestCase(unittest.TestCase):
def setUp(self):
self.user = octoprint.users.User("user", "passwordHash", True, ("user",), apikey="apikey_user", settings=default_settings)
self.admin = octoprint.users.User("admin", "passwordHash", True, ("user","admin"), apikey="apikey_admin", settings=default_settings)
self.inactive = octoprint.users.User("inactive", "passwordHash", False, ("user",), apikey="apikey_inactive", settings=default_settings)
@ddt.data(
("user", dict(name="user",
active=True,
admin=False,
user=True,
apikey="apikey_user",
settings=default_settings)),
("admin", dict(name="admin",
active=True,
admin=True,
user=True,
apikey="apikey_admin",
settings=default_settings)),
("inactive", dict(name="inactive",
active=False,
admin=False,
user=True,
apikey="apikey_inactive",
settings=default_settings))
)
@ddt.unpack
def test_as_dict(self, uservar, expected):
user = getattr(self, uservar)
self.assertDictEqual(expected, user.asDict())
@ddt.data(
("key", "value"),
(["sub", "subkey"], "subvalue"),
("doesntexist", None)
)
@ddt.unpack
def test_get_setting(self, key, expected):
value = self.user.get_setting(key)
self.assertEqual(expected, value)
@ddt.data(
("otherkey", "othervalue", dict(otherkey="othervalue"), True),
(["sub", "othersubkey"], "othersubvalue", dict(sub=dict(othersubkey="othersubvalue")), True),
("booleankey", True, dict(booleankey=True), True),
(["newsub", "newsubkey"], "newsubvalue", dict(newsub=dict(newsubkey="newsubvalue")), True),
(["sub", "subkey", "wontwork"], "wontwork", dict(), False)
)
@ddt.unpack
def test_set_setting_string(self, key, value, update, expected_returnvalue):
returnvalue = self.user.set_setting(key, value)
expected = dict_merge(default_settings, update)
self.assertDictEqual(expected, self.user.get_all_settings())
self.assertEqual(expected_returnvalue, returnvalue)
def test_check_password(self):
self.assertTrue(self.user.check_password("passwordHash"))
self.assertFalse(self.user.check_password("notThePasswordHash"))
@ddt.data(
("user", "User(id=user,name=user,active=True,user=True,admin=False)"),
("admin", "User(id=admin,name=admin,active=True,user=True,admin=True)"),
("inactive", "User(id=inactive,name=inactive,active=False,user=True,admin=False)")
)
@ddt.unpack
def test_repr(self, uservar, output):
self.assertEqual(output, repr(getattr(self, uservar)))
class SessionUserTestCase(unittest.TestCase):
def setUp(self):
self.user = octoprint.users.User("username", "passwordHash", True, ("user",), apikey="apikey", settings=dict(key="value"))
def test_two_sessions(self):
session1 = octoprint.users.SessionUser(self.user)
session2 = octoprint.users.SessionUser(self.user)
self.assertNotEqual(session1.get_session(), session2.get_session())
self.assertEqual(session1._user, session2._user)
self.assertEqual(session1._username, session2._username)
def test_settings_change_propagates(self):
user = octoprint.users.SessionUser(self.user)
self.user.set_setting("otherkey", "othervalue")
self.assertDictEqual(dict(key="value", otherkey="othervalue"), user.get_all_settings())
def test_repr(self):
user = octoprint.users.SessionUser(self.user)
expected = "SessionUser(id=username,name=username,active=True,user=True,admin=False,session={},created={})".format(user._session, user._created)
self.assertEqual(expected, repr(user))
+37
View File
@@ -0,0 +1,37 @@
# coding=utf-8
"""
Unit tests for octoprint.users.SessionUser
"""
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import octoprint.users
class SessionUserTestCase(unittest.TestCase):
def setUp(self):
self.user = octoprint.users.User("username", "passwordHash", True, ("user",), apikey="apikey", settings=dict(key="value"))
def test_two_sessions(self):
session1 = octoprint.users.SessionUser(self.user)
session2 = octoprint.users.SessionUser(self.user)
self.assertNotEqual(session1.get_session(), session2.get_session())
self.assertEqual(session1._user, session2._user)
self.assertEqual(session1._username, session2._username)
def test_settings_change_propagates(self):
user = octoprint.users.SessionUser(self.user)
self.user.set_setting("otherkey", "othervalue")
self.assertDictEqual(dict(key="value", otherkey="othervalue"), user.get_all_settings())
def test_repr(self):
user = octoprint.users.SessionUser(self.user)
expected = "SessionUser(id=username,name=username,active=True,user=True,admin=False,session={},created={})".format(user._session, user._created)
self.assertEqual(expected, repr(user))
+88
View File
@@ -0,0 +1,88 @@
# coding=utf-8
"""
Unit tests for octoprint.users.User
"""
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__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 octoprint.users
from octoprint.util import dict_merge
default_settings = dict(key="value", sub=dict(subkey="subvalue"))
@ddt.ddt
class UserTestCase(unittest.TestCase):
def setUp(self):
self.user = octoprint.users.User("user", "passwordHash", True, ("user",), apikey="apikey_user", settings=default_settings)
self.admin = octoprint.users.User("admin", "passwordHash", True, ("user","admin"), apikey="apikey_admin", settings=default_settings)
self.inactive = octoprint.users.User("inactive", "passwordHash", False, ("user",), apikey="apikey_inactive", settings=default_settings)
@ddt.data(
("user", dict(name="user",
active=True,
admin=False,
user=True,
apikey="apikey_user",
settings=default_settings)),
("admin", dict(name="admin",
active=True,
admin=True,
user=True,
apikey="apikey_admin",
settings=default_settings)),
("inactive", dict(name="inactive",
active=False,
admin=False,
user=True,
apikey="apikey_inactive",
settings=default_settings))
)
@ddt.unpack
def test_as_dict(self, uservar, expected):
user = getattr(self, uservar)
self.assertDictEqual(expected, user.asDict())
@ddt.data(
("key", "value"),
(["sub", "subkey"], "subvalue"),
("doesntexist", None)
)
@ddt.unpack
def test_get_setting(self, key, expected):
value = self.user.get_setting(key)
self.assertEqual(expected, value)
@ddt.data(
("otherkey", "othervalue", dict(otherkey="othervalue"), True),
(["sub", "othersubkey"], "othersubvalue", dict(sub=dict(othersubkey="othersubvalue")), True),
("booleankey", True, dict(booleankey=True), True),
(["newsub", "newsubkey"], "newsubvalue", dict(newsub=dict(newsubkey="newsubvalue")), True),
(["sub", "subkey", "wontwork"], "wontwork", dict(), False)
)
@ddt.unpack
def test_set_setting_string(self, key, value, update, expected_returnvalue):
returnvalue = self.user.set_setting(key, value)
expected = dict_merge(default_settings, update)
self.assertDictEqual(expected, self.user.get_all_settings())
self.assertEqual(expected_returnvalue, returnvalue)
def test_check_password(self):
self.assertTrue(self.user.check_password("passwordHash"))
self.assertFalse(self.user.check_password("notThePasswordHash"))
@ddt.data(
("user", "User(id=user,name=user,active=True,user=True,admin=False)"),
("admin", "User(id=admin,name=admin,active=True,user=True,admin=True)"),
("inactive", "User(id=inactive,name=inactive,active=False,user=True,admin=False)")
)
@ddt.unpack
def test_repr(self, uservar, output):
self.assertEqual(output, repr(getattr(self, uservar)))