Support full UTF8 file names
Files (and folders) are still slugified to ASCII for storage on disk, but now the original filename is stored alongside in metadata.yaml and used for display in the file list and print status. The slicing dialog also inherits that display name for use as base for the suggested GCODE name. Internally, everything still depends completely on the slugified ASCII version. This implements #2094
This commit is contained in:
1 parent
42018ae29a
commit
42ac133436
18 files changed
+538
-136
No files matched your search
+15
-3
@@ -232,12 +232,18 @@ File information
|
||||
* - ``name``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system.
|
||||
- The name of the file without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system. Currently
|
||||
this will always fit into ASCII.
|
||||
* - ``display``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file without the path, this time potentially with non-ASCII unicode characters.
|
||||
E.g. "a turtle 🐢.gco" for a file "a_turtle_turtle.gco" located anywhere in the file system.
|
||||
* - ``path``
|
||||
- 1
|
||||
- String
|
||||
- The path to the file within the location. E.g. "folder/subfolder/file.gco" for a file "file.gco" located within
|
||||
"folder" and "subfolder" relative to the root of the location.
|
||||
"folder" and "subfolder" relative to the root of the location. Currently this will always fit into ASCII.
|
||||
* - ``type``
|
||||
- 1
|
||||
- String
|
||||
@@ -329,11 +335,17 @@ Abridged file or folder information
|
||||
- 1
|
||||
- String
|
||||
- The name of the file or folder without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system.
|
||||
Currently this will always fit into ASCII.
|
||||
* - ``display``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file without the path, this potentially with non-ASCII unicode characters.
|
||||
E.g. "a turtle 🐢.gco" for a file "a_turtle_turtle.gco" located anywhere in the file system.
|
||||
* - ``path``
|
||||
- 1
|
||||
- String
|
||||
- The path to the file or folder within the location. E.g. "folder/subfolder/file.gco" for a file "file.gco" located within
|
||||
"folder" and "subfolder" relative to the root of the location.
|
||||
"folder" and "subfolder" relative to the root of the location. Currently this will always fit into ASCII.
|
||||
* - ``origin``
|
||||
- 1
|
||||
- String, either ``local`` or ``sdcard``
|
||||
|
||||
@@ -50,7 +50,8 @@ INSTALL_REQUIRES = [
|
||||
"websocket-client>=0.40,<0.41",
|
||||
"python-dateutil>=2.6,<2.7",
|
||||
"wrapt>=1.10.10,<1.11",
|
||||
"futures>=3.1.1,<3.2"
|
||||
"futures>=3.1.1,<3.2",
|
||||
"emoji>=0.4.5,<0.5"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
|
||||
@@ -277,10 +277,12 @@ class FileManager(object):
|
||||
return False
|
||||
|
||||
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, display=None,
|
||||
callback=None, callback_args=None):
|
||||
absolute_source_path = self.path_on_disk(source_location, source_path)
|
||||
|
||||
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time,
|
||||
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
|
||||
@@ -305,7 +307,9 @@ class FileManager(object):
|
||||
io.FileIO(tmp_path, "rb"))
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
|
||||
self.add_file(dest_location, dest_path, file_obj,
|
||||
display=display, links=links, allow_overwrite=True,
|
||||
printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = time.time()
|
||||
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
|
||||
@@ -417,7 +421,7 @@ class FileManager(object):
|
||||
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
|
||||
return result
|
||||
|
||||
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None):
|
||||
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None, display=None):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
@@ -434,7 +438,7 @@ class FileManager(object):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
|
||||
|
||||
if analysis is None:
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
|
||||
@@ -501,8 +505,8 @@ class FileManager(object):
|
||||
type=get_file_type(dst_name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def add_folder(self, destination, path, ignore_existing=True):
|
||||
path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
|
||||
def add_folder(self, destination, path, ignore_existing=True, display=None):
|
||||
path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing, display=display)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
@@ -525,7 +529,7 @@ class FileManager(object):
|
||||
|
||||
def copy_folder(self, destination, source, dst):
|
||||
path_in_storage = self._storage(destination).copy_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=path_in_storage)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
@@ -536,13 +540,12 @@ class FileManager(object):
|
||||
def move_folder(self, destination, source, dst):
|
||||
self._analysis_queue.dequeue_folder(destination, source)
|
||||
self._analysis_queue.pause()
|
||||
self._storage(destination).move_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
|
||||
dst_path_in_storage = self._storage(destination).move_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=dst_path_in_storage)
|
||||
self._analysis_queue.resume()
|
||||
|
||||
source_path_in_storage = self._storage(destination).path_in_storage(source)
|
||||
_, source_name = self._storage(destination).split_path(source_path_in_storage)
|
||||
dst_path_in_storage = self._storage(destination).path_in_storage(destination)
|
||||
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
|
||||
|
||||
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
|
||||
@@ -622,6 +625,9 @@ class FileManager(object):
|
||||
def path_on_disk(self, destination, path):
|
||||
return self._storage(destination).path_on_disk(path)
|
||||
|
||||
def canonicalize(self, destination, path):
|
||||
return self._storage(destination).canonicalize(path)
|
||||
|
||||
def sanitize(self, destination, path):
|
||||
return self._storage(destination).sanitize(path)
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import logging
|
||||
import os
|
||||
import pylru
|
||||
import shutil
|
||||
import re
|
||||
|
||||
try:
|
||||
from os import scandir, walk
|
||||
@@ -22,9 +23,12 @@ from copy import deepcopy
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from emoji import demojize
|
||||
from slugify import Slugify
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util import is_hidden_path, to_unicode
|
||||
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
@@ -154,7 +158,7 @@ class StorageInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_folder(self, path, ignore_existing=True):
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
"""
|
||||
Adds a folder as ``path``
|
||||
|
||||
@@ -162,6 +166,7 @@ class StorageInterface(object):
|
||||
|
||||
:param string path: the path of the new folder
|
||||
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
|
||||
:param unicode display: display name of the folder
|
||||
:return: the sanitized name of the new folder to be used for future references to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
@@ -198,7 +203,7 @@ class StorageInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
"""
|
||||
Adds the file ``file_object`` as ``path``
|
||||
|
||||
@@ -209,6 +214,7 @@ class StorageInterface(object):
|
||||
:param list links: any links to add with the file
|
||||
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
|
||||
and its metadata will just be silently overwritten
|
||||
:param unicode display: display name of the file
|
||||
:return: the sanitized name of the file to be used for future references to it
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
@@ -327,6 +333,23 @@ class StorageInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def canonicalize(self, path):
|
||||
"""
|
||||
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
|
||||
implementation must separate those if necessary.
|
||||
|
||||
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
|
||||
of stripping any invalid characters.
|
||||
|
||||
Args:
|
||||
path: the path to canonicalize
|
||||
|
||||
Returns:
|
||||
a 2-tuple containing the canonicalized path and file name
|
||||
|
||||
"""
|
||||
return self.sanitize(path)
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
|
||||
@@ -403,6 +426,7 @@ class StorageError(Exception):
|
||||
INVALID_DESTINATION = "invalid_destination"
|
||||
DOES_NOT_EXIST = "does_not_exist"
|
||||
ALREADY_EXISTS = "already_exists"
|
||||
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
|
||||
NOT_EMPTY = "not_empty"
|
||||
|
||||
def __init__(self, message, code=None, cause=None):
|
||||
@@ -425,6 +449,22 @@ class LocalFileStorage(StorageInterface):
|
||||
This storage type implements :func:`path_on_disk`.
|
||||
"""
|
||||
|
||||
_UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]")
|
||||
|
||||
@classmethod
|
||||
def _no_unicode_variations(cls, text):
|
||||
return cls._UNICODE_VARIATIONS.sub(u"", text)
|
||||
|
||||
_SLUGIFY = Slugify()
|
||||
_SLUGIFY.safe_chars = "-_.()[] "
|
||||
|
||||
@classmethod
|
||||
def _slugify(cls, text):
|
||||
text = to_unicode(text)
|
||||
text = cls._no_unicode_variations(text)
|
||||
text = demojize(text, delimiters=(u"", u""))
|
||||
return cls._SLUGIFY(text)
|
||||
|
||||
def __init__(self, basefolder, create=False):
|
||||
"""
|
||||
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
|
||||
@@ -435,7 +475,7 @@ class LocalFileStorage(StorageInterface):
|
||||
"""
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
|
||||
self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder)))
|
||||
if not os.path.exists(self.basefolder) and create:
|
||||
os.makedirs(self.basefolder)
|
||||
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
|
||||
@@ -447,10 +487,6 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
self._metadata_cache = pylru.lrucache(10)
|
||||
|
||||
from slugify import Slugify
|
||||
self._slugify = Slugify()
|
||||
self._slugify.safe_chars = "-_.()[] "
|
||||
|
||||
self._old_metadata = None
|
||||
self._initialize_metadata()
|
||||
|
||||
@@ -557,17 +593,22 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def list_files(self, path=None, filter=None, recursive=True):
|
||||
if path:
|
||||
path = self.sanitize_path(path)
|
||||
path = self.sanitize_path(to_unicode(path))
|
||||
base = self.path_in_storage(path)
|
||||
if base:
|
||||
base += "/"
|
||||
base += u"/"
|
||||
else:
|
||||
path = self.basefolder
|
||||
base = ""
|
||||
base = u""
|
||||
return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive)
|
||||
|
||||
def add_folder(self, path, ignore_existing=True):
|
||||
path, name = self.sanitize(path)
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
display_path, display_name = self.canonicalize(path)
|
||||
path = self.sanitize_path(display_path)
|
||||
name = self.sanitize_name(display_name)
|
||||
|
||||
if display is not None:
|
||||
display_name = display
|
||||
|
||||
folder_path = os.path.join(path, name)
|
||||
if os.path.exists(folder_path):
|
||||
@@ -576,6 +617,11 @@ class LocalFileStorage(StorageInterface):
|
||||
else:
|
||||
os.mkdir(folder_path)
|
||||
|
||||
if display_name != name:
|
||||
metadata = self._get_metadata_entry(path, name, default=dict())
|
||||
metadata["display"] = display_name
|
||||
self._update_metadata_entry(path, name, metadata)
|
||||
|
||||
return self.path_in_storage((path, name))
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
@@ -598,12 +644,15 @@ class LocalFileStorage(StorageInterface):
|
||||
import shutil
|
||||
shutil.rmtree(folder_path)
|
||||
|
||||
self._delete_metadata(folder_path)
|
||||
self._remove_metadata_entry(path, name)
|
||||
|
||||
def _get_source_destination_data(self, source, destination):
|
||||
def _get_source_destination_data(self, source, destination, must_not_equal=False):
|
||||
"""Prepares data dicts about source and destination for copy/move."""
|
||||
source_path, source_name = self.sanitize(source)
|
||||
destination_path, destination_name = self.sanitize(destination)
|
||||
|
||||
destination_canon_path, destination_canon_name = self.canonicalize(destination)
|
||||
destination_path = self.sanitize_path(destination_canon_path)
|
||||
destination_name = self.sanitize_name(destination_canon_name)
|
||||
|
||||
source_fullpath = os.path.join(source_path, source_name)
|
||||
destination_fullpath = os.path.join(destination_path, destination_name)
|
||||
@@ -613,45 +662,88 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
if not os.path.isdir(destination_path):
|
||||
raise StorageError("Destination path {} does not exist or is not a folder".format(destination_path), code=StorageError.INVALID_DESTINATION)
|
||||
if os.path.exists(destination_fullpath):
|
||||
if os.path.exists(destination_fullpath) and source_fullpath != destination_fullpath:
|
||||
raise StorageError("{} does already exist in {}".format(destination_name, destination_path), code=StorageError.INVALID_DESTINATION)
|
||||
|
||||
source_meta = self._get_metadata_entry(source_path, source_name)
|
||||
if source_meta:
|
||||
source_display = source_meta.get("display", source_name)
|
||||
else:
|
||||
source_display = source_name
|
||||
|
||||
if (must_not_equal or source_display == destination_canon_name) and source_fullpath == destination_fullpath:
|
||||
raise StorageError("Source {} and destination {} are the same folder".format(source_path, destination_path), code=StorageError.SOURCE_EQUALS_DESTINATION)
|
||||
|
||||
source_data = dict(
|
||||
path=source_path,
|
||||
name=source_name,
|
||||
display=source_display,
|
||||
fullpath=source_fullpath,
|
||||
)
|
||||
destination_data = dict(
|
||||
path=destination_path,
|
||||
name=destination_name,
|
||||
display=destination_canon_name,
|
||||
fullpath=destination_fullpath,
|
||||
)
|
||||
return source_data, destination_data
|
||||
|
||||
def _set_display_metadata(self, destination_data, source_data=None):
|
||||
if source_data and destination_data["name"] == source_data["name"] and source_data["name"] != source_data["display"]:
|
||||
display = source_data["display"]
|
||||
elif destination_data["name"] != destination_data["display"]:
|
||||
display = destination_data["display"]
|
||||
else:
|
||||
display = None
|
||||
|
||||
destination_meta = self._get_metadata_entry(destination_data["path"], destination_data["name"],
|
||||
default=dict())
|
||||
if display:
|
||||
destination_meta["display"] = display
|
||||
self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
|
||||
elif "display" in destination_meta:
|
||||
del destination_meta["display"]
|
||||
self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
|
||||
|
||||
def copy_folder(self, source, destination):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True)
|
||||
|
||||
try:
|
||||
shutil.copytree(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
|
||||
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def move_folder(self, source, destination):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
|
||||
# only a display rename? Update that and bail early
|
||||
if source_data["fullpath"] == destination_data["fullpath"]:
|
||||
self._set_display_metadata(destination_data)
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
try:
|
||||
shutil.move(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
|
||||
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
self._remove_metadata_entry(source_data["path"], source_data["name"])
|
||||
self._delete_metadata(source_data["fullpath"])
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
|
||||
path, name = self.sanitize(path)
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
display_path, display_name = self.canonicalize(path)
|
||||
path = self.sanitize_path(display_path)
|
||||
name = self.sanitize_name(display_name)
|
||||
|
||||
if display:
|
||||
display_name = display
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(name):
|
||||
raise StorageError("{name} is an unrecognized file type".format(**locals()), code=StorageError.INVALID_FILE)
|
||||
|
||||
@@ -663,6 +755,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
# make sure folders exist
|
||||
if not os.path.exists(path):
|
||||
# TODO persist display names of path segments!
|
||||
os.makedirs(path)
|
||||
|
||||
# save the file
|
||||
@@ -671,9 +764,19 @@ class LocalFileStorage(StorageInterface):
|
||||
# save the file's hash to the metadata of the folder
|
||||
file_hash = self._create_hash(file_path)
|
||||
metadata = self._get_metadata_entry(path, name, default=dict())
|
||||
metadata_dirty = False
|
||||
if not "hash" in metadata or metadata["hash"] != file_hash:
|
||||
# hash changed -> throw away old metadata
|
||||
self._update_metadata_entry(path, name, dict(hash=file_hash))
|
||||
metadata = dict(hash=file_hash)
|
||||
metadata_dirty = True
|
||||
|
||||
if not "display" in metadata and display_name != name:
|
||||
# display name is not the same as file name -> store in metadata
|
||||
metadata["display"] = display_name
|
||||
metadata_dirty = True
|
||||
|
||||
if metadata_dirty:
|
||||
self._update_metadata_entry(path, name, metadata)
|
||||
|
||||
# process any links that were also provided for adding to the file
|
||||
if not links:
|
||||
@@ -706,7 +809,7 @@ class LocalFileStorage(StorageInterface):
|
||||
self._remove_metadata_entry(path, name)
|
||||
|
||||
def copy_file(self, source, destination):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True)
|
||||
|
||||
try:
|
||||
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
|
||||
@@ -715,12 +818,18 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
self._copy_metadata_entry(source_data["path"], source_data["name"],
|
||||
destination_data["path"], destination_data["name"])
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def move_file(self, source, destination, allow_overwrite=False):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
|
||||
# only a display rename? Update that and bail early
|
||||
if source_data["fullpath"] == destination_data["fullpath"]:
|
||||
self._set_display_metadata(destination_data)
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
try:
|
||||
shutil.move(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
@@ -729,7 +838,8 @@ class LocalFileStorage(StorageInterface):
|
||||
self._copy_metadata_entry(source_data["path"], source_data["name"],
|
||||
destination_data["path"], destination_data["name"],
|
||||
delete_source=True)
|
||||
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def has_analysis(self, path):
|
||||
@@ -762,7 +872,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def remove_history(self, path, index):
|
||||
path, name = self.sanitize(path)
|
||||
self._update_history(name, path, index)
|
||||
self._delete_history(name, path, index)
|
||||
|
||||
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
|
||||
path, name = self.sanitize(path)
|
||||
@@ -800,14 +910,15 @@ class LocalFileStorage(StorageInterface):
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def split_path(self, path):
|
||||
split = path.split("/")
|
||||
path = to_unicode(path)
|
||||
split = path.split(u"/")
|
||||
if len(split) == 1:
|
||||
return "", split[0]
|
||||
return u"", split[0]
|
||||
else:
|
||||
return self.join_path(*split[:-1]), split[-1]
|
||||
|
||||
def join_path(self, *path):
|
||||
return "/".join(path)
|
||||
return u"/".join(map(to_unicode, path))
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
@@ -824,40 +935,48 @@ class LocalFileStorage(StorageInterface):
|
||||
hence be returned at second position. If you only need to convert a folder path, be sure to
|
||||
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
|
||||
"""
|
||||
name = None
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, "/")
|
||||
path = path.split("/")
|
||||
if isinstance(path, (list, tuple)):
|
||||
if len(path) == 1:
|
||||
name = path[0]
|
||||
path = "/"
|
||||
else:
|
||||
name = path[-1]
|
||||
path = "/" + self.join_path(*path[:-1])
|
||||
if not path:
|
||||
path = "/"
|
||||
|
||||
path, name = self.canonicalize(path)
|
||||
name = self.sanitize_name(name)
|
||||
path = self.sanitize_path(path)
|
||||
return path, name
|
||||
|
||||
def canonicalize(self, path):
|
||||
name = None
|
||||
if isinstance(path, basestring):
|
||||
path = to_unicode(path)
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, u"/")
|
||||
path = path.split(u"/")
|
||||
if isinstance(path, (list, tuple)):
|
||||
if len(path) == 1:
|
||||
name = to_unicode(path[0])
|
||||
path = u""
|
||||
else:
|
||||
name = to_unicode(path[-1])
|
||||
path = self.join_path(*map(to_unicode, path[:-1]))
|
||||
if not path:
|
||||
path = u""
|
||||
|
||||
return path, name
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
|
||||
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
|
||||
``(``, and ``)`` as is.
|
||||
"""
|
||||
name = to_unicode(name)
|
||||
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
if u"/" in name or u"\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
result = self._slugify(name).replace(" ", "_")
|
||||
if result and result != "." and result != ".." and result[0] == ".":
|
||||
result = self._slugify(name).replace(u" ", u"_")
|
||||
if result and result != u"." and result != u".." and result[0] == u".":
|
||||
# hidden files under *nix
|
||||
result = result[1:]
|
||||
return result
|
||||
@@ -868,12 +987,15 @@ class LocalFileStorage(StorageInterface):
|
||||
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
|
||||
absolute path including leading ``basefolder`` path.
|
||||
"""
|
||||
if path[0] == "/":
|
||||
path = path[1:]
|
||||
elif path[0] == "." and path[1] == "/":
|
||||
path = path[2:]
|
||||
path = to_unicode(path)
|
||||
|
||||
if len(path):
|
||||
if path[0] == u"/":
|
||||
path = path[1:]
|
||||
elif path[0] == u"." and path[1] == u"/":
|
||||
path = path[2:]
|
||||
|
||||
path_elements = path.split("/")
|
||||
path_elements = path.split(u"/")
|
||||
joined_path = self.basefolder
|
||||
for path_element in path_elements:
|
||||
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
|
||||
@@ -883,6 +1005,7 @@ class LocalFileStorage(StorageInterface):
|
||||
return path
|
||||
|
||||
def _sanitize_entry(self, entry, path, entry_path):
|
||||
entry = to_unicode(entry)
|
||||
sanitized = self.sanitize_name(entry)
|
||||
if sanitized != entry:
|
||||
# entry is not sanitized yet, let's take care of that
|
||||
@@ -892,16 +1015,16 @@ class LocalFileStorage(StorageInterface):
|
||||
counter = 1
|
||||
while os.path.exists(sanitized_path):
|
||||
counter += 1
|
||||
sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
|
||||
sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext))
|
||||
sanitized_path = os.path.join(path, sanitized)
|
||||
|
||||
try:
|
||||
shutil.move(entry_path, sanitized_path)
|
||||
|
||||
self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
|
||||
self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
|
||||
return sanitized, sanitized_path
|
||||
except:
|
||||
self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
|
||||
self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
|
||||
raise
|
||||
|
||||
return entry, entry_path
|
||||
@@ -910,10 +1033,11 @@ class LocalFileStorage(StorageInterface):
|
||||
if isinstance(path, (tuple, list)):
|
||||
path = self.join_path(*path)
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
path = to_unicode(path)
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, "/")
|
||||
if path.startswith("/"):
|
||||
path = path.replace(os.path.sep, u"/")
|
||||
if path.startswith(u"/"):
|
||||
path = path[1:]
|
||||
|
||||
return path
|
||||
@@ -1169,7 +1293,7 @@ class LocalFileStorage(StorageInterface):
|
||||
continue
|
||||
|
||||
try:
|
||||
entry_name = entry.name
|
||||
entry_name = entry_display = entry.name
|
||||
entry_path = entry.path
|
||||
entry_is_file = entry.is_file()
|
||||
entry_is_dir = entry.is_dir()
|
||||
@@ -1182,6 +1306,7 @@ class LocalFileStorage(StorageInterface):
|
||||
try:
|
||||
new_entry_name, new_entry_path = self._sanitize_entry(entry_name, path, entry_path)
|
||||
if entry_name != new_entry_name or entry_path != new_entry_path:
|
||||
entry_display = to_unicode(entry_name)
|
||||
entry_name = new_entry_name
|
||||
entry_path = new_entry_path
|
||||
entry_stat = os.stat(entry_path)
|
||||
@@ -1201,18 +1326,26 @@ class LocalFileStorage(StorageInterface):
|
||||
file_type = type_path[0]
|
||||
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_data = metadata[entry_name]
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
else:
|
||||
entry_data = self._add_basic_metadata(path, entry_name, save=False, metadata=metadata)
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
|
||||
# TODO extract model hash from source if possible to recreate link
|
||||
|
||||
if not entry_filter or entry_filter(entry_name, entry_data):
|
||||
if not entry_filter or entry_filter(entry_name, entry_metadata):
|
||||
# only add files passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_data)
|
||||
extended_entry_data.update(entry_metadata)
|
||||
extended_entry_data["name"] = entry_name
|
||||
extended_entry_data["display"] = entry_metadata.get("display", entry_name)
|
||||
extended_entry_data["path"] = path_in_location
|
||||
extended_entry_data["type"] = file_type
|
||||
extended_entry_data["typePath"] = type_path
|
||||
@@ -1225,11 +1358,27 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
# folder recursion
|
||||
elif entry_is_dir:
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
elif entry_name != entry_display:
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
else:
|
||||
entry_metadata = dict()
|
||||
|
||||
entry_data = dict(
|
||||
name=entry_name,
|
||||
display=entry_metadata.get("display", entry_name),
|
||||
path=path_in_location,
|
||||
type="folder",
|
||||
type_path=["folder"]
|
||||
typePath=["folder"]
|
||||
)
|
||||
if recursive:
|
||||
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
|
||||
@@ -1261,22 +1410,33 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
return result
|
||||
|
||||
def _add_basic_metadata(self, path, entry, additional_metadata=None, save=True, metadata=None):
|
||||
def _add_basic_metadata(self, path, entry, display_name=None, additional_metadata=None, save=True, metadata=None):
|
||||
if additional_metadata is None:
|
||||
additional_metadata = dict()
|
||||
|
||||
if metadata is None:
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
entry_data = dict(
|
||||
hash=self._create_hash(os.path.join(path, entry)),
|
||||
links=[],
|
||||
notes=[]
|
||||
)
|
||||
entry_path = os.path.join(path, entry)
|
||||
|
||||
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
|
||||
# if there is still old metadata available and that contains an analysis for this file, use it!
|
||||
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
|
||||
if os.path.isfile(entry_path):
|
||||
entry_data = dict(
|
||||
hash=self._create_hash(os.path.join(path, entry)),
|
||||
links=[],
|
||||
notes=[]
|
||||
)
|
||||
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
|
||||
# if there is still old metadata available and that contains an analysis for this file, use it!
|
||||
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
|
||||
|
||||
elif os.path.isdir(entry_path):
|
||||
entry_data = dict()
|
||||
|
||||
else:
|
||||
return
|
||||
|
||||
if display_name is not None and not display_name == entry:
|
||||
entry_data["display"] = display_name
|
||||
|
||||
entry_data.update(additional_metadata)
|
||||
metadata[entry] = entry_data
|
||||
@@ -1327,7 +1487,7 @@ class LocalFileStorage(StorageInterface):
|
||||
metadata[name] = data
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False):
|
||||
def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False, updates=None):
|
||||
with self._get_metadata_lock(source_path):
|
||||
source_data = self._get_metadata_entry(source_path, source_name, default=dict())
|
||||
if not source_data:
|
||||
@@ -1336,6 +1496,9 @@ class LocalFileStorage(StorageInterface):
|
||||
if delete_source:
|
||||
self._remove_metadata_entry(source_path, source_name)
|
||||
|
||||
if updates is not None:
|
||||
source_data.update(updates)
|
||||
|
||||
with self._get_metadata_lock(destination_path):
|
||||
self._update_metadata_entry(destination_path, destination_name, source_data)
|
||||
|
||||
|
||||
@@ -887,6 +887,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"file": {
|
||||
"name": None,
|
||||
"path": None,
|
||||
"display": None,
|
||||
"origin": None,
|
||||
"size": None,
|
||||
"date": None
|
||||
@@ -903,6 +904,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
averagePrintTime = None
|
||||
date = None
|
||||
filament = None
|
||||
display_name = name_in_storage
|
||||
if path_on_disk:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
@@ -914,6 +916,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
except:
|
||||
fileData = None
|
||||
if fileData is not None:
|
||||
if "display" in fileData:
|
||||
display_name = fileData["display"]
|
||||
if "analysis" in fileData:
|
||||
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
|
||||
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
|
||||
@@ -938,6 +942,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"file": {
|
||||
"name": name_in_storage,
|
||||
"path": path_in_storage,
|
||||
"display": display_name,
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
|
||||
@@ -464,6 +464,11 @@ class Server(object):
|
||||
def mime_type_guesser(path):
|
||||
from octoprint.filemanager import get_mime_type
|
||||
return get_mime_type(path)
|
||||
|
||||
def download_name_generator(path):
|
||||
metadata = fileManager.get_metadata("local", path)
|
||||
if metadata and "display" in metadata:
|
||||
return metadata["display"]
|
||||
|
||||
download_handler_kwargs = dict(
|
||||
as_attachment=True,
|
||||
@@ -493,7 +498,9 @@ class Server(object):
|
||||
(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads")),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads"),
|
||||
as_attachment=True,
|
||||
name_generator=download_name_generator),
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator,
|
||||
additional_mime_types)),
|
||||
|
||||
@@ -148,6 +148,7 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac
|
||||
file = {
|
||||
"type": "machinecode",
|
||||
"name": sdFile,
|
||||
"display": sdFile,
|
||||
"path": sdFile,
|
||||
"origin": FileDestinations.SDCARD,
|
||||
"refs": {
|
||||
@@ -287,8 +288,11 @@ def uploadGcodeFile(target):
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
# FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet
|
||||
futurePath, futureFilename = fileManager.sanitize(FileDestinations.LOCAL, upload.filename)
|
||||
canonPath, canonFilename = fileManager.canonicalize(FileDestinations.LOCAL, upload.filename)
|
||||
futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath)
|
||||
futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, canonFilename)
|
||||
except:
|
||||
canonFilename = None
|
||||
futurePath = None
|
||||
futureFilename = None
|
||||
|
||||
@@ -335,7 +339,9 @@ def uploadGcodeFile(target):
|
||||
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
|
||||
|
||||
try:
|
||||
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True)
|
||||
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload,
|
||||
allow_overwrite=True,
|
||||
display=canonFilename)
|
||||
except octoprint.filemanager.storage.StorageError as e:
|
||||
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
|
||||
return make_response("Could not upload the file \"{}\", invalid type".format(upload.filename), 400)
|
||||
@@ -401,7 +407,9 @@ def uploadGcodeFile(target):
|
||||
if not target in [FileDestinations.LOCAL]:
|
||||
return make_response("Unknown target: %s" % target, 400)
|
||||
|
||||
futurePath, futureName = fileManager.sanitize(target, foldername)
|
||||
canonPath, canonName = fileManager.canonicalize(target, foldername)
|
||||
futurePath = fileManager.sanitize_path(target, canonPath)
|
||||
futureName = fileManager.sanitize_name(target, canonName)
|
||||
if not futureName or not futurePath:
|
||||
return make_response("Can't create a folder with an empty name", 400)
|
||||
|
||||
@@ -414,7 +422,7 @@ def uploadGcodeFile(target):
|
||||
return make_response("Can't create a folder named %s, please try another name" % futureName, 409)
|
||||
|
||||
try:
|
||||
added_folder = fileManager.add_folder(target, futureFullPath)
|
||||
added_folder = fileManager.add_folder(target, futureFullPath, display=canonName)
|
||||
except octoprint.filemanager.storage.StorageError as e:
|
||||
if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY:
|
||||
return make_response("Could not create folder {}, invalid directory".format(futureName))
|
||||
@@ -540,6 +548,14 @@ def gcodeFileCommand(filename, target):
|
||||
if path:
|
||||
full_path = fileManager.join_path(target, path, destination)
|
||||
|
||||
canon_path, canon_name = fileManager.canonicalize(target, full_path)
|
||||
sanitized_name = fileManager.sanitize_name(target, canon_name)
|
||||
|
||||
if canon_path:
|
||||
full_path = fileManager.join_path(target, canon_path, sanitized_name)
|
||||
else:
|
||||
full_path = sanitized_name
|
||||
|
||||
# prohibit overwriting the file that is currently being printed
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == full_path and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
|
||||
@@ -596,6 +612,7 @@ def gcodeFileCommand(filename, target):
|
||||
printer_profile_id=printerProfile,
|
||||
position=position,
|
||||
overrides=overrides,
|
||||
display=canon_name,
|
||||
callback=slicing_done,
|
||||
callback_args=(target, full_path, select_after_slicing, print_after_slicing))
|
||||
except octoprint.slicing.UnknownProfile:
|
||||
@@ -604,8 +621,9 @@ def gcodeFileCommand(filename, target):
|
||||
files = {}
|
||||
location = url_for(".readGcodeFile", target=target, filename=full_path, _external=True)
|
||||
result = {
|
||||
"name": destination,
|
||||
"name": sanitized_name,
|
||||
"path": full_path,
|
||||
"display": canon_name,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location,
|
||||
@@ -637,14 +655,15 @@ def gcodeFileCommand(filename, target):
|
||||
return make_response("File or folder not found on {}: {}".format(target, filename), 404)
|
||||
|
||||
path, name = fileManager.split_path(target, filename)
|
||||
destination = data["destination"]
|
||||
if _verifyFolderExists(target, destination):
|
||||
# destination is an existing folder, we'll assume we are supposed to move filename to this
|
||||
# folder under the same name
|
||||
destination = fileManager.join_path(target, destination, name)
|
||||
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination):
|
||||
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
|
||||
destination = data["destination"]
|
||||
dst_path, dst_name = fileManager.split_path(target, destination)
|
||||
sanitized_destination = fileManager.join_path(target, dst_path, fileManager.sanitize_name(target, dst_name))
|
||||
|
||||
if _verifyFolderExists(target, destination) and sanitized_destination != filename:
|
||||
# destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed
|
||||
# to move filename to this folder under the same name
|
||||
destination = fileManager.join_path(target, destination, name)
|
||||
|
||||
is_file = fileManager.file_exists(target, filename)
|
||||
is_folder = fileManager.folder_exists(target, filename)
|
||||
@@ -653,14 +672,24 @@ def gcodeFileCommand(filename, target):
|
||||
return make_response("{} on {} is neither file or folder, can't {}".format(filename, target, command), 400)
|
||||
|
||||
if command == "copy":
|
||||
# destination already there? error...
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination):
|
||||
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
|
||||
|
||||
if is_file:
|
||||
fileManager.copy_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.copy_folder(target, filename, destination)
|
||||
|
||||
elif command == "move":
|
||||
if _isBusy(target, filename):
|
||||
return make_response("Trying to move a file or folder that is currently in use: {}".format(filename), 409)
|
||||
|
||||
# destination already there AND not ourselves (= display rename)? error...
|
||||
if (_verifyFileExists(target, destination) or _verifyFolderExists(target, destination)) \
|
||||
and sanitized_destination != filename:
|
||||
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
|
||||
@@ -883,7 +883,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
"""
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True,
|
||||
access_validation=None, path_validation=None, etag_generator=None,
|
||||
access_validation=None, path_validation=None, etag_generator=None, name_generator=None,
|
||||
mime_type_guesser=None):
|
||||
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
@@ -891,6 +891,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
self._access_validation = access_validation
|
||||
self._path_validation = path_validation
|
||||
self._etag_generator = etag_generator
|
||||
self._name_generator = name_generator
|
||||
self._mime_type_guesser = mime_type_guesser
|
||||
|
||||
def get(self, path, include_body=True):
|
||||
@@ -907,7 +908,15 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
|
||||
def set_extra_headers(self, path):
|
||||
if self._as_attachment:
|
||||
self.set_header("Content-Disposition", "attachment; filename=%s" % os.path.basename(path))
|
||||
filename = None
|
||||
if callable(self._name_generator):
|
||||
filename = self._name_generator(path)
|
||||
if filename is None:
|
||||
filename = os.path.basename(path)
|
||||
|
||||
filename = tornado.escape.url_escape(filename, plus=False)
|
||||
self.set_header("Content-Disposition", "attachment; filename=\"{}\"; filename*=UTF-8''{}".format(filename,
|
||||
filename))
|
||||
|
||||
if not self._allow_client_caching:
|
||||
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
|
||||
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
@@ -89,8 +89,8 @@ $(function() {
|
||||
{
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
if (a["display"].toLowerCase() < b["display"].toLowerCase()) return -1;
|
||||
if (a["display"].toLowerCase() > b["display"].toLowerCase()) return 1;
|
||||
return 0;
|
||||
},
|
||||
"upload": function(a, b) {
|
||||
@@ -437,7 +437,7 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.slicing.show(file.origin, file.path, true);
|
||||
self.slicing.show(file.origin, file.path, true, undefined, {display: file.display});
|
||||
};
|
||||
|
||||
self.initSdCard = function() {
|
||||
|
||||
@@ -27,6 +27,7 @@ $(function() {
|
||||
|
||||
self.filename = ko.observable(undefined);
|
||||
self.filepath = ko.observable(undefined);
|
||||
self.filedisplay = ko.observable(undefined);
|
||||
self.progress = ko.observable(undefined);
|
||||
self.filesize = ko.observable(undefined);
|
||||
self.filepos = ko.observable(undefined);
|
||||
@@ -212,11 +213,13 @@ $(function() {
|
||||
self.filename(data.file.name);
|
||||
self.filepath(data.file.path);
|
||||
self.filesize(data.file.size);
|
||||
self.filedisplay(data.file.display);
|
||||
self.sd(data.file.origin == "sdcard");
|
||||
} else {
|
||||
self.filename(undefined);
|
||||
self.filepath(undefined);
|
||||
self.filesize(undefined);
|
||||
self.filedisplay(undefined);
|
||||
self.sd(undefined);
|
||||
}
|
||||
|
||||
|
||||
@@ -126,23 +126,28 @@ $(function() {
|
||||
];
|
||||
self.afterSlicing = ko.observable("none");
|
||||
|
||||
self.show = function(target, file, force, path) {
|
||||
self.show = function(target, file, force, path, options) {
|
||||
options = options || {};
|
||||
|
||||
if (!self.enableSlicingDialog() && !force) {
|
||||
return;
|
||||
}
|
||||
|
||||
var filename = file.substr(0, file.lastIndexOf("."));
|
||||
var filename = file;
|
||||
if (filename.lastIndexOf("/") != 0) {
|
||||
path = path || filename.substr(0, filename.lastIndexOf("/"));
|
||||
filename = filename.substr(filename.lastIndexOf("/") + 1);
|
||||
}
|
||||
|
||||
var display = options.display || filename;
|
||||
var destination = display.substr(0, display.lastIndexOf("."));
|
||||
|
||||
self.requestData();
|
||||
self.target = target;
|
||||
self.file(file);
|
||||
self.path = path;
|
||||
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: filename}));
|
||||
self.destinationFilename(filename);
|
||||
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: display}));
|
||||
self.destinationFilename(destination);
|
||||
self.printerProfile(self.printerProfiles.currentProfile());
|
||||
self.afterSlicing("none");
|
||||
|
||||
@@ -253,7 +258,7 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
var destinationFilename = self._sanitize(self.destinationFilename());
|
||||
var destinationFilename = self.destinationFilename();
|
||||
|
||||
var destinationExtensions = self.data[self.slicer()] && self.data[self.slicer()].extensions && self.data[self.slicer()].extensions.destination
|
||||
? self.data[self.slicer()].extensions.destination
|
||||
|
||||
@@ -686,11 +686,15 @@ ul.dropdown-menu li a {
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.uploaded, .size, .additionalInfo {
|
||||
.internal, .uploaded, .size, .additionalInfo {
|
||||
font-size: 85%;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.internal {
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
position: absolute;
|
||||
bottom: @padding;
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
<!-- /ko -->
|
||||
|
||||
<script type="text/html" id="files_template_machinecode">
|
||||
<div class="title clickable" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: name"></div>
|
||||
<div class="title clickable" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: display"></div>
|
||||
<div class="internal" data-bind="visible: display && name != display">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
|
||||
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
|
||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
|
||||
@@ -26,7 +27,8 @@
|
||||
</script>
|
||||
|
||||
<script type="text/html" id="files_template_model">
|
||||
<div class="title muted" data-bind="text: name"></div>
|
||||
<div class="title muted" data-bind="text: display"></div>
|
||||
<div class="internal" data-bind="visible: name != display">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
|
||||
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
|
||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||
<div class="btn-group action-buttons">
|
||||
@@ -37,7 +39,8 @@
|
||||
</script>
|
||||
|
||||
<script type="text/html" id="files_template_folder">
|
||||
<div class="title clickable" data-bind="click: $root.changeFolder, style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }"><i class="fa fa-folder-open"></i> <span data-bind="text: name"></span></div>
|
||||
<div class="title clickable" data-bind="click: $root.changeFolder, style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }"><i class="fa fa-folder-open"></i> <span data-bind="text: display"></span></div>
|
||||
<div class="internal" data-bind="visible: name != display">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
|
||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||
<div class="btn-group action-buttons">
|
||||
<div class="btn btn-mini" data-bind="click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFolder($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="fa fa-trash-o"></i></div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<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: filename, attr: {title: filepath}"></strong> <strong data-bind="visible: sd">(SD)</strong><br>
|
||||
<span title="{{ _('Name of file currently selected for printing') }}">{{ _('File') }}</span>: <strong data-bind="text: filedisplay, attr: {title: filepath}"></strong> <strong data-bind="visible: sd">(SD)</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>
|
||||
|
||||
@@ -846,8 +846,10 @@ def is_hidden_path(path):
|
||||
# we define a None path as not hidden here
|
||||
return False
|
||||
|
||||
path = to_unicode(path)
|
||||
|
||||
filename = os.path.basename(path)
|
||||
if filename.startswith("."):
|
||||
if filename.startswith(u"."):
|
||||
# filenames starting with a . are hidden
|
||||
return True
|
||||
|
||||
@@ -856,7 +858,7 @@ def is_hidden_path(path):
|
||||
# attribute via the windows api
|
||||
try:
|
||||
import ctypes
|
||||
attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(path))
|
||||
attrs = ctypes.windll.kernel32.GetFileAttributesW(path)
|
||||
assert attrs != -1 # INVALID_FILE_ATTRIBUTES == -1
|
||||
return bool(attrs & 2) # FILE_ATTRIBUTE_HIDDEN == 2
|
||||
except (AttributeError, AssertionError):
|
||||
|
||||
@@ -167,7 +167,11 @@ class FileManagerTest(unittest.TestCase):
|
||||
file_path = self.file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, "test.gcode", wrapper)
|
||||
|
||||
self.assertEqual(("", "test.gcode"), file_path)
|
||||
self.local_storage.add_file.assert_called_once_with("test.gcode", wrapper, printer_profile=test_profile, allow_overwrite=False, links=None)
|
||||
self.local_storage.add_file.assert_called_once_with("test.gcode", wrapper,
|
||||
printer_profile=test_profile,
|
||||
allow_overwrite=False,
|
||||
links=None,
|
||||
display=None)
|
||||
|
||||
expected_events = [mock.call(octoprint.filemanager.Events.FILE_ADDED, dict(storage=octoprint.filemanager.FileDestinations.LOCAL,
|
||||
name="test.gcode",
|
||||
@@ -176,6 +180,26 @@ class FileManagerTest(unittest.TestCase):
|
||||
mock.call(octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables"))]
|
||||
self.fire_event.call_args_list = expected_events
|
||||
|
||||
def test_add_file_display(self):
|
||||
wrapper = object()
|
||||
|
||||
self.local_storage.add_file.return_value = ("", "test.gcode")
|
||||
self.local_storage.path_on_disk.return_value = "prefix/test.gcode"
|
||||
self.local_storage.split_path.return_value = ("", "test.gcode")
|
||||
|
||||
test_profile = dict(id="_default", name="My Default Profile")
|
||||
self.printer_profile_manager.get_current_or_default.return_value = test_profile
|
||||
|
||||
file_path = self.file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, "test.gcode", wrapper,
|
||||
display=u"täst.gcode")
|
||||
|
||||
self.assertEqual(("", "test.gcode"), file_path)
|
||||
self.local_storage.add_file.assert_called_once_with("test.gcode", wrapper,
|
||||
printer_profile=test_profile,
|
||||
allow_overwrite=False,
|
||||
links=None,
|
||||
display=u"täst.gcode")
|
||||
|
||||
def test_remove_file(self):
|
||||
self.local_storage.path_on_disk.return_value = "prefix/test.gcode"
|
||||
self.local_storage.split_path.return_value = ("", "test.gcode")
|
||||
@@ -198,7 +222,10 @@ class FileManagerTest(unittest.TestCase):
|
||||
folder_path = self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder")
|
||||
|
||||
self.assertEqual(("", "test_folder"), folder_path)
|
||||
self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=True)
|
||||
self.local_storage.add_folder.assert_called_once_with("test_folder",
|
||||
ignore_existing=True,
|
||||
display=None)
|
||||
|
||||
expected_events = [mock.call(octoprint.filemanager.Events.FOLDER_ADDED, dict(storage=octoprint.filemanager.FileDestinations.LOCAL,
|
||||
name="test_folder",
|
||||
path="test_folder")),
|
||||
@@ -213,7 +240,20 @@ class FileManagerTest(unittest.TestCase):
|
||||
self.fail("Expected an exception to occur!")
|
||||
except RuntimeError as e:
|
||||
self.assertEqual("already there", e.message)
|
||||
self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=False)
|
||||
self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=False, display=None)
|
||||
|
||||
def test_add_folder_display(self):
|
||||
self.local_storage.add_folder.side_effect = RuntimeError("already there")
|
||||
|
||||
try:
|
||||
self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder",
|
||||
display=u"täst_folder")
|
||||
self.fail("Expected an exception to occur!")
|
||||
except RuntimeError as e:
|
||||
self.assertEqual("already there", e.message)
|
||||
self.local_storage.add_folder.assert_called_once_with("test_folder",
|
||||
ignore_existing=True,
|
||||
display=u"täst_folder")
|
||||
|
||||
def test_remove_folder(self):
|
||||
self.local_storage.split_path.return_value = ("", "test_folder")
|
||||
@@ -409,7 +449,7 @@ class FileManagerTest(unittest.TestCase):
|
||||
self.local_storage.split_path.side_effect = split_path
|
||||
|
||||
# mock add_file method on local storage
|
||||
def add_file(path, file_obj, printer_profile=None, links=None, allow_overwrite=False):
|
||||
def add_file(path, file_obj, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
file_obj.save("prefix/" + path)
|
||||
return path
|
||||
self.local_storage.add_file.side_effect = add_file
|
||||
@@ -447,7 +487,11 @@ class FileManagerTest(unittest.TestCase):
|
||||
|
||||
# assert that model links were added
|
||||
expected_links = [("model", dict(name="source.file"))]
|
||||
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY, printer_profile=expected_printer_profile, allow_overwrite=True, links=expected_links)
|
||||
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY,
|
||||
printer_profile=expected_printer_profile,
|
||||
allow_overwrite=True,
|
||||
links=expected_links,
|
||||
display=None)
|
||||
|
||||
# assert that the generated gcode was manipulated as required
|
||||
expected_atomic_write_calls = [mock.call("prefix/dest.file", "wb")]
|
||||
|
||||
@@ -79,6 +79,13 @@ class LocalStorageTest(unittest.TestCase):
|
||||
|
||||
self._add_and_verify_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, overwrite=True)
|
||||
|
||||
def test_add_file_with_display(self):
|
||||
stl_name = self._add_and_verify_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, display=u"bp_cäse.stl")
|
||||
stl_metadata = self.storage.get_metadata(stl_name)
|
||||
|
||||
self.assertIsNotNone(stl_metadata)
|
||||
self.assertDictContainsSubset(dict(display=u"bp_cäse.stl"), stl_metadata)
|
||||
|
||||
def test_add_file_with_web(self):
|
||||
import time
|
||||
href = "http://www.example.com"
|
||||
@@ -182,6 +189,48 @@ 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:
|
||||
self.storage.copy_file("bp_case.stl", u"bp_cäse.stl")
|
||||
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")
|
||||
|
||||
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "bp_case.stl")))
|
||||
|
||||
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)
|
||||
try:
|
||||
getattr(self.storage, operation)("bp_case.stl", "bp_case.stl")
|
||||
self.fail("Expected an exception")
|
||||
except StorageError as e:
|
||||
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
|
||||
|
||||
@data("copy_file", "move_file")
|
||||
def test_copy_move_file_missing_source(self, operation):
|
||||
@@ -215,6 +264,12 @@ 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")
|
||||
self.assertIsNotNone(metadata)
|
||||
self.assertDictContainsSubset(dict(display=u"täst"), metadata)
|
||||
|
||||
def test_add_subfolder(self):
|
||||
folder_name = self._add_and_verify_folder("folder with some spaces", "folder_with_some_spaces")
|
||||
@@ -247,12 +302,16 @@ class LocalStorageTest(unittest.TestCase):
|
||||
self.assertFalse(os.path.exists(os.path.join(self.basefolder, empty_folder)))
|
||||
self.assertFalse(os.path.isdir(os.path.join(self.basefolder, empty_folder)))
|
||||
|
||||
def test_remove_folder_with_metadata(self):
|
||||
content_folder = self._add_and_verify_folder("content", "content")
|
||||
other_stl_name = self._add_and_verify_file((content_folder, "crazyradio.stl"), content_folder + "/crazyradio.stl", FILE_CRAZYRADIO_STL)
|
||||
self.storage.remove_file(other_stl_name)
|
||||
|
||||
self.storage.remove_folder(content_folder, recursive=False)
|
||||
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)
|
||||
|
||||
def test_copy_folder(self):
|
||||
self._add_folder("source")
|
||||
@@ -296,6 +355,46 @@ class LocalStorageTest(unittest.TestCase):
|
||||
self.assertIsNotNone(copied_metadata)
|
||||
self.assertDictEqual(before_source_metadata, copied_metadata)
|
||||
|
||||
def test_copy_folder_new_display(self):
|
||||
self._add_folder("folder")
|
||||
try:
|
||||
self.storage.copy_folder("folder", u"földer")
|
||||
self.fail("Expected an exception")
|
||||
except StorageError as e:
|
||||
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
|
||||
|
||||
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")
|
||||
|
||||
self.assertIsNotNone(before_metadata)
|
||||
self.assertDictEqual(before_metadata, dict(display=u"földer"))
|
||||
self.assertIsNone(after_metadata)
|
||||
|
||||
@data("copy_folder", "move_folder")
|
||||
def test_copy_move_folder_same(self, operation):
|
||||
self._add_folder("folder")
|
||||
try:
|
||||
getattr(self.storage, operation)("folder", "folder")
|
||||
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:
|
||||
@@ -524,13 +623,23 @@ class LocalStorageTest(unittest.TestCase):
|
||||
self.assertEqual(expected_path, actual_path)
|
||||
self.assertEqual(expected_name, actual_name)
|
||||
|
||||
def _add_and_verify_file(self, path, expected_path, file_object, links=None, overwrite=False):
|
||||
@data(
|
||||
(u"test", u"test"),
|
||||
(u"\u2764", u"red_heart"),
|
||||
(u"\u2764\ufe00", u"red_heart")
|
||||
)
|
||||
@unpack
|
||||
def test_slugify(self, input, expected):
|
||||
output = LocalFileStorage._slugify(input)
|
||||
self.assertEqual(output, expected)
|
||||
|
||||
def _add_and_verify_file(self, path, expected_path, file_object, links=None, overwrite=False, display=None):
|
||||
"""Adds a file to the storage and verifies the sanitized path."""
|
||||
sanitized_path = self._add_file(path, file_object, links=links, overwrite=overwrite)
|
||||
sanitized_path = self._add_file(path, file_object, links=links, overwrite=overwrite, display=display)
|
||||
self.assertEqual(expected_path, sanitized_path)
|
||||
return sanitized_path
|
||||
|
||||
def _add_file(self, path, file_object, links=None, overwrite=False):
|
||||
def _add_file(self, path, file_object, links=None, overwrite=False, display=None):
|
||||
"""
|
||||
Adds a file to the storage.
|
||||
|
||||
@@ -539,7 +648,7 @@ class LocalStorageTest(unittest.TestCase):
|
||||
|
||||
Returns sanitized path.
|
||||
"""
|
||||
sanitized_path = self.storage.add_file(path, file_object, links=links, allow_overwrite=overwrite)
|
||||
sanitized_path = self.storage.add_file(path, file_object, links=links, allow_overwrite=overwrite, display=display)
|
||||
|
||||
split_path = sanitized_path.split("/")
|
||||
if len(split_path) == 1:
|
||||
@@ -565,13 +674,13 @@ class LocalStorageTest(unittest.TestCase):
|
||||
|
||||
return sanitized_path
|
||||
|
||||
def _add_and_verify_folder(self, path, expected_path):
|
||||
def _add_and_verify_folder(self, path, expected_path, display=None):
|
||||
"""Adds a folder to the storage and verifies sanitized path."""
|
||||
sanitized_path = self._add_folder(path)
|
||||
sanitized_path = self._add_folder(path, display=display)
|
||||
self.assertEqual(expected_path, sanitized_path)
|
||||
return sanitized_path
|
||||
|
||||
def _add_folder(self, path):
|
||||
def _add_folder(self, path, display=None):
|
||||
"""
|
||||
Adds a folder to the storage.
|
||||
|
||||
@@ -579,7 +688,7 @@ class LocalStorageTest(unittest.TestCase):
|
||||
|
||||
Returns sanitized path.
|
||||
"""
|
||||
sanitized_path = self.storage.add_folder(path)
|
||||
sanitized_path = self.storage.add_folder(path, display=display)
|
||||
self.assertTrue(os.path.isdir(os.path.join(self.basefolder, os.path.join(*sanitized_path.split("/")))))
|
||||
return sanitized_path
|
||||
|
||||
Reference in new issue
Block a user