Merge branch 'devel' into dev/permission
# Conflicts: # src/octoprint/plugins/announcements/static/js/announcements.js # src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js # src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js # src/octoprint/server/__init__.py # src/octoprint/static/css/octoprint.css # src/octoprint/static/js/app/viewmodels/connection.js # src/octoprint/static/js/app/viewmodels/control.js # src/octoprint/static/js/app/viewmodels/files.js # src/octoprint/static/js/app/viewmodels/gcode.js # src/octoprint/static/js/app/viewmodels/log.js # src/octoprint/static/js/app/viewmodels/loginstate.js # src/octoprint/static/js/app/viewmodels/navigation.js # src/octoprint/static/js/app/viewmodels/printerprofiles.js # src/octoprint/static/js/app/viewmodels/printerstate.js # src/octoprint/static/js/app/viewmodels/settings.js # src/octoprint/static/js/app/viewmodels/temperature.js # src/octoprint/static/js/app/viewmodels/terminal.js # src/octoprint/static/js/app/viewmodels/timelapse.js # src/octoprint/static/js/app/viewmodels/users.js
This commit is contained in:
commit
d8cffc4b22
89 files changed
+1748
-780
No files matched your search
+7
-4
@@ -1,6 +1,6 @@
|
||||
# Authors
|
||||
|
||||
The following people have contributed to OctoPrint's code base (ordered by
|
||||
The following people have contributed to OctoPrint's code base (ordered roughly by
|
||||
date of first contribution):
|
||||
|
||||
* [Gina Häußge](https://github.com/foosel)
|
||||
@@ -61,10 +61,11 @@ date of first contribution):
|
||||
* [Siim Raud](https://github.com/2ndalpha)
|
||||
* ["geoporalis"](https://github.com/geoporalis)
|
||||
* [Andrew Malota](https://github.com/2bitoperations)
|
||||
* [Alexander Leisentritt](https://github.com/Alex9779)
|
||||
* [therealbstern](https://github.com/therealbstern)
|
||||
* [Ishwar Agarwal](https://github.com/agarwali)
|
||||
* [Kye Hoover](https://github.com/eykrevooh)
|
||||
* [Joseph Carrick](https://github.com/carricktel)
|
||||
* [Alexander Leisentritt](https://github.com/Alex9779)
|
||||
* [therealbstern](https://github.com/therealbstern)
|
||||
* [Philipp Baum](https://github.com/philphilphil)
|
||||
* [Kyle Evans](https://github.com/kevans91)
|
||||
* [Javier Martínez Arrieta](https://github.com/Javierma)
|
||||
@@ -80,9 +81,11 @@ date of first contribution):
|
||||
* [Greg Hulands](https://github.com/ghulands)
|
||||
* [Andreas Werner](https://github.com/gallore)
|
||||
* [Shawn Bruce](https://github.com/kantlivelong)
|
||||
* [Claudiu Ceia] (https://github.com/ClaudiuCeia)
|
||||
* [Claudiu Ceia](https://github.com/ClaudiuCeia)
|
||||
* [Goswin von Brederlow](https://github.com/mrvn)
|
||||
* [Luke McKechnie](https://github.com/galamdring)
|
||||
* [Peter Backx](https://github.com/pbackx)
|
||||
* [Josh Major](https://github.com/astateofblank)
|
||||
|
||||
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
|
||||
|
||||
@@ -39,7 +39,7 @@ Get connection settings
|
||||
"options": {
|
||||
"ports": ["/dev/ttyACM0", "VIRTUAL"],
|
||||
"baudrates": [250000, 230400, 115200, 57600, 38400, 19200, 9600],
|
||||
"printerProfiles": [{"name": "Default", id: "_default"}],
|
||||
"printerProfiles": [{"name": "Default", "id": "_default"}],
|
||||
"portPreference": "/dev/ttyACM0",
|
||||
"baudratePreference": 250000,
|
||||
"printerProfilePreference": "_default",
|
||||
|
||||
@@ -192,6 +192,7 @@ Retrieve all files
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/folderA/subfolder",
|
||||
}
|
||||
}
|
||||
],
|
||||
"size": 1334,
|
||||
"refs": {
|
||||
|
||||
@@ -39,9 +39,7 @@ Retrieve installed language packs
|
||||
"_core": {
|
||||
"identifier": "_core",
|
||||
"name": "Core",
|
||||
"languages": [
|
||||
...
|
||||
]
|
||||
"languages": []
|
||||
},
|
||||
"some_plugin": {
|
||||
"identifier": "some_plugin",
|
||||
@@ -61,7 +59,6 @@ Retrieve installed language packs
|
||||
"last_update": 1470859680,
|
||||
"author": "The italian Transifex Team"
|
||||
}
|
||||
...
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -124,9 +121,7 @@ Delete a language pack
|
||||
"_core": {
|
||||
"identifier": "_core",
|
||||
"name": "Core",
|
||||
"languages": [
|
||||
...
|
||||
]
|
||||
"languages": []
|
||||
},
|
||||
"some_plugin": {
|
||||
"identifier": "some_plugin",
|
||||
@@ -138,8 +133,7 @@ Delete a language pack
|
||||
"locale_english": "German",
|
||||
"last_update": 1474574597,
|
||||
"author": "Gina Häußge"
|
||||
},
|
||||
...
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,10 +62,11 @@ Save settings
|
||||
|
||||
{
|
||||
"api": {
|
||||
"enabled": true,
|
||||
// ...
|
||||
"enabled": true
|
||||
},
|
||||
// ...
|
||||
"appearance": {
|
||||
"color": "black"
|
||||
}
|
||||
}
|
||||
|
||||
.. _sec-api-settings-generateapikey:
|
||||
|
||||
@@ -58,11 +58,9 @@ List All Slicers and Slicing Profiles
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
},
|
||||
...
|
||||
}
|
||||
}
|
||||
},
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
@@ -104,8 +102,7 @@ List Slicing Profiles of a Specific Slicer
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
},
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to list the available profiles.
|
||||
@@ -147,8 +144,7 @@ Retrieve Specific Profile
|
||||
"brim_line_count": 20,
|
||||
"cool_head_lift": false,
|
||||
"cool_min_feedrate": 10.0,
|
||||
"cool_min_layer_time": 5.0,
|
||||
...
|
||||
"cool_min_layer_time": 5.0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -154,7 +154,7 @@ Execute a registered system command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
204 No Content
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:param source: The source for which to list commands, currently either ``core`` or ``custom``
|
||||
:param action: The identifier of the command, ``action`` from its definition
|
||||
|
||||
@@ -104,13 +104,13 @@ octoprint.plugin.pluginmanager.reconnect_hooks
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def reconnect_hooks_hook(*args, **kwargs):
|
||||
return ["octoprint.plugin.exampleplugin.some_custom_hook",
|
||||
"octoprint.plugin.exampleplugin.some_other_custom_hook"]
|
||||
def reconnect_hooks_hook(*args, **kwargs):
|
||||
return ["octoprint.plugin.exampleplugin.some_custom_hook",
|
||||
"octoprint.plugin.exampleplugin.some_other_custom_hook"]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook
|
||||
}
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook
|
||||
}
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-sourcecode:
|
||||
|
||||
|
||||
@@ -14,14 +14,14 @@ First Steps
|
||||
|
||||
Out of the box the Software Update Plugin will be able to notify you of any
|
||||
updates that might be available for your OctoPrint installation or any plugins
|
||||
that registered themselves with it. In order to also be able to update
|
||||
your OctoPrint installation, you'll need to configure
|
||||
at least OctoPrint's checkout folder, and you also should
|
||||
configure the restart commands for OctoPrint and the whole server.
|
||||
that registered themselves with it. In order for automatic restarts after updates
|
||||
to work, you should configure the restart commands for OctoPrint and the whole server.
|
||||
|
||||
For configuring the plugin you'll need to go into OctoPrint's Settings Dialog, navigate to the
|
||||
Software Upda.. _section therein and once you are there click on the little wrench icon in the
|
||||
upper right corner.
|
||||
Out of the box the plugin should already be ready to update your OctoPrint installation to current
|
||||
stable release versions, but you can also switch to one of the available release candidate channels
|
||||
or outright git commit tracking via the plugin's configuration dialog. To open this dialog, fire up OctoPrint's
|
||||
Settings Dialog, navigate to the Software Update section therein and once you are there click on the little
|
||||
wrench icon in the upper right corner.
|
||||
|
||||
.. _fig-bundledplugins-softwareupdate-plugin-configuration:
|
||||
.. figure:: ../images/bundledplugins-softwareupdate-plugin-configuration.png
|
||||
@@ -32,31 +32,16 @@ upper right corner.
|
||||
|
||||
There you can adjust the following settings:
|
||||
|
||||
* **OctoPrint checkout folder**: This should be the path to OctoPrint's git checkout folder (``/home/pi/OctoPrint``
|
||||
for OctoPi or `manual installs following the Raspberry Pi setup guide <https://github.com/foosel/OctoPrint/wiki/Setup-on-a-Raspberry-Pi-running-Raspbian>`_).
|
||||
This must be set to allow updating from within OctoPrint
|
||||
|
||||
.. note::
|
||||
|
||||
OctoPi releases 0.12.0 and later ship with this already setup for you.
|
||||
|
||||
.. note::
|
||||
|
||||
**OctoPi 0.11.0 users**: Please also take a look at
|
||||
`the note at the very end of this FAQ entry <https://github.com/foosel/OctoPrint/wiki/FAQ#how-can-i-update-the-octoprint-installation-on-my-octopi-image>`_.
|
||||
Due to a little issue in that OctoPi release 0.11.0 you might have to fix
|
||||
the URL your OctoPrint checkout is using for updating. This can easily be
|
||||
done by SSHing into your OctoPi instance and doing this::
|
||||
|
||||
cd ~/OctoPrint
|
||||
git remote set-url origin https://github.com/foosel/OctoPrint.git
|
||||
|
||||
* **OctoPrint version tracking**: Whether you want to track OctoPrint *releases* or every *commit*. Usually you want to
|
||||
select "Release" here which is also the default, unless you are a developer.
|
||||
* **OctoPrint Release Channel**: The release channel of OctoPrint to track for updates. If you only want stable versions,
|
||||
* **OctoPrint Release Channel** (if tracking releases): The release channel of OctoPrint to track for updates. If you only want stable versions,
|
||||
select "Stable" here which is also the default. "Maintenance RCs" will also allow you to update to maintenance release
|
||||
candidates, "Devel RCs" will also allow you to update to development release candidates. If in doubt, leave it at
|
||||
"Stable". `Read more about Release Channels here <https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels>`_.
|
||||
* **OctoPrint checkout folder** (if tracking git commits): This must be the path to OctoPrint's git checkout folder
|
||||
(``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide <https://github.com/foosel/OctoPrint/wiki/Setup-on-a-Raspberry-Pi-running-Raspbian>`_).
|
||||
Note that since OctoPrint 1.3.6 you will no longer need to set this to be able to update to releases, only if you
|
||||
want to be able to update against some bleeding edge git branch.
|
||||
* **Version cache TTL**: The "time to live" of the cache OctoPrint will use to temporarily persist the version information
|
||||
for the various components registered with the plugin, so that they don't have to be queried from the internet every time
|
||||
you load the page. Defaults to 24h, you usually shouldn't need to change that value.
|
||||
@@ -132,30 +117,29 @@ Configuring the Plugin
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
plugins:
|
||||
softwareupdate:
|
||||
# the time-to-live of the version cache, in minutes
|
||||
cache_ttl: 60
|
||||
plugins:
|
||||
softwareupdate:
|
||||
# the time-to-live of the version cache, in minutes
|
||||
cache_ttl: 60
|
||||
|
||||
# configured version check and update methods
|
||||
checks:
|
||||
# "octoprint" is reserved for OctoPrint
|
||||
octoprint:
|
||||
# this defines an version check that will check against releases
|
||||
# published on OctoPrint's Github repository and an update method
|
||||
# utilizing an (included) update script that will be run on
|
||||
# OctoPrint's checkout folder
|
||||
type: github_release
|
||||
user: foosel
|
||||
repo: OctoPrint
|
||||
update_script: '{python} "/path/to/octoprint-update.py" --python="{python}" "{folder}" "{target}"'
|
||||
update_folder: /path/to/octoprint/checkout/folder
|
||||
# configured version check and update methods
|
||||
checks:
|
||||
# "octoprint" is reserved for OctoPrint
|
||||
octoprint:
|
||||
# this defines an version check that will check against releases
|
||||
# published on OctoPrint's Github repository and pip as update method
|
||||
# against the release archives on Github - this is the default
|
||||
type: github_release
|
||||
user: foosel
|
||||
repo: OctoPrint
|
||||
method: pip
|
||||
pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip'
|
||||
|
||||
# further checks may be define here
|
||||
# further checks may be define here
|
||||
|
||||
# pip command, if another one than the automatically detected one should be
|
||||
# used - should normally NOT be necessary and hence set
|
||||
pip_command: /path/to/pip
|
||||
# pip command, if another one than the automatically detected one should be
|
||||
# used - should normally NOT be necessary and hence set
|
||||
pip_command: /path/to/pip
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-configuration-versionchecks:
|
||||
|
||||
@@ -249,6 +233,32 @@ Update methods
|
||||
:ref:`hook <sec-bundledplugins-softwareupdate-hooks>`. A python callable
|
||||
which performs the update, see below for details.
|
||||
|
||||
.. note::
|
||||
|
||||
To allow default configurations for multiple update methods, if more than one of
|
||||
the above update method specific settings is set the one to use can be selected
|
||||
by setting the property ``method`` to the method specific setting in question.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example defines both ``pip`` and ``update_script``. By setting to
|
||||
``method`` to ``pip``, the Software Update plugin is instructed to use that as
|
||||
update method.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
plugins:
|
||||
softwareupdate:
|
||||
checks:
|
||||
octoprint:
|
||||
type: github_release
|
||||
user: foosel
|
||||
repo: OctoPrint
|
||||
method: pip
|
||||
pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip'
|
||||
update_script: '{python} "/path/to/octoprint-update.py" --python="{python}" "{folder}" "{target}"'
|
||||
checkout_folder: /path/to/octoprint/checkout/folder
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-configuration-patterns:
|
||||
|
||||
Common configuration patterns
|
||||
@@ -268,6 +278,7 @@ plugin itself):
|
||||
user: foosel
|
||||
repo: OctoPrint
|
||||
branch: devel
|
||||
method: update_script
|
||||
update_folder: /home/pi/OctoPrint
|
||||
|
||||
Plugin installed via pip and hosted on Github under
|
||||
|
||||
@@ -855,7 +855,12 @@ Use the following settings to configure the serial connection to the printer:
|
||||
# Command to send in order to initiate a handshake with the printer.
|
||||
# Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
|
||||
# should be acknowledged with a simple "ok".
|
||||
helloCommand: M110 N0
|
||||
helloCommand:
|
||||
- M110 N0
|
||||
|
||||
# Commands that should never be auto-uppercased when sent to the printer. Defaults to only M117.
|
||||
autoUppercaseBlacklist:
|
||||
- M117
|
||||
|
||||
# Whether to disconnect on errors or not
|
||||
disconnectOnErrors: true
|
||||
|
||||
@@ -58,7 +58,7 @@ Then:
|
||||
virtualenv venv
|
||||
source ./venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop]
|
||||
pip install -e .[develop,plugins]
|
||||
|
||||
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
environment.
|
||||
@@ -89,11 +89,11 @@ Open the Git Bash you just installed and in that:
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source ./venv/bin/activate
|
||||
source ./venv/Scripts/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop]
|
||||
pip install -e .[develop,plugins]
|
||||
|
||||
You can then start OctoPrint via ``/c/Devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
You can then start OctoPrint via ``/c/Devel/OctoPrint/venv/Scripts/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
environment.
|
||||
|
||||
.. _sec-development-environment-mac:
|
||||
@@ -136,7 +136,8 @@ You'll need a user account with administrator privileges.
|
||||
cd OctoPrint
|
||||
virtualenv venv
|
||||
source venv/bin/activate
|
||||
pip install -e .[develop]
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop,plugins]
|
||||
|
||||
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
|
||||
environment.
|
||||
@@ -165,10 +166,16 @@ PyCharm
|
||||
|
||||
* Name: OctoPrint server
|
||||
* Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``)
|
||||
* Script parameters: ``--debug``
|
||||
* Script parameters: ``serve --debug``
|
||||
* Project: ``OctoPrint``
|
||||
* Python interpreter: the ``venv`` local virtual environment
|
||||
* Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
* If you want dependencies to auto-update on run if necessary: "Before Launch" > "+" > "Run external tool" > "+"
|
||||
|
||||
* Name: Update OctoPrint dependencies
|
||||
* Program: ``$PyInterpreterDirectory$/pip`` (or ``$PyInterpreterDirectory$/pip.exe`` on Windows)
|
||||
* Parameters: ``install -e .[develop,plugins]``
|
||||
* Working directory: ``$ProjectFileDir$``
|
||||
|
||||
.. note::
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 24 KiB |
@@ -14,7 +14,7 @@ If you are using it from a web page hosted on OctoPrint as a Jinja2 template, yo
|
||||
methods to embed it instead of manually entering the URL, in order to have OctoPrint take care of setting the
|
||||
correct URL prefix:
|
||||
|
||||
.. code-block:: html
|
||||
.. code-block:: html+jinja
|
||||
|
||||
<!--
|
||||
full client library or all individual files, depending
|
||||
@@ -35,7 +35,7 @@ correct URL prefix:
|
||||
Regardless of which way you use to include the library, you'll also need to make sure you included JQuery and lodash,
|
||||
because the library depends on those to be available (as ``$`` and ``_``). You can embed those like this:
|
||||
|
||||
.. code-block:: html
|
||||
.. code-block:: html+jinja
|
||||
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
@@ -821,9 +821,9 @@ Put something like the following into ``helloworld.css``:
|
||||
:linenos:
|
||||
|
||||
#tab_plugin_helloworld iframe {
|
||||
width: 100%;
|
||||
height: 600px;
|
||||
border: 1px solid #808080;
|
||||
width: 100%;
|
||||
height: 600px;
|
||||
border: 1px solid #808080;
|
||||
}
|
||||
|
||||
Don't forget to remove the ``style`` attribute from the ``iframe`` tag in ``helloworld_tab.jinja2``:
|
||||
|
||||
@@ -37,7 +37,7 @@ INSTALL_REQUIRES = [
|
||||
"pkginfo>=1.4.1,<1.5",
|
||||
"requests>=2.18.4,<3",
|
||||
"semantic_version>=2.6.0,<2.7",
|
||||
"psutil>=5.1.3,<5.2",
|
||||
"psutil>=5.4.1,<6",
|
||||
"Click>=6.7,<6.8",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
@@ -67,7 +67,7 @@ EXTRA_REQUIRES = dict(
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.6,<1.7",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid",
|
||||
"sphinxcontrib-mermaid>=0.3",
|
||||
"sphinx_rtd_theme",
|
||||
|
||||
# PyPi upload related
|
||||
|
||||
@@ -60,7 +60,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
uncaught_handler=None, safe_mode=False, ignore_blacklist=False, after_preinit_logging=None,
|
||||
after_settings=None, after_logging=None, after_safe_mode=None,
|
||||
after_event_manager=None, after_connectivity_checker=None,
|
||||
after_plugin_manager=None):
|
||||
after_plugin_manager=None, after_environment_detector=None):
|
||||
kwargs = dict()
|
||||
|
||||
logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler)
|
||||
@@ -115,8 +115,14 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
|
||||
if callable(after_plugin_manager):
|
||||
after_plugin_manager(**kwargs)
|
||||
|
||||
environment_detector = init_environment_detector(plugin_manager)
|
||||
kwargs["environment_detector"] = environment_detector
|
||||
|
||||
if callable(after_environment_detector):
|
||||
after_environment_detector(**kwargs)
|
||||
|
||||
return settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager
|
||||
return settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector
|
||||
|
||||
|
||||
def init_settings(basedir, configfile):
|
||||
@@ -522,6 +528,10 @@ def init_connectivity_checker(settings, event_manager):
|
||||
return connectivityChecker
|
||||
|
||||
|
||||
def init_environment_detector(plugin_manager):
|
||||
from octoprint.environment import EnvironmentDetector
|
||||
return EnvironmentDetector(plugin_manager)
|
||||
|
||||
#~~ server main method
|
||||
|
||||
def main():
|
||||
|
||||
@@ -214,3 +214,28 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
||||
output = pprint.pformat(value)
|
||||
|
||||
click.echo(output)
|
||||
|
||||
|
||||
@config.command(name="effective")
|
||||
@click.option("--json", "as_json", is_flag=True,
|
||||
help="Output value formatted as JSON")
|
||||
@click.option("--yaml", "as_yaml", is_flag=True,
|
||||
help="Output value formatted as YAML")
|
||||
@click.option("--raw", "as_raw", is_flag=True,
|
||||
help="Output value as raw string representation")
|
||||
@standard_options(hidden=True)
|
||||
@click.pass_context
|
||||
def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
|
||||
"""Retrieves the full effective config."""
|
||||
value = ctx.obj.settings.effective
|
||||
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
output = pprint.pformat(value)
|
||||
|
||||
click.echo(output)
|
||||
+15
-12
@@ -48,7 +48,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
|
||||
logger.info(get_divider_line("*"))
|
||||
|
||||
def log_register_rollover(safe_mode=None, plugin_manager=None, **kwargs):
|
||||
def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs):
|
||||
from octoprint.logging import get_handler, log_to_handler, get_divider_line
|
||||
from octoprint.logging.handlers import OctoPrintLogHandler
|
||||
|
||||
@@ -67,22 +67,24 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
if safe_mode:
|
||||
_log("SAFE MODE is active. Third party plugins are disabled!")
|
||||
plugin_manager.log_all_plugins(only_to_handler=handler)
|
||||
environment_detector.log_detected_environment(only_to_handler=handler)
|
||||
_log(get_divider_line("-"))
|
||||
|
||||
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
|
||||
|
||||
try:
|
||||
settings, _, safe_mode, event_manager, \
|
||||
connectivity_checker, plugin_manager = init_platform(basedir,
|
||||
configfile,
|
||||
logging_file=logging_config,
|
||||
debug=debug,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=__name__,
|
||||
safe_mode=safe_mode,
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
after_safe_mode=log_startup,
|
||||
after_plugin_manager=log_register_rollover)
|
||||
components = init_platform(basedir, configfile,
|
||||
logging_file=logging_config,
|
||||
debug=debug,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=__name__,
|
||||
safe_mode=safe_mode,
|
||||
ignore_blacklist=ignore_blacklist,
|
||||
after_safe_mode=log_startup,
|
||||
after_plugin_manager=log_register_rollover)
|
||||
|
||||
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
|
||||
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error starting up OctoPrint.", err=True)
|
||||
@@ -92,6 +94,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
plugin_manager=plugin_manager,
|
||||
event_manager=event_manager,
|
||||
connectivity_checker=connectivity_checker,
|
||||
environment_detector=environment_detector,
|
||||
host=host,
|
||||
port=port,
|
||||
debug=debug,
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import threading
|
||||
import yaml
|
||||
|
||||
import psutil
|
||||
|
||||
from octoprint.plugin import EnvironmentDetectionPlugin
|
||||
from octoprint.util import get_formatted_size
|
||||
from octoprint.util.platform import get_os
|
||||
|
||||
class EnvironmentDetector(object):
|
||||
|
||||
def __init__(self, plugin_manager):
|
||||
self._plugin_manager = plugin_manager
|
||||
|
||||
self._cache = None
|
||||
self._cache_lock = threading.RLock()
|
||||
|
||||
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
@property
|
||||
def environment(self):
|
||||
with self._cache_lock:
|
||||
if self._cache is None:
|
||||
self.run_detection()
|
||||
return copy.deepcopy(self._cache)
|
||||
|
||||
def run_detection(self, notify_plugins=True):
|
||||
environment = dict()
|
||||
environment["os"] = self._detect_os()
|
||||
environment["python"] = self._detect_python()
|
||||
environment["hardware"] = self._detect_hardware()
|
||||
|
||||
plugin_result = self._detect_from_plugins()
|
||||
if plugin_result:
|
||||
environment["plugins"] = plugin_result
|
||||
|
||||
with self._cache_lock:
|
||||
self._cache = environment
|
||||
|
||||
if notify_plugins:
|
||||
self.notify_plugins()
|
||||
|
||||
return environment
|
||||
|
||||
def _detect_os(self):
|
||||
return dict(id=get_os(),
|
||||
platform=sys.platform)
|
||||
|
||||
def _detect_python(self):
|
||||
result = dict()
|
||||
|
||||
# determine python version
|
||||
result["version"] = platform.python_version()
|
||||
|
||||
# determine if we are running from a virtual environment
|
||||
if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
|
||||
result["virtualenv"] = sys.prefix
|
||||
|
||||
# try to find pip version
|
||||
try:
|
||||
import pip
|
||||
result["pip"] = pip.__version__
|
||||
except:
|
||||
result["pip"] = "unknown"
|
||||
|
||||
return result
|
||||
|
||||
def _detect_hardware(self):
|
||||
return dict(cores=psutil.cpu_count(),
|
||||
freq=psutil.cpu_freq().max,
|
||||
ram=get_formatted_size(psutil.virtual_memory().total))
|
||||
|
||||
def _detect_from_plugins(self):
|
||||
result = dict()
|
||||
|
||||
for implementation in self._environment_plugins:
|
||||
try:
|
||||
additional = implementation.get_additional_environment()
|
||||
if additional is not None and isinstance(additional, dict) and len(additional):
|
||||
result[implementation._identifier] = additional
|
||||
except:
|
||||
self._logger.exception("Error while fetching additional "
|
||||
"environment data from plugin {}".format(implementation._identifier))
|
||||
|
||||
return result
|
||||
|
||||
def log_detected_environment(self, only_to_handler=None):
|
||||
def _log(message, level=logging.INFO):
|
||||
if only_to_handler is not None:
|
||||
import octoprint.logging
|
||||
octoprint.logging.log_to_handler(self._logger, only_to_handler, level, message, [])
|
||||
else:
|
||||
self._logger.log(level, message)
|
||||
|
||||
_log(self._format())
|
||||
|
||||
def _format(self):
|
||||
with self._cache_lock:
|
||||
if self._cache is None:
|
||||
self.run_detection()
|
||||
environment = copy.deepcopy(self._cache)
|
||||
|
||||
dumped_environment = yaml.safe_dump(environment,
|
||||
default_flow_style=False,
|
||||
indent=" ",
|
||||
allow_unicode=True).strip()
|
||||
environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n")))
|
||||
return u"Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
|
||||
environment["os"]["id"].title(),
|
||||
environment["os"]["platform"],
|
||||
environment_lines)
|
||||
|
||||
def notify_plugins(self):
|
||||
with self._cache_lock:
|
||||
if self._cache is None:
|
||||
self.run_detection(notify_plugins=False)
|
||||
environment = copy.deepcopy(self._cache)
|
||||
|
||||
for implementation in self._environment_plugins:
|
||||
try:
|
||||
implementation.on_environment_detected(environment)
|
||||
except:
|
||||
self._logger.exception("Error while sending environment "
|
||||
"detection result to plugin {}".format(implementation._identifier))
|
||||
@@ -44,7 +44,7 @@ def _validate_plugin(phase, plugin_info):
|
||||
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
|
||||
return True
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None,
|
||||
plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
|
||||
plugin_validators=None):
|
||||
"""
|
||||
@@ -59,9 +59,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for
|
||||
potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and
|
||||
``src/plugins`` within OctoPrint's code base.
|
||||
plugin_types (list): A list of recognized plugin types for which to look for provided implementations. If not
|
||||
provided this defaults to the plugin types found in :mod:`octoprint.plugin.types` without
|
||||
:class:`~octoprint.plugin.OctoPrintPlugin`.
|
||||
plugin_bases (list): A list of recognized plugin base classes for which to look for provided implementations. If not
|
||||
provided this defaults to :class:`~octoprint.plugin.OctoPrintPlugin`.
|
||||
plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided
|
||||
this defaults to the entry point ``octoprint.plugin``.
|
||||
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
|
||||
@@ -90,20 +89,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
|
||||
else:
|
||||
if init:
|
||||
if plugin_types is None:
|
||||
plugin_types = [StartupPlugin,
|
||||
ShutdownPlugin,
|
||||
TemplatePlugin,
|
||||
SettingsPlugin,
|
||||
SimpleApiPlugin,
|
||||
AssetPlugin,
|
||||
BlueprintPlugin,
|
||||
EventHandlerPlugin,
|
||||
SlicerPlugin,
|
||||
AppPlugin,
|
||||
ProgressPlugin,
|
||||
WizardPlugin,
|
||||
UiPlugin]
|
||||
if plugin_bases is None:
|
||||
plugin_bases = [OctoPrintPlugin]
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
@@ -118,7 +105,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
plugin_validators.append(_validate_plugin)
|
||||
|
||||
_instance = PluginManager(plugin_folders,
|
||||
plugin_types,
|
||||
plugin_bases,
|
||||
plugin_entry_points,
|
||||
logging_prefix="octoprint.plugins.",
|
||||
plugin_disabled_list=plugin_disabled_list,
|
||||
|
||||
+129
-86
@@ -32,6 +32,7 @@ import imp
|
||||
from collections import defaultdict, namedtuple, OrderedDict
|
||||
import logging
|
||||
import fnmatch
|
||||
import inspect
|
||||
|
||||
import pkg_resources
|
||||
import pkginfo
|
||||
@@ -465,7 +466,7 @@ class PluginManager(object):
|
||||
It is able to discover plugins both through possible file system locations as well as customizable entry points.
|
||||
"""
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None,
|
||||
def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None,
|
||||
plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None,
|
||||
plugin_obsolete_hooks=None, plugin_validators=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
@@ -474,8 +475,8 @@ class PluginManager(object):
|
||||
logging_prefix = ""
|
||||
if plugin_folders is None:
|
||||
plugin_folders = []
|
||||
if plugin_types is None:
|
||||
plugin_types = []
|
||||
if plugin_bases is None:
|
||||
plugin_bases = []
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = []
|
||||
if plugin_disabled_list is None:
|
||||
@@ -484,7 +485,7 @@ class PluginManager(object):
|
||||
plugin_blacklist = []
|
||||
|
||||
self.plugin_folders = plugin_folders
|
||||
self.plugin_types = plugin_types
|
||||
self.plugin_bases = plugin_bases
|
||||
self.plugin_entry_points = plugin_entry_points
|
||||
self.plugin_disabled_list = plugin_disabled_list
|
||||
self.plugin_blacklist = plugin_blacklist
|
||||
@@ -551,53 +552,69 @@ class PluginManager(object):
|
||||
|
||||
result = OrderedDict()
|
||||
if self.plugin_folders:
|
||||
result.update(self._find_plugins_from_folders(self.plugin_folders, existing, ignored_uninstalled=ignore_uninstalled))
|
||||
try:
|
||||
result.update(self._find_plugins_from_folders(self.plugin_folders,
|
||||
existing,
|
||||
ignored_uninstalled=ignore_uninstalled))
|
||||
except:
|
||||
self.logger.exception("Error fetching plugins from folders")
|
||||
if self.plugin_entry_points:
|
||||
existing.update(result)
|
||||
result.update(self._find_plugins_from_entry_points(self.plugin_entry_points, existing, ignore_uninstalled=ignore_uninstalled))
|
||||
try:
|
||||
result.update(self._find_plugins_from_entry_points(self.plugin_entry_points,
|
||||
existing,
|
||||
ignore_uninstalled=ignore_uninstalled))
|
||||
except:
|
||||
self.logger.exception("Error fetching plugins from entry points")
|
||||
return result
|
||||
|
||||
def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True):
|
||||
result = OrderedDict()
|
||||
|
||||
for folder in folders:
|
||||
flagged_readonly = False
|
||||
if isinstance(folder, (list, tuple)):
|
||||
if len(folder) == 2:
|
||||
folder, flagged_readonly = folder
|
||||
else:
|
||||
continue
|
||||
actual_readonly = not os.access(folder, os.W_OK)
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
for entry in scandir(folder):
|
||||
if entry.is_dir() and os.path.isfile(os.path.join(entry.path, "__init__.py")):
|
||||
key = entry.name
|
||||
elif entry.is_file() and entry.name.endswith(".py"):
|
||||
key = entry.name[:-3] # strip off the .py extension
|
||||
if key.startswith("__"):
|
||||
# might be an __init__.py in our plugins folder, or something else we don't want
|
||||
# to handle
|
||||
try:
|
||||
flagged_readonly = False
|
||||
if isinstance(folder, (list, tuple)):
|
||||
if len(folder) == 2:
|
||||
folder, flagged_readonly = folder
|
||||
else:
|
||||
continue
|
||||
else:
|
||||
actual_readonly = not os.access(folder, os.W_OK)
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
for entry in scandir(folder):
|
||||
try:
|
||||
if entry.is_dir() and os.path.isfile(os.path.join(entry.path, "__init__.py")):
|
||||
key = entry.name
|
||||
elif entry.is_file() and entry.name.endswith(".py"):
|
||||
key = entry.name[:-3] # strip off the .py extension
|
||||
if key.startswith("__"):
|
||||
# might be an __init__.py in our plugins folder, or something else we don't want
|
||||
# to handle
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
|
||||
plugin = self._import_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.bundled = flagged_readonly
|
||||
if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin.enabled = False
|
||||
plugin = self._import_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.bundled = flagged_readonly
|
||||
|
||||
result[key] = plugin
|
||||
plugin.enabled = False
|
||||
|
||||
result[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
|
||||
except:
|
||||
self.logger.exception("Error processing folder {}".format(folder))
|
||||
|
||||
return result
|
||||
|
||||
@@ -619,51 +636,65 @@ class PluginManager(object):
|
||||
if not isinstance(groups, (list, tuple)):
|
||||
groups = [groups]
|
||||
|
||||
def wrapped(gen):
|
||||
# to protect against some issues in installed packages that make iteration over entry points
|
||||
# fall on its face - e.g. https://groups.google.com/forum/#!msg/octoprint/DyXdqhR0U7c/kKMUsMmIBgAJ
|
||||
try:
|
||||
yield next(gen)
|
||||
except StopIteration:
|
||||
raise
|
||||
except:
|
||||
self.logger.exception("Something went wrong while processing the entry points of a package in the "
|
||||
"Python environment - broken entry_points.txt in some package?")
|
||||
|
||||
for group in groups:
|
||||
for entry_point in working_set.iter_entry_points(group=group, name=None):
|
||||
key = entry_point.name
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined or marked as uninstalled, ignore it
|
||||
continue
|
||||
|
||||
kwargs = dict(module_name=module_name, version=version)
|
||||
package_name = None
|
||||
for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)):
|
||||
try:
|
||||
module_pkginfo = InstalledEntryPoint(entry_point)
|
||||
key = entry_point.name
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined or marked as uninstalled, ignore it
|
||||
continue
|
||||
|
||||
kwargs = dict(module_name=module_name, version=version)
|
||||
package_name = None
|
||||
try:
|
||||
module_pkginfo = InstalledEntryPoint(entry_point)
|
||||
except:
|
||||
self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
|
||||
else:
|
||||
kwargs.update(dict(
|
||||
name=module_pkginfo.name,
|
||||
summary=module_pkginfo.summary,
|
||||
author=module_pkginfo.author,
|
||||
url=module_pkginfo.home_page,
|
||||
license=module_pkginfo.license
|
||||
))
|
||||
package_name = module_pkginfo.name
|
||||
|
||||
plugin = self._import_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
|
||||
|
||||
# plugin is manageable if its location is writable and OctoPrint
|
||||
# is either not running from a virtual env or the plugin is
|
||||
# installed in that virtual env - the virtual env's pip will not
|
||||
# allow us to uninstall stuff that is installed outside
|
||||
# of the virtual env, so this check is necessary
|
||||
plugin.managable = os.access(plugin.location, os.W_OK) \
|
||||
and (not self._python_virtual_env
|
||||
or is_sub_path_of(plugin.location, self._python_prefix)
|
||||
or is_editable_install(self._python_install_dir,
|
||||
package_name,
|
||||
module_name,
|
||||
plugin.location))
|
||||
|
||||
plugin.enabled = False
|
||||
result[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
|
||||
else:
|
||||
kwargs.update(dict(
|
||||
name=module_pkginfo.name,
|
||||
summary=module_pkginfo.summary,
|
||||
author=module_pkginfo.author,
|
||||
url=module_pkginfo.home_page,
|
||||
license=module_pkginfo.license
|
||||
))
|
||||
package_name = module_pkginfo.name
|
||||
|
||||
plugin = self._import_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
|
||||
|
||||
# plugin is manageable if its location is writable and OctoPrint
|
||||
# is either not running from a virtual env or the plugin is
|
||||
# installed in that virtual env - the virtual env's pip will not
|
||||
# allow us to uninstall stuff that is installed outside
|
||||
# of the virtual env, so this check is necessary
|
||||
plugin.managable = os.access(plugin.location, os.W_OK) \
|
||||
and (not self._python_virtual_env
|
||||
or is_sub_path_of(plugin.location, self._python_prefix)
|
||||
or is_editable_install(self._python_install_dir,
|
||||
package_name,
|
||||
module_name,
|
||||
plugin.location))
|
||||
|
||||
plugin.enabled = False
|
||||
result[key] = plugin
|
||||
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
|
||||
|
||||
return result
|
||||
|
||||
@@ -717,10 +748,10 @@ class PluginManager(object):
|
||||
entry_key, entry_version = entry
|
||||
return entry_key == key and entry_version == version
|
||||
return False
|
||||
|
||||
|
||||
return any(map(lambda entry: matches_plugin(entry),
|
||||
self.plugin_blacklist))
|
||||
|
||||
|
||||
def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None):
|
||||
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(
|
||||
folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders))
|
||||
@@ -945,9 +976,9 @@ class PluginManager(object):
|
||||
|
||||
# evaluate registered implementation
|
||||
if plugin.implementation:
|
||||
for plugin_type in self.plugin_types:
|
||||
if isinstance(plugin.implementation, plugin_type):
|
||||
self.plugin_implementations_by_type[plugin_type].append((name, plugin.implementation))
|
||||
mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases)
|
||||
for mixin in mixins:
|
||||
self.plugin_implementations_by_type[mixin].append((name, plugin.implementation))
|
||||
|
||||
self.plugin_implementations[name] = plugin.implementation
|
||||
|
||||
@@ -970,9 +1001,10 @@ class PluginManager(object):
|
||||
if name in self.plugin_implementations:
|
||||
del self.plugin_implementations[name]
|
||||
|
||||
for plugin_type in self.plugin_types:
|
||||
mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases)
|
||||
for mixin in mixins:
|
||||
try:
|
||||
self.plugin_implementations_by_type[plugin_type].remove((name, plugin.implementation))
|
||||
self.plugin_implementations_by_type[mixin].remove((name, plugin.implementation))
|
||||
except ValueError:
|
||||
# that's ok, the plugin was just not registered for the type
|
||||
pass
|
||||
@@ -1057,6 +1089,17 @@ class PluginManager(object):
|
||||
return any(map(lambda h: fnmatch.fnmatch(hook, h),
|
||||
hooks))
|
||||
|
||||
@staticmethod
|
||||
def mixins_matching_bases(klass, *bases):
|
||||
result = set()
|
||||
for c in inspect.getmro(klass):
|
||||
if c == klass or c in bases:
|
||||
# ignore the exact class and our bases
|
||||
continue
|
||||
if issubclass(c, bases):
|
||||
result.add(c)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def has_any_of_mixins(plugin, *mixins):
|
||||
"""
|
||||
|
||||
@@ -105,6 +105,16 @@ class ReloadNeedingPlugin(Plugin):
|
||||
Mixin for plugin types that need a reload of the UI after enabling/disabling them.
|
||||
"""
|
||||
|
||||
|
||||
class EnvironmentDetectionPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
def get_additional_environment(self):
|
||||
pass
|
||||
|
||||
def on_environment_detected(self, environment, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
|
||||
|
||||
@@ -22,7 +22,9 @@ from collections import OrderedDict
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify
|
||||
from flask_babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
|
||||
|
||||
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
@@ -189,6 +191,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
hash = hashlib.sha1()
|
||||
hash.update(repr(sorted(enabled)))
|
||||
hash.update(repr(sorted(forced)))
|
||||
hash.update(OCTOPRINT_VERSION)
|
||||
|
||||
for channel in sorted(channel_configs.keys()):
|
||||
hash.update(repr(channel_configs[channel]))
|
||||
@@ -404,7 +407,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
summary=_lazy_images(entry["summary"]),
|
||||
summary_without_images=_strip_images(entry["summary"]),
|
||||
published=published,
|
||||
link=entry["link"],
|
||||
link=utmify(entry["link"], source="octoprint", medium="announcements", content=OCTOPRINT_VERSION),
|
||||
read=read)
|
||||
|
||||
def _get_channel_cache_path(self, key):
|
||||
|
||||
@@ -55,6 +55,18 @@ $(function() {
|
||||
return !data.forced;
|
||||
};
|
||||
|
||||
self.cleanedLink = function(data) {
|
||||
// Strips any query parameters from the link and returns it
|
||||
var link = data.link;
|
||||
if (!link) return link;
|
||||
|
||||
var queryPos = link.indexOf("?");
|
||||
if (queryPos !== -1) {
|
||||
link = link.substr(0, queryPos);
|
||||
}
|
||||
return link;
|
||||
};
|
||||
|
||||
self.markRead = function(channel, until) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
@@ -327,10 +339,9 @@ $(function() {
|
||||
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([
|
||||
AnnouncementsViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: AnnouncementsViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
|
||||
});
|
||||
});
|
||||
@@ -27,7 +27,7 @@
|
||||
<h3><a data-bind="text: $data.title, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a> <small data-bind="text: formatTimeAgo($data.published), attr: {title: formatDate($data.published)}"></small></h3>
|
||||
<div class="content" data-bind="html: $data.summary"></div>
|
||||
<div class="actions">
|
||||
<span class="articlelink"><small><a data-bind="text: $data.link, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
|
||||
<span class="articlelink"><small><a data-bind="text: $root.cleanedLink($data), attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
|
||||
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="fa fa-eye"></i> {{ _('Mark as last read') }}</a></small></span>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
@@ -321,29 +321,29 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
CoreWizardAclViewModel,
|
||||
["loginStateViewModel"],
|
||||
"#wizard_plugin_corewizard_acl"
|
||||
], [
|
||||
CoreWizardWebcamViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_webcam"
|
||||
], [
|
||||
CoreWizardServerCommandsViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_servercommands"
|
||||
], [
|
||||
CoreWizardOnlineCheckViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_onlinecheck"
|
||||
], [
|
||||
CoreWizardPluginBlacklistViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_pluginblacklist"
|
||||
], [
|
||||
CoreWizardPrinterProfileViewModel,
|
||||
["printerProfilesViewModel"],
|
||||
"#wizard_plugin_corewizard_printerprofile"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: CoreWizardAclViewModel,
|
||||
dependencies: ["loginStateViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_acl"]
|
||||
}, {
|
||||
construct: CoreWizardWebcamViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_webcam"]
|
||||
}, {
|
||||
construct: CoreWizardServerCommandsViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_servercommands"]
|
||||
}, {
|
||||
construct: CoreWizardOnlineCheckViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_onlinecheck"]
|
||||
}, {
|
||||
construct: CoreWizardPluginBlacklistViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_pluginblacklist"]
|
||||
}, {
|
||||
construct: CoreWizardPrinterProfileViewModel,
|
||||
dependencies: ["printerProfilesViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_printerprofile"]
|
||||
});
|
||||
});
|
||||
@@ -311,10 +311,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
CuraViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
|
||||
["#settings_plugin_cura", "#wizard_plugin_cura"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: CuraViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
|
||||
elements: ["#settings_plugin_cura", "#wizard_plugin_cura"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import flask
|
||||
import os
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
|
||||
_CPUINFO_PATH = "/proc/cpuinfo"
|
||||
|
||||
# based on https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F
|
||||
_RPI_REVISION_MAP = {
|
||||
"Beta": "1B (Beta)",
|
||||
"0002": "1B",
|
||||
"0003": "1B",
|
||||
"0004": "1B",
|
||||
"0005": "1B",
|
||||
"0006": "1B",
|
||||
"0007": "1A",
|
||||
"0008": "1A",
|
||||
"0009": "1A",
|
||||
"000d": "1B",
|
||||
"000e": "1B",
|
||||
"000f": "1B",
|
||||
"0010": "B+",
|
||||
"0011": "CM1",
|
||||
"0012": "A+",
|
||||
"0013": "B+",
|
||||
"0014": "CM1",
|
||||
"0015": "A+",
|
||||
"a01040": "2B",
|
||||
"a01041": "2B",
|
||||
"a21041": "2B",
|
||||
"a22042": "2B",
|
||||
"900021": "A+",
|
||||
"900032": "B+",
|
||||
"900092": "Zero",
|
||||
"900093": "Zero",
|
||||
"920093": "Zero",
|
||||
"9000c1": "Zero W",
|
||||
"a02082": "3B",
|
||||
"a020a0": "CM3",
|
||||
"a22082": "3B",
|
||||
"a32082": "3B",
|
||||
}
|
||||
|
||||
|
||||
def get_octopi_version():
|
||||
with open(_OCTOPI_VERSION_PATH, "r") as f:
|
||||
version_line = f.readline()
|
||||
return version_line.strip()
|
||||
|
||||
|
||||
def get_pi_cpuinfo():
|
||||
fields = dict(revision="Revision",
|
||||
hardware="Hardware",
|
||||
serial="Serial")
|
||||
|
||||
result = dict()
|
||||
with open(_CPUINFO_PATH) as f:
|
||||
for line in f:
|
||||
if not line:
|
||||
continue
|
||||
|
||||
for key, prefix in fields.items():
|
||||
if line.startswith(prefix):
|
||||
result[key] = line[line.index(":") + 1:].strip()
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_pi_model(hardware, revision):
|
||||
if hardware not in ("BCM2835",):
|
||||
return "unknown"
|
||||
|
||||
if revision.startswith("1000"):
|
||||
# strip flag for over-volted (https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F)
|
||||
revision = revision[4:]
|
||||
|
||||
return _RPI_REVISION_MAP.get(revision.lower(), "unknown")
|
||||
|
||||
|
||||
class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._version = None
|
||||
self._cpuinfo = None
|
||||
self._model = None
|
||||
|
||||
#~~ EnvironmentDetectionPlugin
|
||||
|
||||
def get_additional_environment(self):
|
||||
return dict(version=self._get_version(),
|
||||
revision=self._get_cpuinfo().get("revision", "unknown"),
|
||||
model=self._get_model())
|
||||
|
||||
#~~ SimpleApiPlugin
|
||||
|
||||
def on_api_get(self, request):
|
||||
return flask.jsonify(version=self._get_version())
|
||||
|
||||
#~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/octopi_support.js"],
|
||||
css=["css/octopi_support.css"]
|
||||
)
|
||||
|
||||
#~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="about", name="About OctoPi", template="octopi_support_about.jinja2")
|
||||
]
|
||||
|
||||
def get_template_vars(self):
|
||||
version = self._get_version()
|
||||
cpuinfo = self._get_cpuinfo()
|
||||
model = self._get_model()
|
||||
|
||||
return dict(version=version,
|
||||
rpi_revision=cpuinfo.get("revision", "unknown"),
|
||||
rpi_serial=cpuinfo.get("serial", "unknown"),
|
||||
rpi_model=model)
|
||||
|
||||
#~~ Helpers
|
||||
|
||||
def _get_version(self):
|
||||
if self._version is None:
|
||||
try:
|
||||
self._version = get_octopi_version()
|
||||
except:
|
||||
self._logger.exception("Error while reading OctoPi version from file {}".format(_OCTOPI_VERSION_PATH))
|
||||
self._version = "unknown"
|
||||
return self._version
|
||||
|
||||
def _get_model(self):
|
||||
if self._model is None:
|
||||
try:
|
||||
cpuinfo = self._get_cpuinfo()
|
||||
self._model = get_pi_model(cpuinfo.get("hardware", "unknown"),
|
||||
cpuinfo.get("revision", "unknown"))
|
||||
except:
|
||||
self._logger.exception("Error while detecting RPi model")
|
||||
self._model = "unknown"
|
||||
return self._model
|
||||
|
||||
def _get_cpuinfo(self):
|
||||
if self._cpuinfo is None:
|
||||
try:
|
||||
self._cpuinfo = get_pi_cpuinfo()
|
||||
except:
|
||||
self._logger.exception("Error while fetching cpu info")
|
||||
self._cpuinfo = dict()
|
||||
return self._cpuinfo
|
||||
|
||||
__plugin_name__ = "OctoPi Support Plugin"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Provides additional information about your OctoPi instance in the UI."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"provide additional information about your OctoPi instance,"
|
||||
"which will make it more tricky to help you if you need support.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
def __plugin_check__():
|
||||
from octoprint.util.platform import get_os
|
||||
return get_os() == "linux" and os.path.exists(_OCTOPI_VERSION_PATH)
|
||||
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = OctoPiSupportPlugin()
|
||||
@@ -0,0 +1,3 @@
|
||||
#octopi_support_footer {
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintOctoPiSupportClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintOctoPiSupportClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("octopi_support"));
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("octopi_support", OctoPrintOctoPiSupportClient);
|
||||
return OctoPrintOctoPiSupportClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
|
||||
function OctoPiSupportViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.octopi_support.get()
|
||||
.done(function(response) {
|
||||
$("#octopi_support_footer").remove();
|
||||
if (!response.version) return;
|
||||
|
||||
var octoPrintVersion = $(".footer span.version");
|
||||
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
|
||||
+ " <span class='octopi_version'>" + response.version + "</span></span>")
|
||||
$(octoPiVersion).insertAfter(octoPrintVersion);
|
||||
})
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onServerReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: OctoPiSupportViewModel
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
<h3>{{ _('About OctoPi') }}</h3>
|
||||
|
||||
<h4>{{ _('The ready-to-go Raspberry Pi image with OctoPrint') }}</h4>
|
||||
|
||||
<p>Version <span class="plugin_octopi_support_version">{{ plugin_octopi_support_version }}</span></p>
|
||||
|
||||
<ul>
|
||||
<li>Website: <a href="http://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a> & <a href="https://octopi.octoprint.org" target="_blank" rel="noreferrer noopener">octopi.octoprint.org</a></li>
|
||||
<li>Source Code: <a href="https://github.com/guysoft/OctoPi" target="_blank" rel="noreferrer noopener">github.com/guysoft/OctoPi</a></li>
|
||||
</ul>
|
||||
|
||||
<p>
|
||||
© 2013-{{ now.strftime("%Y") }} <a href="https://github.com/guysoft/OctoPi/graphs/contributors" target="_blank" rel="noreferrer noopener">The OctoPi Authors</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
OctoPi is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
</p>
|
||||
<p>
|
||||
OctoPi is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
</p>
|
||||
<p>
|
||||
For a copy of the GNU General Public License, see
|
||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html" target="_blank" rel="noreferrer noopener">www.gnu.org/licenses/gpl-3.0.en.html</a>.
|
||||
</p>
|
||||
|
||||
{% if plugin_octopi_support_rpi_model != "unknown" %}
|
||||
<h3>{{ _('About this Raspberry Pi') }}</h3>
|
||||
|
||||
<ul>
|
||||
<li>Model: {{ plugin_octopi_support_rpi_model }}</li>
|
||||
<li>Revision: {{ plugin_octopi_support_rpi_revision }}</li>
|
||||
<li>Serial: {{ plugin_octopi_support_rpi_serial }}</li>
|
||||
</ul>
|
||||
{% endif %}
|
||||
|
||||
@@ -16,6 +16,7 @@ from octoprint.server import VERSION
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util.pip import LocalPipCaller, UnknownPip
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import get_os
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask_babel import gettext
|
||||
@@ -256,7 +257,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
available=self._repository_available,
|
||||
plugins=self._repository_plugins
|
||||
),
|
||||
os=self._get_os(),
|
||||
os=get_os(),
|
||||
octoprint=get_octoprint_version_string(),
|
||||
pip=dict(
|
||||
available=self._pip_caller.available,
|
||||
@@ -776,7 +777,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if repo_data is None:
|
||||
return False
|
||||
|
||||
current_os = self._get_os()
|
||||
current_os = get_os()
|
||||
octoprint_version = get_octoprint_version(base=True)
|
||||
|
||||
def map_repository_entry(entry):
|
||||
@@ -895,14 +896,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
return positive_match and not negative_match
|
||||
|
||||
@classmethod
|
||||
def _get_os(cls):
|
||||
for identifier, platforms in cls.OPERATING_SYSTEMS.items():
|
||||
if (callable(platforms) and platforms(sys.platform)) or (isinstance(platforms, list) and sys.platform in platforms):
|
||||
return identifier
|
||||
else:
|
||||
return "unmapped"
|
||||
|
||||
@property
|
||||
def _reconnect_hooks(self):
|
||||
reconnect_hooks = self.__class__.RECONNECT_HOOKS
|
||||
|
||||
@@ -197,8 +197,8 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
var restartSpec = _.filter(lastResponse.core, function(spec) { return spec.action == "restart" });
|
||||
self.restartCommandSpec = restartSpec != undefined && restartSpec.length > 0 ? restartSpec[0] : undefined;
|
||||
var restartSpec = _.filter(lastResponse.core, function(spec) { return spec.action === "restart" });
|
||||
self.restartCommandSpec = restartSpec !== undefined && restartSpec.length > 0 ? restartSpec[0] : undefined;
|
||||
});
|
||||
|
||||
self.notifications = [];
|
||||
@@ -208,9 +208,9 @@ $(function() {
|
||||
|
||||
self.noticeCountText = ko.pureComputed(function() {
|
||||
var count = self.noticeCount();
|
||||
if (count == 0) {
|
||||
if (count === 0) {
|
||||
return gettext("There are no plugin notices. Great!");
|
||||
} else if (count == 1) {
|
||||
} else if (count === 1) {
|
||||
return gettext("There is a plugin notice for one of your installed plugins.");
|
||||
} else {
|
||||
return _.sprintf(gettext("There are %(count)d plugin notices for one or more of your installed plugins."), {count: count});
|
||||
@@ -225,15 +225,15 @@ $(function() {
|
||||
var command = self._getToggleCommand(data);
|
||||
var not_safemode_victim = !data.safe_mode_victim || data.safe_mode_enabled;
|
||||
var not_blacklisted = !data.blacklisted;
|
||||
return self.enableManagement() && (command == "disable" || (not_safemode_victim && not_blacklisted)) && data.key != 'pluginmanager';
|
||||
return self.enableManagement() && (command === "disable" || (not_safemode_victim && not_blacklisted)) && data.key !== 'pluginmanager';
|
||||
};
|
||||
|
||||
self.enableUninstall = function(data) {
|
||||
return self.enableManagement()
|
||||
&& (data.origin != "entry_point" || self.pipAvailable())
|
||||
&& (data.origin !== "entry_point" || self.pipAvailable())
|
||||
&& data.managable
|
||||
&& !data.bundled
|
||||
&& data.key != 'pluginmanager'
|
||||
&& data.key !== 'pluginmanager'
|
||||
&& !data.pending_uninstall;
|
||||
};
|
||||
|
||||
@@ -300,7 +300,7 @@ $(function() {
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
add: function(e, data) {
|
||||
if (data.files.length == 0) {
|
||||
if (data.files.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -342,7 +342,7 @@ $(function() {
|
||||
|
||||
self.performRepositorySearch = function() {
|
||||
var query = self.repositorySearchQuery();
|
||||
if (query !== undefined && query.trim() != "") {
|
||||
if (query !== undefined && query.trim() !== "") {
|
||||
query = query.toLocaleLowerCase();
|
||||
self.repositoryplugins.changeSearchFunction(function(entry) {
|
||||
return entry && (entry["title"].toLocaleLowerCase().indexOf(query) > -1 || entry["description"].toLocaleLowerCase().indexOf(query) > -1);
|
||||
@@ -448,7 +448,7 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.key == "pluginmanager") return;
|
||||
if (data.key === "pluginmanager") return;
|
||||
|
||||
var onSuccess = function() {
|
||||
self.requestData();
|
||||
@@ -462,7 +462,7 @@ $(function() {
|
||||
})
|
||||
};
|
||||
|
||||
if (self._getToggleCommand(data) == "enable") {
|
||||
if (self._getToggleCommand(data) === "enable") {
|
||||
if (data.safe_mode_victim && !data.safe_mode_enabled) return;
|
||||
OctoPrint.plugins.pluginmanager.enable(data.key)
|
||||
.done(onSuccess)
|
||||
@@ -583,7 +583,7 @@ $(function() {
|
||||
}
|
||||
|
||||
if (data.bundled) return;
|
||||
if (data.key == "pluginmanager") return;
|
||||
if (data.key === "pluginmanager") return;
|
||||
|
||||
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
|
||||
|
||||
@@ -634,7 +634,7 @@ $(function() {
|
||||
|
||||
self.savePluginSettings = function() {
|
||||
var repository = self.config_repositoryUrl();
|
||||
if (repository != undefined && repository.trim() == "") {
|
||||
if (repository !== undefined && repository.trim() === "") {
|
||||
repository = null;
|
||||
}
|
||||
|
||||
@@ -646,7 +646,7 @@ $(function() {
|
||||
}
|
||||
|
||||
var notices = self.config_noticesUrl();
|
||||
if (notices != undefined && notices.trim() == "") {
|
||||
if (notices !== undefined && notices.trim() === "") {
|
||||
notices = null;
|
||||
}
|
||||
|
||||
@@ -658,7 +658,7 @@ $(function() {
|
||||
}
|
||||
|
||||
var pipArgs = self.config_pipAdditionalArgs();
|
||||
if (pipArgs != undefined && pipArgs.trim() == "") {
|
||||
if (pipArgs !== undefined && pipArgs.trim() === "") {
|
||||
pipArgs = null;
|
||||
}
|
||||
|
||||
@@ -710,7 +710,7 @@ $(function() {
|
||||
};
|
||||
|
||||
if (response.result) {
|
||||
if (action == "install" && response.plugin && response.plugin.blacklisted) {
|
||||
if (action === "install" && response.plugin && response.plugin.blacklisted) {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
text: textSuccess,
|
||||
@@ -863,7 +863,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
|
||||
var icon = self._getToggleCommand(data) === "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -871,7 +871,7 @@ $(function() {
|
||||
|
||||
self.toggleButtonTitle = function(data) {
|
||||
var command = self._getToggleCommand(data);
|
||||
if (command == "enable") {
|
||||
if (command === "enable") {
|
||||
if (data.blacklisted) {
|
||||
return gettext("Blacklisted");
|
||||
} else if (data.safe_mode_victim && !data.safe_mode_enabled) {
|
||||
@@ -885,7 +885,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.showPluginNotifications = function(plugin) {
|
||||
if (!plugin.notifications || plugin.notifications.length == 0) return;
|
||||
if (!plugin.notifications || plugin.notifications.length === 0) return;
|
||||
|
||||
self._removeAllNoticeNotificationsForPlugin(plugin.key);
|
||||
_.each(plugin.notifications, function(notification) {
|
||||
@@ -894,7 +894,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.showPluginNotificationsLinkText = function(plugins) {
|
||||
if (!plugins.notifications || plugins.notifications.length == 0) return;
|
||||
if (!plugins.notifications || plugins.notifications.length === 0) return;
|
||||
|
||||
var count = plugins.notifications.length;
|
||||
var importantCount = _.filter(plugins.notifications, function(notification) { return notification.important }).length;
|
||||
@@ -930,7 +930,7 @@ $(function() {
|
||||
var text = "";
|
||||
|
||||
if (notification.versions && notification.versions.length > 0) {
|
||||
var versions = _.map(notification.versions, function(v) { return (v == version) ? "<strong>" + v + "</strong>" : v; }).join(", ");
|
||||
var versions = _.map(notification.versions, function(v) { return (v === version) ? "<strong>" + v + "</strong>" : v; }).join(", ");
|
||||
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + "</small>";
|
||||
} else {
|
||||
text += "<small>" + gettext("Affected versions: all") + "</small>";
|
||||
@@ -1006,7 +1006,7 @@ $(function() {
|
||||
|
||||
self._isNoticeNotificationHidden = function(key, date) {
|
||||
if (!self.hiddenNoticeNotifications[key]) return false;
|
||||
return _.any(_.map(self.hiddenNoticeNotifications[key], function(d) { return date == d; }));
|
||||
return _.any(_.map(self.hiddenNoticeNotifications[key], function(d) { return date === d; }));
|
||||
};
|
||||
|
||||
var noticeLocalStorageKey = "plugin.pluginmanager.seen_notices";
|
||||
@@ -1040,7 +1040,7 @@ $(function() {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
|
||||
if (localStorage[noticeLocalStorageKey] == undefined)
|
||||
if (localStorage[noticeLocalStorageKey] === undefined)
|
||||
return false;
|
||||
|
||||
var knownData = JSON.parse(localStorage[noticeLocalStorageKey]);
|
||||
@@ -1095,7 +1095,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin != "pluginmanager") {
|
||||
if (plugin !== "pluginmanager") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1109,21 +1109,21 @@ $(function() {
|
||||
|
||||
var messageType = data.type;
|
||||
|
||||
if (messageType == "loglines" && self.working()) {
|
||||
if (messageType === "loglines" && self.working()) {
|
||||
_.each(data.loglines, function(line) {
|
||||
self.loglines.push(self._preprocessLine(line));
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
} else if (messageType == "result") {
|
||||
} else if (messageType === "result") {
|
||||
var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError;
|
||||
var action = data.action;
|
||||
|
||||
var name = "Unknown";
|
||||
if (action == "install") {
|
||||
if (action === "install") {
|
||||
var unknown = false;
|
||||
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
if (data.plugin == "unknown") {
|
||||
if (data.plugin === "unknown") {
|
||||
unknown = true;
|
||||
} else {
|
||||
name = data.plugin.name;
|
||||
@@ -1173,13 +1173,13 @@ $(function() {
|
||||
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
if (data.was_reinstalled) {
|
||||
if (sourceType == "path") {
|
||||
if (sourceType === "path") {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from file failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
|
||||
}
|
||||
} else {
|
||||
if (sourceType == "path") {
|
||||
if (sourceType === "path") {
|
||||
textError = _.sprintf(gettext("Installing the plugin from file failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
|
||||
@@ -1187,13 +1187,13 @@ $(function() {
|
||||
}
|
||||
} else {
|
||||
if (data.was_reinstalled) {
|
||||
if (sourceType == "path") {
|
||||
if (sourceType === "path") {
|
||||
textError = gettext("Reinstalling the plugin from file failed, please see the log for details.");
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
|
||||
}
|
||||
} else {
|
||||
if (sourceType == "path") {
|
||||
if (sourceType === "path") {
|
||||
textError = gettext("Installing the plugin from file failed, please see the log for details.");
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
|
||||
@@ -1201,7 +1201,7 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
} else if (action == "uninstall") {
|
||||
} else if (action === "uninstall") {
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
name = data.plugin.name;
|
||||
}
|
||||
@@ -1219,7 +1219,7 @@ $(function() {
|
||||
textError = gettext("Uninstalling the plugin failed, please see the log for details.");
|
||||
}
|
||||
|
||||
} else if (action == "enable") {
|
||||
} else if (action === "enable") {
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
name = data.plugin.name;
|
||||
}
|
||||
@@ -1237,7 +1237,7 @@ $(function() {
|
||||
textError = gettext("Toggling the plugin failed, please see the log for details.");
|
||||
}
|
||||
|
||||
} else if (action == "disable") {
|
||||
} else if (action === "disable") {
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
name = data.plugin.name;
|
||||
}
|
||||
@@ -1266,17 +1266,16 @@ $(function() {
|
||||
|
||||
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([
|
||||
PluginManagerViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel"],
|
||||
"#settings_plugin_pluginmanager"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PluginManagerViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel"],
|
||||
elements: ["#settings_plugin_pluginmanager"]
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
|
||||
DATA_FORMAT_VERSION = "v2"
|
||||
|
||||
def __init__(self):
|
||||
self._update_in_progress = False
|
||||
@@ -234,13 +236,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
def get_settings_defaults(self):
|
||||
update_script = os.path.join(self._basefolder, "scripts", "update-octoprint.py")
|
||||
default_update_script = "{{python}} \"{update_script}\" --branch={{branch}} " \
|
||||
"--force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script)
|
||||
|
||||
return {
|
||||
"checks": {
|
||||
"octoprint": {
|
||||
"type": "github_release",
|
||||
"user": "foosel",
|
||||
"repo": "OctoPrint",
|
||||
"update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script),
|
||||
"method": "pip",
|
||||
"pip": "https://github.com/foosel/OctoPrint/archive/{target_version}.zip",
|
||||
"update_script": default_update_script,
|
||||
"restart": "octoprint",
|
||||
"stable_branch": dict(branch="master", commitish=["master"], name="Stable"),
|
||||
"prerelease_branches": [dict(branch="rc/maintenance",
|
||||
@@ -320,12 +327,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if "octoprint" in checks:
|
||||
check = checks["octoprint"]
|
||||
update_type = check.get("type", None)
|
||||
update_method = self._get_update_method("octoprint", check)
|
||||
checkout_folder = check.get("checkout_folder", None)
|
||||
update_folder = check.get("update_folder", None)
|
||||
prerelease = check.get("prerelease", False)
|
||||
prerelease_channel = check.get("prerelease_channel", None)
|
||||
else:
|
||||
update_type = checkout_folder = update_folder = prerelease_channel = None
|
||||
update_type = update_method = checkout_folder = update_folder = prerelease_channel = None
|
||||
prerelease = False
|
||||
|
||||
defaults = dict(
|
||||
@@ -333,6 +341,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
checks=dict(
|
||||
octoprint=dict(
|
||||
type=update_type,
|
||||
method=update_method,
|
||||
checkout_folder=checkout_folder,
|
||||
update_folder=update_folder,
|
||||
prerelease=prerelease,
|
||||
@@ -350,10 +359,30 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set(["checks", "octoprint", "update_folder"], None, defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "octoprint_type" in data and data["octoprint_type"] in ("github_release", "git_commit"):
|
||||
self._settings.set(["checks", "octoprint", "type"], data["octoprint_type"], defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
if "octoprint_type" in data:
|
||||
octoprint_type = data["octoprint_type"]
|
||||
|
||||
if octoprint_type == "github_release":
|
||||
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
elif octoprint_type == "git_commit":
|
||||
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if "octoprint_release_channel" in data:
|
||||
prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"])
|
||||
if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]:
|
||||
self._settings.set(["checks", "octoprint", "prerelease"], True, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], data["octoprint_release_channel"],
|
||||
defaults=defaults, force=True)
|
||||
else:
|
||||
self._settings.set(["checks", "octoprint", "prerelease"], False, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, defaults=defaults, force=True)
|
||||
updated_octoprint_check_config = True
|
||||
|
||||
if updated_octoprint_check_config:
|
||||
self._refresh_configured_checks = True
|
||||
try:
|
||||
@@ -362,22 +391,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
pass
|
||||
self._version_cache_dirty = True
|
||||
|
||||
if "octoprint_release_channel" in data:
|
||||
prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"])
|
||||
if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]:
|
||||
self._settings.set(["checks", "octoprint", "prerelease"], True, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], data["octoprint_release_channel"], defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
else:
|
||||
self._settings.set(["checks", "octoprint", "prerelease"], False, defaults=defaults, force=True)
|
||||
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
def get_settings_version(self):
|
||||
return 5
|
||||
return 6
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
if current is None or current < 6:
|
||||
# up until & including config version 5 we didn't set the method parameter for the octoprint check
|
||||
# configuration
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is not None and "octoprint" in configured_checks:
|
||||
octoprint_check = dict(configured_checks["octoprint"])
|
||||
|
||||
if not "method" in octoprint_check and octoprint_check.get("type") == "git_commit":
|
||||
defaults = dict(plugins=dict(softwareupdate=dict(checks=dict(octoprint=dict(method="pip")))))
|
||||
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults)
|
||||
|
||||
if current == 4:
|
||||
# config version 4 didn't correctly remove the old settings for octoprint_restart_command
|
||||
# and environment_restart_command
|
||||
@@ -523,6 +553,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(",".join(targets))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
hash.update(str(self._connectivity_checker.online))
|
||||
hash.update(self.DATA_FORMAT_VERSION)
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -584,7 +615,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
checks = self._get_configured_checks()
|
||||
check = checks.get("octoprint", None)
|
||||
checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
|
||||
return check and "update_script" in check and not checkout_folder
|
||||
return check and "method" in check and check["method"] == "update_script" and not checkout_folder
|
||||
|
||||
##~~ EventHandlerPlugin API
|
||||
|
||||
@@ -688,6 +719,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
releaseNotes=release_notes,
|
||||
online=target_online,
|
||||
error=target_error)
|
||||
|
||||
if target == "octoprint" and "released_version" in populated_check:
|
||||
information[target]["released_version"] = populated_check["released_version"]
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
@@ -1010,24 +1044,22 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# we compare versions fully, not just the base so that we see a difference
|
||||
# between RCs + stable for the same version release
|
||||
result["force_base"] = False
|
||||
|
||||
if check.get("prerelease", None):
|
||||
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
|
||||
channel = check.get("prerelease_channel", None)
|
||||
if channel:
|
||||
# if we have a release channel, we also set our update_branch here to our release channel
|
||||
# in case it's not already set
|
||||
result["update_branch"] = check.get("update_branch", channel)
|
||||
|
||||
else:
|
||||
# we are not tracking prereleases, but aren't on the stable branch either => switch back
|
||||
# to stable branch on update
|
||||
result["update_branch"] = check.get("update_branch", stable_branch)
|
||||
|
||||
if check.get("update_script", None):
|
||||
# if we are using the update_script, we need to set our update_branch
|
||||
|
||||
if check.get("prerelease", None):
|
||||
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
|
||||
channel = check.get("prerelease_channel", None)
|
||||
if channel:
|
||||
# if we have a release channel, we also set our update_branch here to our release channel
|
||||
# in case it's not already set
|
||||
result["update_branch"] = check.get("update_branch", channel)
|
||||
|
||||
else:
|
||||
# we are not tracking prereleases, but aren't on the stable branch either => switch back
|
||||
# to stable branch on update
|
||||
result["update_branch"] = check.get("update_branch", stable_branch)
|
||||
|
||||
# we also force an exact version
|
||||
# we force an exact version
|
||||
result["force_exact_version"] = True
|
||||
|
||||
if BRANCH != result.get("prerelease_channel"):
|
||||
@@ -1038,6 +1070,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# branch of the release channel - unequality means we might have to handle
|
||||
# a downgrade
|
||||
result["release_compare"] = "python_unequal"
|
||||
|
||||
elif check.get("pip", None):
|
||||
# we force python unequality check for pip installs, to be able to downgrade
|
||||
result["release_compare"] = "python_unequal"
|
||||
|
||||
else:
|
||||
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
|
||||
if (arguments.length == 1 && _.isObject(arguments[0])) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
entries = params.entries;
|
||||
force = params.force;
|
||||
@@ -22,7 +22,7 @@
|
||||
}
|
||||
|
||||
entries = entries || [];
|
||||
if (typeof entries == "string") {
|
||||
if (typeof entries === "string") {
|
||||
entries = [entries];
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
|
||||
if (arguments.length == 1 && _.isObject(arguments[0])) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
@@ -47,7 +47,7 @@
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.update = function(entries, force, opts) {
|
||||
if (arguments.length == 1 && _.isObject(arguments[0])) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
entries = params.entries;
|
||||
force = params.force;
|
||||
@@ -55,7 +55,7 @@
|
||||
}
|
||||
|
||||
entries = entries || [];
|
||||
if (typeof entries == "string") {
|
||||
if (typeof entries === "string") {
|
||||
entries = [entries];
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
|
||||
if (arguments.length == 1 && _.isObject(arguments[0])) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
force = params.force;
|
||||
opts = params.opts;
|
||||
@@ -109,8 +109,15 @@ $(function() {
|
||||
|
||||
self.checking = ko.observable(false);
|
||||
|
||||
self.octoprintUnconfigured = ko.observable();
|
||||
self.octoprintUnreleased = ko.observable();
|
||||
self.octoprintReleasedVersion = ko.observable();
|
||||
|
||||
self.octoprintUnconfigured = ko.pureComputed(function() {
|
||||
return self.error_checkoutFolder();
|
||||
});
|
||||
self.octoprintUnreleased = ko.pureComputed(function() {
|
||||
return self.settings.settings.plugins.softwareupdate.octoprint_type() === "github_release"
|
||||
&& !self.octoprintReleasedVersion();
|
||||
});
|
||||
|
||||
self.cacheTimestamp = ko.observable();
|
||||
self.cacheTimestampText = ko.pureComputed(function() {
|
||||
@@ -121,9 +128,18 @@ $(function() {
|
||||
self.config_notifyUsers = ko.observable();
|
||||
self.config_checkoutFolder = ko.observable();
|
||||
self.config_checkType = ko.observable();
|
||||
self.config_updateMethod = ko.observable();
|
||||
self.config_releaseChannel = ko.observable();
|
||||
|
||||
self.error_checkoutFolder = ko.pureComputed(function() {
|
||||
return self.config_checkType() === "git_commit"
|
||||
&& (!self.config_checkoutFolder() || self.config_checkoutFolder().trim() === '');
|
||||
});
|
||||
|
||||
self.enable_configSave = ko.pureComputed(function() {
|
||||
return self.config_checkType() === "github_release"
|
||||
|| (self.config_checkType() === "git_commit" && !self.error_checkoutFolder());
|
||||
});
|
||||
|
||||
self.configurationDialog = undefined;
|
||||
self.confirmationDialog = undefined;
|
||||
self._updateClicked = false;
|
||||
@@ -138,8 +154,8 @@ $(function() {
|
||||
{
|
||||
"name": function(a, b) {
|
||||
// sorts ascending, puts octoprint first
|
||||
if (a.key.toLocaleLowerCase() == "octoprint") return -1;
|
||||
if (b.key.toLocaleLowerCase() == "octoprint") return 1;
|
||||
if (a.key.toLocaleLowerCase() === "octoprint") return -1;
|
||||
if (b.key.toLocaleLowerCase() === "octoprint") return 1;
|
||||
|
||||
if (a.displayName.toLocaleLowerCase() < b.displayName.toLocaleLowerCase()) return -1;
|
||||
if (a.displayName.toLocaleLowerCase() > b.displayName.toLocaleLowerCase()) return 1;
|
||||
@@ -214,9 +230,9 @@ $(function() {
|
||||
softwareupdate: {
|
||||
cache_ttl: parseInt(self.config_cacheTtl()),
|
||||
notify_users: self.config_notifyUsers(),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder(),
|
||||
octoprint_type: self.config_checkType(),
|
||||
octoprint_release_channel: self.config_releaseChannel()
|
||||
octoprint_release_channel: self.config_releaseChannel(),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder()
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -234,15 +250,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
var updateMethod = self.settings.settings.plugins.softwareupdate.octoprint_method();
|
||||
|
||||
var availableCheckTypes = [];
|
||||
if (updateMethod == "update_script" || updateMethod == "python") {
|
||||
availableCheckTypes = [{"key": "github_release", "name": gettext("Release")},
|
||||
var availableCheckTypes = [{"key": "github_release", "name": gettext("Release")},
|
||||
{"key": "git_commit", "name": gettext("Commit")}];
|
||||
} else {
|
||||
availableCheckTypes = [];
|
||||
}
|
||||
self.config_availableCheckTypes(availableCheckTypes);
|
||||
|
||||
var availableReleaseChannels = [];
|
||||
@@ -251,12 +260,12 @@ $(function() {
|
||||
});
|
||||
self.config_availableReleaseChannels(availableReleaseChannels);
|
||||
|
||||
self.config_updateMethod(updateMethod);
|
||||
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
||||
self.config_notifyUsers(self.settings.settings.plugins.softwareupdate.notify_users());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
|
||||
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
|
||||
self.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
};
|
||||
|
||||
self._copyConfigBack = function() {
|
||||
@@ -271,13 +280,13 @@ $(function() {
|
||||
_.each(data.information, function(value, key) {
|
||||
value["key"] = key;
|
||||
|
||||
if (!value.hasOwnProperty("displayName") || value.displayName == "") {
|
||||
if (!value.hasOwnProperty("displayName") || value.displayName === "") {
|
||||
value.displayName = value.key;
|
||||
}
|
||||
if (!value.hasOwnProperty("displayVersion") || value.displayVersion == "") {
|
||||
if (!value.hasOwnProperty("displayVersion") || value.displayVersion === "") {
|
||||
value.displayVersion = value.information.local.name;
|
||||
}
|
||||
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes == "") {
|
||||
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes === "") {
|
||||
value.releaseNotes = undefined;
|
||||
}
|
||||
|
||||
@@ -295,27 +304,11 @@ $(function() {
|
||||
self.versions.updateItems(versions);
|
||||
|
||||
var octoprint = data.information["octoprint"];
|
||||
if (octoprint && octoprint.hasOwnProperty("check")) {
|
||||
var check = octoprint.check;
|
||||
if (check["released_version"] === false && check["type"] == "github_release") {
|
||||
self.octoprintUnreleased(true);
|
||||
} else {
|
||||
self.octoprintUnreleased(false);
|
||||
}
|
||||
|
||||
var checkoutFolder = (check["checkout_folder"] || "").trim();
|
||||
var updateFolder = (check["update_folder"] || "").trim();
|
||||
var needsFolder = check["update_script"] || false;
|
||||
if (needsFolder && checkoutFolder == "" && updateFolder == "") {
|
||||
self.octoprintUnconfigured(true);
|
||||
} else {
|
||||
self.octoprintUnconfigured(false);
|
||||
}
|
||||
}
|
||||
self.octoprintReleasedVersion(!octoprint || octoprint.released_version);
|
||||
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE) && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
if (data.status === "updateAvailable" || data.status === "updatePossible") {
|
||||
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
|
||||
|
||||
text += "<ul class='fa-ul'>";
|
||||
@@ -346,7 +339,7 @@ $(function() {
|
||||
var eventListeners = {};
|
||||
|
||||
var singleButtonNotify = false;
|
||||
if (data.status == "updatePossible" && self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) {
|
||||
if (data.status === "updatePossible" && self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) {
|
||||
// if update is possible and user is admin, add action buttons for ignore and update
|
||||
options["confirm"] = {
|
||||
confirm: true,
|
||||
@@ -394,7 +387,7 @@ $(function() {
|
||||
if ((ignoreSeen || !self._hasNotificationBeenSeen(data.information)) && !OctoPrint.coreui.wizardOpen) {
|
||||
self._showPopup(options, eventListeners, singleButtonNotify);
|
||||
}
|
||||
} else if (data.status == "current") {
|
||||
} else if (data.status === "current") {
|
||||
if (showIfNothingNew) {
|
||||
self._showPopup({
|
||||
title: gettext("Everything is up-to-date"),
|
||||
@@ -474,7 +467,7 @@ $(function() {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
|
||||
if (localStorage["plugin.softwareupdate.seen_information"] == undefined)
|
||||
if (localStorage["plugin.softwareupdate.seen_information"] === undefined)
|
||||
return false;
|
||||
|
||||
var knownData = JSON.parse(localStorage["plugin.softwareupdate.seen_information"]);
|
||||
@@ -487,7 +480,7 @@ $(function() {
|
||||
|
||||
var hasBeenSeen = true;
|
||||
_.each(freshData, function(value, key) {
|
||||
if (!_.has(userData, key) || userData[key] != freshData[key]) {
|
||||
if (!_.has(userData, key) || userData[key] !== freshData[key]) {
|
||||
hasBeenSeen = false;
|
||||
}
|
||||
});
|
||||
@@ -552,7 +545,7 @@ $(function() {
|
||||
});
|
||||
self._updateClicked = false;
|
||||
} else {
|
||||
self.forceUpdate = (force == true);
|
||||
self.forceUpdate = (force === true);
|
||||
self.confirmationDialog.modal("show");
|
||||
}
|
||||
|
||||
@@ -604,10 +597,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (next && _.startsWith(next, "wizard_plugin_softwareupdate")) {
|
||||
if (next && next === "#wizard_plugin_softwareupdate") {
|
||||
// switching to the plugin wizard tab
|
||||
self._copyConfig();
|
||||
} else if (current && _.startsWith(current, "wizard_plugin_softwareupdate")) {
|
||||
} else if (current && current === "#wizard_plugin_softwareupdate") {
|
||||
// switching away from the plugin wizard tab
|
||||
self._copyConfigBack();
|
||||
}
|
||||
@@ -652,7 +645,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin != "softwareupdate") {
|
||||
if (plugin !== "softwareupdate") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -743,7 +736,7 @@ $(function() {
|
||||
|
||||
restartType = messageData.restart_type;
|
||||
text = gettext("The update finished successfully, please restart OctoPrint now.");
|
||||
if (restartType == "environment") {
|
||||
if (restartType === "environment") {
|
||||
text = gettext("The update finished successfully, please reboot the server now.");
|
||||
}
|
||||
|
||||
@@ -764,7 +757,7 @@ $(function() {
|
||||
case "restart_failed": {
|
||||
restartType = messageData.restart_type;
|
||||
text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here.");
|
||||
if (restartType == "environment") {
|
||||
if (restartType === "environment") {
|
||||
text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult the log file on what went wrong here.");
|
||||
}
|
||||
|
||||
@@ -821,7 +814,7 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
if (options != undefined) {
|
||||
if (options !== undefined) {
|
||||
self._showPopup(options);
|
||||
}
|
||||
};
|
||||
@@ -831,17 +824,16 @@ $(function() {
|
||||
"'.*?' does not exist -- can't clean it"];
|
||||
self._forcedStdoutLine = new RegExp(self._forcedStdoutPatterns.join("|"));
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([
|
||||
SoftwareUpdateViewModel,
|
||||
["loginStateViewModel", "printerStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog", "#wizard_plugin_softwareupdate"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SoftwareUpdateViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog", "#wizard_plugin_softwareupdate"]
|
||||
});
|
||||
});
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
<div class="control-group" data-bind="visible: config_updateMethod() == 'update_script' || config_updateMethod() == 'python_updater'">
|
||||
<div class="control-group" data-bind="visible: config_checkType() === 'git_commit', css: {error: error_checkoutFolder}">
|
||||
<label class="control-label">{{ _('OctoPrint checkout folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_checkoutFolder">
|
||||
<span class="help-block" data-bind="visible: error_checkoutFolder">{{ _('This needs to be set if you select commit based version tracking.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<div class="control-group" data-bind="visible: config_availableCheckTypes().length > 0 && config_checkType() == 'github_release'">
|
||||
<div class="control-group" data-bind="visible: config_availableReleaseChannels().length && config_checkType() === 'github_release'">
|
||||
<label class="control-label">{{ _('OctoPrint Release Channel') }}</label>
|
||||
<div class="controls">
|
||||
<select data-bind="value: config_releaseChannel, options: config_availableReleaseChannels, optionsText: 'name', optionsValue: 'key'"></select>
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<div class="control-group" data-bind="visible: config_availableCheckTypes().length > 0">
|
||||
<div class="control-group" data-bind="visible: config_availableCheckTypes().length > 1">
|
||||
<label class="control-label">{{ _('OctoPrint version tracking') }}</label>
|
||||
<div class="controls">
|
||||
<select data-bind="value: config_checkType, options: config_availableCheckTypes, optionsText: 'name', optionsValue: 'key'"></select>
|
||||
|
||||
@@ -76,8 +76,8 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/releaseChannel.jinja2" %}
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Version cache TTL') }}</label>
|
||||
@@ -100,7 +100,7 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: savePluginSettings" aria-hidden="true">{{ _('Save') }}</button>
|
||||
<button class="btn btn-primary" data-bind="enable: enable_configSave, css: {disabled: !enable_configSave()}, click: savePluginSettings" aria-hidden="true">{{ _('Save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
<h3>{{ _('Software Update') }}</h3>
|
||||
|
||||
{% trans %}<p>
|
||||
OctoPrint can update itself via <code>git</code>, but it needs to know its checkout folder and the way
|
||||
it should track available updates in order to be able to do that. You can configure that here.
|
||||
By default, OctoPrint will update itself via <code>pip</code> to published releases. OctoPrint can
|
||||
also update itself via <code>git</code> to arbitrary development branches you need to check out manually.
|
||||
If you want to do that though it needs to know its checkout folder. You can configure that here.
|
||||
</p>{% endtrans %}
|
||||
|
||||
<form class="form-horizontal">
|
||||
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
</form>
|
||||
|
||||
{% trans %}<p>
|
||||
|
||||
@@ -15,6 +15,8 @@ from .. import exceptions
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
|
||||
|
||||
_ALREADY_INSTALLED = "Requirement already satisfied (use --upgrade to upgrade)"
|
||||
|
||||
_pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
@@ -35,7 +37,7 @@ def _get_pip_caller(command=None):
|
||||
|
||||
return _pip_callers[key]
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
|
||||
pip_command = None
|
||||
if "pip_command" in check:
|
||||
pip_command = check["pip_command"]
|
||||
@@ -66,10 +68,10 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
pip_caller.on_log_stdout = _log_stdout
|
||||
pip_caller.on_log_stderr = _log_stderr
|
||||
|
||||
install_arg = check["pip"].format(target_version=target_version)
|
||||
install_arg = check["pip"].format(target_version=target_version, target=target_version)
|
||||
|
||||
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
|
||||
pip_args = ["install", check["pip"].format(target_version=target_version, target=target_version)]
|
||||
pip_args = ["install", install_arg]
|
||||
|
||||
if "dependency_links" in check and check["dependency_links"]:
|
||||
pip_args += ["--process-dependency-links"]
|
||||
@@ -77,12 +79,17 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||
|
||||
if not force and any(map(lambda x: x.strip().startswith(_ALREADY_INSTALLED) and (install_arg in x or install_arg in x.lower()), stdout)):
|
||||
logger.debug(u"Looks like we were already installed in this version. Forcing a reinstall.")
|
||||
force = True
|
||||
|
||||
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
|
||||
if force:
|
||||
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
|
||||
|
||||
return "ok"
|
||||
@@ -64,6 +64,8 @@ class VirtualPrinter(object):
|
||||
for prep in prepared:
|
||||
self._prepared_oks.append(prep)
|
||||
|
||||
self._prepared_errors = []
|
||||
|
||||
self.currentExtruder = 0
|
||||
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||
self.pinnedExtruders = settings().get(["devel", "virtualPrinter", "pinnedExtruders"])
|
||||
@@ -145,6 +147,7 @@ class VirtualPrinter(object):
|
||||
self._triggerResendAt100 = True
|
||||
self._triggerResendWithTimeoutAt105 = True
|
||||
self._triggeredResendWithTimeoutAt105 = False
|
||||
self._triggerResendWithMissingLinenoAt110 = True
|
||||
|
||||
readThread = threading.Thread(target=self._processIncoming, name="octoprint.plugins.virtual_printer.wait_thread")
|
||||
readThread.start()
|
||||
@@ -256,6 +259,18 @@ class VirtualPrinter(object):
|
||||
self._dont_answer = True
|
||||
self.lastN = linenumber
|
||||
continue
|
||||
elif linenumber == 110 and self._triggerResendWithMissingLinenoAt110 and not self._writingToSd:
|
||||
self._triggerResendWithMissingLinenoAt110 = False
|
||||
self._send("Error: No Line Number with checksum, Last Line: {}".format(self.lastN))
|
||||
continue
|
||||
elif len(self._prepared_errors):
|
||||
prepared = self._prepared_errors.pop(0)
|
||||
if callable(prepared):
|
||||
prepared(linenumber, self.lastN, data)
|
||||
continue
|
||||
elif isinstance(prepared, basestring):
|
||||
self._send(prepared)
|
||||
continue
|
||||
else:
|
||||
self.lastN = linenumber
|
||||
data = data.split(None, 1)[1].strip()
|
||||
@@ -276,8 +291,8 @@ class VirtualPrinter(object):
|
||||
continue
|
||||
|
||||
if data.strip() == "version":
|
||||
from octoprint._version import get_versions
|
||||
self._send("OctoPrint VirtualPrinter v" + get_versions()["version"])
|
||||
from octoprint import __version__
|
||||
self._send("OctoPrint VirtualPrinter v" + __version__)
|
||||
continue
|
||||
|
||||
# if we are sending oks before command output, send it now
|
||||
@@ -523,7 +538,7 @@ class VirtualPrinter(object):
|
||||
self._killed = True
|
||||
self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
|
||||
|
||||
def _triggerResend(self, expected=None, actual=None):
|
||||
def _triggerResend(self, expected=None, actual=None, checksum=None):
|
||||
with self._incoming_lock:
|
||||
if expected is None:
|
||||
expected = self.lastN + 1
|
||||
@@ -531,7 +546,10 @@ class VirtualPrinter(object):
|
||||
self.lastN = expected - 1
|
||||
|
||||
if actual is None:
|
||||
self._send("Error: Wrong checksum")
|
||||
if checksum:
|
||||
self._send("Error: Wrong checksum")
|
||||
else:
|
||||
self._send("Error: Missing checksum")
|
||||
else:
|
||||
self._send("Error: expected line %d got %d" % (expected, actual))
|
||||
|
||||
@@ -575,6 +593,10 @@ class VirtualPrinter(object):
|
||||
| Triggers a resend error with a line number mismatch
|
||||
trigger_resend_checksum
|
||||
| Triggers a resend error with a checksum mismatch
|
||||
trigger_missing_checksum
|
||||
| Triggers a resend error with a missing checksum
|
||||
trigger_missing_lineno
|
||||
| Triggers a "no line number with checksum" error w/o resend request
|
||||
drop_connection
|
||||
| Drops the serial connection
|
||||
prepare_ok <broken ok>
|
||||
@@ -606,15 +628,19 @@ class VirtualPrinter(object):
|
||||
elif data == "dont_answer":
|
||||
self._dont_answer = True
|
||||
elif data == "trigger_resend_lineno":
|
||||
self._triggerResend(expected=self.lastN, actual=self.lastN+1)
|
||||
self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, actual=last+1))
|
||||
elif data == "trigger_resend_checksum":
|
||||
self._triggerResend(expected=self.lastN)
|
||||
self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, checksum=True))
|
||||
elif data == "trigger_missing_checksum":
|
||||
self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, checksum=False))
|
||||
elif data == "trigger_missing_lineno":
|
||||
self._prepared_errors.append(lambda cur, last, line: self._send("Error: No Line Number with checksum, Last Line: {}".format(last)))
|
||||
elif data == "drop_connection":
|
||||
self._debug_drop_connection = True
|
||||
elif data == "maxtemp_error":
|
||||
self._output("Error: MAXTEMP triggered!")
|
||||
self._send("Error: MAXTEMP triggered!")
|
||||
elif data == "go_awol":
|
||||
self._output("// Going AWOL")
|
||||
self._send("// Going AWOL")
|
||||
self._debug_awol = True
|
||||
else:
|
||||
try:
|
||||
|
||||
@@ -236,7 +236,7 @@ class PrinterInterface(object):
|
||||
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
|
||||
:since: 1.3.2
|
||||
|
||||
.. warning::
|
||||
|
||||
@@ -259,7 +259,7 @@ class PrinterInterface(object):
|
||||
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
|
||||
:since: 1.3.2
|
||||
|
||||
.. warning::
|
||||
|
||||
|
||||
@@ -117,7 +117,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
}
|
||||
},
|
||||
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
current_z=None
|
||||
current_z=None,
|
||||
offsets=dict()
|
||||
)
|
||||
|
||||
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished)
|
||||
@@ -366,7 +367,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
return
|
||||
|
||||
self._comm.setTemperatureOffset(offsets)
|
||||
self._stateMonitor.set_temp_offsets(offsets)
|
||||
self._setOffsets(offsets)
|
||||
|
||||
def _convert_rate_value(self, factor, min=0, max=200):
|
||||
if not isinstance(factor, (int, float, long)):
|
||||
@@ -633,6 +634,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
#~~ state monitoring
|
||||
|
||||
def _setOffsets(self, offsets):
|
||||
self._stateMonitor.set_temp_offsets(offsets)
|
||||
|
||||
def _setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
self._stateMonitor.set_current_z(self._currentZ)
|
||||
@@ -828,27 +832,30 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return printTimeLeft, printTimeLeftOrigin
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp):
|
||||
def _addTemperatureData(self, tools=None, bed=None):
|
||||
if tools is None:
|
||||
tools = dict()
|
||||
|
||||
currentTimeUtc = int(time.time())
|
||||
|
||||
data = {
|
||||
"time": currentTimeUtc
|
||||
}
|
||||
for tool in temp.keys():
|
||||
for tool in tools.keys():
|
||||
data["tool%d" % tool] = {
|
||||
"actual": temp[tool][0],
|
||||
"target": temp[tool][1]
|
||||
"actual": tools[tool][0],
|
||||
"target": tools[tool][1]
|
||||
}
|
||||
if bedTemp is not None and isinstance(bedTemp, tuple):
|
||||
if bed is not None and isinstance(bed, tuple):
|
||||
data["bed"] = {
|
||||
"actual": bedTemp[0],
|
||||
"target": bedTemp[1]
|
||||
"actual": bed[0],
|
||||
"target": bed[1]
|
||||
}
|
||||
|
||||
self._temps.append(data)
|
||||
|
||||
self._temp = temp
|
||||
self._bedTemp = bedTemp
|
||||
self._temp = tools
|
||||
self._bedTemp = bed
|
||||
|
||||
self._stateMonitor.add_temperature(data)
|
||||
|
||||
@@ -988,7 +995,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._addLog(to_unicode(message, "utf-8", errors="replace"))
|
||||
|
||||
def on_comm_temperature_update(self, temp, bedTemp):
|
||||
self._addTemperatureData(copy.deepcopy(temp), copy.deepcopy(bedTemp))
|
||||
self._addTemperatureData(tools=copy.deepcopy(temp), bed=copy.deepcopy(bedTemp))
|
||||
|
||||
def on_comm_position_update(self, position, reason=None):
|
||||
payload = dict(reason=reason)
|
||||
@@ -1032,6 +1039,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._updateProgressData()
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setOffsets(None)
|
||||
self._addTemperatureData()
|
||||
self._printerProfileManager.deselect()
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
@@ -1266,7 +1275,7 @@ class StateMonitor(object):
|
||||
self._state = None
|
||||
self._job_data = None
|
||||
self._current_z = None
|
||||
self._offsets = {}
|
||||
self._offsets = dict()
|
||||
self._progress = None
|
||||
|
||||
self._progress_dirty = False
|
||||
@@ -1285,11 +1294,12 @@ class StateMonitor(object):
|
||||
return self._on_get_progress()
|
||||
return self._progress
|
||||
|
||||
def reset(self, state=None, job_data=None, progress=None, current_z=None):
|
||||
def reset(self, state=None, job_data=None, progress=None, current_z=None, offsets=None):
|
||||
self.set_state(state)
|
||||
self.set_job_data(job_data)
|
||||
self.set_progress(progress)
|
||||
self.set_current_z(current_z)
|
||||
self.set_temp_offsets(offsets)
|
||||
|
||||
def add_temperature(self, temperature):
|
||||
self._on_add_temperature(temperature)
|
||||
@@ -1328,6 +1338,8 @@ class StateMonitor(object):
|
||||
self._change_event.set()
|
||||
|
||||
def set_temp_offsets(self, offsets):
|
||||
if offsets is None:
|
||||
offsets = dict()
|
||||
self._offsets = offsets
|
||||
self._change_event.set()
|
||||
|
||||
|
||||
@@ -159,11 +159,13 @@ def load_user(id):
|
||||
|
||||
|
||||
class Server(object):
|
||||
def __init__(self, settings=None, plugin_manager=None, connectivity_checker=None, event_manager=None,
|
||||
host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False, octoprint_daemon=None):
|
||||
def __init__(self, settings=None, plugin_manager=None, connectivity_checker=None, environment_detector=None,
|
||||
event_manager=None, host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False,
|
||||
octoprint_daemon=None):
|
||||
self._settings = settings
|
||||
self._plugin_manager = plugin_manager
|
||||
self._connectivity_checker = connectivity_checker
|
||||
self._environment_detector = environment_detector
|
||||
self._event_manager = event_manager
|
||||
self._host = host
|
||||
self._port = port
|
||||
@@ -313,7 +315,8 @@ class Server(object):
|
||||
preemptive_cache=preemptiveCache,
|
||||
json_encoder=jsonEncoder,
|
||||
json_decoder=jsonDecoder,
|
||||
connectivity_checker=connectivityChecker
|
||||
connectivity_checker=connectivityChecker,
|
||||
environment_detector=self._environment_detector
|
||||
)
|
||||
|
||||
#~~ setup access control
|
||||
@@ -441,6 +444,9 @@ class Server(object):
|
||||
|
||||
pluginManager.log_all_plugins()
|
||||
|
||||
# log environment data now
|
||||
self._environment_detector.log_detected_environment()
|
||||
|
||||
# initialize file manager and register it for changes in the registered plugins
|
||||
fileManager.initialize()
|
||||
pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: fileManager.reload_plugins())
|
||||
@@ -543,6 +549,8 @@ class Server(object):
|
||||
joined.update(d)
|
||||
return joined
|
||||
|
||||
util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug
|
||||
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
# .mpg and .mp4 timelapses:
|
||||
@@ -1305,16 +1313,19 @@ class Server(object):
|
||||
less_plugins = list(dynamic_plugin_assets["external"]["less"])
|
||||
|
||||
# a couple of custom filters
|
||||
from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, SourceMapRewrite, SourceMapRemove
|
||||
from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, JsPluginDelimiterBundler, \
|
||||
SourceMapRewrite, SourceMapRemove
|
||||
from webassets.filter import register_filter
|
||||
|
||||
register_filter(LessImportRewrite)
|
||||
register_filter(SourceMapRewrite)
|
||||
register_filter(SourceMapRemove)
|
||||
register_filter(JsDelimiterBundler)
|
||||
register_filter(JsPluginDelimiterBundler)
|
||||
|
||||
# JS
|
||||
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
|
||||
js_plugin_filters = ["sourcemap_remove", "js_plugin_delimiter_bundler"]
|
||||
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters))
|
||||
|
||||
@@ -1324,7 +1335,7 @@ class Server(object):
|
||||
if len(js_plugins) == 0:
|
||||
js_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters=",".join(js_filters))
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters=",".join(js_plugin_filters))
|
||||
|
||||
js_app_bundle = Bundle(js_plugins_bundle, js_core_bundle, output="webassets/packed_app.js", filters=",".join(js_filters))
|
||||
|
||||
|
||||
@@ -156,6 +156,7 @@ def getSettings():
|
||||
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
|
||||
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
|
||||
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
|
||||
"autoUppercaseBlacklist": s.get(["serial", "autoUppercaseBlacklist"]),
|
||||
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
|
||||
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
|
||||
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
|
||||
@@ -383,6 +384,7 @@ def _saveSettings(data):
|
||||
if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean(["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"])
|
||||
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
|
||||
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
|
||||
if "autoUppercaseBlacklist" in data["serial"] and isinstance(data["serial"]["autoUppercaseBlacklist"], (list, tuple)): s.set(["serial", "autoUppercaseBlacklist"], data["serial"]["autoUppercaseBlacklist"])
|
||||
if "supportResendsWithoutOk" in data["serial"]: s.setBoolean(["serial", "supportResendsWithoutOk"], data["serial"]["supportResendsWithoutOk"])
|
||||
if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"])
|
||||
if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"])
|
||||
|
||||
@@ -1232,7 +1232,7 @@ def get_json_command_from_request(request, valid_commands):
|
||||
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
return None, None, make_response("Malformed JSON body or wrong content-type in request", 400)
|
||||
|
||||
if not "command" in data.keys() or not data["command"] in valid_commands.keys():
|
||||
return None, None, make_response("Expected valid command", 400)
|
||||
|
||||
@@ -25,11 +25,35 @@ import tornado.util
|
||||
import octoprint.util
|
||||
|
||||
|
||||
|
||||
#~~ More sensible logging
|
||||
|
||||
|
||||
class RequestlessExceptionLoggingMixin(tornado.web.RequestHandler):
|
||||
|
||||
LOG_REQUEST = False
|
||||
|
||||
def log_exception(self, typ, value, tb, *args, **kwargs):
|
||||
if isinstance(value, tornado.web.HTTPError):
|
||||
if value.log_message:
|
||||
format = "%d %s: " + value.log_message
|
||||
args = ([value.status_code, self._request_summary()] +
|
||||
list(value.args))
|
||||
tornado.web.gen_log.warning(format, *args)
|
||||
else:
|
||||
if self.LOG_REQUEST:
|
||||
tornado.web.app_log.error("Uncaught exception %s\n%r", self._request_summary(),
|
||||
self.request, exc_info=(typ, value, tb))
|
||||
else:
|
||||
tornado.web.app_log.error("Uncaught exception %s", self._request_summary(),
|
||||
exc_info=(typ, value, tb))
|
||||
|
||||
|
||||
#~~ WSGI middleware
|
||||
|
||||
|
||||
@tornado.web.stream_request_body
|
||||
class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin):
|
||||
"""
|
||||
A ``RequestHandler`` similar to ``tornado.web.FallbackHandler`` which fetches any files contained in the request bodies
|
||||
of content type ``multipart``, stores them in temporary files and supplies the ``fallback`` with the file's ``name``,
|
||||
@@ -827,7 +851,7 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar
|
||||
#~~ customized large response handler
|
||||
|
||||
|
||||
class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
class LargeResponseHandler(RequestlessExceptionLoggingMixin, tornado.web.StaticFileHandler):
|
||||
"""
|
||||
Customized `tornado.web.StaticFileHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#tornado.web.StaticFileHandler>`_
|
||||
that allows delivery of the requested resource as attachment and access and request path validation through
|
||||
@@ -888,7 +912,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
filename = self._name_generator(path)
|
||||
if filename is None:
|
||||
filename = os.path.basename(path)
|
||||
|
||||
|
||||
filename = tornado.escape.url_escape(filename, plus=False)
|
||||
self.set_header("Content-Disposition", "attachment; filename=\"{}\"; filename*=UTF-8''{}".format(filename,
|
||||
filename))
|
||||
@@ -917,10 +941,11 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
import stat
|
||||
return os.stat(abspath)[stat.ST_MTIME]
|
||||
|
||||
|
||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||
|
||||
|
||||
class UrlProxyHandler(tornado.web.RequestHandler):
|
||||
class UrlProxyHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
||||
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
|
||||
@@ -1013,7 +1038,7 @@ class UrlProxyHandler(tornado.web.RequestHandler):
|
||||
return "%s%s" % (self._basename, extension)
|
||||
|
||||
|
||||
class StaticDataHandler(tornado.web.RequestHandler):
|
||||
class StaticDataHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandler):
|
||||
def initialize(self, data="", content_type="text/plain"):
|
||||
self.data = data
|
||||
self.content_type = content_type
|
||||
|
||||
@@ -96,5 +96,21 @@ class JsDelimiterBundler(Filter):
|
||||
options = {}
|
||||
|
||||
def input(self, _in, out, **kwargs):
|
||||
source = kwargs.get("source", "n/a")
|
||||
|
||||
out.write("// source: " + source + "\n")
|
||||
out.write(_in.read())
|
||||
out.write("\n;\n")
|
||||
|
||||
|
||||
class JsPluginDelimiterBundler(Filter):
|
||||
name = "js_plugin_delimiter_bundler"
|
||||
options = {}
|
||||
|
||||
def input(self, _in, out, **kwargs):
|
||||
source = kwargs.get("source", "n/a")
|
||||
|
||||
out.write("// source: " + source + "\n")
|
||||
out.write("(function () {\n try {\n ")
|
||||
out.write(_in.read().replace('\n', '\n '))
|
||||
out.write("\n } catch (error) {\n log.error(\"Error in bundled asset " + source + ":\", (error.stack || error));\n }\n})();\n")
|
||||
@@ -111,6 +111,7 @@ default_settings = {
|
||||
"disconnectOnErrors": True,
|
||||
"ignoreErrorsFromFirmware": False,
|
||||
"logResends": True,
|
||||
"autoUppercaseBlacklist": ["M117"],
|
||||
"supportResendsWithoutOk": False,
|
||||
"logPositionOnPause": True,
|
||||
"logPositionOnCancel": True,
|
||||
@@ -273,7 +274,7 @@ default_settings = {
|
||||
],
|
||||
"usersettings": ["access", "interface"],
|
||||
"wizard": ["access"],
|
||||
"about": ["about", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"],
|
||||
"about": ["about", "plugin_octopi_support", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"],
|
||||
"generic": []
|
||||
},
|
||||
"disabled": {
|
||||
@@ -804,7 +805,7 @@ class Settings(object):
|
||||
def last_modified(self):
|
||||
"""
|
||||
Returns:
|
||||
int: The last modification time of the configuration file.
|
||||
(int) The last modification time of the configuration file.
|
||||
"""
|
||||
stat = os.stat(self._configfile)
|
||||
return stat.st_mtime
|
||||
|
||||
@@ -147,7 +147,7 @@ class SlicingManager(object):
|
||||
def slicing_enabled(self):
|
||||
"""
|
||||
Returns:
|
||||
boolean: True if there is at least one configured slicer available, False otherwise.
|
||||
(boolean) True if there is at least one configured slicer available, False otherwise.
|
||||
"""
|
||||
return len(self.configured_slicers) > 0
|
||||
|
||||
@@ -155,7 +155,7 @@ class SlicingManager(object):
|
||||
def registered_slicers(self):
|
||||
"""
|
||||
Returns:
|
||||
list of str: Identifiers of all available slicers.
|
||||
(list of str) Identifiers of all available slicers.
|
||||
"""
|
||||
return self._slicers.keys()
|
||||
|
||||
@@ -163,7 +163,7 @@ class SlicingManager(object):
|
||||
def configured_slicers(self):
|
||||
"""
|
||||
Returns:
|
||||
list of str: Identifiers of all available configured slicers.
|
||||
(list of str) Identifiers of all available configured slicers.
|
||||
"""
|
||||
return map(lambda slicer: slicer.get_slicer_properties()["type"], filter(lambda slicer: slicer.is_slicer_configured(), self._slicers.values()))
|
||||
|
||||
@@ -173,7 +173,7 @@ class SlicingManager(object):
|
||||
Retrieves the default slicer.
|
||||
|
||||
Returns:
|
||||
str: The identifier of the default slicer or ``None`` if the default slicer is not registered in the
|
||||
(str) The identifier of the default slicer or ``None`` if the default slicer is not registered in the
|
||||
system.
|
||||
"""
|
||||
slicer_name = settings().get(["slicing", "defaultSlicer"])
|
||||
|
||||
@@ -1154,7 +1154,7 @@ var escapeUnprintableCharacters = function(str) {
|
||||
};
|
||||
|
||||
var copyToClipboard = function(text) {
|
||||
var temp = $("<input>");
|
||||
var temp = $("<textarea>");
|
||||
$("body").append(temp);
|
||||
temp.val(text).select();
|
||||
document.execCommand("copy");
|
||||
|
||||
@@ -322,11 +322,14 @@ $(function() {
|
||||
// no alternative names? empty array
|
||||
viewModel.additionalNames = viewModel.additionalNames || [];
|
||||
|
||||
// make sure all value's are in an array
|
||||
viewModel.dependencies = (_.isArray(viewModel.dependencies)) ? viewModel.dependencies : [viewModel.dependencies];
|
||||
viewModel.elements = (_.isArray(viewModel.elements)) ? viewModel.elements : [viewModel.elements];
|
||||
viewModel.optional = (_.isArray(viewModel.optional)) ? viewModel.optional : [viewModel.optional];
|
||||
viewModel.additionalNames = (_.isArray(viewModel.additionalNames)) ? viewModel.additionalNames : [viewModel.additionalNames];
|
||||
// make sure all value's are set and in an array
|
||||
_.each(["dependencies", "elements", "optional", "additionalNames"], function(key) {
|
||||
if (viewModel[key] === undefined) {
|
||||
viewModel[key] = [];
|
||||
} else {
|
||||
viewModel[key] = (_.isArray(viewModel[key])) ? viewModel[key] : [viewModel[key]];
|
||||
}
|
||||
});
|
||||
|
||||
// make sure that we don't have two view models going by the same name
|
||||
if (_.has(viewModelMap, viewModel.name)) {
|
||||
|
||||
@@ -37,9 +37,8 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AboutViewModel,
|
||||
[],
|
||||
["#about_dialog", "#footer_about"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: AboutViewModel,
|
||||
elements: ["#about_dialog", "#footer_about"]
|
||||
});
|
||||
});
|
||||
@@ -28,9 +28,9 @@ $(function() {
|
||||
});
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AppearanceViewModel,
|
||||
["settingsViewModel"],
|
||||
"head"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: AppearanceViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["head"]
|
||||
});
|
||||
});
|
||||
@@ -152,9 +152,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
ConnectionViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "printerProfilesViewModel", "accessViewModel"],
|
||||
"#connection_wrapper"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ConnectionViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerProfilesViewModel", "accessViewModel"],
|
||||
elements: ["#connection_wrapper"]
|
||||
});
|
||||
});
|
||||
@@ -51,7 +51,7 @@ $(function() {
|
||||
});
|
||||
|
||||
self.webcamRatioClass = ko.pureComputed(function() {
|
||||
if (self.settings.webcam_streamRatio() == "4:3") {
|
||||
if (self.settings.webcam_streamRatio() === "4:3") {
|
||||
return "ratio43";
|
||||
} else {
|
||||
return "ratio169";
|
||||
@@ -161,7 +161,7 @@ $(function() {
|
||||
|
||||
if (control.hasOwnProperty("children")) {
|
||||
control.children = ko.observableArray(self._processControls(control.children));
|
||||
if (!control.hasOwnProperty("layout") || !(control.layout == "vertical" || control.layout == "horizontal" || control.layout == "horizontal_grid")) {
|
||||
if (!control.hasOwnProperty("layout") || !(control.layout === "vertical" || control.layout === "horizontal" || control.layout === "horizontal_grid")) {
|
||||
control.layout = "vertical";
|
||||
}
|
||||
|
||||
@@ -376,23 +376,23 @@ $(function() {
|
||||
};
|
||||
|
||||
self._enableWebcam = function() {
|
||||
if (OctoPrint.coreui.selectedTab != "#control" || !OctoPrint.coreui.browserTabVisible) {
|
||||
if (OctoPrint.coreui.selectedTab !== "#control" || !OctoPrint.coreui.browserTabVisible) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.webcamDisableTimeout != undefined) {
|
||||
if (self.webcamDisableTimeout !== undefined) {
|
||||
clearTimeout(self.webcamDisableTimeout);
|
||||
}
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
|
||||
// safari bug doesn't release the mjpeg stream, so we just set it up the once
|
||||
if (OctoPrint.coreui.browser.safari && currentSrc != undefined) {
|
||||
if (OctoPrint.coreui.browser.safari && currentSrc !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
var newSrc = self.settings.webcam_streamUrl();
|
||||
if (currentSrc != newSrc) {
|
||||
if (currentSrc !== newSrc) {
|
||||
if (newSrc.lastIndexOf("?") > -1) {
|
||||
newSrc += "&";
|
||||
} else {
|
||||
@@ -421,9 +421,9 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onTabChange = function (current, previous) {
|
||||
if (current == "#control") {
|
||||
if (current === "#control") {
|
||||
self._enableWebcam();
|
||||
} else if (previous == "#control") {
|
||||
} else if (previous === "#control") {
|
||||
self._disableWebcam();
|
||||
}
|
||||
};
|
||||
@@ -559,9 +559,9 @@ $(function() {
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
ControlViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
["#control", "#control_link"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ControlViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#control", "#control_link"]
|
||||
});
|
||||
});
|
||||
@@ -1193,6 +1193,6 @@ $(function() {
|
||||
name: "filesViewModel",
|
||||
additionalNames: ["gcodeFilesViewModel"],
|
||||
dependencies: ["settingsViewModel", "loginStateViewModel", "printerStateViewModel", "slicingViewModel", "printerProfilesViewModel", "accessViewModel"],
|
||||
elements: ["#files_wrapper", "#add_folder_dialog"],
|
||||
elements: ["#files_wrapper", "#add_folder_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -195,7 +195,7 @@ $(function() {
|
||||
});
|
||||
|
||||
self._retrieveBedDimensions = function(currentProfileData) {
|
||||
if (currentProfileData == undefined) {
|
||||
if (currentProfileData === undefined) {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
@@ -203,7 +203,7 @@ $(function() {
|
||||
var x = undefined, y = undefined, r = undefined, circular = false, centeredOrigin = false;
|
||||
|
||||
var formFactor = currentProfileData.volume.formFactor();
|
||||
if (formFactor == "circular") {
|
||||
if (formFactor === "circular") {
|
||||
r = currentProfileData.volume.width() / 2;
|
||||
circular = true;
|
||||
centeredOrigin = true;
|
||||
@@ -211,7 +211,7 @@ $(function() {
|
||||
x = currentProfileData.volume.width();
|
||||
y = currentProfileData.volume.depth();
|
||||
if (currentProfileData.volume.origin) {
|
||||
centeredOrigin = currentProfileData.volume.origin() == "center";
|
||||
centeredOrigin = currentProfileData.volume.origin() === "center";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,7 +228,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self._retrieveToolOffsets = function(currentProfileData) {
|
||||
if (currentProfileData == undefined) {
|
||||
if (currentProfileData === undefined) {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
@@ -247,7 +247,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self._retrieveAxesConfiguration = function(currentProfileData) {
|
||||
if (currentProfileData == undefined) {
|
||||
if (currentProfileData === undefined) {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
@@ -381,7 +381,7 @@ $(function() {
|
||||
self.loadFile = function(path, date){
|
||||
self.enableReload(false);
|
||||
self.needsLoad = false;
|
||||
if (self.status == "idle" && self.errorCount < 3) {
|
||||
if (self.status === "idle" && self.errorCount < 3) {
|
||||
self.status = "request";
|
||||
OctoPrint.files.download("local", path)
|
||||
.done(function(response, rstatus) {
|
||||
@@ -409,10 +409,10 @@ $(function() {
|
||||
GCODE.renderer.clear();
|
||||
GCODE.gCodeReader.loadFile(par);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
if (self.layerSlider !== undefined) {
|
||||
self.layerSlider.slider("disable");
|
||||
}
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
if (self.layerCommandSlider !== undefined) {
|
||||
self.layerCommandSlider.slider("disable");
|
||||
}
|
||||
};
|
||||
@@ -437,10 +437,10 @@ $(function() {
|
||||
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
|
||||
GCODE.ui.updateLayerInfo(cmdIndex.layer);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
if (self.layerSlider !== undefined) {
|
||||
self.layerSlider.slider("setValue", cmdIndex.layer);
|
||||
}
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
if (self.layerCommandSlider !== undefined) {
|
||||
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
|
||||
}
|
||||
};
|
||||
@@ -462,17 +462,17 @@ $(function() {
|
||||
self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused);
|
||||
|
||||
if(self.loadedFilepath
|
||||
&& self.loadedFilepath == data.job.file.path
|
||||
&& self.loadedFileDate == data.job.file.date) {
|
||||
&& self.loadedFilepath === data.job.file.path
|
||||
&& self.loadedFileDate === data.job.file.date) {
|
||||
if (OctoPrint.coreui.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
self._renderPercentage(data.progress.completion);
|
||||
}
|
||||
self.errorCount = 0
|
||||
} else {
|
||||
self.clear();
|
||||
if (data.job.file.path && data.job.file.origin != "sdcard"
|
||||
&& self.status != "request"
|
||||
&& (!self.waitForApproval() || self.selectedFile.path() != data.job.file.path || self.selectedFile.date() != data.job.file.date)) {
|
||||
if (data.job.file.path && data.job.file.origin !== "sdcard"
|
||||
&& self.status !== "request"
|
||||
&& (!self.waitForApproval() || self.selectedFile.path() !== data.job.file.path || self.selectedFile.date() !== data.job.file.date)) {
|
||||
self.selectedFile.path(data.job.file.path);
|
||||
self.selectedFile.date(data.job.file.date);
|
||||
self.selectedFile.size(data.job.file.size);
|
||||
@@ -512,7 +512,7 @@ $(function() {
|
||||
self._onModelLoaded = function(model) {
|
||||
if (!model) {
|
||||
self.ui_modelInfo("");
|
||||
if (self.layerSlider != undefined) {
|
||||
if (self.layerSlider !== undefined) {
|
||||
self.layerSlider.slider("disable");
|
||||
self.layerSlider.slider("setMax", 1);
|
||||
self.layerSlider.slider("setValue", 0);
|
||||
@@ -532,7 +532,7 @@ $(function() {
|
||||
self.ui_modelInfo(output.join("<br>"));
|
||||
|
||||
self.maxLayer = model.layersPrinted - 1;
|
||||
if (self.layerSlider != undefined) {
|
||||
if (self.layerSlider !== undefined) {
|
||||
self.layerSlider.slider("enable");
|
||||
self.layerSlider.slider("setMax", self.maxLayer);
|
||||
self.layerSlider.slider("setValue", 0);
|
||||
@@ -546,7 +546,7 @@ $(function() {
|
||||
self._onLayerSelected = function(layer) {
|
||||
if (!layer) {
|
||||
self.ui_layerInfo("");
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
if (self.layerCommandSlider !== undefined) {
|
||||
self.layerCommandSlider.slider("disable");
|
||||
self.layerCommandSlider.slider("setMax", 1);
|
||||
self.layerCommandSlider.slider("setValue", [0, 1]);
|
||||
@@ -560,8 +560,8 @@ $(function() {
|
||||
output.push(gettext("Layer number") + ": " + (layer.number + 1));
|
||||
output.push(gettext("Layer height") + " (mm): " + layer.height);
|
||||
output.push(gettext("GCODE commands") + ": " + layer.commands);
|
||||
if (layer.filament != undefined) {
|
||||
if (layer.filament.length == 1) {
|
||||
if (layer.filament !== undefined) {
|
||||
if (layer.filament.length === 1) {
|
||||
output.push(gettext("Filament") + ": " + layer.filament[0].toFixed(2) + "mm");
|
||||
} else {
|
||||
for (var i = 0; i < layer.filament.length; i++) {
|
||||
@@ -573,7 +573,7 @@ $(function() {
|
||||
|
||||
self.ui_layerInfo(output.join("<br>"));
|
||||
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
if (self.layerCommandSlider !== undefined) {
|
||||
self.layerCommandSlider.slider("enable");
|
||||
self.layerCommandSlider.slider("setMax", layer.commands - 1);
|
||||
self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]);
|
||||
@@ -588,11 +588,11 @@ $(function() {
|
||||
if (!options) return;
|
||||
|
||||
for (var opt in options) {
|
||||
if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) {
|
||||
if (opt === "zoomInOnModel" && options[opt] !== self.renderer_zoomOnModel()) {
|
||||
self.renderer_zoomOnModel(false);
|
||||
} else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) {
|
||||
} else if (opt === "centerViewport" && options[opt] !== self.renderer_centerViewport()) {
|
||||
self.renderer_centerViewport(false);
|
||||
} else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) {
|
||||
} else if (opt === "moveModel" && options[opt] !== self.renderer_centerModel()) {
|
||||
self.renderer_centerModel(false);
|
||||
}
|
||||
}
|
||||
@@ -602,7 +602,7 @@ $(function() {
|
||||
if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);
|
||||
|
||||
var value = event.value;
|
||||
if (self.currentLayer !== undefined && self.currentLayer == value) return;
|
||||
if (self.currentLayer !== undefined && self.currentLayer === value) return;
|
||||
self.currentLayer = value;
|
||||
|
||||
GCODE.ui.changeSelectedLayer(value);
|
||||
@@ -642,7 +642,7 @@ $(function() {
|
||||
if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);
|
||||
|
||||
var tuple = event.value;
|
||||
if (self.currentCommand !== undefined && self.currentCommand[0] == tuple[0] && self.currentCommand[1] == tuple[1]) return;
|
||||
if (self.currentCommand !== undefined && self.currentCommand[0] === tuple[0] && self.currentCommand[1] === tuple[1]) return;
|
||||
self.currentCommand = tuple;
|
||||
|
||||
GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
|
||||
@@ -657,14 +657,14 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onTabChange = function(current, previous) {
|
||||
self.tabActive = current == "#gcode";
|
||||
self.tabActive = current === "#gcode";
|
||||
if (self.tabActive && self.needsLoad) {
|
||||
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
|
||||
}
|
||||
};
|
||||
|
||||
self.shiftLayer = function(value){
|
||||
if (value != self.currentLayer) {
|
||||
if (value !== self.currentLayer) {
|
||||
self.layerSlider.slider('setValue', value);
|
||||
value = self.layerSlider.slider('getValue');
|
||||
//This sets the scroll bar to the appropriate position.
|
||||
@@ -743,9 +743,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
GcodeViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
["#gcode", "#gcode_link"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: GcodeViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#gcode", "#gcode_link"]
|
||||
});
|
||||
});
|
||||
@@ -65,9 +65,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
LogViewModel,
|
||||
["loginStateViewModel", "accessViewModel"],
|
||||
"#logs"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: LogViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"],
|
||||
elements: ["#logs"]
|
||||
});
|
||||
});
|
||||
@@ -261,9 +261,7 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
LoginStateViewModel,
|
||||
[],
|
||||
[]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: LoginStateViewModel
|
||||
});
|
||||
});
|
||||
@@ -19,9 +19,9 @@ $(function() {
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
NavigationViewModel,
|
||||
["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "userSettingsViewModel", "systemViewModel", "accessViewModel"],
|
||||
"#navbar"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: NavigationViewModel,
|
||||
dependencies: ["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "userSettingsViewModel", "systemViewModel", "accessViewModel"],
|
||||
elements: ["#navbar"]
|
||||
});
|
||||
});
|
||||
@@ -51,7 +51,7 @@ $(function() {
|
||||
self.volumeOrigin = ko.observable();
|
||||
|
||||
self.volumeFormFactor.subscribe(function(value) {
|
||||
if (value == "circular") {
|
||||
if (value === "circular") {
|
||||
self.volumeOrigin("center");
|
||||
}
|
||||
});
|
||||
@@ -123,10 +123,10 @@ $(function() {
|
||||
data = placeholder;
|
||||
}
|
||||
|
||||
var validCharacters = (data && (data == self._sanitize(data)));
|
||||
var validCharacters = (data && (data === self._sanitize(data)));
|
||||
|
||||
var existingProfile = self.profiles.getItem(function(item) {return item.id == data});
|
||||
return !data || !validCharacters || (self.isNew() && existingProfile != undefined);
|
||||
var existingProfile = self.profiles.getItem(function(item) {return item.id === data});
|
||||
return !data || !validCharacters || (self.isNew() && existingProfile !== undefined);
|
||||
});
|
||||
|
||||
self.identifierInvalidText = ko.pureComputed(function() {
|
||||
@@ -136,7 +136,7 @@ $(function() {
|
||||
|
||||
if (!self.identifier() && !self.identifierPlaceholder()) {
|
||||
return gettext("Identifier must be set");
|
||||
} else if (self.identifier() != self._sanitize(self.identifier())) {
|
||||
} else if (self.identifier() !== self._sanitize(self.identifier())) {
|
||||
return gettext("Invalid characters, only a-z, A-Z, 0-9, -, ., _, ( and ) are allowed")
|
||||
} else {
|
||||
return gettext("A profile with such an identifier already exists");
|
||||
@@ -170,9 +170,9 @@ $(function() {
|
||||
};
|
||||
|
||||
var keys = [];
|
||||
if (formFactor == "rectangular") {
|
||||
if (formFactor === "rectangular") {
|
||||
keys = ["lowerleft", "center"];
|
||||
} else if (formFactor == "circular") {
|
||||
} else if (formFactor === "circular") {
|
||||
keys = ["center"];
|
||||
}
|
||||
|
||||
@@ -312,7 +312,7 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
if (profile.volume.formFactor == "circular") {
|
||||
if (profile.volume.formFactor === "circular") {
|
||||
profile.volume.depth = profile.volume.width;
|
||||
}
|
||||
|
||||
@@ -320,7 +320,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.defaultBoundingBox = function(width, depth, height, origin) {
|
||||
if (origin == "center") {
|
||||
if (origin === "center") {
|
||||
var halfWidth = width / 2.0;
|
||||
var halfDepth = depth / 2.0;
|
||||
|
||||
@@ -526,7 +526,7 @@ $(function() {
|
||||
})
|
||||
.fail(function(xhr) {
|
||||
var text;
|
||||
if (xhr.status == 409) {
|
||||
if (xhr.status === 409) {
|
||||
text = gettext("Cannot delete the default profile or the currently active profile.");
|
||||
} else {
|
||||
text = gettext("There was unexpected error while removing the printer profile, please consult the logs.");
|
||||
@@ -541,7 +541,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.updateProfile = function(profile, callback) {
|
||||
if (profile == undefined) {
|
||||
if (profile === undefined) {
|
||||
profile = self.editor.toProfileData();
|
||||
}
|
||||
|
||||
@@ -610,9 +610,8 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
PrinterProfilesViewModel,
|
||||
["loginStateViewModel", "accessViewModel"],
|
||||
[]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PrinterProfilesViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ $(function() {
|
||||
self.isReady() &&
|
||||
!self.isPrinting() &&
|
||||
self.loginState.hasPermission(self.access.permissions.PRINT) &&
|
||||
self.filename() != undefined;
|
||||
self.filename() !== undefined;
|
||||
});
|
||||
self.enablePause = ko.pureComputed(function() {
|
||||
return self.isOperational() &&
|
||||
@@ -84,7 +84,7 @@ $(function() {
|
||||
return formatDuration(self.printTime());
|
||||
});
|
||||
self.printTimeLeftString = ko.pureComputed(function() {
|
||||
if (self.printTimeLeft() == undefined) {
|
||||
if (self.printTimeLeft() === undefined) {
|
||||
if (!self.printTime() || !(self.isPrinting() || self.isPaused())) {
|
||||
return "-";
|
||||
} else {
|
||||
@@ -163,9 +163,9 @@ $(function() {
|
||||
return "-";
|
||||
|
||||
var type = timelapse["type"];
|
||||
if (type == "zchange") {
|
||||
if (type === "zchange") {
|
||||
return gettext("On Z Change");
|
||||
} else if (type == "timed") {
|
||||
} else if (type === "timed") {
|
||||
return gettext("Timed") + " (" + timelapse["options"]["interval"] + " " + gettext("sec") + ")";
|
||||
} else {
|
||||
return "-";
|
||||
@@ -204,7 +204,7 @@ $(function() {
|
||||
self.isReady(data.flags.ready);
|
||||
self.isSdReady(data.flags.sdReady);
|
||||
|
||||
if (self.isPaused() != prevPaused) {
|
||||
if (self.isPaused() !== prevPaused) {
|
||||
if (self.isPaused()) {
|
||||
self.titlePrintButton(self.TITLE_PRINT_BUTTON_PAUSED);
|
||||
self.titlePauseButton(self.TITLE_PAUSE_BUTTON_PAUSED);
|
||||
@@ -221,7 +221,7 @@ $(function() {
|
||||
self.filepath(data.file.path);
|
||||
self.filesize(data.file.size);
|
||||
self.filedisplay(data.file.display);
|
||||
self.sd(data.file.origin == "sdcard");
|
||||
self.sd(data.file.origin === "sdcard");
|
||||
} else {
|
||||
self.filename(undefined);
|
||||
self.filepath(undefined);
|
||||
@@ -234,7 +234,7 @@ $(function() {
|
||||
self.lastPrintTime(data.lastPrintTime);
|
||||
|
||||
var result = [];
|
||||
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
|
||||
if (data.filament && typeof(data.filament) === "object" && _.keys(data.filament).length > 0) {
|
||||
var keys = _.keys(data.filament);
|
||||
keys.sort();
|
||||
_.each(keys, function(key) {
|
||||
@@ -316,9 +316,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
PrinterStateViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
["#state_wrapper", "#drop_overlay"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PrinterStateViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#state_wrapper", "#drop_overlay"]
|
||||
});
|
||||
});
|
||||
@@ -41,7 +41,7 @@ $(function() {
|
||||
});
|
||||
self.enableTranslationUpload = ko.pureComputed(function() {
|
||||
var name = self.translationUploadFilename();
|
||||
return name !== undefined && name.trim() != "" && !self.invalidTranslationArchive();
|
||||
return name !== undefined && name.trim() !== "" && !self.invalidTranslationArchive();
|
||||
});
|
||||
|
||||
self.translations = new ItemListHelper(
|
||||
@@ -176,6 +176,7 @@ $(function() {
|
||||
self.serial_ignoreErrorsFromFirmware = ko.observable(undefined);
|
||||
self.serial_disconnectOnErrors = ko.observable(undefined);
|
||||
self.serial_triggerOkForM29 = ko.observable(undefined);
|
||||
self.serial_autoUppercaseBlacklist = ko.observable(undefined);
|
||||
self.serial_supportResendsWithoutOk = ko.observable(undefined);
|
||||
self.serial_logPositionOnPause = ko.observable(undefined);
|
||||
self.serial_logPositionOnCancel = ko.observable(undefined);
|
||||
@@ -417,7 +418,7 @@ $(function() {
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
if (data.files.length == 0) {
|
||||
if (data.files.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -446,14 +447,14 @@ $(function() {
|
||||
|
||||
self.settingsDialog.on('show', function(event) {
|
||||
OctoPrint.coreui.settingsOpen = true;
|
||||
if (event.target.id == "settings_dialog") {
|
||||
if (event.target.id === "settings_dialog") {
|
||||
self.requestTranslationData();
|
||||
callViewModels(allViewModels, "onSettingsShown");
|
||||
}
|
||||
});
|
||||
self.settingsDialog.on('hidden', function(event) {
|
||||
OctoPrint.coreui.settingsOpen = false;
|
||||
if (event.target.id == "settings_dialog") {
|
||||
if (event.target.id === "settings_dialog") {
|
||||
callViewModels(allViewModels, "onSettingsHidden");
|
||||
}
|
||||
});
|
||||
@@ -527,11 +528,11 @@ $(function() {
|
||||
self.requestData = function(local) {
|
||||
// handle old parameter format
|
||||
var callback = undefined;
|
||||
if (arguments.length == 2 || _.isFunction(local)) {
|
||||
if (arguments.length === 2 || _.isFunction(local)) {
|
||||
var exc = new Error();
|
||||
log.warn("The callback parameter of SettingsViewModel.requestData is deprecated, the method now returns a promise, please use that instead. Stacktrace:", (exc.stack || exc.stacktrace || "<n/a>"));
|
||||
|
||||
if (arguments.length == 2) {
|
||||
if (arguments.length === 2) {
|
||||
callback = arguments[0];
|
||||
local = arguments[1];
|
||||
} else {
|
||||
@@ -628,8 +629,8 @@ $(function() {
|
||||
var translations = [];
|
||||
_.each(translationsByLocale, function(item) {
|
||||
item["packs"].sort(function(a, b) {
|
||||
if (a.identifier == "_core") return -1;
|
||||
if (b.identifier == "_core") return 1;
|
||||
if (a.identifier === "_core") return -1;
|
||||
if (b.identifier === "_core") return 1;
|
||||
|
||||
if (a.display < b.display) return -1;
|
||||
if (a.display > b.display) return 1;
|
||||
@@ -642,7 +643,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.languagePackDisplay = function(item) {
|
||||
return item.display + ((item.english != undefined) ? ' (' + item.english + ')' : '');
|
||||
return item.display + ((item.english !== undefined) ? ' (' + item.english + ')' : '');
|
||||
};
|
||||
|
||||
self.languagePacksAvailable = ko.pureComputed(function() {
|
||||
@@ -659,7 +660,7 @@ $(function() {
|
||||
*/
|
||||
self.getLocalData = function() {
|
||||
var data = {};
|
||||
if (self.settings != undefined) {
|
||||
if (self.settings !== undefined) {
|
||||
data = ko.mapping.toJS(self.settings);
|
||||
}
|
||||
|
||||
@@ -667,14 +668,15 @@ $(function() {
|
||||
var specialMappings = {
|
||||
feature: {
|
||||
externalHeatupDetection: function() { return !self.feature_disableExternalHeatupDetection()},
|
||||
alwaysSendChecksum: function() { return self.feature_sendChecksum() == "always"},
|
||||
neverSendChecksum: function() { return self.feature_sendChecksum() == "never"}
|
||||
alwaysSendChecksum: function() { return self.feature_sendChecksum() === "always"},
|
||||
neverSendChecksum: function() { return self.feature_sendChecksum() === "never"}
|
||||
},
|
||||
serial: {
|
||||
additionalPorts : function() { return commentableLinesToArray(self.serial_additionalPorts()) },
|
||||
additionalBaudrates: function() { return _.map(splitTextToArray(self.serial_additionalBaudrates(), ",", true, function(item) { return !isNaN(parseInt(item)); }), function(item) { return parseInt(item); }) },
|
||||
longRunningCommands: function() { return splitTextToArray(self.serial_longRunningCommands(), ",", true) },
|
||||
checksumRequiringCommands: function() { return splitTextToArray(self.serial_checksumRequiringCommands(), ",", true) }
|
||||
checksumRequiringCommands: function() { return splitTextToArray(self.serial_checksumRequiringCommands(), ",", true) },
|
||||
autoUppercaseBlacklist: function() { return splitTextToArray(self.serial_autoUppercaseBlacklist(), ",", true) }
|
||||
},
|
||||
scripts: {
|
||||
gcode: function() {
|
||||
@@ -708,7 +710,7 @@ $(function() {
|
||||
// process all key-value-pairs here
|
||||
_.forOwn(data, function(value, key) {
|
||||
var observable = key;
|
||||
if (keyPrefix != undefined) {
|
||||
if (keyPrefix !== undefined) {
|
||||
observable = keyPrefix + "_" + observable;
|
||||
}
|
||||
|
||||
@@ -718,7 +720,7 @@ $(function() {
|
||||
} else if (_.isPlainObject(value)) {
|
||||
// value is another object, we'll dive deeper
|
||||
var subresult = mapFromObservables(value, (mapping && mapping[key]) ? mapping[key] : undefined, observable);
|
||||
if (subresult != undefined) {
|
||||
if (subresult !== undefined) {
|
||||
// we only set something on our result if we got something back
|
||||
result[key] = subresult;
|
||||
flag = true;
|
||||
@@ -785,7 +787,8 @@ $(function() {
|
||||
additionalPorts : function(value) { self.serial_additionalPorts(value.join("\n"))},
|
||||
additionalBaudrates: function(value) { self.serial_additionalBaudrates(value.join(", "))},
|
||||
longRunningCommands: function(value) { self.serial_longRunningCommands(value.join(", "))},
|
||||
checksumRequiringCommands: function(value) { self.serial_checksumRequiringCommands(value.join(", "))}
|
||||
checksumRequiringCommands: function(value) { self.serial_checksumRequiringCommands(value.join(", "))},
|
||||
autoUppercaseBlacklist: function(value) { self.serial_autoUppercaseBlacklist(value.join(", "))}
|
||||
},
|
||||
terminalFilters: function(value) { self.terminalFilters($.extend(true, [], value)) },
|
||||
temperature: {
|
||||
@@ -801,7 +804,7 @@ $(function() {
|
||||
// process all key-value-pairs here
|
||||
_.forOwn(data, function(value, key) {
|
||||
var observable = key;
|
||||
if (keyPrefix != undefined) {
|
||||
if (keyPrefix !== undefined) {
|
||||
observable = keyPrefix + "_" + observable;
|
||||
}
|
||||
|
||||
@@ -832,16 +835,16 @@ $(function() {
|
||||
} else {
|
||||
options = {
|
||||
success: successCallback,
|
||||
sending: (setAsSending == true)
|
||||
sending: (setAsSending === true)
|
||||
}
|
||||
}
|
||||
|
||||
self.settingsDialog.trigger("beforeSave");
|
||||
|
||||
self.sawUpdateEventWhileSending = false;
|
||||
self.sending(data == undefined || options.sending || false);
|
||||
self.sending(data === undefined || options.sending || false);
|
||||
|
||||
if (data == undefined) {
|
||||
if (data === undefined) {
|
||||
// we also only send data that actually changed when no data is specified
|
||||
data = getOnlyChangedData(self.getLocalData(), self.lastReceivedSettings);
|
||||
}
|
||||
@@ -920,7 +923,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.selectTab = function(tab) {
|
||||
if (tab != undefined) {
|
||||
if (tab !== undefined) {
|
||||
if (!_.startsWith(tab, "#")) {
|
||||
tab = "#" + tab;
|
||||
}
|
||||
@@ -949,9 +952,9 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
SettingsViewModel,
|
||||
["loginStateViewModel", "accessViewModel", "printerProfilesViewModel", "aboutViewModel", "usersViewModel"],
|
||||
["#settings_dialog", "#navbar_settings"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SettingsViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel", "printerProfilesViewModel", "aboutViewModel", "usersViewModel"],
|
||||
elements: ["#settings_dialog", "#navbar_settings"]
|
||||
});
|
||||
});
|
||||
@@ -41,10 +41,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.profilesForSlicer = function(key) {
|
||||
if (key == undefined) {
|
||||
if (key === undefined) {
|
||||
key = self.slicer();
|
||||
}
|
||||
if (key == undefined || !self.data.hasOwnProperty(key)) {
|
||||
if (key === undefined || !self.data.hasOwnProperty(key)) {
|
||||
return;
|
||||
}
|
||||
var slicer = self.data[key];
|
||||
@@ -53,7 +53,7 @@ $(function() {
|
||||
self.profiles.removeAll();
|
||||
_.each(_.values(slicer.profiles), function(profile) {
|
||||
var name = profile.displayName;
|
||||
if (name == undefined) {
|
||||
if (name === undefined) {
|
||||
name = profile.key;
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.metadataForSlicer = function(key) {
|
||||
if (key == undefined || !self.data.hasOwnProperty(key)) {
|
||||
if (key === undefined || !self.data.hasOwnProperty(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ $(function() {
|
||||
|
||||
var containsSlicer = function(key) {
|
||||
return _.any(slicers, function(slicer) {
|
||||
return slicer.key == key;
|
||||
return slicer.key === key;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -134,7 +134,7 @@ $(function() {
|
||||
}
|
||||
|
||||
var filename = file;
|
||||
if (filename.lastIndexOf("/") != 0) {
|
||||
if (filename.lastIndexOf("/") !== 0) {
|
||||
path = path || filename.substr(0, filename.lastIndexOf("/"));
|
||||
filename = filename.substr(filename.lastIndexOf("/") + 1);
|
||||
}
|
||||
@@ -173,10 +173,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.enableSliceButton = ko.pureComputed(function() {
|
||||
return self.destinationFilename() != undefined
|
||||
&& self.destinationFilename().trim() != ""
|
||||
&& self.slicer() != undefined
|
||||
&& self.profile() != undefined
|
||||
return self.destinationFilename() !== undefined
|
||||
&& self.destinationFilename().trim() !== ""
|
||||
&& self.slicer() !== undefined
|
||||
&& self.profile() !== undefined
|
||||
&& (!(self.printerState.isPrinting() || self.printerState.isPaused()) || !self.slicerSameDevice());
|
||||
});
|
||||
|
||||
@@ -227,7 +227,7 @@ $(function() {
|
||||
self.slicers.removeAll();
|
||||
_.each(_.values(data), function(slicer) {
|
||||
var name = slicer.displayName;
|
||||
if (name == undefined) {
|
||||
if (name === undefined) {
|
||||
name = slicer.key;
|
||||
}
|
||||
|
||||
@@ -276,13 +276,13 @@ $(function() {
|
||||
destination: destinationFilename
|
||||
};
|
||||
|
||||
if (self.path != undefined) {
|
||||
if (self.path !== undefined) {
|
||||
data["path"] = self.path;
|
||||
}
|
||||
|
||||
if (self.afterSlicing() == "print") {
|
||||
if (self.afterSlicing() === "print") {
|
||||
data["print"] = true;
|
||||
} else if (self.afterSlicing() == "select") {
|
||||
} else if (self.afterSlicing() === "select") {
|
||||
data["select"] = true;
|
||||
}
|
||||
|
||||
@@ -313,9 +313,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
SlicingViewModel,
|
||||
["loginStateViewModel", "printerProfilesViewModel", "printerStateViewModel"],
|
||||
"#slicing_configuration_dialog"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SlicingViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerProfilesViewModel", "printerStateViewModel"],
|
||||
elements: ["#slicing_configuration_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -110,10 +110,8 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([
|
||||
SystemViewModel,
|
||||
["loginStateViewModel"],
|
||||
[]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SystemViewModel,
|
||||
dependencies: ["loginStateViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -119,7 +119,7 @@ $(function() {
|
||||
tools[extruder]["name"](gettext("Tool") + " " + extruder);
|
||||
tools[extruder]["key"]("tool" + extruder);
|
||||
}
|
||||
} else if (numExtruders == 1 || sharedNozzle) {
|
||||
} else if (numExtruders === 1 || sharedNozzle) {
|
||||
// only one extruder, no need to add numbers
|
||||
color = graphColors[0];
|
||||
heaterOptions["tool0"] = {name: "T", color: color};
|
||||
@@ -224,6 +224,9 @@ $(function() {
|
||||
if (lastData.hasOwnProperty("bed")) {
|
||||
self.bedTemp["actual"](lastData.bed.actual);
|
||||
self.bedTemp["target"](lastData.bed.target);
|
||||
} else {
|
||||
self.bedTemp["actual"](0);
|
||||
self.bedTemp["target"](0);
|
||||
}
|
||||
|
||||
if (!CONFIG_TEMPERATURE_GRAPH) return;
|
||||
@@ -242,11 +245,15 @@ $(function() {
|
||||
for (var i = 0; i < tools.length; i++) {
|
||||
if (data.hasOwnProperty("tool" + i)) {
|
||||
tools[i]["offset"](data["tool" + i]);
|
||||
} else {
|
||||
tools[i]["offset"](0);
|
||||
}
|
||||
}
|
||||
|
||||
if (data.hasOwnProperty("bed")) {
|
||||
self.bedTemp["offset"](data["bed"]);
|
||||
} else {
|
||||
self.bedTemp["offset"](0);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -727,9 +734,13 @@ $(function() {
|
||||
if (value === undefined || (typeof(value) === "string" && value.trim() === "")) {
|
||||
item.newTarget(item.target());
|
||||
}
|
||||
event.target.select();
|
||||
window.setTimeout(function() {
|
||||
event.target.select();
|
||||
}, 0);
|
||||
} else if (type === "offset") {
|
||||
event.target.select();
|
||||
window.setTimeout(function() {
|
||||
event.target.select();
|
||||
}, 0);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -781,9 +792,9 @@ $(function() {
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TemperatureViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
["#temp", "#temp_link", "#change_offset_dialog"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: TemperatureViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#temp", "#temp_link", "#change_offset_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -58,7 +58,7 @@ $(function() {
|
||||
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function(entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
return regex === undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
var filtered = false;
|
||||
@@ -91,7 +91,7 @@ $(function() {
|
||||
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function(entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
return regex === undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
var lines = self.log();
|
||||
@@ -125,6 +125,11 @@ $(function() {
|
||||
self.updateFilterRegex();
|
||||
});
|
||||
|
||||
self.blacklist=[];
|
||||
self.settings.serial_autoUppercaseBlacklist.subscribe(function(newValue) {
|
||||
self.blacklist = splitTextToArray(newValue, ",", true);
|
||||
});
|
||||
|
||||
self._reenableFancyTimer = undefined;
|
||||
self._reenableUnfancyTimer = undefined;
|
||||
self._disableFancy = function(difference) {
|
||||
@@ -200,7 +205,7 @@ $(function() {
|
||||
if (!self.terminalLogDuringPrinting() && self.isPrinting()) {
|
||||
var last = self.plainLogLines()[self.plainLogLines().length - 1];
|
||||
var disabled = "--- client too slow, log output disabled while printing ---";
|
||||
if (last != disabled) {
|
||||
if (last !== disabled) {
|
||||
self.plainLogLines.push(disabled);
|
||||
}
|
||||
return;
|
||||
@@ -221,7 +226,7 @@ $(function() {
|
||||
}
|
||||
|
||||
var newLog = self.log().concat(_.map(newData, function(line) { return self._toInternalFormat(line) }));
|
||||
if (newData.length != data.length) {
|
||||
if (newData.length !== data.length) {
|
||||
var cutoff = "--- too many lines to buffer, cut off ---";
|
||||
newLog.push(self._toInternalFormat(cutoff, "cut"));
|
||||
}
|
||||
@@ -241,7 +246,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self._toInternalFormat = function(line, type) {
|
||||
if (type == undefined) {
|
||||
if (type === undefined) {
|
||||
type = "line";
|
||||
}
|
||||
return {line: escapeUnprintableCharacters(line), type: type}
|
||||
@@ -259,7 +264,7 @@ $(function() {
|
||||
|
||||
self.updateFilterRegex = function() {
|
||||
var filterRegexStr = self.activeFilters().join("|").trim();
|
||||
if (filterRegexStr == "") {
|
||||
if (filterRegexStr === "") {
|
||||
self.filterRegex(undefined);
|
||||
} else {
|
||||
self.filterRegex(new RegExp(filterRegexStr));
|
||||
@@ -301,20 +306,41 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.copyAll = function() {
|
||||
copyToClipboard(self.plainLogLines().join("\n"));
|
||||
};
|
||||
|
||||
// command matching regex
|
||||
// (Example output for inputs G0, G1, G28.1, M117 test)
|
||||
// - 1: code including optional subcode. Example: G0, G1, G28.1, M117
|
||||
// - 2: main code only. Example: G0, G1, G28, M117
|
||||
// - 3: sub code, if available. Example: undefined, undefined, .1, undefined
|
||||
// - 4: command parameters incl. leading whitespace, if any. Example: "", "", "", " test"
|
||||
var commandRe = /^(([gmt][0-9]+)(\.[0-9+])?)(\s.*)?/i;
|
||||
|
||||
self.sendCommand = function() {
|
||||
var command = self.command();
|
||||
if (!command) {
|
||||
return;
|
||||
}
|
||||
|
||||
var re = /^([gmt][0-9]+)(\s.*)?/;
|
||||
var commandMatch = command.match(re);
|
||||
if (commandMatch != null) {
|
||||
command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : "");
|
||||
var commandToSend = command;
|
||||
var commandMatch = commandToSend.match(commandRe);
|
||||
if (commandMatch !== null) {
|
||||
var fullCode = commandMatch[1].toUpperCase(); // full code incl. sub code
|
||||
var mainCode = commandMatch[2].toUpperCase(); // main code only without sub code
|
||||
|
||||
if (self.blacklist.indexOf(mainCode) < 0 && self.blacklist.indexOf(fullCode) < 0) {
|
||||
// full or main code not on blacklist -> upper case the whole command
|
||||
commandToSend = commandToSend.toUpperCase();
|
||||
} else {
|
||||
// full or main code on blacklist -> only upper case that and leave parameters as is
|
||||
commandToSend = fullCode + (commandMatch[4] !== undefined ? commandMatch[4] : "");
|
||||
}
|
||||
}
|
||||
|
||||
if (command) {
|
||||
OctoPrint.control.sendGcode(command)
|
||||
if (commandToSend) {
|
||||
OctoPrint.control.sendGcode(commandToSend)
|
||||
.done(function() {
|
||||
self.cmdHistory.push(command);
|
||||
self.cmdHistory.slice(-300); // just to set a sane limit to how many manually entered commands will be saved...
|
||||
@@ -331,10 +357,10 @@ $(function() {
|
||||
self.handleKeyDown = function(event) {
|
||||
var keyCode = event.keyCode;
|
||||
|
||||
if (keyCode == 38 || keyCode == 40) {
|
||||
if (keyCode == 38 && self.cmdHistory.length > 0 && self.cmdHistoryIdx > 0) {
|
||||
if (keyCode === 38 || keyCode === 40) {
|
||||
if (keyCode === 38 && self.cmdHistory.length > 0 && self.cmdHistoryIdx > 0) {
|
||||
self.cmdHistoryIdx--;
|
||||
} else if (keyCode == 40 && self.cmdHistoryIdx < self.cmdHistory.length - 1) {
|
||||
} else if (keyCode === 40 && self.cmdHistoryIdx < self.cmdHistory.length - 1) {
|
||||
self.cmdHistoryIdx++;
|
||||
}
|
||||
|
||||
@@ -353,7 +379,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.handleKeyUp = function(event) {
|
||||
if (event.keyCode == 13) {
|
||||
if (event.keyCode === 13) {
|
||||
self.sendCommand();
|
||||
}
|
||||
|
||||
@@ -362,15 +388,15 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function(current, previous) {
|
||||
self.tabActive = current == "#term";
|
||||
self.tabActive = current === "#term";
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TerminalViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
["#term", "#term_link"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: TerminalViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#term", "#term_link"]
|
||||
});
|
||||
});
|
||||
@@ -94,7 +94,7 @@ $(function() {
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
},
|
||||
"creation": function(a, b) {
|
||||
"date": function(a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
@@ -555,9 +555,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TimelapseViewModel,
|
||||
["loginStateViewModel", "accessViewModel"],
|
||||
["#timelapse", "#timelapse_link"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: TimelapseViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"],
|
||||
elements: ["#timelapse", "#timelapse_link"]
|
||||
});
|
||||
});
|
||||
@@ -71,9 +71,8 @@ $(function() {
|
||||
self.deprecatedUsersMethod("deleteApikey");
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UsersViewModel,
|
||||
["accessViewModel"],
|
||||
[]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: UsersViewModel,
|
||||
dependencies: ["accessViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,7 @@ $(function() {
|
||||
self.access_apikey(undefined);
|
||||
self.interface_language("_default");
|
||||
|
||||
if (newUser != undefined) {
|
||||
if (newUser !== undefined) {
|
||||
self.access_apikey(newUser.apikey);
|
||||
if (newUser.settings.hasOwnProperty("interface") && newUser.settings.interface.hasOwnProperty("language")) {
|
||||
self.interface_language(newUser.settings.interface.language);
|
||||
@@ -34,13 +34,13 @@ $(function() {
|
||||
});
|
||||
|
||||
self.passwordMismatch = ko.pureComputed(function() {
|
||||
return self.access_password() != self.access_repeatedPassword();
|
||||
return self.access_password() !== self.access_repeatedPassword();
|
||||
});
|
||||
|
||||
self.show = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
if (user == undefined) {
|
||||
if (user === undefined) {
|
||||
user = self.loginState.currentUser();
|
||||
}
|
||||
|
||||
@@ -126,9 +126,9 @@ $(function() {
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UserSettingsViewModel,
|
||||
["loginStateViewModel", "usersViewModel"],
|
||||
["#usersettings_dialog"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: UserSettingsViewModel,
|
||||
dependencies: ["loginStateViewModel", "usersViewModel"],
|
||||
elements: ["#usersettings_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,9 @@ $(function() {
|
||||
}
|
||||
|
||||
callViewModels(self.allViewModels, "onWizardShow");
|
||||
|
||||
callViewModels(self.allViewModels, "onBeforeWizardTabChange", [OCTOPRINT_INITIAL_WIZARD, undefined]);
|
||||
callViewModels(self.allViewModels, "onAfterWizardTabChange", [OCTOPRINT_INITIAL_WIZARD]);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -69,13 +72,13 @@ $(function() {
|
||||
return false;
|
||||
},
|
||||
onTabShow: function(tab, navigation, index) {
|
||||
if (index < 0 || tab.length == 0) {
|
||||
if (index < 0 || tab.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var total = self.wizardDialog.bootstrapWizard("navigationLength");
|
||||
|
||||
if (index == total) {
|
||||
if (index === total) {
|
||||
self.wizardDialog.find(".button-next").hide();
|
||||
self.wizardDialog.find(".button-finish").show().removeClass("disabled");
|
||||
} else {
|
||||
@@ -84,17 +87,17 @@ $(function() {
|
||||
}
|
||||
|
||||
var active = tab[0].id;
|
||||
if (active != undefined) {
|
||||
if (active !== undefined) {
|
||||
callViewModels(allViewModels, "onAfterWizardTabChange", [active]);
|
||||
}
|
||||
},
|
||||
onTabChange: function(tab, navigation, index, nextTabIndex, nextTab) {
|
||||
var current, next;
|
||||
|
||||
if (index == undefined || index < 0 ||
|
||||
nextTabIndex == undefined || nextTabIndex < 0 ||
|
||||
index == nextTabIndex ||
|
||||
tab.length == 0 || nextTab.length == 0) {
|
||||
if (index === undefined || index < 0 ||
|
||||
nextTabIndex === undefined || nextTabIndex < 0 ||
|
||||
index === nextTabIndex ||
|
||||
tab.length === 0 || nextTab.length === 0) {
|
||||
// let's ignore that nonsense
|
||||
return;
|
||||
}
|
||||
@@ -102,7 +105,7 @@ $(function() {
|
||||
current = tab[0].id;
|
||||
next = nextTab[0].id;
|
||||
|
||||
if (current != undefined && next != undefined) {
|
||||
if (current !== undefined && next !== undefined) {
|
||||
var result = true;
|
||||
callViewModels(allViewModels, "onBeforeWizardTabChange", function(method) {
|
||||
// we want to continue evaluating even if result becomes false
|
||||
@@ -142,7 +145,7 @@ $(function() {
|
||||
// first, or it won't happen after the reload flag has been
|
||||
// set once due to the || making further evaluation unnecessary
|
||||
// then
|
||||
reload = (method() == "reload") || reload;
|
||||
reload = (method() === "reload") || reload;
|
||||
});
|
||||
self.finishWizard()
|
||||
.done(function() {
|
||||
@@ -217,9 +220,9 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
WizardViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
"#wizard_dialog"
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: WizardViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#wizard_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -949,6 +949,11 @@ ul.dropdown-menu li a {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#footer_version,
|
||||
#footer_link {
|
||||
max-width: 50%;
|
||||
}
|
||||
}
|
||||
|
||||
/** Notifications */
|
||||
|
||||
@@ -141,6 +141,13 @@
|
||||
<span class="help-inline">{{ _('Use this to specify which commands <strong>always</strong> need to be sent with a checksum. Comma separated list.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Commands to not completely auto uppercase in the terminal tab') }}">
|
||||
<label class="control-label" for="settings-serialAutoUppercaseBlacklist">{{ _('Terminal Auto Uppercase Blacklist') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialAutoUppercaseBlacklist" data-bind="value: serial_autoUppercaseBlacklist">
|
||||
<span class="help-inline">{{ _('Use this to specify the commands that should not have their parameters automatically uppercased in the terminal tab. Just the G or M code, comma separated.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_triggerOkForM29" id="settings-triggerOkForM29"> {{ _('Generate additional <code>ok</code> for <code>M29</code>') }} <span class="label">{{ _('Most Marlin < v1.1.0') }}</span>
|
||||
|
||||
@@ -111,14 +111,14 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="footer">
|
||||
<ul class="pull-left muted">
|
||||
<ul id="footer_version" class="pull-left muted">
|
||||
<li><small>{{ _('OctoPrint') }} <span class="version">{{ display_version|e }}</span></small></li>
|
||||
</ul>
|
||||
<ul class="pull-right">
|
||||
<ul id="footer_links" class="pull-right">
|
||||
<li><a href="http://octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-home"></i> {{ _('Homepage') }}</a></li>
|
||||
<li><a href="https://github.com/foosel/OctoPrint/" target="_blank" rel="noreferrer noopener"><i class="fa fa-github"></i> {{ _('Sourcecode') }}</a></li>
|
||||
<li><a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-book"></i> {{ _('Documentation') }}</a></li>
|
||||
<li><a href="https://github.com/foosel/OctoPrint/issues" target="_blank" rel="noreferrer noopener"><i class="fa fa-flag"></i> {{ _('Bugs and Requests') }}</a></li>
|
||||
<li><a href="https://github.com/foosel/OctoPrint/" target="_blank" rel="noreferrer noopener"><i class="fa fa-github"></i> {{ _('Source') }}</a></li>
|
||||
<li><a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-book"></i> {{ _('Docs') }}</a></li>
|
||||
<li><a href="https://github.com/foosel/OctoPrint/issues" target="_blank" rel="noreferrer noopener"><i class="fa fa-flag"></i> {{ _('Issues') }}</a></li>
|
||||
<li><a href="https://github.com/foosel/OctoPrint/wiki/FAQ" target="_blank" rel="noreferrer noopener"><i class="fa fa-question-circle"></i> {{ _('FAQ') }}</a></li>
|
||||
<li id="footer_about"><a href="javascript:void(0)" data-bind="click: show"><i class="fa fa-info-circle"></i> {{ _('About') }}</a></li>
|
||||
</ul>
|
||||
|
||||
@@ -49,4 +49,12 @@
|
||||
{% else %}
|
||||
var OCTOPRINT_INITIAL_TAB = undefined;
|
||||
{% endif %}
|
||||
|
||||
{% if templates.wizard and templates.wizard.order %}
|
||||
{% set first_tab = templates.wizard.order[0] %}
|
||||
{% set entry, data = templates.wizard.entries[first_tab] %}
|
||||
var OCTOPRINT_INITIAL_WIZARD = "#{{ data._div }}";
|
||||
{% else %}
|
||||
var OCTOPRINT_INITIAL_WIZARD = undefined;
|
||||
{% endif %}
|
||||
</script>
|
||||
@@ -7,9 +7,17 @@
|
||||
<a class="btn add-on" id="terminal-send" data-bind="click: sendCommand, enable: isOperational() && loginState.isUser()">{{ _('Send') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
<small class="pull-left" data-bind="visible: fancyFunctionality()"><button class="btn btn-mini" data-bind="click: toggleAutoscroll, css: {active: autoscrollEnabled}">{{ _('Autoscroll') }}</button> <span data-bind="text: lineCount, visible: enableFancyFunctionality"></span></small>
|
||||
<small class="pull-right" data-bind="visible: fancyFunctionality()"><a href="#" data-bind="click: scrollToEnd">{{ _("Scroll to end") }}</a> | <a href="#" data-bind="click: selectAll">{{ _("Select all") }}</a></small>
|
||||
<small class="pull-left text-warning" data-bind="visible: !fancyFunctionality()" style="display: none">{{ _('For performance reasons only a limited amount of terminal functionality is enabled right now.') }}</small>
|
||||
<small class="pull-left" data-bind="visible: fancyFunctionality()">
|
||||
<button class="btn btn-mini" data-bind="click: toggleAutoscroll, css: {active: autoscrollEnabled}">{{ _('Autoscroll') }}</button>
|
||||
<span data-bind="text: lineCount, visible: enableFancyFunctionality"></span>
|
||||
<span data-bind="visible: !autoscrollEnabled() && enableFancyFunctionality()" style="display: none">(<a href="javascript:void(0)" data-bind="click: scrollToEnd">{{ _("Scroll to end") }}</a>)</span>
|
||||
</small>
|
||||
<small class="pull-right">
|
||||
<a href="javascript:void(0)" data-bind="click: copyAll"><i class="fa fa-copy" title="{{ _('Copy all') }}"></i> {{ _('Copy all') }}</a>
|
||||
</small>
|
||||
<small class="pull-left text-warning" data-bind="visible: !fancyFunctionality()" style="display: none">
|
||||
{{ _('For performance reasons only a limited amount of terminal functionality is enabled right now.') }}
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="row-fluid">
|
||||
|
||||
@@ -106,7 +106,7 @@
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-wrench"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu dropdown-menu-right">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('name'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('creation'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'creation' ? 'visible' : 'hidden'}"></i> {{ _('Sort by creation date') }} ({{ _('descending') }})</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('date'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'date' ? 'visible' : 'hidden'}"></i> {{ _('Sort by date') }} ({{ _('descending') }})</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('size'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
+48
-30
@@ -93,7 +93,7 @@ def get_finished_timelapses():
|
||||
"name": entry.name,
|
||||
"size": util.get_formatted_size(entry.stat().st_size),
|
||||
"bytes": entry.stat().st_size,
|
||||
"date": util.get_formatted_datetime(datetime.datetime.fromtimestamp(entry.stat().st_ctime))
|
||||
"date": util.get_formatted_datetime(datetime.datetime.fromtimestamp(entry.stat().st_mtime))
|
||||
})
|
||||
return files
|
||||
|
||||
@@ -117,8 +117,8 @@ def get_unrendered_timelapses():
|
||||
|
||||
jobs[prefix]["count"] += 1
|
||||
jobs[prefix]["bytes"] += entry.stat().st_size
|
||||
if jobs[prefix]["timestamp"] is None or entry.stat().st_ctime < jobs[prefix]["timestamp"]:
|
||||
jobs[prefix]["timestamp"] = entry.stat().st_ctime
|
||||
if jobs[prefix]["timestamp"] is None or entry.stat().st_mtime < jobs[prefix]["timestamp"]:
|
||||
jobs[prefix]["timestamp"] = entry.stat().st_mtime
|
||||
|
||||
with _job_lock:
|
||||
global current_render_job
|
||||
@@ -141,7 +141,7 @@ def get_unrendered_timelapses():
|
||||
|
||||
def delete_unrendered_timelapse(name):
|
||||
global _cleanup_lock
|
||||
|
||||
|
||||
pattern = "{}*.jpg".format(util.glob_escape(name))
|
||||
|
||||
basedir = settings().getBaseFolder("timelapse_tmp")
|
||||
@@ -287,40 +287,58 @@ def configure_timelapse(config=None, persist=False):
|
||||
if current is not None:
|
||||
current.unload()
|
||||
|
||||
snapshot_url = settings().get(["webcam", "snapshot"])
|
||||
ffmpeg_path = settings().get(["webcam", "ffmpeg"])
|
||||
timelapse_precondition = snapshot_url is not None and snapshot_url.strip() != "" \
|
||||
and ffmpeg_path is not None and ffmpeg_path.strip() != ""
|
||||
|
||||
type = config["type"]
|
||||
if not timelapse_precondition and type is not None and type != "off":
|
||||
logging.getLogger(__name__).warn("Essential timelapse settings unconfigured (snapshot URL or FFMPEG path) "
|
||||
"but timelapse enabled, forcing disabled timelapse and disabling it "
|
||||
"in the config as well.")
|
||||
type = "off"
|
||||
config["type"] = "off"
|
||||
|
||||
postRoll = 0
|
||||
if "postRoll" in config and config["postRoll"] >= 0:
|
||||
postRoll = config["postRoll"]
|
||||
|
||||
fps = 25
|
||||
if "fps" in config and config["fps"] > 0:
|
||||
fps = config["fps"]
|
||||
if not persist:
|
||||
# make sure we persist at least that timelapse is now disabled by default - we don't want the above
|
||||
# warning to log
|
||||
settings().set(["webcam", "timelapse", "type"], "off")
|
||||
settings().save()
|
||||
|
||||
if type is None or "off" == type:
|
||||
current = None
|
||||
|
||||
elif "zchange" == type:
|
||||
retractionZHop = 0
|
||||
if "options" in config and "retractionZHop" in config["options"] and config["options"]["retractionZHop"] >= 0:
|
||||
retractionZHop = config["options"]["retractionZHop"]
|
||||
else:
|
||||
postRoll = 0
|
||||
if "postRoll" in config and config["postRoll"] >= 0:
|
||||
postRoll = config["postRoll"]
|
||||
|
||||
minDelay = 5
|
||||
if "options" in config and "minDelay" in config["options"] and config["options"]["minDelay"] > 0:
|
||||
minDelay = config["options"]["minDelay"]
|
||||
fps = 25
|
||||
if "fps" in config and config["fps"] > 0:
|
||||
fps = config["fps"]
|
||||
|
||||
current = ZTimelapse(post_roll=postRoll, retraction_zhop=retractionZHop, min_delay=minDelay, fps=fps)
|
||||
if "zchange" == type:
|
||||
retractionZHop = 0
|
||||
if "options" in config and "retractionZHop" in config["options"] and config["options"]["retractionZHop"] >= 0:
|
||||
retractionZHop = config["options"]["retractionZHop"]
|
||||
|
||||
elif "timed" == type:
|
||||
interval = 10
|
||||
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
|
||||
interval = config["options"]["interval"]
|
||||
minDelay = 5
|
||||
if "options" in config and "minDelay" in config["options"] and config["options"]["minDelay"] > 0:
|
||||
minDelay = config["options"]["minDelay"]
|
||||
|
||||
capture_post_roll = True
|
||||
if "options" in config and "capturePostRoll" in config["options"] and isinstance(config["options"]["capturePostRoll"], bool):
|
||||
capture_post_roll = config["options"]["capturePostRoll"]
|
||||
current = ZTimelapse(post_roll=postRoll, retraction_zhop=retractionZHop, min_delay=minDelay, fps=fps)
|
||||
|
||||
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps, capture_post_roll=capture_post_roll)
|
||||
elif "timed" == type:
|
||||
interval = 10
|
||||
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
|
||||
interval = config["options"]["interval"]
|
||||
|
||||
capture_post_roll = True
|
||||
if "options" in config and "capturePostRoll" in config["options"] and isinstance(config["options"]["capturePostRoll"], bool):
|
||||
capture_post_roll = config["options"]["capturePostRoll"]
|
||||
|
||||
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps, capture_post_roll=capture_post_roll)
|
||||
|
||||
notify_callbacks(current)
|
||||
|
||||
@@ -639,10 +657,10 @@ class Timelapse(object):
|
||||
class ZTimelapse(Timelapse):
|
||||
def __init__(self, retraction_zhop=0, min_delay=5.0, post_roll=0, fps=25):
|
||||
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
|
||||
|
||||
|
||||
if min_delay < 0:
|
||||
min_delay = 0
|
||||
|
||||
|
||||
self._retraction_zhop = retraction_zhop
|
||||
self._min_delay = min_delay
|
||||
self._last_snapshot = None
|
||||
@@ -651,7 +669,7 @@ class ZTimelapse(Timelapse):
|
||||
@property
|
||||
def retraction_zhop(self):
|
||||
return self._retraction_zhop
|
||||
|
||||
|
||||
@property
|
||||
def min_delay(self):
|
||||
return self._min_delay
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
"""
|
||||
This module bundles commonly used utility methods or helper classes that are used in multiple places within
|
||||
OctoPrint's source code.
|
||||
"""
|
||||
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'
|
||||
@@ -940,14 +939,14 @@ except ImportError:
|
||||
# no glob.escape - we need to implement our own
|
||||
_glob_escape_check = re.compile("([*?[])")
|
||||
_glob_escape_check_bytes = re.compile(b"([*?[])")
|
||||
|
||||
|
||||
def glob_escape(pathname):
|
||||
"""
|
||||
Ported from Python 3.4
|
||||
|
||||
|
||||
See https://github.com/python/cpython/commit/fd32fffa5ada8b8be8a65bd51b001d989f99a3d3
|
||||
"""
|
||||
|
||||
|
||||
drive, pathname = os.path.splitdrive(pathname)
|
||||
if isinstance(pathname, bytes):
|
||||
pathname = _glob_escape_check_bytes.sub(br"[\1]", pathname)
|
||||
@@ -965,6 +964,40 @@ except RuntimeError:
|
||||
monotonic_time = time.time
|
||||
|
||||
|
||||
def utmify(link, source=None, medium=None, name=None, term=None, content=None):
|
||||
if source is None:
|
||||
return link
|
||||
|
||||
from collections import OrderedDict
|
||||
try:
|
||||
import urlparse
|
||||
from urllib import urlencode
|
||||
except ImportError:
|
||||
# python 3
|
||||
import urllib.parse as urlparse
|
||||
from urllib.parse import urlencode
|
||||
|
||||
# inspired by https://stackoverflow.com/a/2506477
|
||||
parts = list(urlparse.urlparse(link))
|
||||
|
||||
# parts[4] is the url query
|
||||
query = OrderedDict(urlparse.parse_qs(parts[4]))
|
||||
|
||||
query["utm_source"] = source
|
||||
if medium is not None:
|
||||
query["utm_medium"] = medium
|
||||
if name is not None:
|
||||
query["utm_name"] = name
|
||||
if term is not None:
|
||||
query["utm_term"] = term
|
||||
if content is not None:
|
||||
query["utm_content"] = content
|
||||
|
||||
parts[4] = urlencode(query, doseq=True)
|
||||
|
||||
return urlparse.urlunparse(parts)
|
||||
|
||||
|
||||
class RepeatedTimer(threading.Thread):
|
||||
"""
|
||||
This class represents an action that should be run repeatedly in an interval. It is similar to python's
|
||||
|
||||
+41
-19
@@ -1244,7 +1244,7 @@ class MachineCom(object):
|
||||
return stripped_line, stripped_line.lower()
|
||||
|
||||
##~~ Error handling
|
||||
line = self._handleErrors(line)
|
||||
line = self._handle_errors(line)
|
||||
line, lower_line = convert_line(line)
|
||||
|
||||
##~~ SD file list
|
||||
@@ -1951,36 +1951,53 @@ class MachineCom(object):
|
||||
|
||||
return False
|
||||
|
||||
def _handleErrors(self, line):
|
||||
_resend_request_communication_errors = ("line number",
|
||||
"wrong checksum",
|
||||
"missing checksum",
|
||||
"format error",
|
||||
"expected line")
|
||||
_recoverable_communication_errors = ("no line number with checksum",)
|
||||
_sd_card_errors = ("volume.init",
|
||||
"openroot",
|
||||
"workdir",
|
||||
"error writing to file",
|
||||
"cannot open",
|
||||
"cannot enter")
|
||||
def _handle_errors(self, line):
|
||||
if line is None:
|
||||
return
|
||||
|
||||
lower_line = line.lower()
|
||||
|
||||
# No matter the state, if we see an error, goto the error state and store the error for reference.
|
||||
if lower_line.startswith('error:') or line.startswith('!!'):
|
||||
#Oh YEAH, consistency.
|
||||
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
|
||||
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
|
||||
# So we can have an extra newline in the most common case. Awesome work people.
|
||||
if regex_minMaxError.match(line):
|
||||
# special delivery for firmware that goes "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
|
||||
line = line.rstrip() + self._readline()
|
||||
|
||||
if 'line number' in lower_line or 'checksum' in lower_line or 'format error' in lower_line or 'expected line' in lower_line:
|
||||
#Skip the communication errors, as those get corrected.
|
||||
if any(map(lambda x: x in lower_line, self._recoverable_communication_errors)):
|
||||
# manually trigger an ack for comm errors the printer doesn't send a resend request for but
|
||||
# from which we can recover from by just pushing on (because that then WILL trigger a fitting
|
||||
# resend request)
|
||||
self._handle_ok()
|
||||
|
||||
elif any(map(lambda x: x in lower_line, self._resend_request_communication_errors)):
|
||||
# skip comm errors that the printer sends a resend request for anyhow
|
||||
self._lastCommError = line[6:] if lower_line.startswith("error:") else line[2:]
|
||||
|
||||
elif any(map(lambda x: x in lower_line, self._sd_card_errors)):
|
||||
# skip errors with the SD card
|
||||
pass
|
||||
elif 'volume.init' in lower_line or "openroot" in lower_line or 'workdir' in lower_line\
|
||||
or "error writing to file" in lower_line or "cannot open" in lower_line\
|
||||
or "cannot enter" in lower_line:
|
||||
#Also skip errors with the SD card
|
||||
pass
|
||||
|
||||
elif 'unknown command' in lower_line:
|
||||
#Ignore unknown command errors, it could be a typo or some missing feature
|
||||
# ignore unknown command errors, it could be a typo or some missing feature
|
||||
pass
|
||||
|
||||
elif not self.isError():
|
||||
# handle everything else
|
||||
error_text = line[6:] if lower_line.startswith("error:") else line[2:]
|
||||
self._to_logfile_with_terminal("Received an error from the printer's firmware: {}".format(error_text), level=logging.WARN)
|
||||
self._to_logfile_with_terminal("Received an error from the printer's firmware: {}".format(error_text),
|
||||
level=logging.WARN)
|
||||
|
||||
if not self._ignore_errors:
|
||||
if self._disconnect_on_errors:
|
||||
self._errorValue = error_text
|
||||
@@ -1992,6 +2009,8 @@ class MachineCom(object):
|
||||
else:
|
||||
self._log("WARNING! Received an error from the printer's firmware, ignoring that as configured but you might want to investigate what happened here! Error: {}".format(error_text))
|
||||
self._clear_to_send.set()
|
||||
|
||||
# finally return the line
|
||||
return line
|
||||
|
||||
def _readline(self):
|
||||
@@ -2078,7 +2097,8 @@ class MachineCom(object):
|
||||
# an active (prior) resend request.
|
||||
#
|
||||
# We will ignore this resend request and just continue normally.
|
||||
self._logger.debug("Ignoring resend request for line %d == current line, we haven't sent that yet so the printer got N-1 twice from us, probably due to a timeout" % lineToResend)
|
||||
self._logger.info("Ignoring resend request for line %d == current line, we haven't sent that yet so "
|
||||
"the printer got N-1 twice from us, probably due to a timeout" % lineToResend)
|
||||
return False
|
||||
|
||||
lastCommError = self._lastCommError
|
||||
@@ -2090,7 +2110,8 @@ class MachineCom(object):
|
||||
and ("line number" in lastCommError.lower() or "expected line" in lastCommError.lower()) \
|
||||
and lineToResend == self._lastResendNumber \
|
||||
and self._resendDelta is not None and self._currentResendCount < self._resendDelta:
|
||||
self._logger.debug("Ignoring resend request for line %d, that still originates from lines we sent before we got the first resend request" % lineToResend)
|
||||
self._logger.info("Ignoring resend request for line %d, that still originates from lines we sent "
|
||||
"before we got the first resend request" % lineToResend)
|
||||
self._currentResendCount += 1
|
||||
return True
|
||||
|
||||
@@ -2098,7 +2119,8 @@ class MachineCom(object):
|
||||
# need to do this now. If the same line number has been requested we
|
||||
# already saw and resent, we'll ignore it up to <counter> times.
|
||||
if self._resendSwallowRepetitions and lineToResend == self._lastResendNumber and self._resendSwallowRepetitionsCounter > 0:
|
||||
self._logger.debug("Ignoring resend request for line %d, that is probably a repetition sent by the firmware to ensure it arrives, not a real request" % lineToResend)
|
||||
self._logger.info("Ignoring resend request for line %d, that is probably a repetition sent by the "
|
||||
"firmware to ensure it arrives, not a real request" % lineToResend)
|
||||
self._resendSwallowRepetitionsCounter -= 1
|
||||
return True
|
||||
|
||||
|
||||
@@ -39,3 +39,19 @@ else:
|
||||
def set_close_exec(handle):
|
||||
# no-op
|
||||
pass
|
||||
|
||||
|
||||
# current os
|
||||
|
||||
_OPERATING_SYSTEMS = dict(windows=["win32"],
|
||||
linux=lambda x: x.startswith("linux"),
|
||||
macos=["darwin"],
|
||||
freebsd=lambda x: x.startswith("freebsd"))
|
||||
OPERATING_SYSTEM_UNMAPPED = "unmapped"
|
||||
|
||||
def get_os():
|
||||
for identifier, platforms in _OPERATING_SYSTEMS.items():
|
||||
if (callable(platforms) and platforms(sys.platform)) or (isinstance(platforms, list) and sys.platform in platforms):
|
||||
return identifier
|
||||
else:
|
||||
return OPERATING_SYSTEM_UNMAPPED
|
||||
@@ -9,30 +9,27 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
import pkg_resources
|
||||
import logging
|
||||
|
||||
from octoprint._version import get_versions
|
||||
|
||||
|
||||
_VERSION = get_versions()["version"]
|
||||
from octoprint import __version__
|
||||
|
||||
|
||||
def get_octoprint_version_string():
|
||||
return _VERSION
|
||||
return __version__
|
||||
|
||||
|
||||
def get_octoprint_version(base=False):
|
||||
octoprint_version_string = get_octoprint_version_string()
|
||||
|
||||
|
||||
if "-" in octoprint_version_string:
|
||||
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 contain 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
|
||||
@@ -52,22 +49,22 @@ def get_octoprint_version(base=False):
|
||||
def is_octoprint_compatible(*compatibility_entries, **kwargs):
|
||||
"""
|
||||
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
|
||||
|
||||
|
||||
Arguments:
|
||||
compatibility_entries (str): compatibility string(s) to test against, result will be `True` if any match
|
||||
is found
|
||||
octoprint_version (tuple or SetuptoolsVersion): optional OctoPrint version to match against, if not current
|
||||
base version will be determined via :func:`get_octoprint_version`.
|
||||
|
||||
|
||||
Returns:
|
||||
(bool) ``True`` if any of the provided compatibility entries matches or there are no entries, else ``False``
|
||||
"""
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
if not compatibility_entries:
|
||||
return True
|
||||
|
||||
|
||||
octoprint_version = kwargs.get("octoprint_version")
|
||||
if octoprint_version is None:
|
||||
octoprint_version = get_octoprint_version(base=True)
|
||||
|
||||
@@ -5,6 +5,48 @@ import ddt
|
||||
import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
|
||||
##~~ Helpers for testing mixin type extraction
|
||||
|
||||
class A(object):
|
||||
pass
|
||||
|
||||
|
||||
class A_1(A):
|
||||
pass
|
||||
|
||||
|
||||
class A_2(A):
|
||||
pass
|
||||
|
||||
|
||||
class A_3(A):
|
||||
pass
|
||||
|
||||
|
||||
class A1_1(A_1):
|
||||
pass
|
||||
|
||||
|
||||
class B(object):
|
||||
pass
|
||||
|
||||
|
||||
class B_1(B):
|
||||
pass
|
||||
|
||||
|
||||
class C(object):
|
||||
pass
|
||||
|
||||
|
||||
class C_1(C):
|
||||
pass
|
||||
|
||||
|
||||
class D(object):
|
||||
pass
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
class PluginTestCase(unittest.TestCase):
|
||||
|
||||
@@ -18,12 +60,10 @@ class PluginTestCase(unittest.TestCase):
|
||||
self.plugin_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "_plugins")
|
||||
|
||||
plugin_folders = [self.plugin_folder]
|
||||
plugin_types = [octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.AssetPlugin]
|
||||
plugin_bases = [octoprint.plugin.OctoPrintPlugin]
|
||||
plugin_entry_points = None
|
||||
self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders,
|
||||
plugin_types,
|
||||
plugin_bases,
|
||||
plugin_entry_points,
|
||||
plugin_disabled_list=[],
|
||||
logging_prefix="logging_prefix.")
|
||||
@@ -274,3 +314,20 @@ class PluginTestCase(unittest.TestCase):
|
||||
|
||||
result = octoprint.plugin.core.PluginManager.has_any_of_mixins(plugin, octoprint.plugin.RestartNeedingPlugin)
|
||||
self.assertFalse(result)
|
||||
|
||||
@ddt.data(
|
||||
((A1_1, A_2, B_1, C_1), (A, C), (A_1, A1_1, A_2, C_1)),
|
||||
((A1_1, A_2, B_1, C_1), (B,), (B_1,)),
|
||||
|
||||
# not a subclass
|
||||
((A1_1, A_2, B_1, C_1), (D,), ()),
|
||||
|
||||
# subclass only of base
|
||||
((A,), (A,), ())
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_mixins_matching_bases(self, bases_to_set, bases_to_check, expected):
|
||||
Foo = type("Foo", bases_to_set, dict())
|
||||
actual = octoprint.plugin.core.PluginManager.mixins_matching_bases(Foo, *bases_to_check)
|
||||
self.assertSetEqual(actual, set(expected))
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
|
||||
import unittest
|
||||
import ddt
|
||||
import mock
|
||||
|
||||
OCTOPI_VERSION = "0.14.0"
|
||||
|
||||
CPUINFO = """
|
||||
processor : 0
|
||||
model name : ARMv7 Processor rev 4 (v7l)
|
||||
BogoMIPS : 38.40
|
||||
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
|
||||
CPU implementer : 0x41
|
||||
CPU architecture: 7
|
||||
CPU variant : 0x0
|
||||
CPU part : 0xd03
|
||||
CPU revision : 4
|
||||
|
||||
processor : 1
|
||||
model name : ARMv7 Processor rev 4 (v7l)
|
||||
BogoMIPS : 38.40
|
||||
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
|
||||
CPU implementer : 0x41
|
||||
CPU architecture: 7
|
||||
CPU variant : 0x0
|
||||
CPU part : 0xd03
|
||||
CPU revision : 4
|
||||
|
||||
processor : 2
|
||||
model name : ARMv7 Processor rev 4 (v7l)
|
||||
BogoMIPS : 38.40
|
||||
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
|
||||
CPU implementer : 0x41
|
||||
CPU architecture: 7
|
||||
CPU variant : 0x0
|
||||
CPU part : 0xd03
|
||||
CPU revision : 4
|
||||
|
||||
processor : 3
|
||||
model name : ARMv7 Processor rev 4 (v7l)
|
||||
BogoMIPS : 38.40
|
||||
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
|
||||
CPU implementer : 0x41
|
||||
CPU architecture: 7
|
||||
CPU variant : 0x0
|
||||
CPU part : 0xd03
|
||||
CPU revision : 4
|
||||
|
||||
Hardware : BCM2835
|
||||
Revision : a02082
|
||||
Serial : 000000000abcdef1
|
||||
"""
|
||||
|
||||
@ddt.ddt
|
||||
class OctoPiSupportTestCase(unittest.TestCase):
|
||||
|
||||
def test_get_octopi_version(self):
|
||||
from octoprint.plugins.octopi_support import get_octopi_version
|
||||
|
||||
with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m:
|
||||
m.return_value.readline.return_value = OCTOPI_VERSION
|
||||
version = get_octopi_version()
|
||||
|
||||
m.assert_called_once_with("/etc/octopi_version", "r")
|
||||
self.assertEqual(version, "0.14.0")
|
||||
|
||||
def test_get_pi_cpuinfo(self):
|
||||
from octoprint.plugins.octopi_support import get_pi_cpuinfo
|
||||
|
||||
with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m:
|
||||
m.return_value.__iter__.return_value = CPUINFO.splitlines()
|
||||
cpuinfo = get_pi_cpuinfo()
|
||||
|
||||
m.assert_called_once_with("/proc/cpuinfo")
|
||||
self.assertDictEqual(cpuinfo, dict(hardware="BCM2835", revision="a02082", serial="000000000abcdef1"))
|
||||
|
||||
@ddt.data(
|
||||
("BCM2835", "a02082", "3B"),
|
||||
("BCM2835", "1000a02082", "3B"),
|
||||
|
||||
# failures
|
||||
("something else", "a02082", "unknown"),
|
||||
("BCM2835", "aabbccdd", "unknown")
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_get_pi_model(self, hardware, revision, expected):
|
||||
from octoprint.plugins.octopi_support import get_pi_model
|
||||
actual = get_pi_model(hardware, revision)
|
||||
self.assertEqual(actual, expected)
|
||||
@@ -42,20 +42,3 @@ class PluginManagerPluginTests(unittest.TestCase):
|
||||
with mock.patch("sys.platform", sys_platform):
|
||||
actual = PluginManagerPlugin._is_os_compatible(current_os, entries)
|
||||
self.assertEqual(actual, expected)
|
||||
|
||||
@ddt.data(
|
||||
("win32", "windows"),
|
||||
("linux2", "linux"),
|
||||
("darwin", "macos"),
|
||||
("linux", "linux"),
|
||||
("linux3", "linux"),
|
||||
("freebsd", "freebsd"),
|
||||
("freebsd2342", "freebsd"),
|
||||
("os2", "unmapped"),
|
||||
("sunos5", "unmapped")
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_get_os(self, sys_platform, expected):
|
||||
with mock.patch("sys.platform", sys_platform):
|
||||
actual = PluginManagerPlugin._get_os()
|
||||
self.assertEqual(actual, expected)
|
||||
@@ -6,9 +6,11 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import unittest
|
||||
import ddt
|
||||
|
||||
import octoprint.util
|
||||
|
||||
@ddt.ddt
|
||||
class MiscTestCase(unittest.TestCase):
|
||||
|
||||
def test_get_class(self):
|
||||
@@ -29,3 +31,17 @@ class MiscTestCase(unittest.TestCase):
|
||||
except ImportError:
|
||||
# success
|
||||
pass
|
||||
|
||||
@ddt.data(
|
||||
("http://example.com", dict(source="source"), "http://example.com?utm_source=source"),
|
||||
("http://example.com?q=1", dict(source="source"), "http://example.com?q=1&utm_source=source"),
|
||||
("http://example.com", dict(source="source", medium="medium"), "http://example.com?utm_source=source&utm_medium=medium"),
|
||||
("http://example.com", dict(source="source", medium="medium", content="content with spaces"), "http://example.com?utm_source=source&utm_medium=medium&utm_content=content+with+spaces"),
|
||||
|
||||
# no handling
|
||||
("http://example.com", dict(), "http://example.com"),
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_utmify(self, link, kwargs, expected):
|
||||
actual = octoprint.util.utmify(link, **kwargs)
|
||||
self.assertEqual(actual, expected)
|
||||
@@ -0,0 +1,30 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
import ddt
|
||||
import mock
|
||||
|
||||
@ddt.ddt
|
||||
class PlatformUtilTest(unittest.TestCase):
|
||||
|
||||
@ddt.data(
|
||||
("win32", "windows"),
|
||||
("linux2", "linux"),
|
||||
("darwin", "macos"),
|
||||
("linux", "linux"),
|
||||
("linux3", "linux"),
|
||||
("freebsd", "freebsd"),
|
||||
("freebsd2342", "freebsd"),
|
||||
("os2", "unmapped"),
|
||||
("sunos5", "unmapped")
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_get_os(self, sys_platform, expected):
|
||||
with mock.patch("sys.platform", sys_platform):
|
||||
from octoprint.util.platform import get_os
|
||||
actual = get_os()
|
||||
self.assertEqual(actual, expected)
|
||||
Reference in new issue
Block a user