Merge branch 'maintenance' into devel

# Conflicts:
#	setup.py
This commit is contained in:
Gina Häußge committed 2018-04-26 19:10:16 +02:00
commit d8072f0e05
40 files changed
+568 -282

No files matched your search

+1
View File
@@ -90,6 +90,7 @@ date of first contribution):
* [Bernd Zeimetz](https://github.com/bzed)
* [Daniele Forsi](https://github.com/dforsi)
* [Ganey](https://github.com/ganey)
* [Sven Lohrmann](https://github.com/malnvenshorn)
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
View File
File renamed without changes.
-1
View File
@@ -71,7 +71,6 @@
* [ddt](https://github.com/txels/ddt): MIT
* [mock](https://github.com/testing-cabal/mock): BSD
* [nose](http://pythonhosted.org/nose/): LGPL
* [pypandoc](https://github.com/bebraw/pypandoc): MIT
* [Sphinx](http://sphinx-doc.org/): BSD
* [sphinxcontrib-httpdomain](https://bitbucket.org/birkenfeld/sphinx-contrib/src/default/httpdomain/): BSD
* [sphinxcontrib-mermad](https://github.com/mgaitan/sphinxcontrib-mermaid): BSD
+6
View File
@@ -65,6 +65,12 @@ Test paths or URLs
from the URL check will be returned as part of the check result as well. ``json`` will attempt
to parse the response as json and return the parsed result. ``true`` or ``bytes`` will base64 encode the body
and return that.
* ``content_type_whitelist``: Optional array of supported content types. If set and the URL returns a content
type not included in this list, the test will fail. E.g. ``["image/*", "text/plain"]``.
* ``content_type_blacklist``: Optional array of unsupported content types. If set and the URL returns a content
type included in this list, the test wil fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist``
to further limit broader content type definition, e.g. by putting ``image/*`` into the whitelist, but disallowing
PNG by including ``image/png`` on the blacklist.
The ``url`` command returns :http:statuscode:`200` with a :ref:`URL test result <sec-api-util-datamodel-urltestresult>`
when the test could be performed. The status code of the response does NOT reflect the
+1 -1
View File
@@ -1,5 +1,5 @@
[metadata]
description-file = README.md
license_file = LICENSE.txt
[versioneer]
VCS = git
+30 -22
View File
@@ -16,7 +16,7 @@ import octoprint_setuptools
INSTALL_REQUIRES = [
"flask>=0.12,<0.13",
"werkzeug>=0.11.1,<0.12",
"tornado>=5.0.1,<6",
"tornado>=4.5.3,<5",
"Jinja2>=2.8,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
@@ -72,9 +72,6 @@ EXTRA_REQUIRES = dict(
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid>=0.3",
"sphinx_rtd_theme",
# PyPi upload related
"pypandoc"
],
# Dependencies for developing OctoPrint plugins
@@ -92,6 +89,13 @@ DEPENDENCY_LINKS = []
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
here = os.path.abspath(os.path.dirname(__file__))
def read_file_contents(path):
import codecs
with codecs.open(path, encoding="utf-8") as f:
return f.read()
def data_copy_build_py_factory(files, baseclass):
class data_copy_build_py(baseclass):
files = dict()
@@ -147,45 +151,49 @@ def params():
version = versioneer.get_version()
cmdclass = get_cmdclass()
description = "A snappy web interface for 3D printers"
long_description = open("README.md").read()
description = "The snappy web interface for your 3D printer"
long_description = read_file_contents(os.path.join(here, "README.md"))
long_description_content_type = "text/markdown"
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
setup_requires = SETUP_REQUIRES
try:
import pypandoc
setup_requires += ["setuptools-markdown"]
long_description_markdown_filename = "README.md"
del pypandoc
except:
pass
classifiers = [
"Development Status :: 4 - Beta",
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Printing",
"Topic :: System :: Networking :: Monitoring"
"Topic :: System :: Monitoring"
]
author = "Gina Häußge"
author_email = "osd@foosel.net"
url = "http://octoprint.org"
license = "AGPLv3"
author_email = "gina@octoprint.org"
url = "https://octoprint.org"
license = "GNU Affero General Public License v3"
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
project_urls={
"Community Forum": "https://discourse.octoprint.org",
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
"Source": "https://github.com/foosel/OctoPrint",
"Funding": "https://donate.octoprint.org"
}
packages = find_packages(where="src")
package_dir = {
+60 -21
View File
@@ -177,8 +177,8 @@ class StorageInterface(object):
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
@@ -444,7 +444,7 @@ class LocalFileStorage(StorageInterface):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
Metadata is managed inside ``.metadata.yaml`` files in the respective folders, indexed by the sanitized filenames
Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames
stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead.
This storage type implements :func:`path_on_disk`.
@@ -565,7 +565,7 @@ class LocalFileStorage(StorageInterface):
path = os.path.join(self.basefolder, path)
def last_modified_for_path(p):
metadata = os.path.join(p, ".metadata.yaml")
metadata = os.path.join(p, ".metadata.json")
if os.path.exists(metadata):
return max(os.stat(p).st_mtime, os.stat(metadata).st_mtime)
else:
@@ -634,7 +634,7 @@ class LocalFileStorage(StorageInterface):
empty = True
for entry in scandir(folder_path):
if entry.name == ".metadata.yaml":
if entry.name == ".metadata.json" or entry.name == ".metadata.yaml":
continue
empty = False
break
@@ -1115,7 +1115,7 @@ class LocalFileStorage(StorageInterface):
try:
print_time = float(print_time)
except:
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.yaml: {!r}".format(name, path, print_time))
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
continue
if not printer_profile in former_print_times:
@@ -1518,14 +1518,16 @@ class LocalFileStorage(StorageInterface):
if path in self._metadata_cache:
return deepcopy(self._metadata_cache[path])
metadata_path = os.path.join(path, ".metadata.yaml")
self._migrate_metadata(path)
metadata_path = os.path.join(path, ".metadata.json")
if os.path.exists(metadata_path):
with open(metadata_path) as f:
try:
import yaml
metadata = yaml.safe_load(f)
import json
metadata = json.load(f)
except:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
else:
if isinstance(metadata, dict):
self._metadata_cache[path] = deepcopy(metadata)
@@ -1534,27 +1536,63 @@ class LocalFileStorage(StorageInterface):
def _save_metadata(self, path, metadata):
with self._get_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.yaml")
metadata_path = os.path.join(path, ".metadata.json")
try:
import yaml
import json
with atomic_write(metadata_path) as f:
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
json.dump(metadata, f, indent=4, separators=(",", ": "))
except:
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
else:
self._metadata_cache[path] = deepcopy(metadata)
def _delete_metadata(self, path):
with self._get_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.yaml")
if os.path.exists(metadata_path):
try:
os.remove(metadata_path)
except:
self._logger.exception("Error while deleting .metadata.yaml from {path}".format(**locals()))
metadata_files = (".metadata.json", ".metadata.yaml")
for metadata_file in metadata_files:
metadata_path = os.path.join(path, metadata_file)
if os.path.exists(metadata_path):
try:
os.remove(metadata_path)
except:
self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
if path in self._metadata_cache:
del self._metadata_cache[path]
def _migrate_metadata(self, path):
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
import yaml
import json
with self._get_metadata_lock(path):
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
metadata_path_json = os.path.join(path, ".metadata.json")
if not os.path.exists(metadata_path_yaml):
# nothing to migrate
return
if os.path.exists(metadata_path_json):
# already migrated
# TODO 1.3.10 Remove ".metadata.yaml" files
return
with open(metadata_path_yaml) as f:
try:
metadata = yaml.safe_load(f)
except:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
return
if not isinstance(metadata, dict):
# looks invalid, ignore it
return
with atomic_write(metadata_path_json) as f:
json.dump(metadata, f, indent=4, separators=(",", ": "))
# TODO 1.3.10 Remove ".metadata.yaml" files
@contextmanager
def _get_metadata_lock(self, path):
with self._metadata_lock_mutex:
@@ -1566,8 +1604,9 @@ class LocalFileStorage(StorageInterface):
counter += 1
self._metadata_locks[path] = (counter, lock)
yield lock
yield lock
with self._metadata_lock_mutex:
counter = self._metadata_locks[path][0]
counter -= 1
if counter <= 0:
@@ -2,7 +2,7 @@
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine, valueUpdate: 'afterkeydown'">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine, valueUpdate: 'afterkeydown'" id="settings-cura-path">
<button class="btn" type="button" data-bind="click: testEnginePath, enable: settings.plugins.cura.cura_engine(), css: {disabled: !settings.plugins.cura.cura_engine()}">{{ _('Test') }}</button>
</div>
<span class="help-block" data-bind="visible: pathBroken() || pathOk(), text: pathText"></span>
@@ -293,7 +293,7 @@ def get_latest(target, check, custom_compare=None, online=True):
commitishes = dict((x["branch"], x.get("commitish", [x["branch"]])) for x in prerelease_branches)
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
force_base = check.get("force_base", True)
force_base = check.get("force_base", False)
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
custom=custom_compare)
@@ -529,19 +529,19 @@ class VirtualPrinter(object):
self._busyInterval = interval
def _gcode_M114(self, data):
if settings().getBoolean(["devel", "virtualPrinter", "reprapfwM114"]):
output = "X:{} Y:{} Z:{} {}".format(self._lastX,
self._lastY,
self._lastZ,
" ".join(["E{}:{}".format(num, self._lastE[self.currentExtruder]) for num in range(self.extruderCount)]))
else:
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX,
self._lastY,
self._lastZ,
self._lastE[self.currentExtruder],
int(self._lastX*100),
int(self._lastY*100),
int(self._lastZ*100))
m114FormatString = settings().get(["devel", "virtualPrinter", "m114FormatString"])
e = dict((index, value) for index, value in enumerate(self._lastE))
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(["E{}:{}".format(num, self._lastE[self.currentExtruder]) for num in range(self.extruderCount)])
output = m114FormatString.format(x=self._lastX,
y=self._lastY,
z=self._lastZ,
e=e,
f=self._lastF,
a=int(self._lastX*100),
b=int(self._lastY*100),
c=int(self._lastZ*100))
if not self._okBeforeCommandOutput:
ok = self._ok()
if ok:
@@ -735,7 +735,7 @@ class VirtualPrinter(object):
| Sleeps <seconds> s after execution of next <command>
# SD printing
start_sd <str:file>
| Start printing file <file> from SD
cancel_sd
+48 -27
View File
@@ -113,7 +113,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
estimatedPrintTime=None,
lastPrintTime=None,
filament=self._dict(length=None,
volume=None)),
volume=None),
user=None),
progress=self._dict(completion=None,
filepos=None,
printTime=None,
@@ -174,14 +175,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
self._selectedFile["sd"],
self._selectedFile["user"])
def _on_event_MetadataStatisticsUpdated(self, event, data):
with self._selectedFileMutex:
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
self._selectedFile["sd"],
self._selectedFile["user"])
#~~ progress plugin reporting
@@ -418,26 +421,30 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self.commands("M221 S%d" % factor,
tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"})
def select_file(self, path, sd, printAfterSelect=False, pos=None, *args, **kwargs):
def select_file(self, path, sd, printAfterSelect=False, user=None, pos=None, *args, **kwargs):
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
self._logger.info("Cannot load file: printer not connected or currently busy")
return
self._validateJob(path, sd)
origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
path_on_disk = self._fileManager.path_on_disk(origin, path)
path_in_storage = self._fileManager.path_in_storage(origin, path_on_disk)
recovery_data = self._fileManager.get_recovery_data()
if recovery_data:
# clean up recovery data if we just selected a different file than is logged in that
expected_origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
actual_origin = recovery_data.get("origin", None)
actual_path = recovery_data.get("path", None)
if actual_origin is None or actual_path is None or actual_origin != expected_origin or actual_path != path:
if actual_origin is None or actual_path is None or actual_origin != origin or actual_path != path_in_storage:
self._fileManager.delete_recovery_data()
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd else path, sd,
self._comm.selectFile("/" + path if sd else path_on_disk, sd,
user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.select_file"})
self._updateProgressData()
self._setCurrentZ(None)
@@ -460,7 +467,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm.getFilePosition()
def start_print(self, pos=None, *args, **kwargs):
def start_print(self, pos=None, user=None, *args, **kwargs):
"""
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
@@ -744,22 +751,33 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printTime = self._comm.getPrintTime()
cleanedPrintTime = self._comm.getCleanedPrintTime()
statisticalTotalPrintTime = None
statisticalTotalPrintTimeType = None
with self._selectedFileMutex:
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
printTimeLeft, printTimeLeftOrigin = self._estimatePrintTimeLeft(progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType)
if progress is not None:
progress_int = int(progress * 100)
if self._lastProgressReport != progress_int:
self._lastProgressReport = progress_int
self._reportPrintProgressToPlugins(progress_int)
if progress == 0:
printTimeLeft = None
printTimeLeftOrigin = None
elif progress == 1.0:
printTimeLeft = 0
printTimeLeftOrigin = None
else:
statisticalTotalPrintTime = None
statisticalTotalPrintTimeType = None
with self._selectedFileMutex:
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
printTimeLeft, printTimeLeftOrigin = self._estimatePrintTimeLeft(progress,
printTime,
cleanedPrintTime,
statisticalTotalPrintTime,
statisticalTotalPrintTimeType)
return self._dict(completion=progress * 100 if progress is not None else None,
filepos=filepos,
printTime=int(printTime) if printTime is not None else None,
@@ -912,7 +930,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not os.path.isfile(path_on_disk):
raise InvalidFileLocation("{} does not exist in local storage, cannot select for printing".format(filename))
def _setJobData(self, filename, filesize, sd):
def _setJobData(self, filename, filesize, sd, user=None):
with self._selectedFileMutex:
if filename is not None:
if sd:
@@ -929,7 +947,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"filename": path_in_storage,
"filesize": filesize,
"sd": sd,
"estimatedPrintTime": None
"estimatedPrintTime": None,
"user": user
}
else:
self._selectedFile = None
@@ -942,7 +961,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
estimatedPrintTime=None,
averagePrintTime=None,
lastPrintTime=None,
filament=None))
filament=None,
user=None))
return
estimatedPrintTime = None
@@ -993,7 +1013,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
estimatedPrintTime=estimatedPrintTime,
averagePrintTime=averagePrintTime,
lastPrintTime=lastPrintTime,
filament=filament))
filament=filament,
user=user))
def _sendInitialStateUpdate(self, callback):
try:
@@ -1117,7 +1138,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
self._sdFilelistAvailable.set()
def on_comm_file_selected(self, full_path, size, sd):
def on_comm_file_selected(self, full_path, size, sd, user=None):
if full_path is not None:
payload = self._payload_for_print_job_event(location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
print_job_file=full_path)
@@ -1125,12 +1146,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
eventManager().fire(Events.FILE_DESELECTED)
self._setJobData(full_path, size, sd)
self._setJobData(full_path, size, sd, user=user)
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
if self._printAfterSelect:
self._printAfterSelect = False
self.start_print(pos=self._posAfterSelect)
self.start_print(pos=self._posAfterSelect, user=user)
def on_comm_print_job_started(self):
payload = self._payload_for_print_job_event()
@@ -1228,10 +1249,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
context=dict(event=payload),
must_be_set=False)
def on_comm_file_transfer_started(self, filename, filesize):
def on_comm_file_transfer_started(self, filename, filesize, user=None):
self._sdStreaming = True
self._setJobData(filename, filesize, True)
self._setJobData(filename, filesize, True, user=user)
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
+20 -12
View File
@@ -490,7 +490,7 @@ class Server(object):
## Tornado initialization starts here
ioloop = IOLoop()
ioloop.make_current()
ioloop.install()
self._router = SockJSRouter(self._create_socket_connection, "/sockjs",
session_kls=util.sockjs.ThreadSafeSession)
@@ -760,9 +760,7 @@ class Server(object):
except (KeyboardInterrupt, SystemExit):
pass
except:
self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report "
"this including reproduction steps, octoprint.log and the stacktrace below in "
"OctoPrint's bugtracker. Thanks!")
self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!")
self._logger.exception("Stacktrace follows:")
def _create_socket_connection(self, session):
@@ -1462,7 +1460,12 @@ class Server(object):
global loginManager
loginManager = LoginManager()
loginManager.session_protection = "strong"
# "strong" is incompatible to remember me, see maxcountryman/flask-login#156. It also causes issues with
# clients toggling between IPv4 and IPv6 client addresses due to names being resolved one way or the other as
# at least observed on a Win10 client targeting "localhost", resolved as both "127.0.0.1" and "::1"
loginManager.session_protection = "basic"
loginManager.user_callback = load_user
loginManager.anonymous_user = users.AnonymousUser # TODO: remove in 1.5.0
loginManager.unauthorized_callback = unauthorized_user
@@ -1477,20 +1480,25 @@ class Server(object):
loginManager.init_app(app, add_context_processor=False)
def _start_intermediary_server(self):
import BaseHTTPServer
import SimpleHTTPServer
try:
# noinspection PyCompatibility
from http.server import HTTPServer, BaseHTTPRequestHandler
except ImportError:
# noinspection PyCompatibility
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import threading
import socket
host = self._host
port = self._port
class IntermediaryServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
class IntermediaryServerHandler(BaseHTTPRequestHandler):
def __init__(self, rules=None, *args, **kwargs):
if rules is None:
rules = []
self.rules = rules
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def do_GET(self):
request_path = self.path
@@ -1540,11 +1548,11 @@ class Server(object):
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
class HTTPServerV6(BaseHTTPServer.HTTPServer):
class HTTPServerV6(HTTPServer):
address_family = socket.AF_INET6
def __init__(self, *args, **kwargs):
BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)
HTTPServer.__init__(self, *args, **kwargs)
# make sure to enable dual stack mode, otherwise the socket might only listen on IPv6
self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0)
@@ -1554,7 +1562,7 @@ class Server(object):
ServerClass = HTTPServerV6
else:
# v4
ServerClass = BaseHTTPServer.HTTPServer
ServerClass = HTTPServer
self._logger.debug("Starting intermediary server on http://{}:{}".format(host if not ":" in host else "[" + host + "]", port))
+45 -20
View File
@@ -342,6 +342,8 @@ def utilTestPath():
timeout = 3.0
valid_ssl = True
check_status = [status_ranges["normal"]]
content_type_whitelist = None
content_type_blacklist = None
if "timeout" in data:
try:
@@ -369,34 +371,57 @@ def utilTestPath():
if code is not None:
check_status.append([code])
if "content_type_whitelist" in data:
if not isinstance(data["content_type_whitelist"], (list, tuple)):
return make_response("content_type_whitelist must be a list of mime types")
content_type_whitelist = map(util.parse_mime_type, data["content_type_whitelist"])
if "content_type_blacklist" in data:
if not isinstance(data["content_type_whitelist"], (list, tuple)):
return make_response("content_type_blacklist must be a list of mime types")
content_type_blacklist = map(util.parse_mime_type, data["content_type_blacklist"])
response_result = None
outcome = True
status = 0
try:
response = requests.request(method=method, url=url, timeout=timeout, verify=valid_ssl)
status = response.status_code
with requests.request(method=method, url=url, timeout=timeout, verify=valid_ssl, stream=True) as response:
status = response.status_code
outcome = outcome and any(map(lambda x: status in x, check_status))
content_type = response.headers.get("content-type")
response_result = dict(headers=dict(response.headers),
content_type=content_type)
parsed_content_type = util.parse_mime_type(content_type)
in_whitelist = content_type_whitelist is None or any(map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_whitelist))
in_blacklist = content_type_blacklist is not None and any(map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_blacklist))
if not in_whitelist or in_blacklist:
# we don't support this content type
response.close()
outcome = False
elif "response" in data and (data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes")):
if data["response"] == "json":
content = response.json()
else:
import base64
content = base64.standard_b64encode(response.content)
response_result["content"] = content
except:
status = 0
logging.getLogger(__name__).exception("Error while running a test {} request on {}".format(method, url))
outcome = False
result = dict(
url=url,
status=status,
result=any(map(lambda x: status in x, check_status))
result=outcome
)
if response_result:
result["response"] = response_result
if "response" in data and (data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes")):
import base64
content = base64.standard_b64encode(response.content)
if data["response"] == "json":
try:
content = response.json()
except:
logging.getLogger(__name__).exception("Couldn't convert response to json")
result["result"] = False
result["response"] = dict(
headers=dict(response.headers),
content=content
)
return jsonify(**result)
elif command == "server":
+8 -4
View File
@@ -9,7 +9,7 @@ from flask import request, jsonify, make_response, url_for
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT, current_user
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, with_revalidation_checking
from octoprint.server.api import api
from octoprint.events import Events
@@ -316,6 +316,8 @@ def uploadGcodeFile(target):
reselect = printer.is_current_file(futureFullPathInStorage, sd)
user = current_user.get_name()
def fileProcessingFinished(filename, absFilename, destination):
"""
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
@@ -340,7 +342,7 @@ def uploadGcodeFile(target):
exact file is already selected, such reloading it.
"""
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or reselect):
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect, user)
try:
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload,
@@ -485,6 +487,8 @@ def gcodeFileCommand(filename, target):
if response is not None:
return response
user = current_user.get_name()
if command == "select":
if not _verifyFileExists(target, filename):
return make_response("File not found on '%s': %s" % (target, filename), 404)
@@ -505,7 +509,7 @@ def gcodeFileCommand(filename, target):
sd = True
else:
filenameToSelect = fileManager.path_on_disk(target, filename)
printer.select_file(filenameToSelect, sd, printAfterLoading)
printer.select_file(filenameToSelect, sd, printAfterLoading, user)
elif command == "slice":
if not _verifyFileExists(target, filename):
@@ -608,7 +612,7 @@ def gcodeFileCommand(filename, target):
sd = True
else:
filenameToSelect = fileManager.path_on_disk(target, path)
printer.select_file(filenameToSelect, sd, print_after_slicing)
printer.select_file(filenameToSelect, sd, print_after_slicing, user)
try:
fileManager.slice(slicer, target, filename, target, full_path,
+7 -4
View File
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from flask import request, make_response, jsonify
from octoprint.server import printer, NO_CONTENT
from octoprint.server import printer, NO_CONTENT, current_user
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
from octoprint.server.api import api
import octoprint.util as util
@@ -34,14 +34,16 @@ def controlJob():
tags = {"source:api", "api:job"}
user = current_user.get_name()
if command == "start":
if activePrintjob:
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
printer.start_print(tags=tags)
printer.start_print(tags=tags, user=user)
elif command == "restart":
if not printer.is_paused():
return make_response("Printer does not have an active print job or is not paused", 409)
printer.start_print(tags=tags)
printer.start_print(tags=tags, user=user)
elif command == "pause":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
@@ -67,5 +69,6 @@ def jobState():
return jsonify({
"job": currentData["job"],
"progress": currentData["progress"],
"state": currentData["state"]["text"]
"state": currentData["state"]["text"],
"printingUser": currentData["printingUser"],
})
+2
View File
@@ -140,6 +140,7 @@ def getSettings():
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
"timeoutSdStatusAutoreport": s.getFloat(["serial", "timeout", "sdStatusAutoreport"]),
"timeoutBaudrateDetectionPause": s.getFloat(["serial", "timeout", "baudrateDetectionPause"]),
"timeoutPositionLogWait": s.getFloat(["serial", "timeout", "positionLogWait"]),
"log": s.getBoolean(["serial", "log"]),
"additionalPorts": s.get(["serial", "additionalPorts"]),
"additionalBaudrates": s.get(["serial", "additionalBaudrates"]),
@@ -376,6 +377,7 @@ def _saveSettings(data):
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"])
if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat(["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"])
if "timeoutPositionLogWait" in data["serial"]: s.setFloat(["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"])
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
+4 -2
View File
@@ -101,7 +101,8 @@ default_settings = {
"sdStatus": 1,
"sdStatusAutoreport": 1,
"resendOk": .5,
"baudrateDetectionPause": 1.0
"baudrateDetectionPause": 1.0,
"positionLogWait": 10.0,
},
"maxCommunicationTimeouts": {
"idle": 2,
@@ -119,7 +120,7 @@ default_settings = {
"logResends": True,
"supportResendsWithoutOk": "detect",
"logPositionOnPause": True,
"logPositionOnCancel": True,
"logPositionOnCancel": False,
"waitForStartOnConnect": False,
"alwaysSendChecksum": False,
"neverSendChecksum": False,
@@ -409,6 +410,7 @@ default_settings = {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"ambientTemperature": 21.3,
"errors": {
"checksum_mismatch": "Checksum mismatch",
@@ -38,6 +38,7 @@ $(function() {
self.printTimeLeftOrigin = ko.observable(undefined);
self.sd = ko.observable(undefined);
self.timelapse = ko.observable(undefined);
self.user = ko.observable(undefined);
self.busyFiles = ko.observableArray([]);
@@ -167,6 +168,12 @@ $(function() {
}
});
self.userString = ko.pureComputed(function() {
var user = self.user();
var file = self.filename();
return (user ? user : (file ? "-" : ""));
});
self.fromCurrentData = function(data) {
self._fromData(data);
};
@@ -244,6 +251,8 @@ $(function() {
});
}
self.filament(result);
self.user(data.user);
};
self._processProgressData = function(data) {
@@ -159,6 +159,7 @@ $(function() {
self.serial_timeoutSdStatus = ko.observable(undefined);
self.serial_timeoutSdStatusAutoreport = ko.observable(undefined);
self.serial_timeoutBaudrateDetectionPause = ko.observable(undefined);
self.serial_timeoutPositionLogWait = ko.observable(undefined);
self.serial_log = ko.observable(undefined);
self.serial_additionalPorts = ko.observable(undefined);
self.serial_additionalBaudrates = ko.observable(undefined);
@@ -330,23 +331,36 @@ $(function() {
method: "GET",
response: "bytes",
timeout: self.webcam_snapshotTimeout(),
validSsl: self.webcam_snapshotSslValidation()
validSsl: self.webcam_snapshotSslValidation(),
content_type_whitelist: ["image/*"]
})
.done(function(response) {
if (!response.result) {
if (response.status && response.response && response.response.content_type) {
// we could contact the server, but something else was wrong, probably the mime type
errorText = gettext("Could retrieve the snapshot URL, but it didn't look like an " +
"image. Got this as a content type header: <code>%(content_type)s</code>. Please " +
"double check that the URL is returning static images, not multipart data " +
"or videos.");
errorText = _.sprintf(errorText, {content_type: response.response.content_type});
}
showMessageDialog({
title: errorTitle,
message: errorText
message: errorText,
onclose: function() {
self.testWebcamSnapshotUrlBusy(false);
}
});
return;
}
var content = response.response.content;
var mimeType = "image/jpeg";
var contentType = response.response.content_type
var headers = response.response.headers;
if (headers && headers["content-type"]) {
mimeType = headers["content-type"].split(";")[0];
var mimeType = "image/jpeg";
if (contentType) {
mimeType = contentType.split(";")[0];
}
var text = gettext("If you see your webcam snapshot picture below, the entered snapshot URL is ok.");
@@ -886,6 +900,13 @@ $(function() {
firstRequest.resolve();
};
self.cancelData = function () {
// revert unsaved changes
self.fromResponse(self.lastReceivedSettings);
self.hide();
}
self.saveData = function (data, successCallback, setAsSending) {
var options;
if (_.isPlainObject(successCallback)) {
@@ -54,11 +54,12 @@ $(function() {
});
self.editorPasswordMismatch = ko.pureComputed(function() {
return self.editorPassword() != self.editorRepeatedPassword();
return self.editorPassword() !== self.editorRepeatedPassword();
});
self.requestData = function() {
if (!CONFIG_ACCESS_CONTROL) return;
if (!self.loginState.isAdmin()) return;
OctoPrint.users.list()
.done(self.fromResponse);
@@ -97,8 +98,20 @@ $(function() {
self.showEditUserDialog = function(user) {
if (!CONFIG_ACCESS_CONTROL) return;
self.currentUser(user);
self.editUserDialog.modal("show");
var process = function(user) {
self.currentUser(user);
self.editUserDialog.modal("show");
};
// make sure we have the current user data, see #2534
OctoPrint.users.get(user.name)
.done(function(data) {
process(data);
})
.fail(function() {
log.warn("Could not fetch current user data, proceeding with client side data copy");
process(user);
});
};
self.confirmEditUser = function() {
@@ -175,6 +188,7 @@ $(function() {
if (!user) {
throw OctoPrint.InvalidArgumentError("user must be set");
}
if (!self.loginState.isAdmin()) return $.Deferred().reject("You are not authorized to perform this action").promise();
return OctoPrint.users.add(user)
.done(self.fromResponse);
@@ -184,8 +198,9 @@ $(function() {
if (!user) {
throw OctoPrint.InvalidArgumentError("user must be set");
}
if (!self.loginState.isAdmin()) return $.Deferred().reject("You are not authorized to perform this action").promise();
if (user.name == self.loginState.username()) {
if (user.name === self.loginState.username()) {
// we do not allow to delete ourselves
new PNotify({
title: gettext("Not possible"),
@@ -213,7 +228,10 @@ $(function() {
};
self.generateApikey = function(username) {
return OctoPrint.users.generateApiKey(username);
return OctoPrint.users.generateApiKey(username)
.done(function() {
self.requestData();
});
};
self.deleteApikey = function(username) {
@@ -221,9 +239,7 @@ $(function() {
};
self.onUserLoggedIn = function(user) {
if (user.admin) {
self.requestData();
}
self.requestData();
}
}
@@ -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,18 +34,30 @@ $(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();
}
self.currentUser(user);
self.userSettingsDialog.modal("show");
var process = function(user) {
self.currentUser(user);
self.userSettingsDialog.modal("show");
};
// make sure we have the current user data, see #2534
OctoPrint.users.get(user.name)
.done(function(data) {
process(data);
})
.fail(function() {
log.warn("Could not fetch current user data, proceeding with client side data copy");
process(user);
});
};
self.save = function() {
@@ -49,7 +49,7 @@
</div>
<div class="modal-footer">
<button class="btn aboutlink" data-bind="click: about.show"><i class="fa fa-info-circle"></i> {{ _('About OctoPrint') }}</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
<button class="btn" data-bind="click: function() { cancelData() }" aria-hidden="true">{{ _('Cancel') }}</button>
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }, enable: !exchanging(), css: {disabled: exchanging()}"><i class="fa fa-spinner fa-spin" data-bind="visible: sending"></i> {{ _('Save') }}</button>
</div>
</div>
@@ -14,7 +14,7 @@
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-apiKey">{{ _('API Key') }}</label>
<label class="control-label" for="settings-apikey">{{ _('API Key') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" readonly="readonly" id="settings-apikey" data-bind="value: api_key, attr: {placeholder: '{{ _('N/A') }}'}">
@@ -22,7 +22,7 @@
<div class="control-group" title="">
<label class="control-label" for="settings-appearanceLanguages">{{ _('Language Packs') }}</label>
<div class="controls">
<button class="btn" data-bind="click: showTranslationManager">{{ _('Manage...') }}</button>
<button class="btn" data-bind="click: showTranslationManager" id="settings-appearanceLanguages">{{ _('Manage...') }}</button>
</div>
</div>
<div class="control-group" title="">
@@ -26,7 +26,7 @@
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-watchedLogs">{{ _('Watched Folder') }}</label>
<label class="control-label" for="settings-folderWatched">{{ _('Watched Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_watched" id="settings-folderWatched">
</div>
@@ -44,15 +44,15 @@
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
<div class="control-group" title="{{ ('Threshold after which to warn about the remaining free space on disk.') }}">
<label class="control-label" for="settings.serverDiskusageWarning">{{ _('Warning') }}</label>
<label class="control-label" for="settings-serverDiskusageWarning">{{ _('Warning') }}</label>
<div class="controls">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_warning_str">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_warning_str" id="settings-serverDiskusageWarning">
</div>
</div>
<div class="control-group" title="{{ ('Threshold after which to consider remaining free space on disk as critical.') }}">
<label class="control-label" for="settings.serverDiskusageCritical">{{ _('Critical') }}</label>
<label class="control-label" for="settings-serverDiskusageCritical">{{ _('Critical') }}</label>
<div class="controls">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str" id="settings-serverDiskusageCritical">
</div>
</div>
@@ -7,10 +7,10 @@
</div>
</div>
<div class="control-group" title="{{ _('Maximum size the GCodeViewer autoloads the file for preview') }}">
<label class="control-label" for="settings-gcodeviewer">{{ _('GCode Visualizer file size threshold') }}</label>
<label class="control-label" for="settings-featureSizeThreshold">{{ _('GCode Visualizer file size threshold') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-mini text-right" data-bind="value: feature_sizeThreshold_str">
<input type="text" class="input-mini text-right" data-bind="value: feature_sizeThreshold_str" id="settings-featureSizeThreshold">
</div>
<span class="help-inline">{{ _('on desktop')}}</span>
</div>
@@ -77,7 +77,7 @@
</div>
</div>
<div class="control-group" title="{{ _('Temperature report interval to request from autoreport capable firmwares. A value of 0 disables autoreporting by the firmware and forces polling.') }}">
<label class="control-label">{{ _('Temperature interval (autoreport)') }}</label>
<label class="control-label" for="settings-serialTimeoutTemperatureAutoreport">{{ _('Temperature interval (autoreport)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutTemperatureAutoreport" id="settings-serialTimeoutTemperatureAutoreport">
@@ -96,7 +96,7 @@
</div>
</div>
<div class="control-group" title="{{ _('SD status interval to request from autoreport capable firmwares. A value of 0 disables autoreporting by the firmware and forces polling.') }}">
<label class="control-label" for="settings-serialTimeoutSdStatus">{{ _('SD status interval (autoreport)') }}</label>
<label class="control-label" for="settings-serialTimeoutSdStatusAutoreport">{{ _('SD status interval (autoreport)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutSdStatusAutoreport" id="settings-serialTimeoutSdStatusAutoreport">
@@ -143,6 +143,15 @@
</div>
</div>
</div>
<div class="control-group" title="{{ _('Time after which to consider a position query on pause or cancel to have failed') }}">
<label class="control-label" for="settings-serialTimeoutPositionLogWait">{{ _('Position query timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutPositionLogWait" id="settings-serialTimeoutPositionLogWait">
<span class="add-on">s</span>
</div>
</div>
</div>
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#settings_serial_timeouts_timeouts .hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
@@ -1,10 +1,10 @@
<form class="form-horizontal">
<h3>{{ _('Graph') }}</h3>
<div class="control-group">
<label class="control-label">{{ _('Graph cutoff') }}</label>
<label class="control-label" for="settings-temperatureCutoff">{{ _('Graph cutoff') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini text-right" data-bind="value: temperature_cutoff">
<input type="number" min="1" class="input-mini text-right" data-bind="value: temperature_cutoff" id="settings-temperatureCutoff">
<span class="add-on">min</span>
</div>
<span class="help-block">{{ _('Needs a restart of OctoPrint to become active.') }}</span>
@@ -1,4 +1,4 @@
<div id="offline_overlay" xmlns="http://www.w3.org/1999/html">
<div id="offline_overlay">
<div id="offline_overlay_background"></div>
<div id="offline_overlay_wrapper">
<div class="container">
@@ -1,4 +1,4 @@
<div id="reloadui_overlay" xmlns="http://www.w3.org/1999/html">
<div id="reloadui_overlay">
<div id="reloadui_overlay_background"></div>
<div id="reloadui_overlay_wrapper">
<div class="container">
@@ -1,6 +1,7 @@
<span title="{{ _('Current printer state') }}">{{ _('State') }}</span>: <strong data-bind="text: stateString"></strong><br>
<hr>
<span title="{{ _('Name of file currently selected for printing') }}">{{ _('File') }}</span>: <strong data-bind="text: filedisplay, attr: {title: filepath}"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
<span title="{{ _('User who selected this file for printing') }}">{{ _('User') }}</span>: <strong data-bind="text: userString"></strong><br>
<span title="{{ _('Current timelapse configuration') }}">{{ _('Timelapse') }}</span>: <strong data-bind="text: timelapseString"></strong><br>
<!-- ko foreach: filament -->
<span data-bind="text: 'Filament (' + name() + '): ', title: 'Filament usage for ' + name()"></span><strong data-bind="text: formatFilament(data())"></strong><br>
@@ -1,5 +1,5 @@
<div class="control-group" title="{{ _('Port against which to check for internet connectivity') }}" data-bind="css: {error: server_onlineCheckBroken, success: server_onlineCheckOk}">
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Port') }}</label>
<label class="control-label" for="settings-serverOnlineCheckPort">{{ _('Port') }}</label>
<div class="controls">
<input type="number" min="1" max="65535" step="1" class="input-small" data-bind="value: server_onlineCheck_port" id="settings-serverOnlineCheckPort">
</div>
@@ -1,8 +1,8 @@
<div class="control-group" title="{{ _('How long to cache the blacklist, in minutes. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Blacklist cache TTL') }}</label>
<label class="control-label" for="settings-serverPluginBlacklistTtl">{{ _('Blacklist cache TTL') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" data-bind="value: server_pluginBlacklist_ttl">
<input type="number" class="input-mini" data-bind="value: server_pluginBlacklist_ttl" id="settings-serverPluginBlacklistTtl">
<span class="add-on">min</span>
</div>
</div>
@@ -1,5 +1,5 @@
<div class="control-group" title="{{ _('Number of FFMPEG encoding threads') }}">
<label class="control-label" for="settings-webcam_ffmpegThreads">{{ _('FFMPEG threads') }}</label>
<label class="control-label" for="settings-webcamFfmpegThreads">{{ _('FFMPEG threads') }}</label>
<div class="controls">
<input class="input-mini" data-bind="value: webcam_ffmpegThreads" id="settings-webcamFfmpegThreads" type="number" step="1" min="1">
</div>
@@ -1,7 +1,7 @@
<div class="control-group" title="{{ _('Aspect ratio of the webcam stream, either 16:9 or 4:3') }}">
<label class="control-label" for="settings-webcamStreamRatio">{{ _('Stream aspect ratio') }}</label>
<div class="controls">
<select data-bind="options: webcam_available_ratios, value: webcam_streamRatio"></select>
<select data-bind="options: webcam_available_ratios, value: webcam_streamRatio" id="settings-webcamStreamRatio"></select>
<span class="help-inline">{% trans %}If the stream has a different aspect ratio than configured here it will be letterboxed.{% endtrans %}</span>
</div>
</div>
+32
View File
@@ -849,6 +849,38 @@ def server_reachable(host, port, timeout=3.05, proto="tcp", source=None):
except:
return False
def parse_mime_type(mime):
import cgi
if not mime or not isinstance(mime, basestring):
raise ValueError("mime must be a non empty str or unicode")
mime, params = cgi.parse_header(mime)
if mime == "*":
mime = "*/*"
parts = mime.split("/") if "/" in mime else None
if not parts or len(parts) != 2:
raise ValueError("mime must be a mime type of format type/subtype")
mime_type, mime_subtype = parts
return mime_type.strip(), mime_subtype.strip(), params
def mime_type_matches(mime, other):
if not isinstance(mime, tuple):
mime = parse_mime_type(mime)
if not isinstance(other, tuple):
other = parse_mime_type(other)
mime_type, mime_subtype, _ = mime
other_type, other_subtype, _ = other
type_matches = (mime_type == other_type or mime_type == "*" or other_type == "*")
subtype_matches = (mime_subtype == other_subtype or mime_subtype == "*" or other_subtype == "*")
return type_matches and subtype_matches
@contextlib.contextmanager
def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777):
if os.path.exists(filename):
+129 -91
View File
@@ -22,55 +22,6 @@ import logging
import serial
# TODO 1.3.8 remove after pyserial upgrade to 3.4
try:
serial.Timeout(0)
except AttributeError:
# pyserial < 3.2: add backported Timeout abstraction, slightly modified since we have monotonic available
from octoprint.util import monotonic_time
class _Timeout(object):
def __init__(self, duration):
"""Initialize a timeout with given duration"""
self.is_infinite = (duration is None)
self.is_non_blocking = (duration == 0)
self.duration = duration
if duration is not None:
self.target_time = monotonic_time() + duration
else:
self.target_time = None
def expired(self):
"""Return a boolean, telling if the timeout has expired"""
return self.target_time is not None and self.time_left() <= 0
def time_left(self):
"""Return how many seconds are left until the timeout expires"""
if self.is_non_blocking:
return 0
elif self.is_infinite:
return None
else:
delta = self.target_time - monotonic_time()
if delta > self.duration:
# clock jumped, recalculate
self.target_time = monotonic_time() + self.duration
return self.duration
else:
return max(0, delta)
def restart(self, duration):
"""\
Restart a timeout, only supported if a timeout was already set up
before.
"""
self.duration = duration
self.target_time = monotonic_time() + duration
serial.Timeout = _Timeout
del _Timeout
import wrapt
import octoprint.plugin
@@ -85,7 +36,7 @@ from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks
to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks, ResettableTimer
try:
import _winreg
@@ -550,6 +501,7 @@ class MachineCom(object):
self._sdFileList = False
self._sdFiles = []
self._sdFileToSelect = None
self._sdFileToSelectUser = None
self._ignore_select = False
self._manualStreaming = False
@@ -564,6 +516,11 @@ class MachineCom(object):
self._record_pause_data = False
self._record_cancel_data = False
self._pause_position_timer = None
self._pause_mutex = threading.RLock()
self._cancel_position_timer = None
self._cancel_mutex = threading.RLock()
self._log_position_on_pause = settings().getBoolean(["serial", "logPositionOnPause"])
self._log_position_on_cancel = settings().getBoolean(["serial", "logPositionOnCancel"])
@@ -1072,7 +1029,7 @@ class MachineCom(object):
self.sendCommand("M28 %s" % remoteFilename, tags=tags | {"trigger:comm.start_file_transfer",})
eventManager().fire(Events.TRANSFER_STARTED, {"local": localFilename, "remote": remoteFilename})
self._callback.on_comm_file_transfer_started(remoteFilename, self._currentFile.getFilesize())
self._callback.on_comm_file_transfer_started(remoteFilename, self._currentFile.getFilesize(), user=self._currentFile.getUser())
def cancelFileTransfer(self, tags=None):
if not self.isOperational() or not self.isStreaming():
@@ -1112,7 +1069,7 @@ class MachineCom(object):
self.refreshSdFiles(tags={"trigger:comm.finish_file_transfer",})
self._sendCommand(SendQueueMarker(finalize))
def selectFile(self, filename, sd, tags=None):
def selectFile(self, filename, sd, user=None, tags=None):
if self.isBusy():
return
@@ -1128,26 +1085,42 @@ class MachineCom(object):
filename = filename[1:]
self._sdFileToSelect = filename
self._sdFileToSelectUser = user
self.sendCommand("M23 %s" % filename, tags=tags | {"trigger:comm.select_file",})
else:
self._currentFile = PrintingGcodeFileInformation(filename, offsets_callback=self.getOffsets, current_tool_callback=self.getCurrentTool)
self._callback.on_comm_file_selected(filename, self._currentFile.getFilesize(), False)
self._currentFile = PrintingGcodeFileInformation(filename,
offsets_callback=self.getOffsets,
current_tool_callback=self.getCurrentTool,
user=user)
self._callback.on_comm_file_selected(filename, self._currentFile.getFilesize(), False, user=user)
def unselectFile(self):
if self.isBusy():
return
self._currentFile = None
self._callback.on_comm_file_selected(None, None, False)
self._callback.on_comm_file_selected(None, None, False, user=None)
def _cancel_preparation_done(self):
self._recordFilePosition()
self._callback.on_comm_print_job_cancelled()
def _cancel_preparation_failed(self):
timeout = self._timeout_intervals.get("positionLogWait", 10.0)
self._log("Did not receive parseable position data from printer within {}s, continuing without it".format(timeout))
self._cancel_preparation_done()
def finalize():
self._changeState(self.STATE_OPERATIONAL)
self.sendCommand(SendQueueMarker(finalize))
self._continue_sending()
def _cancel_preparation_done(self, check_timer=True):
with self._cancel_mutex:
if self._cancel_position_timer is not None:
self._cancel_position_timer.cancel()
self._cancel_position_timer = None
elif check_timer:
return
self._recordFilePosition()
self._callback.on_comm_print_job_cancelled()
def finalize():
self._changeState(self.STATE_OPERATIONAL)
self.sendCommand(SendQueueMarker(finalize))
self._continue_sending()
def cancelPrint(self, firmware_error=None, disable_log_position=False, tags=None, external_sd=False):
if not self.isOperational():
@@ -1170,7 +1143,16 @@ class MachineCom(object):
# because we do this only after our M114 has been answered
# by the firmware
self._record_cancel_data = True
self.sendCommand("M114", tags=tags | {"trigger:comm.cancel", "trigger:record_position"})
with self._cancel_mutex:
if self._cancel_position_timer is not None:
self._cancel_position_timer.cancel()
self._cancel_position_timer = ResettableTimer(self._timeout_intervals.get("positionLogWait", 10.0),
self._cancel_preparation_done)
self._cancel_position_timer.daemon = True
self._cancel_position_timer.start()
self.sendCommand("M114", tags=tags | {"trigger:comm.cancel",
"trigger:record_position"})
self._callback.on_comm_print_job_cancelling(firmware_error=firmware_error)
@@ -1189,17 +1171,33 @@ class MachineCom(object):
pass
if self._log_position_on_cancel and not disable_log_position:
self.sendCommand("M400", on_sent=_on_M400_sent, tags=tags | {"trigger:comm.cancel", "trigger:record_position"})
self.sendCommand("M400",
on_sent=_on_M400_sent,
tags=tags | {"trigger:comm.cancel",
"trigger:record_position"})
self._continue_sending()
else:
self._cancel_preparation_done()
self._cancel_preparation_done(check_timer=False)
def _pause_preparation_done(self):
self._callback.on_comm_print_job_paused()
def _pause_preparation_failed(self):
timeout = self._timeout_intervals.get("positionLogWait", 10.0)
self._log("Did not receive parseable position data from printer within {}s, continuing without it".format(timeout))
self._pause_preparation_done()
def finalize():
self._changeState(self.STATE_PAUSED)
self.sendCommand(SendQueueMarker(finalize))
self._continue_sending()
def _pause_preparation_done(self, check_timer=True):
with self._pause_mutex:
if self._pause_position_timer is not None:
self._pause_position_timer.cancel()
self._pause_position_timer = None
elif check_timer:
return
self._callback.on_comm_print_job_paused()
def finalize():
self._changeState(self.STATE_PAUSED)
self.sendCommand(SendQueueMarker(finalize))
self._continue_sending()
def setPause(self, pause, tags=None):
if self.isStreaming():
@@ -1251,12 +1249,28 @@ class MachineCom(object):
# because we do this only after our M114 has been answered
# by the firmware
self._record_pause_data = True
self.sendCommand("M114", tags=tags | {"trigger:comm.set_pause", "trigger:pause", "trigger:record_position"})
with self._pause_mutex:
if self._pause_position_timer is not None:
self._pause_position_timer.cancel()
self._pause_position_timer = None
self._pause_position_timer = ResettableTimer(self._timeout_intervals.get("positionLogWait", 10.0),
self._pause_preparation_failed)
self._pause_position_timer.daemon = True
self._pause_position_timer.start()
self.sendCommand("M114", tags=tags | {"trigger:comm.set_pause",
"trigger:pause",
"trigger:record_position"})
if self._log_position_on_pause:
self.sendCommand("M400", on_sent=_on_M400_sent, tags=tags | {"trigger:comm.set_pause", "trigger:pause", "trigger:record_position"})
self.sendCommand("M400",
on_sent=_on_M400_sent,
tags=tags | {"trigger:comm.set_pause",
"trigger:pause",
"trigger:record_position"})
self._continue_sending()
else:
self._pause_preparation_done()
self._pause_preparation_done(check_timer=False)
def getSdFiles(self):
return self._sdFiles
@@ -1814,14 +1828,18 @@ class MachineCom(object):
else:
name = "Unknown"
size = 0
user = None
expected = False
if self._sdFileToSelect:
expected = True
name = self._sdFileToSelect
self._sdFileToSelect = None
user = self._sdFileToSelectUser
self._currentFile = PrintingSdFileInformation(name, size)
self._sdFileToSelect = None
self._sdFileToSelectUser = None
self._currentFile = PrintingSdFileInformation(name, size, user=user)
if not expected:
# It doesn't look like we expected this, so it might be that someone just started a print
@@ -1833,7 +1851,10 @@ class MachineCom(object):
self._ignore_select = False
elif self._currentFile is not None and self.isSdFileSelected():
# final answer to M23, at least on Marlin, Repetier and Sprinter: "File selected"
self._callback.on_comm_file_selected(self._currentFile.getFilename(), self._currentFile.getFilesize(), True)
self._callback.on_comm_file_selected(self._currentFile.getFilename(),
self._currentFile.getFilesize(),
True,
user=self._currentFile.getUser())
elif 'Writing to file' in line and self.isStreaming():
self._changeState(self.STATE_PRINTING)
elif 'Done printing file' in line and self.isSdPrinting():
@@ -2310,13 +2331,13 @@ class MachineCom(object):
serial_obj = serial.Serial(str(port),
baudrates[0],
timeout=read_timeout,
writeTimeout=10000, # TODO 1.3.8 rename to write_timeout for pyserial >= 3.x
write_timeout=10000,
parity=serial.PARITY_ODD)
else:
serial_obj = serial.Serial(str(port),
baudrate,
timeout=read_timeout,
writeTimeout=10000, # TODO 1.3.8 rename to write_timeout for pyserial >= 3.x
write_timeout=10000,
parity=serial.PARITY_ODD)
serial_obj.close()
serial_obj.parity = serial.PARITY_NONE
@@ -2350,9 +2371,12 @@ class MachineCom(object):
return False
_recoverable_communication_errors = ("no line number with checksum",)
_recoverable_communication_errors = ("no line number with checksum",
"missing linenumber")
_resend_request_communication_errors = ("line number", # since this error class get's checked after recoverable
# communication errors, we can use this broad term here
"linenumber", # since this error class get's checked after recoverable
# communication errors, we can use this broad term here
"checksum", # since this error class get's checked after recoverable
# communication errors, we can use this broad term here
"format error",
@@ -3286,6 +3310,10 @@ class MachineCom(object):
# I hope it got it the first time because as far as I can tell, there is no way to know
return None,
def _gcode_M114_queued(self, *args, **kwargs):
self._reset_position_timers()
_gcode_M114_sent = _gcode_M114_queued
def _gcode_G4_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
# we are intending to dwell for a period of time, increase the timeout to match
p_match = regexes_parameters["floatP"].search(cmd)
@@ -3303,6 +3331,12 @@ class MachineCom(object):
def _validate_tool(self, tool):
return tool < self._printerProfileManager.get_current_or_default()["extruder"]["count"] and not tool in self._knownInvalidTools
def _reset_position_timers(self):
if self._cancel_position_timer:
self._cancel_position_timer.reset()
if self._pause_position_timer:
self._pause_position_timer.reset()
## atcommands
def _atcommand_pause_queuing(self, command, parameters, tags=None, *args, **kwargs):
@@ -3375,7 +3409,7 @@ class MachineComPrintCallback(object):
def on_comm_z_change(self, newZ):
pass
def on_comm_file_selected(self, filename, filesize, sd):
def on_comm_file_selected(self, filename, filesize, sd, user=None):
pass
def on_comm_sd_state_change(self, sdReady):
@@ -3384,7 +3418,7 @@ class MachineComPrintCallback(object):
def on_comm_sd_files(self, files):
pass
def on_comm_file_transfer_started(self, filename, filesize):
def on_comm_file_transfer_started(self, filename, filesize, user=None):
pass
def on_comm_file_transfer_done(self, filename):
@@ -3411,9 +3445,10 @@ class PrintingFileInformation(object):
checksum = True
def __init__(self, filename):
def __init__(self, filename, user=None):
self._logger = logging.getLogger(__name__)
self._filename = filename
self._user = user
self._pos = 0
self._size = None
self._start_time = None
@@ -3434,6 +3469,9 @@ class PrintingFileInformation(object):
def getFileLocation(self):
return FileDestinations.LOCAL
def getUser(self):
return self._user
def getProgress(self):
"""
The current progress of the file, calculated as relation between file position and absolute size. Returns -1
@@ -3473,8 +3511,8 @@ class PrintingSdFileInformation(PrintingFileInformation):
checksum = False
def __init__(self, filename, size):
PrintingFileInformation.__init__(self, filename)
def __init__(self, filename, size, user=None):
PrintingFileInformation.__init__(self, filename, user=user)
self._size = size
def getFileLocation(self):
@@ -3510,8 +3548,8 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
that the file is closed in case of an error.
"""
def __init__(self, filename, offsets_callback=None, current_tool_callback=None):
PrintingFileInformation.__init__(self, filename)
def __init__(self, filename, offsets_callback=None, current_tool_callback=None, user=None):
PrintingFileInformation.__init__(self, filename, user=user)
self._handle = None
self._handle_mutex = threading.RLock()
@@ -3612,8 +3650,8 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
pass
class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
def __init__(self, path, localFilename, remoteFilename):
PrintingGcodeFileInformation.__init__(self, path)
def __init__(self, path, localFilename, remoteFilename, user=None):
PrintingGcodeFileInformation.__init__(self, path, user=user)
self._localFilename = localFilename
self._remoteFilename = remoteFilename
@@ -4344,7 +4382,7 @@ class BufferedReadlineWrapper(wrapt.ObjectProxy):
while True:
# make sure we always read everything that is waiting
data += bytearray(self.read(self.inWaiting())) # TODO 1.3.8 migrate to in_waiting after pyserial upgrade to 3.4
data += bytearray(self.read(self.in_waiting))
# check for terminator, if it's there we have found our line
termpos = data.find(terminator)
@@ -4418,7 +4456,7 @@ def upload_cli():
self._target = target
self._state = None
def on_comm_file_transfer_started(self, filename, filesize):
def on_comm_file_transfer_started(self, filename, filesize, user=None):
# transfer started, report
logger.info("Started file transfer of {}, size {}B".format(filename, filesize))
self.started = True
+3 -2
View File
@@ -91,7 +91,7 @@ class SockJSRouter(object):
self._connection = connection
# Initialize io_loop
self.io_loop = io_loop or ioloop.IOLoop.current()
self.io_loop = io_loop or ioloop.IOLoop.instance()
# Settings
self.settings = DEFAULT_SETTINGS.copy()
@@ -107,7 +107,8 @@ class SockJSRouter(object):
check_interval = self.settings['session_check_interval'] * 1000
self._sessions_cleanup = ioloop.PeriodicCallback(self._sessions.expire,
check_interval)
check_interval,
self.io_loop)
self._sessions_cleanup.start()
# Stats
+2 -1
View File
@@ -67,7 +67,8 @@ class StatsCollector(object):
self.pack_recv_ps = MovingAverage()
self._callback = ioloop.PeriodicCallback(self._update,
1000)
1000,
io_loop)
self._callback.start()
def _update(self):
+46 -18
View File
@@ -189,7 +189,7 @@ class LocalStorageTest(unittest.TestCase):
self.assertIsNone(after_stl_metadata)
self.assertIsNotNone(copied_metadata)
self.assertDictEqual(before_stl_metadata, copied_metadata)
def test_copy_file_new_display(self):
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
try:
@@ -197,10 +197,10 @@ class LocalStorageTest(unittest.TestCase):
self.fail("Expected an exception")
except StorageError as e:
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
def test_move_file_new_display(self):
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
before_metadata = self.storage.get_metadata("bp_case.stl")
self.storage.move_file("bp_case.stl", u"bp_cäse.stl")
after_metadata = self.storage.get_metadata("bp_case.stl")
@@ -210,19 +210,19 @@ class LocalStorageTest(unittest.TestCase):
self.assertIsNotNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertDictContainsSubset(dict(display=u"bp_cäse.stl"), after_metadata)
@data("copy_file", "move_file")
def test_copy_move_file_different_display(self, operation):
self._add_file("bp_case.stl", FILE_BP_CASE_STL, display=u"bp_cäse.stl")
before_metadata = self.storage.get_metadata("bp_case.stl")
getattr(self.storage, operation)("bp_case.stl", "test.stl")
after_metadata = self.storage.get_metadata("test.stl")
self.assertIsNotNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertNotIn("display", after_metadata)
@data("copy_file", "move_file")
def test_copy_move_file_same(self, operation):
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
@@ -264,7 +264,7 @@ class LocalStorageTest(unittest.TestCase):
def test_add_folder(self):
self._add_and_verify_folder("test", "test")
def test_add_folder_with_display(self):
self._add_and_verify_folder("test", "test", display=u"täst")
metadata = self.storage.get_metadata("test")
@@ -304,11 +304,11 @@ class LocalStorageTest(unittest.TestCase):
def test_remove_folder_with_display(self):
self._add_folder("folder", display=u"földer")
before_metadata = self.storage.get_metadata("folder")
self.storage.remove_folder("folder")
after_metadata = self.storage.get_metadata("folder")
self.assertIsNotNone(before_metadata)
self.assertDictEqual(before_metadata, dict(display=u"földer"))
self.assertIsNone(after_metadata)
@@ -326,7 +326,7 @@ class LocalStorageTest(unittest.TestCase):
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "source", "crazyradio.stl")))
self.assertTrue(os.path.isdir(os.path.join(self.basefolder, "destination")))
self.assertTrue(os.path.isdir(os.path.join(self.basefolder, "destination", "copied")))
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "destination", "copied", ".metadata.yaml")))
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "destination", "copied", ".metadata.json")))
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "destination", "copied", "crazyradio.stl")))
self.assertIsNotNone(source_metadata)
@@ -347,7 +347,7 @@ class LocalStorageTest(unittest.TestCase):
self.assertFalse(os.path.isfile(os.path.join(self.basefolder, "source", "crazyradio.stl")))
self.assertTrue(os.path.isdir(os.path.join(self.basefolder, "destination")))
self.assertTrue(os.path.isdir(os.path.join(self.basefolder, "destination", "copied")))
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "destination", "copied", ".metadata.yaml")))
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "destination", "copied", ".metadata.json")))
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "destination", "copied", "crazyradio.stl")))
self.assertIsNotNone(before_source_metadata)
@@ -365,19 +365,19 @@ class LocalStorageTest(unittest.TestCase):
def test_move_folder_new_display(self):
self._add_folder("folder")
before_metadata = self.storage.get_metadata("folder")
self.storage.move_folder("folder", u"földer")
after_metadata = self.storage.get_metadata("folder")
self.assertIsNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertDictEqual(after_metadata, dict(display=u"földer"))
@data("copy_folder", "move_folder")
def test_copy_move_folder_different_display(self, operation):
self._add_folder("folder", display=u"földer")
before_metadata = self.storage.get_metadata("folder")
getattr(self.storage, operation)("folder", "test")
after_metadata = self.storage.get_metadata("test")
@@ -394,7 +394,7 @@ class LocalStorageTest(unittest.TestCase):
self.fail("Expected an exception")
except StorageError as e:
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
@data("copy_folder", "move_folder")
def test_copy_move_folder_missing_source(self, operation):
try:
@@ -639,6 +639,34 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual(expected_path, sanitized_path)
return sanitized_path
def test_migrate_metadata_to_json(self):
metadata = {
"test.gco": {
"hash": "aabbccddeeff",
"links": [],
"notes": []
}
}
yaml_path = os.path.join(self.basefolder, ".metadata.yaml")
json_path = os.path.join(self.basefolder, ".metadata.json")
# prepare
import yaml
with open(yaml_path, "wb") as f:
yaml.safe_dump(metadata, f)
# migrate
self.storage._migrate_metadata(self.basefolder)
# verify
self.assertTrue(os.path.exists(json_path))
self.assertTrue(os.path.exists(yaml_path)) # TODO 1.3.10 change to assertFalse
import json
with open(json_path) as f:
json_metadata = json.load(f)
self.assertDictEqual(metadata, json_metadata)
def _add_file(self, path, file_object, links=None, overwrite=False, display=None):
"""
Adds a file to the storage.
@@ -659,7 +687,7 @@ class LocalStorageTest(unittest.TestCase):
folder_path = os.path.join(self.basefolder, os.path.join(*split_path[:-1]))
self.assertTrue(os.path.isfile(file_path))
self.assertTrue(os.path.isfile(os.path.join(folder_path, ".metadata.yaml")))
self.assertTrue(os.path.isfile(os.path.join(folder_path, ".metadata.json")))
metadata = self.storage.get_metadata(sanitized_path)
self.assertIsNotNone(metadata)