✨ Confirm overwrite dialog

On file upload, if the target file already exists, a confirmation will
now be shown that allows to explicitly overwrite the existing file,
rename the file prior to upload (with a collision free suggestion
provided) or cancel the upload.

A feature flag allows to disable this confirmation again to restore the
old behaviour in case the new one clashes with people's workflows.

Implements #3873
This commit is contained in:
Gina Häußge committed 2021-03-25 18:05:13 +01:00
1 parent 983dd4d437
commit 84373a7617
8 files changed
+219 -33

No files matched your search

+59 -6
View File
@@ -163,6 +163,54 @@ def readGcodeFiles():
return jsonify(files=files, free=usage.free, total=usage.total)
@api.route("/files/test", methods=["POST"])
@Permissions.FILES_LIST.require(403)
def runFilesTest():
valid_commands = {
"sanitize": ["storage", "path", "filename"],
"exists": ["storage", "path", "filename"],
}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
def sanitize(storage, path, filename):
sanitized_path = fileManager.sanitize_path(storage, path)
sanitized_name = fileManager.sanitize_name(storage, filename)
joined = fileManager.join_path(storage, sanitized_path, sanitized_name)
return sanitized_path, sanitized_name, joined
if command == "sanitize":
_, _, sanitized = sanitize(data["storage"], data["path"], data["filename"])
return jsonify(sanitized=sanitized)
elif command == "exists":
storage = data["storage"]
path = data["path"]
filename = data["filename"]
sanitized_path, _, sanitized = sanitize(storage, path, filename)
exists = fileManager.file_exists(storage, sanitized)
if exists:
suggestion = filename
name, ext = os.path.splitext(filename)
counter = 0
while fileManager.file_exists(
storage,
fileManager.join_path(
storage,
sanitized_path,
fileManager.sanitize_name(storage, suggestion),
),
):
counter += 1
suggestion = name + "_{}".format(counter) + ext
return jsonify(exists=True, suggestion=suggestion)
else:
return jsonify(exists=False)
@api.route("/files/<string:origin>", methods=["GET"])
@Permissions.FILES_LIST.require(403)
@with_revalidation_checking(
@@ -507,6 +555,11 @@ def uploadGcodeFile(target):
canonPath, canonFilename = fileManager.canonicalize(
FileDestinations.LOCAL, upload.filename
)
if request.values.get("path"):
canonPath = request.values.get("path")
if request.values.get("filename"):
canonFilename = request.values.get("filename")
futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath)
futureFilename = fileManager.sanitize_name(
FileDestinations.LOCAL, canonFilename
@@ -519,12 +572,6 @@ def uploadGcodeFile(target):
if futureFilename is None:
abort(415, description="Can not upload file, wrong format?")
if "path" in request.values and request.values["path"]:
# we currently only support uploads to sdcard via local, so first target is local instead of "target"
futurePath = fileManager.sanitize_path(
FileDestinations.LOCAL, request.values["path"]
)
# prohibit overwriting currently selected file while it's being printed
futureFullPath = fileManager.join_path(
FileDestinations.LOCAL, futurePath, futureFilename
@@ -539,6 +586,12 @@ def uploadGcodeFile(target):
description="Trying to overwrite file that is currently being printed",
)
if (
fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage)
and request.values.get("noOverwrite") in valid_boolean_trues
):
abort(409, description="File already exists and noOverwrite was set")
reselect = printer.is_current_file(futureFullPathInStorage, sd)
user = current_user.get_name()
+8
View File
@@ -150,6 +150,9 @@ def getSettings():
"printCancelConfirmation": s.getBoolean(
["feature", "printCancelConfirmation"]
),
"uploadOverwriteConfirmation": s.getBoolean(
["feature", "uploadOverwriteConfirmation"]
),
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]),
"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]),
},
@@ -617,6 +620,11 @@ def _saveSettings(data):
["feature", "printCancelConfirmation"],
data["feature"]["printCancelConfirmation"],
)
if "uploadOverwriteConfirmation" in data["feature"]:
s.setBoolean(
["feature", "uploadOverwriteConfirmation"],
data["feature"]["uploadOverwriteConfirmation"],
)
if "g90InfluencesExtruder" in data["feature"]:
s.setBoolean(
["feature", "g90InfluencesExtruder"],
+1
View File
@@ -281,6 +281,7 @@ default_settings = {
"modelSizeDetection": True,
"printStartConfirmation": False,
"printCancelConfirmation": True,
"uploadOverwriteConfirmation": True,
"autoUppercaseBlacklist": ["M117", "M118"],
"g90InfluencesExtruder": False,
},
+13 -10
View File
@@ -7,6 +7,7 @@
})(this, function (OctoPrintClient, $, _) {
var url = "api/files";
var downloadUrl = "downloads/files";
var testUrl = url + "/test";
var OctoPrintFilesClient = function (base) {
this.base = base;
@@ -198,20 +199,22 @@
return recursiveSearch(path.split("/"), root);
};
OctoPrintFilesClient.prototype.pathForElement = function (element) {
// TODO Remove in 1.4.x
log.warn(
"pathForElement has been renamed to pathForEntry, please use that instead"
OctoPrintFilesClient.prototype.sanitize = function (location, path, filename, opts) {
return this.base.issueCommand(
testUrl,
"sanitize",
{storage: location, path: path, filename: filename},
opts
);
return this.pathForEntry(element);
};
OctoPrintFilesClient.prototype.elementByPath = function (location, startElement) {
// TODO Remove in 1.4.x
log.warn(
"elementByPath has been renamed to entryForPath, please use that instead"
OctoPrintFilesClient.prototype.exists = function (location, path, filename, opts) {
return this.base.issueCommand(
testUrl,
"exists",
{storage: location, path: path, filename: filename},
opts
);
return this.entryForPath(location, startElement);
};
OctoPrintClient.registerComponent("files", OctoPrintFilesClient);
+106 -17
View File
@@ -97,6 +97,9 @@ $(function () {
);
});
self.uploadExistsDialog = undefined;
self.uploadFilename = ko.observable(undefined);
self.allItems = ko.observable(undefined);
self.currentPath = ko.observable("");
self.uploadProgressText = ko.observable();
@@ -1221,6 +1224,8 @@ $(function () {
}
});
self.uploadExistsDialog = $("#upload_exists_dialog");
//~~ Gcode upload
self.uploadButton = $("#gcode_upload");
@@ -1419,22 +1424,18 @@ $(function () {
if (button === undefined) return;
button
.fileupload({
url: url,
dataType: "json",
dropZone: enable ? drop : null,
drop: function (e, data) {},
submit: self._handleUploadStart,
done: self._handleUploadDone,
fail: self._handleUploadFail,
always: self._handleUploadAlways,
progressall: self._handleUploadProgress
})
.bind("fileuploadsubmit", function (e, data) {
if (self.currentPath() !== "")
data.formData = {path: self.currentPath()};
});
button.fileupload({
url: url,
dataType: "json",
dropZone: enable ? drop : null,
drop: function (e, data) {},
add: self._handleUploadAdd,
submit: self._handleUploadStart,
done: self._handleUploadDone,
fail: self._handleUploadFail,
always: self._handleUploadAlways,
progressall: self._handleUploadProgress
});
};
self._enableDragNDrop = function (enable) {
@@ -1460,6 +1461,89 @@ $(function () {
}
};
self._handleUploadAdd = function (e, data) {
var file = data.files[0];
var path = self.currentPath();
var formData = {};
if (path !== "") {
formData.path = path;
}
if (self.settingsViewModel.feature_uploadOverwriteConfirmation()) {
OctoPrint.files
.exists("local", path, file.name)
.done(function (response) {
if (response.exists) {
$("h3", self.uploadExistsDialog).text(
_.sprintf(gettext("File already exists: %(name)s"), {
name: file.name
})
);
$("input", self.uploadExistsDialog)
.val("")
.prop("placeholder", response.suggestion);
$("a.upload-rename", self.uploadExistsDialog)
.prop("disabled", false)
.off("click")
.on("click", function () {
var newName = $(
"input",
self.uploadExistsDialog
).val();
if (newName === "") newName = response.suggestion;
OctoPrint.files
.exists("local", path, newName)
.done(function (r) {
if (r.exists) {
$(
".control-group",
self.uploadExistsDialog
).addClass("error");
$(
".help-block",
self.uploadExistsDialog
).show();
} else {
$(
".control-group",
self.uploadExistsDialog
).removeClass("error");
$(
".help-block",
self.uploadExistsDialog
).hide();
self.uploadExistsDialog.modal("hide");
formData.filename = newName;
formData.noOverwrite = true;
data.formData = formData;
data.submit();
}
});
});
$("a.upload-overwrite", self.uploadExistsDialog)
.off("click")
.on("click", function () {
self.uploadExistsDialog.modal("hide");
data.formData = formData;
data.submit();
});
self.uploadExistsDialog.modal("show");
} else {
data.formData = formData;
data.submit();
}
});
} else {
data.formData = formData;
data.submit();
}
};
self._handleUploadStart = function (e, data) {
self.ignoreUpdatedFilesEvent = true;
return true;
@@ -1607,6 +1691,11 @@ $(function () {
"printerProfilesViewModel",
"accessViewModel"
],
elements: ["#files_wrapper", "#add_folder_dialog", "#move_file_or_folder_dialog"]
elements: [
"#files_wrapper",
"#add_folder_dialog",
"#move_file_or_folder_dialog",
"#upload_exists_dialog"
]
});
});
@@ -173,6 +173,7 @@ $(function () {
self.feature_modelSizeDetection = ko.observable(undefined);
self.feature_printStartConfirmation = ko.observable(undefined);
self.feature_printCancelConfirmation = ko.observable(undefined);
self.feature_uploadOverwriteConfirmation = ko.observable(undefined);
self.feature_g90InfluencesExtruder = ko.observable(undefined);
self.feature_autoUppercaseBlacklist = ko.observable(undefined);
@@ -41,3 +41,27 @@
<a href="#" class="btn btn-primary" data-bind="click: function() { if (moveSource() !== moveDestination() && !movingFileOrFolder()) { $root.moveFileOrFolder(moveEntry().path, moveDestination()) } else {} }, css: {disabled: moveSource() === moveDestination() || movingFileOrFolder()}"><i class="fas fa-spinner fa-spin" data-bind="visible: movingFileOrFolder"></i> {{ _('Move') }}</a>
</div>
</div>
<div id="upload_exists_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('File already exists') }}</h3>
</div>
<div class="modal-body">
<p>{{ _('If you want to rename the file, you may do so below. A collision free suggestion has already been made.') }}</p>
<form class="form-horizontal" action="javascript:void(0)">
<div class="control-group">
<label class="control-label">{{ _('Rename to') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
<span class="help-block" style="display: none">{{ _('File already exists') }}</span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="javascript:void(0)" class="btn btn-primary upload-rename">{{ _('Upload (rename)') }}</a>
<a href="javascript:void(0)" class="btn btn-danger upload-overwrite">{{ _('Upload (overwrite)') }}</a>
</div>
</div>
@@ -28,6 +28,13 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_uploadOverwriteConfirmation" id="settings-uploadOverwriteConfirmation"> {{ _('Confirm before overwriting a file by upload') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">