Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission
This commit is contained in:
commit
95310991b8
90 files changed
+2323
-1596
No files matched your search
+4
-4
@@ -16,11 +16,11 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.1
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.2
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
fix/.* 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
improve/.* 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
maintenance 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
fix/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
improve/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -75,6 +75,8 @@ date of first contribution):
|
||||
* [Clemens Niemeyer](https://github.com/clemniem)
|
||||
* ["I-am-me"](https://github.com/I-am-me)
|
||||
* [J-J Heinonen](https://github.com/jammi)
|
||||
* [Noah Martin](https://github.com/noahsmartin)
|
||||
* [Eyal Soha](https://github.com/eyal0)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
@@ -1,5 +1,61 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.1 (2017-01-25)
|
||||
|
||||
### Note for upgraders
|
||||
|
||||
#### Change in stock terminal filter configuration
|
||||
|
||||
1.3.1 fixes an issue with the two terminal filters for suppressing temperature and SD status messages and adds a new filter for filtering out firmware `wait` messages. These changes will only be active automatically though for stock terminal filter configurations. If you have customized your terminal filters, you'll need to apply these changes manually under "Settings > Terminal filters":
|
||||
- Changed "Suppress temperature messages" filter, new regex is `(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)`
|
||||
- Changed "Suppress SD status messages" filter, new regex is `(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)`
|
||||
- New "Suppress wait responses" filter, regex is `Recv: wait`
|
||||
|
||||
### Improvements
|
||||
- [#1607](https://github.com/foosel/OctoPrint/issues/1607) - Way better support for password managers (e.g. browser built-in, 1Password, Lastpass, Dashlane)
|
||||
- [#1638](https://github.com/foosel/OctoPrint/issues/1638) - Make confirmation dialog when cancelling a print optional.
|
||||
- [#1656](https://github.com/foosel/OctoPrint/issues/1656) - Make wording of buttons on print cancel dialog less confusing.
|
||||
- [#1705](https://github.com/foosel/OctoPrint/pull/1705) - Simplified install process on Mac by removing dependency on pyobjc.
|
||||
- [#1706](https://github.com/foosel/OctoPrint/pull/1706) - Added a mask icon for Safari pinned tab and touchbar.
|
||||
- Support extraction of filament diameter for volume calculation from GCODE files sliced through Simplify3D.
|
||||
- Abort low priority jobs in the file analysis queue when a high priority job comes in - should make file analysis and hence time estimates show up faster for newly uploaded files.
|
||||
- Added a terminal filter for firmware `wait` messages to the stock terminal filters. If you did modify your terminal filter configuration, you might want to add this manually:
|
||||
- New "Suppress wait responses" filter: `Recv: wait`
|
||||
|
||||
### Bug fixes
|
||||
- [#1344](https://github.com/foosel/OctoPrint/issues/1344) - Fix ProgressBarPlugins to not correctly be triggered for 0% (second try, this time hopefully for good).
|
||||
- [#1637](https://github.com/foosel/OctoPrint/issues/1637) - Fix issue preventing a folder to be deleted that has a name which is a common prefix of the file currently being printed.
|
||||
- [#1641](https://github.com/foosel/OctoPrint/issues/1641) - Fix issue with `octoprint --daemon` not working.
|
||||
- [#1647](https://github.com/foosel/OctoPrint/issues/1647) - Fix issue with `octoprint` command throwing an error if an environment variable `OCTOPRINT_VERSION` was set to its version number.
|
||||
- [#1648](https://github.com/foosel/OctoPrint/issues/1648) - Added missing `websocket-client` dependency of `octoprint client` to install script.
|
||||
- [#1653](https://github.com/foosel/OctoPrint/issues/1653) - Fix for an issue with the included init script on the BBB (see also [#1654](https://github.com/foosel/OctoPrint/issues/1654))
|
||||
- [#1657](https://github.com/foosel/OctoPrint/issues/1657) - Fix init script regarding check for configured `CONFIGFILE` variable.
|
||||
- [#1657](https://github.com/foosel/OctoPrint/issues/1657) - Don't care about ordering of common parameters (like `--basedir`, `--config`) on CLI.
|
||||
- [#1660](https://github.com/foosel/OctoPrint/issues/1660) - Do not show hint regarding keyboard controls beneath webcam stream if keyboard control feature is disabled.
|
||||
- [#1667](https://github.com/foosel/OctoPrint/issues/1667) - Fix for matching folders not getting listed in the results when performing a search in the file list.
|
||||
- [#1675](https://github.com/foosel/OctoPrint/issues/1675) - Fix model size calculation in GCODE analysis, produced wrong values in some cases. Also adjusted calculation to match implementation in GCODE viewer, now both produce identical results.
|
||||
- [#1685](https://github.com/foosel/OctoPrint/issues/1685) - Cura Plugin: Fix filament extraction from CuraEngine slicing output
|
||||
- [#1692](https://github.com/foosel/OctoPrint/issues/1692) - Cura Plugin: Fix solid layer calculation (backport from [Ultimaker/CuraEngine#140](https://github.com/Ultimaker/CuraEngine/issues/140))
|
||||
- [#1693](https://github.com/foosel/OctoPrint/issues/1693) - Cura Plugin: Support `perimeter_before_infill` profile setting. Additionally added support for `solidarea_speed`, `raft_airgap_all`, `raft_surface_thickness`, `raft_surface_linewidth` profile settings and adjusted mapping for engine settings `raftAirGapLayer0`, `raftFanSpeed`, `raftSurfaceThickness`and `raftSurfaceLinewidth` according to current mapping in Cura Legacy and adjusted Mach3 GCODE flavor to substitute `S` with `P` in temperature commands of generated start code, also like in Cura Legacy.
|
||||
- [#1697](https://github.com/foosel/OctoPrint/issues/1697) - Pin Jinja to versions <2.9 for now due to a backwards compatibility issue with templates for versions newer than that. Also pushed as a hotfix to 1.3.0 (as 1.3.0post1).
|
||||
- [#1708](https://github.com/foosel/OctoPrint/issues/1708) - Cura Plugin: Fixed selection of `start.gcode` for sliced file
|
||||
- Allow a retraction z-hop of 0 in timelapse configuration.
|
||||
- Fix files in sub folders to not be processed by the initial analysis backlog check during startup of the server.
|
||||
- Various fixes in the file analysis queue:
|
||||
- High priority items are now really high priority
|
||||
- Abort analysis for items that are to be deleted/moved to get around an issue with file access under Windows systems.
|
||||
- Fix stock terminal filters for suppressing temperature messages and SD status messages to also be able to deal with line number prefixes. If you have added additional terminal filters, you will have to apply this fix manually:
|
||||
- Changed "Suppress temperature messages" filter: `(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)`
|
||||
- Changed "Suppress SD status messages" filter: `(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)`
|
||||
- Fix issue in german translation.
|
||||
|
||||
### More information
|
||||
|
||||
- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.0...1.3.1)
|
||||
- Release Candidates:
|
||||
- [1.3.1rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.1rc1)
|
||||
- [1.3.1rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.1rc2)
|
||||
|
||||
## 1.3.0 (2016-12-08)
|
||||
|
||||
### Features
|
||||
|
||||
+2
-1
@@ -320,7 +320,7 @@ There are three main branches in OctoPrint:
|
||||
add a commit after release to this branch - `<x>.<y>.<z>.post<commits since x.y.z>`
|
||||
(e.g. `1.2.9.post1`).
|
||||
* `maintenance`: Improvements and fixes of the current release that make up
|
||||
the next release go here. More or less continously updated. You can consider
|
||||
the next release go here. More or less continuously updated. You can consider
|
||||
this a preview of the next release version. It should be very stable at all
|
||||
times. Anything you spot in here helps tremendously with getting a rock solid
|
||||
next stable release, so if you want to help out development, running the
|
||||
@@ -396,6 +396,7 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 2016-09-09: New `rc/*` branches explained.
|
||||
* 2016-09-23: Some more work on "How to file a bug report" based on recent
|
||||
experiences
|
||||
* 2017-01-25: Fixed a typo
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
+2
-6
@@ -11,12 +11,10 @@ thanks to everyone who contributed!
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* Aurelio Bernal
|
||||
* Bart Zudell
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brent Fiegle
|
||||
* Brian E. Tyler
|
||||
* Charles Mitchell
|
||||
* Christopher Day
|
||||
* Christian Petropolis
|
||||
* COLLE+McVOY
|
||||
@@ -25,7 +23,6 @@ thanks to everyone who contributed!
|
||||
* DeltaMaker 3D Printers
|
||||
* Doug Johnson
|
||||
* E3D BigBox
|
||||
* Erik de Bruijn
|
||||
* Ernesto Martinez
|
||||
* Exovite
|
||||
* Frank Sander
|
||||
@@ -34,7 +31,6 @@ thanks to everyone who contributed!
|
||||
* George Robles
|
||||
* J. Eckert
|
||||
* Jamie van Dyke
|
||||
* Jason Galarneau
|
||||
* Josh Daniels
|
||||
* Joshua David Gregory
|
||||
* Kaile Riser
|
||||
@@ -59,7 +55,6 @@ thanks to everyone who contributed!
|
||||
* Samer Najia
|
||||
* SD3D
|
||||
* SeeMeCNC
|
||||
* Shane Ekerbicer
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Stephane Schittly
|
||||
@@ -67,6 +62,7 @@ thanks to everyone who contributed!
|
||||
* Sven Mueller
|
||||
* Terrance Shaw
|
||||
* Thomas Hatley
|
||||
* Timeshell.ca
|
||||
* Trent Shumay
|
||||
|
||||
and 972 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1016 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -32,6 +32,7 @@
|
||||
|
||||
## Server
|
||||
|
||||
* [appdirs](http://github.com/ActiveState/appdirs): MIT
|
||||
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
|
||||
* [Click](http://click.pocoo.org/): BSD
|
||||
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
|
||||
|
||||
@@ -145,7 +145,6 @@ You'll need a user account with administrator privileges.
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source venv/bin/activate
|
||||
pip install -U pyobjc
|
||||
pip install -e .[develop]
|
||||
|
||||
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
|
||||
@@ -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
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
@@ -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``.
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
|
||||
@@ -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``.
|
||||
|
||||
|
||||
@@ -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``.
|
||||
|
||||
|
||||
@@ -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).
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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``.
|
||||
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
|
||||
@@ -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``.
|
||||
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -50,6 +50,9 @@ INSTALL_REQUIRES = [
|
||||
"websocket-client>=0.40,<0.41"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
INSTALL_REQUIRES.append("appdirs>=1.4.0")
|
||||
|
||||
# Additional requirements for optional install options
|
||||
EXTRA_REQUIRES = dict(
|
||||
# Dependencies for developing OctoPrint
|
||||
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import click
|
||||
import octoprint
|
||||
import sys
|
||||
|
||||
#~~ click context
|
||||
|
||||
@@ -55,6 +56,8 @@ def set_ctx_obj_option(ctx, param, value):
|
||||
ctx.obj = OctoPrintContext()
|
||||
if value != param.default:
|
||||
setattr(ctx.obj, param.name, value)
|
||||
elif param.default is not None:
|
||||
setattr(ctx.obj, param.name, param.default)
|
||||
|
||||
#~~ helper for retrieving context options
|
||||
|
||||
@@ -139,7 +142,7 @@ from .config import config_commands
|
||||
@legacy_options
|
||||
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
|
||||
@click.pass_context
|
||||
def octo(ctx, debug, host, port, logging, daemon, pid, allow_root):
|
||||
def octo(ctx, **kwargs):
|
||||
|
||||
if ctx.invoked_subcommand is None:
|
||||
# We have to support calling the octoprint command without any
|
||||
@@ -148,16 +151,23 @@ def octo(ctx, debug, host, port, logging, daemon, pid, allow_root):
|
||||
# But better print a message to inform people that they should
|
||||
# use the sub commands instead.
|
||||
|
||||
def get_value(key):
|
||||
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
||||
daemon = get_value("daemon")
|
||||
|
||||
if daemon:
|
||||
click.echo("Daemon operation via \"octoprint --daemon "
|
||||
"start|stop|restart\" is deprecated, please use "
|
||||
"\"octoprint daemon start|stop|restart\" from now on")
|
||||
|
||||
from octoprint.cli.server import daemon_command
|
||||
ctx.invoke(daemon_command, debug=debug, host=host, port=port, logging=logging, allow_root=allow_root, command=daemon, pid=pid)
|
||||
if sys.platform == "linux2":
|
||||
from octoprint.cli.server import daemon_command
|
||||
ctx.invoke(daemon_command, command=daemon, **kwargs)
|
||||
else:
|
||||
click.echo("Sorry, daemon mode is only supported under Linux right now")
|
||||
else:
|
||||
click.echo("Starting the server via \"octoprint\" is deprecated, "
|
||||
"please use \"octoprint serve\" from now on.")
|
||||
|
||||
from octoprint.cli.server import serve_command
|
||||
ctx.invoke(serve_command, debug=debug, host=host, port=port, logging=logging, allow_root=allow_root)
|
||||
ctx.invoke(serve_command, **kwargs)
|
||||
+57
-59
@@ -121,75 +121,73 @@ def serve_command(ctx, **kwargs):
|
||||
allow_root, logging, verbosity, safe_mode)
|
||||
|
||||
|
||||
@server_commands.command(name="daemon")
|
||||
@server_options
|
||||
@daemon_options
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
|
||||
metavar="start|stop|restart|status")
|
||||
@click.pass_context
|
||||
def daemon_command(ctx, command, **kwargs):
|
||||
"""
|
||||
Starts, stops or restarts in daemon mode.
|
||||
if sys.platform == "linux2":
|
||||
# we only support daemon mode under Linux
|
||||
|
||||
Please note that daemon mode is only supported under Linux right now.
|
||||
"""
|
||||
@server_commands.command(name="daemon")
|
||||
@server_options
|
||||
@daemon_options
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
|
||||
metavar="start|stop|restart|status")
|
||||
@click.pass_context
|
||||
def daemon_command(ctx, command, **kwargs):
|
||||
"""
|
||||
Starts, stops or restarts in daemon mode.
|
||||
|
||||
def get_value(key):
|
||||
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
||||
Please note that daemon mode is only supported under Linux right now.
|
||||
"""
|
||||
|
||||
host = get_value("host")
|
||||
port = get_value("port")
|
||||
logging = get_value("logging")
|
||||
allow_root = get_value("allow_root")
|
||||
debug = get_value("debug")
|
||||
pid = get_value("pid")
|
||||
def get_value(key):
|
||||
return get_ctx_obj_option(ctx, key, kwargs.get(key))
|
||||
|
||||
basedir = get_value("basedir")
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = get_value("safe_mode")
|
||||
host = get_value("host")
|
||||
port = get_value("port")
|
||||
logging = get_value("logging")
|
||||
allow_root = get_value("allow_root")
|
||||
debug = get_value("debug")
|
||||
pid = get_value("pid")
|
||||
|
||||
if sys.platform == "darwin" or sys.platform == "win32":
|
||||
click.echo("Sorry, daemon mode is only supported under Linux right now",
|
||||
file=sys.stderr)
|
||||
sys.exit(2)
|
||||
basedir = get_value("basedir")
|
||||
configfile = get_value("configfile")
|
||||
verbosity = get_value("verbosity")
|
||||
safe_mode = get_value("safe_mode")
|
||||
|
||||
if pid is None:
|
||||
click.echo("No path to a pidfile set",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if pid is None:
|
||||
click.echo("No path to a pidfile set",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
from octoprint.daemon import Daemon
|
||||
class OctoPrintDaemon(Daemon):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
|
||||
Daemon.__init__(self, pidfile)
|
||||
from octoprint.daemon import Daemon
|
||||
class OctoPrintDaemon(Daemon):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
|
||||
Daemon.__init__(self, pidfile)
|
||||
|
||||
self._basedir = basedir
|
||||
self._configfile = configfile
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._debug = debug
|
||||
self._allow_root = allow_root
|
||||
self._logging_config = logging_config
|
||||
self._verbosity = verbosity
|
||||
self._safe_mode = safe_mode
|
||||
self._basedir = basedir
|
||||
self._configfile = configfile
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._debug = debug
|
||||
self._allow_root = allow_root
|
||||
self._logging_config = logging_config
|
||||
self._verbosity = verbosity
|
||||
self._safe_mode = safe_mode
|
||||
|
||||
def run(self):
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
|
||||
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
|
||||
octoprint_daemon=self)
|
||||
def run(self):
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
|
||||
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
|
||||
octoprint_daemon=self)
|
||||
|
||||
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
|
||||
safe_mode)
|
||||
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
|
||||
safe_mode)
|
||||
|
||||
if command == "start":
|
||||
octoprint_daemon.start()
|
||||
elif command == "stop":
|
||||
octoprint_daemon.stop()
|
||||
elif command == "restart":
|
||||
octoprint_daemon.restart()
|
||||
elif command == "status":
|
||||
octoprint_daemon.status()
|
||||
if command == "start":
|
||||
octoprint_daemon.start()
|
||||
elif command == "stop":
|
||||
octoprint_daemon.stop()
|
||||
elif command == "restart":
|
||||
octoprint_daemon.restart()
|
||||
elif command == "status":
|
||||
octoprint_daemon.status()
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -246,11 +246,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
machinecode_path = path + ".gco"
|
||||
|
||||
if position and isinstance(position, dict) and "x" in position and "y" in position:
|
||||
posX = position["x"]
|
||||
posY = position["y"]
|
||||
pos_x = position["x"]
|
||||
pos_y = position["y"]
|
||||
else:
|
||||
posX = None
|
||||
posY = None
|
||||
pos_x = None
|
||||
pos_y = None
|
||||
|
||||
if on_progress:
|
||||
if not on_progress_args:
|
||||
@@ -266,8 +266,24 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
working_dir = os.path.dirname(executable)
|
||||
|
||||
slicing_profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
|
||||
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
|
||||
slicing_profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y)
|
||||
|
||||
# NOTE: We can assume an extruder count of 1 here since the only way we currently
|
||||
# support dual extrusion in this implementation is by using the second extruder for support (which
|
||||
# the engine conversion will automatically detect and adapt accordingly).
|
||||
#
|
||||
# We currently do only support STL files as sliceables, which by default can only contain one mesh,
|
||||
# so no risk of having to slice multi-objects at the moment, which would necessitate a full analysis
|
||||
# of the objects to slice to determine amount of needed extruders to use here. If we ever decide to
|
||||
# also support dual extrusion slicing (including composition from multiple STLs or support for OBJ or
|
||||
# AMF files and the like), this code needs to be adapted!
|
||||
#
|
||||
# The extruder count is needed to decide which start/end gcode will be used from the Cura profile.
|
||||
# Stock Cura implementation counts the number of objects in the scene for this (and also takes a look
|
||||
# at the support usage, like the engine conversion here does). We only ever have one object.
|
||||
engine_settings = self._convert_to_engine(profile_path, printer_profile,
|
||||
pos_x=pos_x, pos_y=pos_y,
|
||||
used_extruders=1)
|
||||
|
||||
# Start building the argument list for the CuraEngine command execution
|
||||
args = [executable, '-v', '-p']
|
||||
@@ -443,9 +459,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
|
||||
return profile.convert_to_engine()
|
||||
def _convert_to_engine(self, profile_path, printer_profile, pos_x=None, pos_y=None, used_extruders=1):
|
||||
profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y)
|
||||
return profile.convert_to_engine(used_extruders=used_extruders)
|
||||
|
||||
def _sanitize_name(name):
|
||||
if name is None:
|
||||
|
||||
@@ -602,8 +602,8 @@ class Profile(object):
|
||||
diameters = self._get("filament_diameter")
|
||||
if not match.group(1):
|
||||
return diameters[0]
|
||||
index = int(match.group(1))
|
||||
if index >= len(diameters):
|
||||
index = int(match.group(1)) - 1
|
||||
if index >= len(diameters) or index < 0:
|
||||
return 0.0
|
||||
return diameters[index]
|
||||
|
||||
@@ -615,8 +615,8 @@ class Profile(object):
|
||||
temperatures = self._get("print_temperature")
|
||||
if not match.group(1):
|
||||
return temperatures[0]
|
||||
index = int(match.group(1))
|
||||
if index >= len(temperatures):
|
||||
index = int(match.group(1)) - 1
|
||||
if index >= len(temperatures) or index < 0:
|
||||
return 0.0
|
||||
return temperatures[index]
|
||||
|
||||
@@ -674,9 +674,7 @@ class Profile(object):
|
||||
return default
|
||||
return int(value * 1000)
|
||||
|
||||
def get_gcode_template(self, key):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
def get_gcode_template(self, key, extruder_count=1):
|
||||
if key in self._profile:
|
||||
gcode = self._profile[key]
|
||||
else:
|
||||
@@ -736,7 +734,7 @@ class Profile(object):
|
||||
|
||||
return pre + str(f)
|
||||
|
||||
def get_gcode(self, key):
|
||||
def get_gcode(self, key, extruder_count=1):
|
||||
prefix = ""
|
||||
postfix = ""
|
||||
|
||||
@@ -746,11 +744,11 @@ class Profile(object):
|
||||
return ""
|
||||
|
||||
if key == "start_gcode":
|
||||
contents = self.get_gcode_template("start_gcode")
|
||||
contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count)
|
||||
prefix += self.get_start_gcode_prefix(contents)
|
||||
|
||||
else:
|
||||
contents = self.get_gcode_template(key)
|
||||
contents = self.get_gcode_template(key, extruder_count=extruder_count)
|
||||
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
|
||||
|
||||
@@ -861,13 +859,14 @@ class Profile(object):
|
||||
|
||||
return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def convert_to_engine(self):
|
||||
def convert_to_engine(self, used_extruders=1):
|
||||
|
||||
edge_width, line_count = self.calculate_edge_width_and_line_count()
|
||||
solid_layer_count = self.calculate_solid_layer_count()
|
||||
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
minimal_extruder_count = self.calculate_minimal_extruder_count()
|
||||
actual_extruder_count = max(minimal_extruder_count, used_extruders)
|
||||
|
||||
settings = {
|
||||
"layerThickness": self.get_microns("layer_height"),
|
||||
@@ -916,10 +915,10 @@ class Profile(object):
|
||||
"posy": self.get_pos_y() * 1000, # in microns
|
||||
|
||||
# gcodes
|
||||
"startCode": self.get_gcode("start_gcode"),
|
||||
"endCode": self.get_gcode("end_gcode"),
|
||||
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode"),
|
||||
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode"),
|
||||
"startCode": self.get_gcode("start_gcode", extruder_count=actual_extruder_count),
|
||||
"endCode": self.get_gcode("end_gcode", extruder_count=actual_extruder_count),
|
||||
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode", extruder_count=actual_extruder_count),
|
||||
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode", extruder_count=actual_extruder_count),
|
||||
|
||||
# fixing
|
||||
"fixHorrible": 0,
|
||||
|
||||
@@ -35,6 +35,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
|
||||
|
||||
OPERATING_SYSTEMS = dict(windows=["win32"],
|
||||
linux=["linux2"],
|
||||
macos=["darwin"])
|
||||
|
||||
pip_inapplicable_arguments = dict(uninstall=["--user"])
|
||||
|
||||
def __init__(self):
|
||||
@@ -610,10 +614,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
)
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and len(entry["compatibility"]["octoprint"]):
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
|
||||
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"])
|
||||
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and len(entry["compatibility"]["os"]):
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
|
||||
|
||||
return result
|
||||
@@ -627,12 +631,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
"""
|
||||
|
||||
for octo_compat in compatibility_entries:
|
||||
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
|
||||
octo_compat = ">={}".format(octo_compat)
|
||||
try:
|
||||
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
|
||||
octo_compat = ">={}".format(octo_compat)
|
||||
|
||||
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
|
||||
if octoprint_version in s:
|
||||
break
|
||||
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
|
||||
if octoprint_version in s:
|
||||
break
|
||||
except:
|
||||
self._logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat))
|
||||
else:
|
||||
return False
|
||||
|
||||
@@ -642,15 +649,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
"""
|
||||
Tests if the ``current_os`` matches any of the provided ``compatibility_entries``.
|
||||
"""
|
||||
return current_os in compatibility_entries
|
||||
return current_os in filter(lambda x: x in self.__class__.OPERATING_SYSTEMS.keys(), compatibility_entries)
|
||||
|
||||
def _get_os(self):
|
||||
if sys.platform == "win32":
|
||||
return "windows"
|
||||
elif sys.platform == "linux2":
|
||||
return "linux"
|
||||
elif sys.platform == "darwin":
|
||||
return "macos"
|
||||
for identifier, platforms in self.__class__.OPERATING_SYSTEMS.items():
|
||||
if sys.platform in platforms:
|
||||
return identifier
|
||||
else:
|
||||
return "unknown"
|
||||
|
||||
@@ -664,6 +668,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
|
||||
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
|
||||
|
||||
# A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's
|
||||
# versions should never contains such a prefix, we'll make sure to have stuff behave the same
|
||||
# regardless of setuptools version anyhow.
|
||||
if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v":
|
||||
octoprint_version = octoprint_version[1:]
|
||||
|
||||
if base:
|
||||
if isinstance(octoprint_version, tuple):
|
||||
# old setuptools
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -76,19 +76,53 @@ 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()
|
||||
except:
|
||||
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
||||
else:
|
||||
for key, data in hook_checks.items():
|
||||
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()
|
||||
effective_config = default_config
|
||||
if key in self._configured_checks:
|
||||
data = dict_merge(data, self._configured_checks[key])
|
||||
self._configured_checks[key] = data
|
||||
yaml_config = self._configured_checks[key]
|
||||
effective_config = dict_merge(default_config, yaml_config)
|
||||
|
||||
# Make sure there's nothing persisted in that check that shouldn't be persisted
|
||||
#
|
||||
# This used to be part of the settings migration (version 2) due to a bug - it can't
|
||||
# stay there though since it interferes with manual entries to the checks not
|
||||
# originating from within a plugin. Hence we do that step now here.
|
||||
if "type" not in effective_config or effective_config["type"] != "github_commit":
|
||||
deletables = ["current", "displayVersion"]
|
||||
else:
|
||||
deletables = []
|
||||
self._clean_settings_check(key, yaml_config, default_config, delete=deletables, save=False)
|
||||
|
||||
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()
|
||||
|
||||
@@ -288,11 +322,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
def get_settings_version(self):
|
||||
return 4
|
||||
return 5
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
if current is None or current < 4:
|
||||
if current == 4:
|
||||
# config version 4 didn't correctly remove the old settings for octoprint_restart_command
|
||||
# and environment_restart_command
|
||||
|
||||
self._settings.set(["environment_restart_command"], None)
|
||||
self._settings.set(["octoprint_restart_command"], None)
|
||||
|
||||
if current is None or current < 5:
|
||||
# config version 4 and higher moves octoprint_restart_command and
|
||||
# environment_restart_command to the core configuration
|
||||
|
||||
@@ -316,50 +357,27 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
if current is None or current == 2:
|
||||
# No config version and config version 2 need the same fix, stripping
|
||||
# accidentally persisted data off the checks
|
||||
# accidentally persisted data off the checks.
|
||||
#
|
||||
# We used to do the same processing for the plugin entries too here, but that interfered
|
||||
# with manual configuration entries. Stuff got deleted that wasn't supposed to be deleted.
|
||||
#
|
||||
# The problem is that we don't know if an entry we are looking at and which didn't come through
|
||||
# a plugin hook is simply an entry from a now uninstalled/unactive plugin, or if it was something
|
||||
# manually configured by the user. So instead of just blindly removing anything that doesn't
|
||||
# come from a plugin here we instead clean up anything that indeed comes from a plugin
|
||||
# during run time and leave everything else as is in the hopes that will not cause trouble.
|
||||
#
|
||||
# We still handle the "octoprint" entry here though.
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
configured_checks = dict()
|
||||
|
||||
check_keys = configured_checks.keys()
|
||||
|
||||
# take care of the octoprint entry
|
||||
if "octoprint" in configured_checks:
|
||||
if configured_checks is not None and "octoprint" in configured_checks:
|
||||
octoprint_check = dict(configured_checks["octoprint"])
|
||||
if "type" not in octoprint_check or octoprint_check["type"] != "github_commit":
|
||||
deletables=["current", "displayName", "displayVersion"]
|
||||
else:
|
||||
deletables=[]
|
||||
octoprint_check = self._clean_settings_check("octoprint", octoprint_check, self.get_settings_defaults()["checks"]["octoprint"], delete=deletables, save=False)
|
||||
check_keys.remove("octoprint")
|
||||
|
||||
# and the hooks
|
||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||
for name, hook in update_check_hooks.items():
|
||||
try:
|
||||
hook_checks = hook()
|
||||
except:
|
||||
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
||||
else:
|
||||
for key, data in hook_checks.items():
|
||||
if key in configured_checks:
|
||||
settings_check = dict(configured_checks[key])
|
||||
merged = dict_merge(data, settings_check)
|
||||
if "type" not in merged or merged["type"] != "github_commit":
|
||||
deletables = ["current", "displayVersion"]
|
||||
else:
|
||||
deletables = []
|
||||
|
||||
self._clean_settings_check(key, settings_check, data, delete=deletables, save=False)
|
||||
check_keys.remove(key)
|
||||
|
||||
# and anything that's left over we'll just remove now
|
||||
for key in check_keys:
|
||||
dummy_defaults = dict(plugins=dict())
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults["plugins"][self._identifier]["checks"][key] = None
|
||||
self._settings.set(["checks", key], None, defaults=dummy_defaults)
|
||||
self._clean_settings_check("octoprint", octoprint_check, self.get_settings_defaults()["checks"]["octoprint"], delete=deletables, save=False)
|
||||
|
||||
elif current == 1:
|
||||
# config version 1 had the error that the octoprint check got accidentally
|
||||
@@ -378,6 +396,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 = []
|
||||
|
||||
@@ -417,6 +439,15 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
def view():
|
||||
try:
|
||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||
|
||||
# we don't want to transfer python_checker or python_updater values through json - replace with True
|
||||
for key, data in information.items():
|
||||
if "check" in data:
|
||||
if "python_checker" in data["check"]:
|
||||
data["check"]["python_checker"] = True
|
||||
if "python_updater" in data["check"]:
|
||||
data["check"]["python_updater"] = True
|
||||
|
||||
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
information=information))
|
||||
except exceptions.ConfigurationInvalid as e:
|
||||
@@ -527,6 +558,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)
|
||||
@@ -678,6 +712,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
target_restart_type = check["restart"]
|
||||
elif "pip" in check:
|
||||
target_restart_type = "octoprint"
|
||||
else:
|
||||
target_restart_type = None
|
||||
|
||||
# if our update requires a restart we have to determine which type
|
||||
if restart_type is None or (restart_type == "octoprint" and target_restart_type == "environment"):
|
||||
@@ -808,8 +844,15 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
if target == "octoprint":
|
||||
from flask_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 = []
|
||||
@@ -864,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:
|
||||
@@ -931,7 +982,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
elif "pip" in check:
|
||||
method = "pip"
|
||||
elif "python_updater" in check:
|
||||
method = "python_updated"
|
||||
method = "python_updater"
|
||||
|
||||
if method is None or (valid_methods and not method in valid_methods):
|
||||
raise exceptions.UnknownUpdateType()
|
||||
|
||||
@@ -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,8 +7,8 @@ __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):
|
||||
return check["python_updater"].perform_update(target, check, target_version, log_cb=None)
|
||||
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
|
||||
@@ -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
|
||||
|
||||
@@ -8,8 +8,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
|
||||
@@ -117,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
|
||||
|
||||
@@ -152,6 +152,10 @@ def _get_comparable_version_pkg_resources(version_string, force_base=True):
|
||||
|
||||
version = pkg_resources.parse_version(version_string)
|
||||
|
||||
# A leading v is common in github release tags and old setuptools doesn't remove it.
|
||||
if version and isinstance(version, tuple) and version[0].lower() == "*v":
|
||||
version = version[1:]
|
||||
|
||||
if force_base:
|
||||
if isinstance(version, tuple):
|
||||
# old setuptools
|
||||
@@ -207,18 +211,20 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
|
||||
|
||||
Tests:
|
||||
|
||||
>>> _is_current(dict(remote=dict(value=None))
|
||||
>>> _is_current(dict(remote=dict(value=None)), "python")
|
||||
True
|
||||
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")))
|
||||
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")), "python")
|
||||
False
|
||||
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")))
|
||||
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python")
|
||||
True
|
||||
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), force_base=False)
|
||||
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
|
||||
False
|
||||
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), force_base=False)
|
||||
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
|
||||
True
|
||||
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), force_base=False, compare_type="python_unequal")
|
||||
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python_unequal", force_base=False)
|
||||
False
|
||||
>>> _is_current(dict(local=dict(value="1.3.0.post1+g1014712"), remote=dict(value="1.3.0")), "python")
|
||||
True
|
||||
|
||||
"""
|
||||
|
||||
@@ -241,10 +247,14 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
|
||||
|
||||
|
||||
def get_latest(target, check, custom_compare=None):
|
||||
if not "user" in check or not "repo" in check:
|
||||
raise ConfigurationInvalid("github_release update configuration for %s needs user and repo set" % target)
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -77,6 +77,8 @@ import octoprint._version
|
||||
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 octoprint.server.util.serialization import OctoPrintJsonEncoder, OctoPrintJsonDecoder
|
||||
|
||||
@@ -309,7 +311,7 @@ class Server(object):
|
||||
|
||||
return dict(settings=plugin_settings)
|
||||
|
||||
def settings_plugin_config_migration_and_cleanup(name, implementation):
|
||||
def settings_plugin_config_migration_and_cleanup(identifier, implementation):
|
||||
"""Take care of migrating and cleaning up any old settings"""
|
||||
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
@@ -322,7 +324,7 @@ class Server(object):
|
||||
stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key])
|
||||
if stored_version is None or stored_version < settings_version:
|
||||
settings_migrator(settings_version, stored_version)
|
||||
implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)
|
||||
implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version, force=True)
|
||||
|
||||
implementation.on_settings_cleanup()
|
||||
implementation._settings.save()
|
||||
@@ -421,7 +423,8 @@ class Server(object):
|
||||
log_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.logs))
|
||||
camera_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.webcam))
|
||||
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))
|
||||
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):
|
||||
@@ -450,7 +453,7 @@ class Server(object):
|
||||
# camera snapshot
|
||||
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, joined_dict(dict(url=self._settings.get(["webcam", "snapshot"]),
|
||||
as_attachment=True),
|
||||
camera_permission_validator)),
|
||||
camera_permission_validator)),
|
||||
# generated webassets
|
||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"))),
|
||||
|
||||
@@ -950,8 +953,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)
|
||||
|
||||
@@ -19,7 +19,7 @@ import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import noCachingExceptGetResponseHandler, 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
|
||||
from octoprint.permissions import Permissions
|
||||
|
||||
@@ -47,7 +47,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
|
||||
@@ -155,7 +157,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()
|
||||
|
||||
@@ -294,17 +294,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
|
||||
@@ -321,8 +310,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):
|
||||
"""
|
||||
@@ -347,13 +341,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)
|
||||
|
||||
@@ -73,6 +73,7 @@ def slicingListAll():
|
||||
result[slicer] = dict(
|
||||
key=slicer,
|
||||
displayName=slicer_impl.get_slicer_properties()["name"],
|
||||
sameDevice=slicer_impl.get_slicer_properties()["same_device"],
|
||||
default=default_slicer == slicer,
|
||||
configured=slicer_impl.is_slicer_configured(),
|
||||
profiles=_getSlicingProfilesData(slicer),
|
||||
|
||||
@@ -72,9 +72,19 @@ def executeSystemCommand(source, command):
|
||||
if not "command" in command_spec:
|
||||
return make_response("Command {}:{} does not define a command to execute, can't proceed".format(source, command), 500)
|
||||
|
||||
async = command_spec["async"] if "async" in command_spec else False
|
||||
ignore = command_spec["ignore"] if "ignore" in command_spec else False
|
||||
do_async = command_spec.get("async", False)
|
||||
do_ignore = command_spec.get("ignore", False)
|
||||
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
|
||||
|
||||
try:
|
||||
if "before" in command_spec and callable(command_spec["before"]):
|
||||
command_spec["before"]()
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = "Command \"before\" failed: {}".format(str(e))
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
|
||||
try:
|
||||
# we run this with shell=True since we have to trust whatever
|
||||
# our admin configured as command and since we want to allow
|
||||
@@ -83,9 +93,9 @@ def executeSystemCommand(source, command):
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
shell=True,
|
||||
async=async)
|
||||
if not async:
|
||||
if not ignore and p.returncode != 0:
|
||||
async=do_async)
|
||||
if not do_async:
|
||||
if not do_ignore and p.returncode != 0:
|
||||
returncode = p.returncode
|
||||
stdout_text = p.stdout.text
|
||||
stderr_text = p.stderr.text
|
||||
@@ -94,7 +104,7 @@ def executeSystemCommand(source, command):
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
except Exception as e:
|
||||
if not ignore:
|
||||
if not do_ignore:
|
||||
error = "Command failed: {}".format(str(e))
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
@@ -126,6 +136,10 @@ def _get_command_spec(source, action):
|
||||
|
||||
|
||||
def _get_core_command_specs():
|
||||
def enable_safe_mode():
|
||||
s().set(["server", "startOnceInSafeMode"], True)
|
||||
s().save()
|
||||
|
||||
commands = collections.OrderedDict(
|
||||
shutdown=dict(
|
||||
command=s().get(["server", "commands", "systemShutdownCommand"]),
|
||||
@@ -138,7 +152,12 @@ def _get_core_command_specs():
|
||||
restart=dict(
|
||||
command=s().get(["server", "commands", "serverRestartCommand"]),
|
||||
name=gettext("Restart OctoPrint"),
|
||||
confirm=gettext("You are about to restart the OctoPrint server."))
|
||||
confirm=gettext("You are about to restart the OctoPrint server.")),
|
||||
restart_safe=dict(
|
||||
command=s().get(["server", "commands", "serverRestartCommand"]),
|
||||
name=gettext("Restart OctoPrint in safe mode"),
|
||||
confirm=gettext("You are about to restart the OctoPrint server in safe mode."),
|
||||
before=enable_safe_mode)
|
||||
)
|
||||
|
||||
available_commands = collections.OrderedDict()
|
||||
|
||||
@@ -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
|
||||
@@ -19,51 +21,58 @@ from . import watchdog
|
||||
from . import serialization
|
||||
|
||||
|
||||
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):
|
||||
|
||||
@@ -63,12 +63,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:
|
||||
@@ -105,20 +111,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
|
||||
@@ -1079,20 +1085,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):
|
||||
@@ -1100,23 +1099,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_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_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_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id()))
|
||||
return func(*args, **kwargs)
|
||||
return flask_login.login_required(func)(*args, **kwargs)
|
||||
|
||||
return decorated_view
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -933,14 +934,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
|
||||
|
||||
|
||||
+12
-10
@@ -359,7 +359,8 @@ default_settings = {
|
||||
"echoOnM117": True,
|
||||
"brokenM29": True,
|
||||
"supportF": False,
|
||||
"firmwareName": "Virtual Marlin 1.0"
|
||||
"firmwareName": "Virtual Marlin 1.0",
|
||||
"sharedNozzle": False
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1399,13 +1400,18 @@ class Settings(object):
|
||||
|
||||
try:
|
||||
current = chain.get_by_path(path)
|
||||
except KeyError:
|
||||
current = None
|
||||
|
||||
try:
|
||||
default_value = chain.get_by_path(path, only_defaults=True)
|
||||
in_local = chain.has_path(path, only_local=True)
|
||||
in_defaults = chain.has_path(path, only_defaults=True)
|
||||
except KeyError:
|
||||
if error_on_path:
|
||||
raise NoSuchSettingsPath()
|
||||
return
|
||||
default_value = None
|
||||
|
||||
in_local = chain.has_path(path, only_local=True)
|
||||
in_defaults = chain.has_path(path, only_defaults=True)
|
||||
|
||||
if not force and in_defaults and in_local and default_value == value:
|
||||
try:
|
||||
@@ -1493,12 +1499,8 @@ class Settings(object):
|
||||
def _default_basedir(applicationName):
|
||||
# taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python
|
||||
if sys.platform == "darwin":
|
||||
from AppKit import NSSearchPathForDirectoriesInDomains
|
||||
# http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
|
||||
# NSApplicationSupportDirectory = 14
|
||||
# NSUserDomainMask = 1
|
||||
# True for expanding the tilde into a fully qualified path
|
||||
return os.path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], applicationName)
|
||||
import appdirs
|
||||
return appdirs.user_data_dir(applicationName, "")
|
||||
elif sys.platform == "win32":
|
||||
return os.path.join(os.environ["APPDATA"], applicationName)
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="16"
|
||||
height="16"
|
||||
id="svg4693"
|
||||
version="1.1"
|
||||
inkscape:version="0.48.4 r9939"
|
||||
sodipodi:docname="octoprint-favicon-apple.svg">
|
||||
<defs
|
||||
id="defs4695" />
|
||||
<sodipodi:namedview
|
||||
id="base"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1.0"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:zoom="31.678384"
|
||||
inkscape:cx="11.852657"
|
||||
inkscape:cy="8.0632297"
|
||||
inkscape:document-units="px"
|
||||
inkscape:current-layer="layer1"
|
||||
showgrid="false"
|
||||
inkscape:window-width="1920"
|
||||
inkscape:window-height="1017"
|
||||
inkscape:window-x="1912"
|
||||
inkscape:window-y="760"
|
||||
inkscape:window-maximized="1" />
|
||||
<metadata
|
||||
id="metadata4698">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
inkscape:label="Layer 1"
|
||||
inkscape:groupmode="layer"
|
||||
id="layer1"
|
||||
transform="translate(0,-1036.3622)">
|
||||
<path
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:0.30326968;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
|
||||
d="m 8.4712216,1037.1861 c -2.1050908,0.04 -4.0163689,0.8056 -5.7487668,2.3398 -1.0712052,0.9142 -1.82198358,1.9725 -2.25345195,3.1787 -0.37398533,1.751 -0.40029296,3.4654 -0.0863535,5.0991 0.18720389,1.0348 0.58340878,2.2568 1.19251915,3.6886 l 4.2190532,0 c -0.293453,-0.8621 -0.577953,-1.5323 -0.8471012,-2.0232 -1.153287,-2.1277 -1.411065,-4.2066 -0.7607457,-6.2052 0.2367104,-0.6185 0.5586836,-1.2169 0.9581276,-1.7806 0.1426595,-0.2013 0.3287285,-0.4113 0.5345786,-0.588 0.268515,-0.2936 0.8787071,-0.6679 1.8463495,-1.1514 0.3797863,-0.1946 0.7802208,-0.3318 1.2254154,-0.4195 0.055375,-0.021 0.4121338,-0.071 1.0485963,-0.1439 0.4166658,-0.047 0.9826928,0.01 1.7024248,0.218 0.68338,0.202 1.192041,0.4217 1.554388,0.6785 0.46971,0.3328 0.860598,0.6899 1.196632,1.0691 0.08834,0.1029 0.152532,0.1851 0.217943,0.292 0.119092,0.1449 0.28643,0.3643 0.501681,0.6579 0.120782,0.086 0.202303,0.1674 0.217943,0.2591 0.04417,0.051 0.07097,0.072 0.115138,0.1233 0.109582,0.1583 0.220475,0.3159 0.316636,0.4647 0.07883,0.1164 0.137371,0.2581 0.193271,0.3783 0.07894,-0.3674 0.06507,-0.8608 -0.08636,-1.4721 -0.180483,-0.7126 -0.391176,-1.2047 -0.633269,-1.5174 -0.507116,-0.6215 -0.808763,-0.9976 -0.933455,-1.1062 -0.03075,-0.042 -0.311374,-0.2417 -0.834763,-0.6127 -0.48313,-0.3423 -0.991284,-0.6213 -1.496819,-0.8183 -0.992045,-0.4208 -2.1359359,-0.6284 -3.3596164,-0.6086 z"
|
||||
id="path3017-7-8"
|
||||
sodipodi:nodetypes="ccccccccscccccsccccccccccscc" />
|
||||
<path
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#000000;stroke:#000000;stroke-width:0.30326967999999999;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;fill-opacity:1"
|
||||
d="m 10.140749,1039.1641 c -0.122741,0 -0.2371399,0 -0.3413068,0.016 -0.6364625,0.073 -0.9932215,0.1227 -1.0485963,0.1439 -0.4451946,0.088 -0.8456291,0.2249 -1.2254154,0.4195 -0.9676424,0.4835 -1.5778345,0.8578 -1.8463495,1.1514 -0.2058501,0.1767 -0.3919191,0.3867 -0.5345786,0.588 -0.399444,0.5637 -0.7214172,1.1621 -0.9581276,1.7806 -0.6503193,1.9986 -0.3925413,4.0775 0.7607457,6.2052 0.2691482,0.4909 0.5536482,1.1611 0.8471012,2.0232 l 4.2601723,0 c -0.1550496,-0.4598 -0.3855015,-0.9829 -0.7113982,-1.5709 -0.2465293,-0.4771 -0.5321843,-0.9815 -0.8553245,-1.4927 -0.013422,-0.01 -0.00409,-0.021 -0.00409,-0.021 -0.051988,-0.097 -0.098669,-0.1734 -0.1562603,-0.2343 -0.030751,-0.042 -0.051492,-0.073 -0.082242,-0.1152 l -0.1809343,-0.2549 c -0.069319,-0.1298 -0.140197,-0.2592 -0.2056073,-0.366 -0.2460015,-0.3356 -0.4342851,-0.6086 -0.5880347,-0.8183 -0.1308197,-0.2137 -0.2609169,-0.4291 -0.3783173,-0.6333 -1.1170471,-1.6383 -1.0194278,-3.0575 0.2878496,-4.2478 0.3736582,-0.2997 0.8097656,-0.577 1.3405561,-0.7855 0.3188143,-0.1369 0.6574538,-0.2389 0.9745783,-0.3166 2.3182336,-0.3127 4.3630076,0.4721 6.1270826,2.3069 -0.09616,-0.1488 -0.207055,-0.3105 -0.316635,-0.4688 -0.04417,-0.051 -0.07097,-0.068 -0.115139,-0.1192 -0.01564,-0.092 -0.09716,-0.1735 -0.217944,-0.2591 -0.215251,-0.2936 -0.382589,-0.5131 -0.50168,-0.6579 -0.06541,-0.1069 -0.129604,-0.1891 -0.217944,-0.292 -0.336034,-0.3792 -0.726922,-0.7363 -1.196632,-1.0691 -0.362348,-0.2568 -0.871009,-0.4765 -1.554388,-0.6785 -0.539798,-0.1558 -0.992892,-0.2286 -1.361116,-0.2344 z"
|
||||
id="path3101-4-0" />
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 5.0 KiB |
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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,15 +15,18 @@
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrint.users = {
|
||||
list: function (opts) {
|
||||
return OctoPrint.get(url(), opts);
|
||||
},
|
||||
var OctoPrintUserClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
add: function (user, opts) {
|
||||
if (!user.name || !user.password) {
|
||||
throw new OctoPrint.InvalidArgumentError("Both user's name and password need to be set");
|
||||
}
|
||||
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,
|
||||
@@ -34,81 +37,83 @@
|
||||
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, permissions, groups, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
active: !!active,
|
||||
groups: groups,
|
||||
permissions: permissions,
|
||||
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);
|
||||
}
|
||||
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, permissions, groups, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
active: !!active,
|
||||
groups: groups,
|
||||
permissions: permissions,
|
||||
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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -175,7 +175,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: {
|
||||
|
||||
@@ -204,7 +204,8 @@ $(function() {
|
||||
name: name,
|
||||
configured: slicer.configured,
|
||||
sourceExtensions: slicer.extensions.source,
|
||||
destinationExtensions: slicer.extensions.destination
|
||||
destinationExtensions: slicer.extensions.destination,
|
||||
sameDevice: slicer.sameDevice
|
||||
};
|
||||
self.slicers.push(props);
|
||||
});
|
||||
|
||||
@@ -50,7 +50,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();
|
||||
@@ -63,7 +64,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
@@ -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
|
||||
@@ -4,6 +4,7 @@
|
||||
<title data-bind="text: title">OctoPrint</title>
|
||||
|
||||
<link rel="shortcut icon" href="{{ url_for('static', filename='img/tentacle-32x32.png') }}">
|
||||
<link rel="mask-icon" href="{{ url_for('static', filename='img/favicon.svg') }}" color="#56BE37">
|
||||
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
|
||||
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
|
||||
|
||||
@@ -121,6 +122,7 @@
|
||||
<li><a href="https://github.com/foosel/OctoPrint/" target="_blank" rel="noreferrer noopener"><i class="icon-github"></i> {{ _('Sourcecode') }}</a></li>
|
||||
<li><a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="icon-book"></i> {{ _('Documentation') }}</a></li>
|
||||
<li><a href="https://github.com/foosel/OctoPrint/issues" target="_blank" rel="noreferrer noopener"><i class="icon-flag"></i> {{ _('Bugs and Requests') }}</a></li>
|
||||
<li><a href="https://github.com/foosel/OctoPrint/wiki/FAQ" target="_blank" rel="noreferrer noopener"><i class="icon-question-sign"></i> {{ _('FAQ') }}</a></li>
|
||||
<li id="footer_about"><a href="javascript:void(0)" data-bind="click: show"><i class="icon-info-sign"></i> {{ _('About') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
+25
-15
@@ -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>
|
||||
|
||||
+12
-29
@@ -809,17 +809,10 @@ class TimelapseRenderJob(object):
|
||||
|
||||
@classmethod
|
||||
def _create_ffmpeg_command_string(cls, ffmpeg, fps, bitrate, threads, input, output, hflip=False, vflip=False,
|
||||
rotate=False, watermark=None):
|
||||
rotate=False, watermark=None, pixfmt="yuv420p"):
|
||||
"""
|
||||
Create ffmpeg command string based on input parameters.
|
||||
|
||||
Examples:
|
||||
|
||||
>>> TimelapseRenderJob._create_ffmpeg_command_string("/path/to/ffmpeg", 25, "10000k", 1, "/path/to/input/files_%d.jpg", "/path/to/output.mpg")
|
||||
'/path/to/ffmpeg -framerate 25 -loglevel error -i "/path/to/input/files_%d.jpg" -vcodec mpeg2video -threads 1 -pix_fmt yuv420p -r 25 -y -b 10000k -f vob "/path/to/output.mpg"'
|
||||
>>> TimelapseRenderJob._create_ffmpeg_command_string("/path/to/ffmpeg", 25, "10000k", 1, "/path/to/input/files_%d.jpg", "/path/to/output.mpg", hflip=True)
|
||||
'/path/to/ffmpeg -framerate 25 -loglevel error -i "/path/to/input/files_%d.jpg" -vcodec mpeg2video -threads 1 -pix_fmt yuv420p -r 25 -y -b 10000k -f vob -vf \\'[in] hflip [out]\\' "/path/to/output.mpg"'
|
||||
|
||||
Arguments:
|
||||
ffmpeg (str): Path to ffmpeg
|
||||
fps (int): Frames per second for output
|
||||
@@ -831,16 +824,19 @@ class TimelapseRenderJob(object):
|
||||
vflip (bool): Perform vertical flip on input material.
|
||||
rotate (bool): Perform 90° CCW rotation on input material.
|
||||
watermark (str): Path to watermark to apply to lower left corner.
|
||||
pixfmt (str): Pixel format to use for output. Default of yuv420p should usually fit the bill.
|
||||
|
||||
Returns:
|
||||
(str): Prepared command string to render `input` to `output` using ffmpeg.
|
||||
"""
|
||||
|
||||
### See unit tests in test/timelapse/test_timelapse_renderjob.py
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
command = [
|
||||
ffmpeg, '-framerate', str(fps), '-loglevel', 'error', '-i', '"{}"'.format(input), '-vcodec', 'mpeg2video',
|
||||
'-threads', str(threads), '-pix_fmt', 'yuv420p', '-r', "25", '-y', '-b', str(bitrate),
|
||||
'-threads', str(threads), '-r', "25", '-y', '-b', str(bitrate),
|
||||
'-f', 'vob']
|
||||
|
||||
filter_string = cls._create_filter_string(hflip=hflip,
|
||||
@@ -859,38 +855,25 @@ class TimelapseRenderJob(object):
|
||||
return " ".join(command)
|
||||
|
||||
@classmethod
|
||||
def _create_filter_string(cls, hflip=False, vflip=False, rotate=False, watermark=None):
|
||||
def _create_filter_string(cls, hflip=False, vflip=False, rotate=False, watermark=None, pixfmt="yuv420p"):
|
||||
"""
|
||||
Creates an ffmpeg filter string based on input parameters.
|
||||
|
||||
Examples:
|
||||
|
||||
>>> TimelapseRenderJob._create_filter_string()
|
||||
>>> TimelapseRenderJob._create_filter_string(hflip=True)
|
||||
'[in] hflip [out]'
|
||||
>>> TimelapseRenderJob._create_filter_string(vflip=True)
|
||||
'[in] vflip [out]'
|
||||
>>> TimelapseRenderJob._create_filter_string(rotate=True)
|
||||
'[in] transpose=2 [out]'
|
||||
>>> TimelapseRenderJob._create_filter_string(vflip=True, rotate=True)
|
||||
'[in] vflip,transpose=2 [out]'
|
||||
>>> TimelapseRenderJob._create_filter_string(vflip=True, hflip=True, rotate=True)
|
||||
'[in] hflip,vflip,transpose=2 [out]'
|
||||
>>> TimelapseRenderJob._create_filter_string(watermark="/path/to/watermark.png")
|
||||
'movie=/path/to/watermark.png [wm]; [in][wm] overlay=10:main_h-overlay_h-10 [out]'
|
||||
>>> TimelapseRenderJob._create_filter_string(hflip=True, watermark="/path/to/watermark.png")
|
||||
'[in] hflip [postprocessed]; movie=/path/to/watermark.png [wm]; [postprocessed][wm] overlay=10:main_h-overlay_h-10 [out]'
|
||||
|
||||
Arguments:
|
||||
hflip (bool): Perform horizontal flip on input material.
|
||||
vflip (bool): Perform vertical flip on input material.
|
||||
rotate (bool): Perform 90° CCW rotation on input material.
|
||||
watermark (str): Path to watermark to apply to lower left corner.
|
||||
pixfmt (str): Pixel format to use, defaults to "yuv420p" which should usually fit the bill
|
||||
|
||||
Returns:
|
||||
(str or None): filter string or None if no filters are required
|
||||
"""
|
||||
filters = []
|
||||
|
||||
### See unit tests in test/timelapse/test_timelapse_renderjob.py
|
||||
|
||||
# apply pixel format
|
||||
filters = ["format={}".format(pixfmt)]
|
||||
|
||||
# flip video if configured
|
||||
if hflip:
|
||||
|
||||
@@ -406,7 +406,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]
|
||||
|
||||
@@ -534,6 +534,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
|
||||
@@ -545,6 +551,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)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
|
||||
from ddt import ddt, data, unpack
|
||||
|
||||
from octoprint.timelapse import TimelapseRenderJob
|
||||
|
||||
@ddt
|
||||
class TimelapseRenderJobTest(unittest.TestCase):
|
||||
|
||||
@data(
|
||||
(("/path/to/ffmpeg", 25, "10000k", 1, "/path/to/input/files_%d.jpg", "/path/to/output.mpg"),
|
||||
dict(),
|
||||
'/path/to/ffmpeg -framerate 25 -loglevel error -i "/path/to/input/files_%d.jpg" -vcodec mpeg2video -threads 1 -r 25 -y -b 10000k -f vob -vf \'[in] format=yuv420p [out]\' "/path/to/output.mpg"'),
|
||||
|
||||
(("/path/to/ffmpeg", 25, "10000k", 1, "/path/to/input/files_%d.jpg", "/path/to/output.mpg"),
|
||||
dict(hflip=True),
|
||||
'/path/to/ffmpeg -framerate 25 -loglevel error -i "/path/to/input/files_%d.jpg" -vcodec mpeg2video -threads 1 -r 25 -y -b 10000k -f vob -vf \'[in] format=yuv420p,hflip [out]\' "/path/to/output.mpg"'),
|
||||
|
||||
(("/path/to/ffmpeg", 25, "20000k", 4, "/path/to/input/files_%d.jpg", "/path/to/output.mpg"),
|
||||
dict(rotate=True, watermark="/path/to/watermark.png"),
|
||||
'/path/to/ffmpeg -framerate 25 -loglevel error -i "/path/to/input/files_%d.jpg" -vcodec mpeg2video -threads 4 -r 25 -y -b 20000k -f vob -vf \'[in] format=yuv420p,transpose=2 [postprocessed]; movie=/path/to/watermark.png [wm]; [postprocessed][wm] overlay=10:main_h-overlay_h-10 [out]\' "/path/to/output.mpg"')
|
||||
)
|
||||
@unpack
|
||||
def test_create_ffmpeg_command_string(self, args, kwargs, expected):
|
||||
actual = TimelapseRenderJob._create_ffmpeg_command_string(*args, **kwargs)
|
||||
self.assertEquals(actual, expected)
|
||||
|
||||
@data(
|
||||
(dict(),
|
||||
'[in] format=yuv420p [out]'),
|
||||
|
||||
(dict(pixfmt="test"),
|
||||
'[in] format=test [out]'),
|
||||
|
||||
(dict(hflip=True),
|
||||
'[in] format=yuv420p,hflip [out]'),
|
||||
|
||||
(dict(vflip=True),
|
||||
'[in] format=yuv420p,vflip [out]'),
|
||||
|
||||
(dict(rotate=True),
|
||||
'[in] format=yuv420p,transpose=2 [out]'),
|
||||
|
||||
(dict(vflip=True, rotate=True),
|
||||
'[in] format=yuv420p,vflip,transpose=2 [out]'),
|
||||
|
||||
(dict(vflip=True, hflip=True, rotate=True),
|
||||
'[in] format=yuv420p,hflip,vflip,transpose=2 [out]'),
|
||||
|
||||
(dict(watermark="/path/to/watermark.png"),
|
||||
'[in] format=yuv420p [postprocessed]; movie=/path/to/watermark.png [wm]; [postprocessed][wm] overlay=10:main_h-overlay_h-10 [out]'),
|
||||
|
||||
(dict(hflip=True, watermark="/path/to/watermark.png"),
|
||||
'[in] format=yuv420p,hflip [postprocessed]; movie=/path/to/watermark.png [wm]; [postprocessed][wm] overlay=10:main_h-overlay_h-10 [out]'),
|
||||
|
||||
)
|
||||
@unpack
|
||||
def test_create_filter_string(self, kwargs, expected):
|
||||
actual = TimelapseRenderJob._create_filter_string(**kwargs)
|
||||
self.assertEquals(actual, expected)
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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)))
|
||||
Reference in new issue
Block a user