From 6251031d6e2e36bf182cd26ece181f6ff673cb89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 6 Aug 2018 13:35:02 +0200 Subject: [PATCH] Backup works, incl management UI --- src/octoprint/plugins/backup/__init__.py | 69 ++++++++---- .../plugins/backup/static/css/backup.css | 1 + .../plugins/backup/static/js/backup.js | 100 ++++++++++++++++-- .../plugins/backup/static/less/backup.less | 20 ++++ .../backup/templates/backup_settings.jinja2 | 57 +++++++++- 5 files changed, 218 insertions(+), 29 deletions(-) create mode 100644 src/octoprint/plugins/backup/static/css/backup.css create mode 100644 src/octoprint/plugins/backup/static/less/backup.less diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index b1f45a223..7bc9d7864 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -8,7 +8,7 @@ import octoprint.plugin from octoprint.settings import default_settings from octoprint.plugin.core import FolderOrigin -from octoprint.server import admin_permission +from octoprint.server import admin_permission, NO_CONTENT from octoprint.server.util.flask import restricted_access from octoprint.util import is_hidden_path @@ -35,12 +35,6 @@ import json """ TODO: -* Backup: - * UI to select things to backup (timelapse? uploads?) and start the backup - * perform backup - x sanity check of available space (must be at least what the selected parts currently consume unzipped) - x zip stuff to disk, incl. plugin list as json - * trigger download in browser * Restore: * UI to upload a backup zip * tornado endpoint to stream the upload @@ -70,12 +64,15 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, ##~~ AssetPlugin def get_assets(self): - return dict(js=["js/backup.js"]) + return dict(js=["js/backup.js"], + css=["css/backup.css"], + less=["less/backup.less"]) ##~~ BlueprintPlugin @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"]) @admin_permission.require(403) + @restricted_access def get_backups(self): # TODO add caching backups = [] @@ -85,37 +82,69 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, backups.append(dict(name=entry.name, date=entry.stat().st_mtime, size=entry.stat().st_size, - url=flask.url_for("index") + "downloads/backup/" + entry.name)) - return flask.jsonify(backups=backups) + url=flask.url_for("index") + "plugin/backup/download/" + entry.name)) + return flask.jsonify(backups=backups, + in_progress=len(self._in_progress) > 0) @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"]) @admin_permission.require(403) + @restricted_access def create_backup(self): backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S")) + data = flask.request.json + exclude = data.get("exclude", []) + thread = threading.Thread(target=self._create_backup, args=(backup_file,), - kwargs=dict(exclude=["timelapse", - "timelapse_tmp", - "uploads"])) + kwargs=dict(exclude=exclude)) thread.daemon = True thread.start() response = flask.jsonify(started=True) - response.headers["Location"] = flask.url_for("index") + "downloads/backup/" + backup_file + response.headers["Location"] = flask.url_for("index") + "plugin/backup/download/" + backup_file response.status_code = 201 return response - @octoprint.plugin.BlueprintPlugin.route("/backup/", methods=["DELETE"]) + @octoprint.plugin.BlueprintPlugin.route("/backup/", methods=["DELETE"]) @admin_permission.require(403) - def delete_backup(self, backup): - pass + @restricted_access + def delete_backup(self, filename): + backup_folder = self.get_plugin_data_folder() + full_path = os.path.realpath(os.path.join(backup_folder, filename)) + if full_path.startswith(backup_folder) \ + and os.path.exists(full_path) \ + and not is_hidden_path(full_path): + try: + os.remove(full_path) + except: + self._logger.exception("Could not delete {}".format(filename)) + raise + return NO_CONTENT @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) @admin_permission.require(403) + @restricted_access def perform_restore(self): pass + ##~~ tornado hook + + def route_hook(self, *args, **kwargs): + from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory + from octoprint.util import is_hidden_path + from octoprint.server import app + from octoprint.server.util.tornado import access_validation_factory + from octoprint.server.util.flask import admin_validator + + return [ + (r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(), + as_attachment=True, + path_validation=path_validation_factory(lambda path: not is_hidden_path(path), + status_code=404), + access_validation=access_validation_factory(app, admin_validator))) + ] + ##~~ helpers def _get_disk_size(self, path): @@ -155,7 +184,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, self._in_progress.append(name) self._send_client_message("backup_started", payload=dict(name=name)) - self._logger.info("Creating backup zip at {}...".format(temporary_path)) + self._logger.info("Creating backup zip at {} (excluded: {})...".format(temporary_path, + ",".join(exclude) if len(exclude) else "-")) with zipfile.ZipFile(temporary_path, "w", compression) as zip: def add_to_zip(source, target, ignored=None): @@ -228,3 +258,6 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin you will no long "& restore your OctoPrint settings and data.") __plugin_license__ = "AGPLv3" __plugin_implementation__ = BackupPlugin() +__plugin_hooks__ = { + "octoprint.server.http.routes": __plugin_implementation__.route_hook +} diff --git a/src/octoprint/plugins/backup/static/css/backup.css b/src/octoprint/plugins/backup/static/css/backup.css new file mode 100644 index 000000000..573f78b4f --- /dev/null +++ b/src/octoprint/plugins/backup/static/css/backup.css @@ -0,0 +1 @@ +#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:50px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right} \ No newline at end of file diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 62195f969..174c0ea8a 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -22,16 +22,20 @@ return this.get(false, opts); }; - OctoPrintBackupClient.prototype.createBackup = function(excludes, opts) { - excludes = excludes || []; + OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) { + exclude = exclude || []; var data = { - excludes: excludes + exclude: exclude }; return this.base.postJson(this.url + "backup", data, opts); }; + OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) { + return this.base.delete(this.url + "backup/" + backup, opts); + }; + OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient); return OctoPrintBackupClient; }); @@ -58,8 +62,11 @@ $(function() { "date", [], [], - 0 + 10 ); + self.markedForBackupDeletion = ko.observableArray([]); + self.excludeFromBackup = ko.observableArray([]); + self.backupInProgress = ko.observable(false); self.requestData = function() { OctoPrint.plugins.backup.get() @@ -71,7 +78,42 @@ $(function() { }; self.createBackup = function() { - OctoPrint.plugins.backup.createBackup(); + var excluded = self.excludeFromBackup(); + OctoPrint.plugins.backup.createBackup(excluded) + .done(function() { + self.excludeFromBackup([]); + }) + }; + + self.removeBackup = function(backup) { + OctoPrint.plugins.backup.deleteBackup(backup) + .done(function() { + self.requestData(); + }) + }; + + self.markFilesOnPage = function() { + self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name")))); + }; + + self.markAllFiles = function() { + self.markedForBackupDeletion(_.map(self.backups.allItems, "name")); + }; + + self.clearMarkedFiles = function() { + self.markedForBackupDeletion.removeAll(); + }; + + self.removeMarkedFiles = function() { + var perform = function() { + self._bulkRemove(self.markedForBackupDeletion()) + .done(function() { + self.markedForBackupDeletion.removeAll(); + }); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}), + perform); }; self.onSettingsShown = function() { @@ -83,8 +125,54 @@ $(function() { if (data.type === "backup_done") { self.requestData(); + self.backupInProgress(false); + } else if (data.type === "backup_started") { + self.backupInProgress(true); } - } + }; + + self._bulkRemove = function(files) { + var title, message, handler; + + title = gettext("Deleting backups"); + message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length}); + handler = function(filename) { + return OctoPrint.plugins.backup.deleteBackup(filename) + .done(function() { + deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true); + }) + .fail(function(jqXHR) { + var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}); + var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText}); + deferred.notify(short, long, false); + }); + }; + + var deferred = $.Deferred(); + + var promise = deferred.promise(); + + var options = { + title: title, + message: message, + max: files.length, + output: true + }; + showProgressModal(options, promise); + + var requests = []; + _.each(files, function(filename) { + var request = handler(filename); + requests.push(request) + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)) + .done(function() { + deferred.resolve(); + self.requestData(); + }); + + return promise; + }; } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/plugins/backup/static/less/backup.less b/src/octoprint/plugins/backup/static/less/backup.less new file mode 100644 index 000000000..1037380cb --- /dev/null +++ b/src/octoprint/plugins/backup/static/less/backup.less @@ -0,0 +1,20 @@ +#settings_plugin_backup_backup_table { + .settings_plugin_backup_name { + } + .settings_plugin_backup_actions { + width: 50px; + text-align: center; + + a { + color: black; + } + } + .settings_plugin_backup_date { + width: 200px; + text-align: right; + } + .settings_plugin_backup_size { + width: 100px; + text-align: right; + } +} diff --git a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 index 16e0b739d..5fa0aa249 100644 --- a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 +++ b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 @@ -1,5 +1,3 @@ -

{{ _('Backup & Restore') }}

-