Merge branch 'devel' into dev/permission

# Conflicts:
#	src/octoprint/templates/dialogs/settings/accesscontrol.jinja2
This commit is contained in:
Gina Häußge committed 2017-11-28 12:07:39 +01:00
commit 2a96864c07
18 files changed
+214 -53

No files matched your search

+1
View File
@@ -86,6 +86,7 @@ date of first contribution):
* [Luke McKechnie](https://github.com/galamdring)
* [Peter Backx](https://github.com/pbackx)
* [Josh Major](https://github.com/astateofblank)
* ["alex-gh"](https://github.com/alex-gh)
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
+14 -1
View File
@@ -263,6 +263,8 @@ See [How to open the Javascript Console in different browsers](https://webmaster
## Setting up a development environment
See [the corresponding chapter in the documentation](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment).
This also includes information on how to run the test suite and how to build
the documentation.
## Pull requests
@@ -303,7 +305,17 @@ See [the corresponding chapter in the documentation](http://docs.octoprint.org/e
* Make sure you do not add dead code (e.g. commented out left-overs
from experiments).
8. Ensure your changes **pass the existing unit tests**. PRs that break
those cannot be accepted.
those cannot be accepted. You can run the unit tests locally (after
[initial development environment setup with "develop" dependencies](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment))
by running
```
nosetests --with-doctest
```
in the OctoPrint checkout folder. A [travis build](https://travis-ci.org/foosel/OctoPrint)
is also setup so that if the tests should fail, your PR will be marked
accordingly.
9. **Test your changes thoroughly**. That also means testing with usage
scenarios you don't normally use, e.g. if you only use access control, test
without and vice versa. If you only test with your printer, test with the
@@ -432,6 +444,7 @@ the local version identifier to allow for an exact determination of the active c
* 2017-03-10: Reproduce bugs in safe mode to make sure they are really caused
by OctoPrint itself and not a misbehaving plugin.
* 2017-03-27: Added safe mode section to ticket template.
* 2017-11-22: Added note on how to run the unit tests
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
+44 -10
View File
@@ -17,13 +17,21 @@ below.
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
* Create a virtual environment in the checkout folder to use for installing and running OctoPrint and its
* Enter the checked out source folder: ``cd OctoPrint``
* Create a virtual environment in the checked out source folder to use for installing and running OctoPrint and its
dependencies (this avoids potential versioning issues for the dependencies with system wide installed
instances): ``virtualenv venv``
* Activate the virtual environment: ``source venv/bin/activate`` (might differ per your platform/OS)
* Activate the virtual environment: ``source venv/bin/activate`` (Linux, MacOS) or
``source venv/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
including its regular *and* development dependencies: ``pip install -e .[develop]``
including its regular *and* development and plugin development dependencies: ``pip install -e .[develop,plugins]``
When the virtual environment is activated you can then:
* run the OctoPrint server via ``octoprint serve``
* run the test suite from the checked out source folder via ``nosetests --with-doctest``
* build the documentation from the ``docs`` sub folder of the checked out sources via ``sphinx-build -b html . _build``
.. _sec-development-environment-source-linux:
@@ -42,9 +50,18 @@ installed:
sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential
* On zypper based distributions (example below for SLES 12 SP2):
.. code-block:: none
sudo zypper ar https://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP2/ python_devel
sudo zypper ref
sudo zypper in python python-pip python-devel python-setuptools python-virtualenv git libyaml-devel
sudo zypper in -t pattern Basis-Devel
.. todo::
Using a Linux distribution that doesn't use ``apt``? Please send a
Using a Linux distribution that doesn't use ``apt`` or ``zypper``? Please send a
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
@@ -93,9 +110,6 @@ Open the Git Bash you just installed and in that:
pip install --upgrade pip
pip install -e .[develop,plugins]
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:
Mac OS X
@@ -139,9 +153,6 @@ You'll need a user account with administrator privileges.
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.
.. _sec-development-environment-ides:
IDE Setup
@@ -177,6 +188,29 @@ PyCharm
* Parameters: ``install -e .[develop,plugins]``
* Working directory: ``$ProjectFileDir$``
- Add Run/Debug Configuration, select "Python tests" and therein "Nosetests":
* Name: OctoPrint nosetests
* Target: Path, ``.``
* Project: ``OctoPrint``
* Python interpreter: the ``venv`` local virtual environment
* Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
* Just like with the run configuration for the server you can also have the dependencies auto-update on run of
the tests, see above on how to set this up.
- Add Run/Debug Configuration, select "Python docs" and therein "Sphinx task"
* Name: OctoPrint docs
* Command: ``html``
* Input: the ``docs`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs`` or
``C:\Devel\OctoPrint\docs``)
* Output: the ``docs/_build`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs/_build`` or
``C:\Devel\OctoPrint\docs\_build``)
* Project: ``OctoPrint``
* Python interpreter: the ``venv`` local virtual environment
* Just like with the run configuration for the server you can also have the dependencies auto-update when building
the documentation, see above on how to set this up.
.. note::
Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
+12 -3
View File
@@ -75,9 +75,18 @@ class EnvironmentDetector(object):
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))
cores = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
ram = psutil.virtual_memory()
result = dict()
if cores:
result["cores"] = cores
if cpu_freq and hasattr(cpu_freq, "max"):
result["freq"] = cpu_freq.max
if ram and hasattr(ram, "total"):
result["ram"] = ram.total
return result
def _detect_from_plugins(self):
result = dict()
+35 -1
View File
@@ -40,13 +40,47 @@ def full_extension_tree():
)
)
def leaf_merger(a, b):
supported_leaf_types = (ContentTypeMapping, ContentTypeDetector, list)
if not isinstance(a, supported_leaf_types) or not isinstance(b, supported_leaf_types):
raise ValueError()
if isinstance(a, ContentTypeDetector) and isinstance(b, ContentTypeMapping):
raise ValueError()
if isinstance(a, ContentTypeMapping) and isinstance(b, ContentTypeDetector):
raise ValueError()
a_list = a if isinstance(a, list) else a.extensions
b_list = b if isinstance(b, list) else b.extensions
merged = a_list + b_list
content_type = None
if isinstance(b, ContentTypeMapping):
content_type = b.content_type
elif isinstance(a, ContentTypeMapping):
content_type = a.content_type
detector = None
if isinstance(b, ContentTypeDetector):
detector = b.detector
elif isinstance(a, ContentTypeDetector):
detector = a.detector
if content_type is not None:
return ContentTypeMapping(merged, content_type)
elif detector is not None:
return ContentTypeDetector(merged, detector)
else:
return merged
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
for name, hook in extension_tree_hooks.items():
try:
hook_result = hook()
if hook_result is None or not isinstance(hook_result, dict):
continue
result = octoprint.util.dict_merge(result, hook_result)
result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger)
except:
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name))
+6 -7
View File
@@ -639,13 +639,12 @@ class PluginManager(object):
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 entry in gen:
try:
yield entry
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 wrapped(working_set.iter_entry_points(group=group, name=None)):
@@ -424,7 +424,9 @@ class VirtualPrinter(object):
def _gcode_M114(self, data):
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self._lastY*100), int(self._lastZ*100))
if not self._okBeforeCommandOutput:
output = "{} {}".format(self._ok(), output)
ok = self._ok()
if ok:
output = "{} {}".format(self._ok(), output)
self._send(output)
return True
@@ -555,7 +557,7 @@ class VirtualPrinter(object):
def request_resend():
self._send("Resend:%d" % expected)
self._send(self._ok())
self._sendOk()
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
request_resend()
@@ -772,7 +774,9 @@ class VirtualPrinter(object):
output = self._generateTemperatureOutput()
if includeOk:
output = "{} {}".format(self._ok(), output)
ok = self._ok()
if ok:
output = "{} {}".format(ok, output)
self._send(output)
def _parseHotendCommand(self, line, wait=False, support_r=False):
@@ -1156,7 +1160,9 @@ class VirtualPrinter(object):
def _sendOk(self):
if self.outgoing is None:
return
self._send(self._ok())
ok = self._ok()
if ok:
self._send(ok)
def _sendWaitAfterTimeout(self, timeout=5):
time.sleep(timeout)
@@ -1171,6 +1177,8 @@ class VirtualPrinter(object):
ok = self._okFormatString
if self._prepared_oks:
ok = self._prepared_oks.pop(0)
if ok is None:
return ok
return ok.format(ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize())
+9 -5
View File
@@ -600,12 +600,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self.refresh_sd_files(blocking=True)
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
remoteName = util.get_dos_filename(filename,
existing_filenames=existingSdFiles,
extension="gco",
whitelisted_extensions=["gco", "g"])
if valid_file_type(filename, "gcode"):
remoteName = util.get_dos_filename(filename,
existing_filenames=existingSdFiles,
extension="gco",
whitelisted_extensions=["gco", "g"])
else:
# probably something else added through a plugin, use it's basename as-is
remoteName = os.path.basename(filename)
self._timeEstimationData = TimeEstimationHelper()
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName)
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName, special=not valid_file_type(filename, "gcode"))
return remoteName
+1 -1
View File
@@ -1325,7 +1325,7 @@ class Server(object):
# JS
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
js_plugin_filters = ["sourcemap_remove", "js_plugin_delimiter_bundler"]
js_plugin_filters = ["sourcemap_remove", "js_delimiter_bundler"] # TODO: replace with IIFE wrapper again, see #2200
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters))
+1 -1
View File
@@ -329,7 +329,7 @@ def uploadGcodeFile(target):
Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint.
"""
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"):
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode"):
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint)
else:
selectAndOrPrint(filename, absFilename, destination)
+1 -1
View File
@@ -174,7 +174,7 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin):
if self.is_multipart():
if not self._bytes_left:
# we don't support requests without a content-length
raise tornado.web.HTTPError(400, log_message="No Content-Length supplied")
raise tornado.web.HTTPError(411, log_message="No Content-Length supplied")
# extract the multipart boundary
fields = self._content_type.split(";")
+16 -6
View File
@@ -416,7 +416,7 @@ function formatFuzzyPrintTime(totalSeconds) {
var seconds = d.seconds();
var minutes = d.minutes();
var hours = d.hours();
var days = d.asDays();
var days = d.days();
var replacements = {
days: days,
@@ -432,11 +432,16 @@ function formatFuzzyPrintTime(totalSeconds) {
// days
if (hours >= 16) {
replacements.days += 1;
text = gettext("%(days)d days");
if (replacements.days === 1) {
text = gettext("%(days)d day");
} else {
text = gettext("%(days)d days");
}
} else if (hours >= 8 && hours < 16) {
text = gettext("%(days)d.5 days");
} else {
if (days == 1) {
if (days === 1) {
text = gettext("%(days)d day");
} else {
text = gettext("%(days)d days");
@@ -447,7 +452,7 @@ function formatFuzzyPrintTime(totalSeconds) {
if (hours < 12) {
if (minutes < 15) {
// less than .15 => .0
if (hours == 1) {
if (hours === 1) {
text = gettext("%(hours)d hour");
} else {
text = gettext("%(hours)d hours");
@@ -458,10 +463,15 @@ function formatFuzzyPrintTime(totalSeconds) {
} else {
// over .75 => hours + 1
replacements.hours += 1;
text = gettext("%(hours)d hours");
if (replacements.hours === 1) {
text = gettext("%(hours)d hour");
} else {
text = gettext("%(hours)d hours");
}
}
} else {
if (hours == 23 && minutes > 30) {
if (hours === 23 && minutes > 30) {
// over 23.5 hours => 1 day
text = gettext("1 day");
} else {
@@ -49,9 +49,9 @@ $(function() {
.done(function() {
var text;
if (commandSpec.async) {
text = gettext("The command \"%(command)s\" executed successfully");
} else {
text = gettext("The command \"%(command)s\" was triggered asynchronously");
} else {
text = gettext("The command \"%(command)s\" executed successfully");
}
new PNotify({
@@ -25,7 +25,7 @@
<label class="control-label" for="settings-apiKey">{{ _('API Key') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" disabled="disabled" id="settings-apikey" data-bind="value: api_key, attr: {placeholder: '{{ _('N/A') }}'}">
<input type="text" readonly="readonly" id="settings-apikey" data-bind="value: api_key, attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: copyApiKey, enable: api_key"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: generateApiKey, enable: api_key"><i class="fa fa-refresh"></i></a>
</div>
@@ -24,7 +24,7 @@
<label class="control-label" for="userSettings-access_apikey">{{ _('Current API Key') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" disabled="disabled" id="userSettings-access_apikey" data-bind="value: access_apikey, attr: {placeholder: '{{ _('N/A') }}'}">
<input type="text" readonly="readonly" id="userSettings-access_apikey" data-bind="value: access_apikey, attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: copyApikey, enable: access_apikey"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: generateApikey"><i class="fa fa-refresh"></i></a>
<a class="btn btn-danger add-on" title="Delete API Key" data-bind="click: deleteApikey, enable: access_apikey"><i class="fa fa-trash-o"></i></a>
@@ -156,7 +156,7 @@
<label class="control-label">{{ _('Current API Key') }}</label>
<div class="controls">
<div class="input-append input-block-level ">
<input type="text" disabled="disabled" data-bind="value: $root.access.users.editor.apikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
<input type="text" readonly="readonly" data-bind="value: $root.access.users.editor.apikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: $root.access.users.copyApikey, enable: $root.access.users.editor.apikey"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: function() { $root.access.users.confirmGenerateApikey(); }"><i class="fa fa-refresh"></i></a>
<a class="btn add-on btn-danger" title="Delete API Key" data-bind="click: function() { $root.access.users.confirmDeleteApikey(); }"><i class="fa fa-trash-o"></i></a>
+28 -3
View File
@@ -524,7 +524,7 @@ def is_running_from_source():
return os.path.isdir(os.path.join(root, "src")) and os.path.isfile(os.path.join(root, "setup.py"))
def dict_merge(a, b):
def dict_merge(a, b, leaf_merger=None):
"""
Recursively deep-merges two dictionaries.
@@ -543,10 +543,24 @@ def dict_merge(a, b):
True
>>> dict_merge(None, None) == dict()
True
>>> def leaf_merger(a, b):
... if isinstance(a, list) and isinstance(b, list):
... return a + b
... raise ValueError()
>>> result = dict_merge(dict(l1=[3, 4], l2=[1], a="a"), dict(l1=[1, 2], l2="foo", b="b"), leaf_merger=leaf_merger)
>>> result.get("l1") == [3, 4, 1, 2]
True
>>> result.get("l2") == "foo"
True
>>> result.get("a") == "a"
True
>>> result.get("b") == "b"
True
Arguments:
a (dict): The dictionary to merge ``b`` into
b (dict): The dictionary to merge into ``a``
leaf_merger (callable): An optional callable to use to merge leaves (non-dict values)
Returns:
dict: ``b`` deep-merged into ``a``
@@ -564,9 +578,20 @@ def dict_merge(a, b):
result = deepcopy(a)
for k, v in b.items():
if k in result and isinstance(result[k], dict):
result[k] = dict_merge(result[k], v)
result[k] = dict_merge(result[k], v, leaf_merger=leaf_merger)
else:
result[k] = deepcopy(v)
merged = None
if k in result and callable(leaf_merger):
try:
merged = leaf_merger(result[k], v)
except ValueError:
# can't be merged by leaf merger
pass
if merged is None:
merged = deepcopy(v)
result[k] = merged
return result
+29 -5
View File
@@ -878,7 +878,7 @@ class MachineCom(object):
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
def startFileTransfer(self, filename, localFilename, remoteFilename):
def startFileTransfer(self, filename, localFilename, remoteFilename, special=False):
if not self.isOperational() or self.isBusy():
self._logger.info("Printer is not operational or busy")
return
@@ -886,7 +886,10 @@ class MachineCom(object):
with self._jobLock:
self.resetLineNumbers()
self._currentFile = StreamingGcodeFileInformation(filename, localFilename, remoteFilename)
if special:
self._currentFile = SpecialStreamingGcodeFileInformation(filename, localFilename, remoteFilename)
else:
self._currentFile = StreamingGcodeFileInformation(filename, localFilename, remoteFilename)
self._currentFile.start()
self.sendCommand("M28 %s" % remoteFilename)
@@ -2357,7 +2360,7 @@ class MachineCom(object):
# now comes the part where we increase line numbers and send stuff - no turning back now
command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands
command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands
checksum_enabled = not self._neverSendChecksum and (self.isPrinting() or
checksum_enabled = not self._neverSendChecksum and ((self.isPrinting() and self._currentFile and self._currentFile.checksum) or
self._alwaysSendChecksum or
not self._firmware_info_received)
@@ -2473,8 +2476,8 @@ class MachineCom(object):
def _do_send_with_checksum(self, command, linenumber):
command_to_send = "N" + str(linenumber) + " " + command
checksum = 0
for c in command_to_send:
checksum ^= ord(c)
for c in bytearray(command_to_send):
checksum ^= c
command_to_send = command_to_send + "*" + str(checksum)
self._do_send_without_checksum(command_to_send)
@@ -2826,6 +2829,8 @@ class PrintingFileInformation(object):
value between 0 and 1.
"""
checksum = True
def __init__(self, filename):
self._logger = logging.getLogger(__name__)
self._filename = filename
@@ -2880,6 +2885,8 @@ class PrintingSdFileInformation(PrintingFileInformation):
Encapsulates information regarding an ongoing print from SD.
"""
checksum = False
def __init__(self, filename, size):
PrintingFileInformation.__init__(self, filename)
self._size = size
@@ -3026,6 +3033,23 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
self._logger.info("Finished in {duration:.3f} s. Approx. transfer rate of {rate:.3f} lines/s or {time_per_line:.3f} ms per line".format(**stats))
class SpecialStreamingGcodeFileInformation(StreamingGcodeFileInformation):
"""
For streaming files to the printer that aren't GCODE.
Difference to regular StreamingGcodeFileInformation: no checksum requirement, only rudimentary line processing
(stripping of whitespace from the end and ignoring of empty lines)
"""
checksum = False
def _process(self, line, offsets, current_tool):
line = line.rstrip()
if not len(line):
return None
return line
class SendQueue(PrependableQueue):
def __init__(self, maxsize=0):