From cd7f0ce60d3f4f34adedea2afec66840e5abdd15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 17 Jan 2023 10:11:54 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20WIP:=20multi=20install=20of=20pl?= =?UTF-8?q?ugins=20from=20JSON=20export?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plugins/pluginmanager/__init__.py | 206 +++++++++++++++--- .../pluginmanager/static/js/pluginmanager.js | 63 ++++-- 2 files changed, 225 insertions(+), 44 deletions(-) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index a32123038..a9ff5690b 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -123,6 +123,7 @@ class PluginManagerPlugin( ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar", ".gz", ".whl") PYTHON_EXTENSIONS = (".py",) + JSON_EXTENSIONS = (".json",) # valid pip install URL schemes according to https://pip.pypa.io/en/stable/reference/pip_install/ URL_SCHEMES = ( @@ -174,6 +175,7 @@ class PluginManagerPlugin( self._repository_available = False self._repository_plugins = [] + self._repository_plugins_by_id = {} self._repository_cache_path = None self._repository_cache_ttl = 0 self._repository_mtime = None @@ -192,6 +194,7 @@ class PluginManagerPlugin( self._install_task = None self._install_lock = threading.RLock() + self._jsoninstall_lock = threading.Lock() self._queued_installs = [] self._queued_installs_abort_timer = None @@ -348,7 +351,9 @@ class PluginManagerPlugin( return { "all": plugins, "thirdparty": list(filter(lambda p: not p["bundled"], plugins)), - "file_extensions": self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS, + "file_extensions": self.ARCHIVE_EXTENSIONS + + self.PYTHON_EXTENSIONS + + self.JSON_EXTENSIONS, } def get_template_types(self, template_sorting, template_rules, *args, **kwargs): @@ -391,7 +396,7 @@ class PluginManagerPlugin( exts = list( filter( lambda x: upload_name.lower().endswith(x), - self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS, + self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS + self.JSON_EXTENSIONS, ) ) if not len(exts): @@ -445,11 +450,15 @@ class PluginManagerPlugin( def export_plugin_list(self): import json - plugins = self.generate_plugins_json(self._settings, self._plugin_manager) + plugins = self.generate_plugins_json( + self._settings, + self._plugin_manager, + repo_plugins=self._repository_plugins_by_id, + ) return Response( json.dumps(plugins), - mimetype="text/plain", + mimetype="application/json", headers={"Content-Disposition": 'attachment; filename="plugin_list.json"'}, ) @@ -472,6 +481,7 @@ class PluginManagerPlugin( "supported_extensions": { "archive": self.ARCHIVE_EXTENSIONS, "python": self.PYTHON_EXTENSIONS, + "json": self.JSON_EXTENSIONS, }, } @@ -877,6 +887,18 @@ class PluginManagerPlugin( return False + def _is_jsonfile(self, path): + _, ext = os.path.splitext(path) + if ext in PluginManagerPlugin.JSON_EXTENSIONS: + import json + + try: + with open(path) as f: + json.load(f) + return True + except Exception as exc: + self._logger.exception(f"Could not parse {path} as json file: {exc}") + def command_install( self, url=None, @@ -885,6 +907,7 @@ class PluginManagerPlugin( force=False, reinstall=None, dependency_links=False, + send_notifications=True, ): folder = None @@ -909,11 +932,25 @@ class PluginManagerPlugin( force=force, reinstall=reinstall, dependency_links=dependency_links, + send_notifications=send_notifications, ) elif self._is_pythonfile(path): result = self._command_install_pythonfile( - path, source=source, source_type=source_type, name=name + path, + source=source, + source_type=source_type, + name=name, + send_notifications=send_notifications, + ) + + elif self._is_jsonfile(path) and not self._jsonfile_install: + result = self._command_install_jsonfile( + path, + source=source, + source_type=source_type, + name=name, + send_notifications=send_notifications, ) else: @@ -927,7 +964,8 @@ class PluginManagerPlugin( "source_type": source_type, "reason": f"Could not fetch plugin from server, got {e}", } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) except exceptions.InvalidPackageFormat: self._logger.error( @@ -942,7 +980,8 @@ class PluginManagerPlugin( "reason": "Could not install plugin from {}, was neither " "a plugin archive nor a single file plugin".format(source), } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) except Exception: error_msg = ( @@ -957,7 +996,8 @@ class PluginManagerPlugin( "source_type": source_type, "reason": error_msg, } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) finally: if folder is not None: @@ -975,6 +1015,7 @@ class PluginManagerPlugin( force=False, reinstall=None, dependency_links=False, + send_notifications=True, ): throttled = self._get_throttled() if ( @@ -995,7 +1036,8 @@ class PluginManagerPlugin( "source_type": source_type, "reason": error_msg, } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result from urllib.parse import quote as url_quote @@ -1049,11 +1091,14 @@ class PluginManagerPlugin( source ), } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result if is_python_mismatch(stderr): - return self.handle_python_mismatch(source, source_type) + return self.handle_python_mismatch( + source, source_type, send_notifications=send_notifications + ) if force: # We don't use --upgrade here because that will also happily update all our dependencies - we'd rather @@ -1072,7 +1117,8 @@ class PluginManagerPlugin( source ), } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result if is_python_mismatch(stderr): @@ -1091,7 +1137,8 @@ class PluginManagerPlugin( "reason": "Could not parse output from pip, see plugin_pluginmanager_console.log " "for generated output", } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result # We'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split @@ -1118,7 +1165,8 @@ class PluginManagerPlugin( "source_type": source_type, "reason": "Pip did not report successful installation", } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result installed = list( @@ -1145,7 +1193,8 @@ class PluginManagerPlugin( "was_reinstalled": False, "plugin": "unknown", } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result self._plugin_manager.reload_plugins() @@ -1201,10 +1250,11 @@ class PluginManagerPlugin( or reinstall is not None, "plugin": self._to_external_plugin(new_plugin), } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result - def _handle_python_mismatch(self, source, source_type): + def _handle_python_mismatch(self, source, source_type, send_notifications=True): self._logger.error( "Installing the plugin from {} failed, pip reported a Python version mismatch".format( source @@ -1217,11 +1267,14 @@ class PluginManagerPlugin( "reason": "Pip reported a Python version mismatch", "faq": "https://faq.octoprint.org/plugin-python-mismatch", } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result # noinspection DuplicatedCode - def _command_install_pythonfile(self, path, source=None, source_type=None, name=None): + def _command_install_pythonfile( + self, path, source=None, source_type=None, name=None, send_notifications=True + ): if name is None: name = os.path.basename(path) @@ -1250,7 +1303,8 @@ class PluginManagerPlugin( ) ) result = PYTHON_MISMATCH - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result pythoncompat = metadata.get( @@ -1264,7 +1318,8 @@ class PluginManagerPlugin( ) ) result = PYTHON_MISMATCH - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result # copy plugin @@ -1279,7 +1334,8 @@ class PluginManagerPlugin( "source_type": source_type, "reason": "Plugin could not be copied", } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False) @@ -1299,7 +1355,8 @@ class PluginManagerPlugin( "was_reinstalled": False, "plugin": "unknown", } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) return result self._plugin_manager.reload_plugins() @@ -1343,7 +1400,96 @@ class PluginManagerPlugin( "was_reinstalled": new_plugin.key in all_plugins_before, "plugin": self._to_external_plugin(new_plugin), } - self._send_result_notification("install", result) + if send_notifications: + self._send_result_notification("install", result) + return result + + def _command_install_jsonfile( + self, path, source=None, source_type=None, name=None, send_notifications=True + ): + import json + + sub_results = [] + + try: + if not self._jsoninstall_lock.acquire(blocking=False): + self._logger.error( + "Attempting to install from json file from within an install running from a json install - this is not supported" + ) + result = { + "result": False, + "source": source, + "source_type": source_type, + "reason": "Recursive json install", + } + if send_notifications: + self._send_result_notification("install", result) + return result + + if name is None: + name = os.path.basename(path) + + self._logger.info(f"Installing plugins from export {name} from {source}") + + with open(path) as f: + export = json.load(f) + + if not isinstance(export, list): + self._logger.error( + f"Installing plugins from export {name} from {source} failed, export is not a list" + ) + result = { + "result": False, + "source": source, + "source_type": source_type, + "reason": "Invalid export", + } + if send_notifications: + self._send_result_notification("install", result) + return result + + for entry in export: + if isinstance(entry, dict): + archive = entry.get("archive") + name = None + + if archive is None: + if not self._repository_available: + continue + key = entry.get("key") + if not key: + continue + repo_entry = self._repository_plugins_by_id.get(key) + if not repo_entry: + continue + archive = repo_entry.get("archive") + if not archive: + continue + + elif isinstance(entry, str): + # just a URL? + archive = entry + + try: + self._logger.info(f"Installing plugin from {archive}") + sub_result = self.command_install(url=archive, name=name) + sub_results.append(sub_result) + + except Exception: + self._logger.exception( + f"Installing plugin from {archive} failed, continuing with next entry" + ) + finally: + self._jsoninstall_lock.release() + + result = { + "result": True, + "source": source, + "source_type": source_type, + "sub_results": sub_results, + } + if send_notifications: + self._send_result_notification("install", result) return result def command_uninstall(self, plugin, cleanup=False): @@ -1912,6 +2058,7 @@ class PluginManagerPlugin( self._repository_plugins = list( filter(lambda x: x is not None, map(map_repository_entry, repo_data)) ) + self._repository_plugins_by_id = {x["id"]: x for x in self._repository_plugins} return True def _is_notices_cache_valid(self, mtime=None): @@ -2089,7 +2236,11 @@ class PluginManagerPlugin( @staticmethod def generate_plugins_json( - settings, plugin_manager, ignore_bundled=True, ignore_plugins_folder=True + settings, + plugin_manager, + ignore_bundled=True, + ignore_plugins_folder=True, + repo_plugins=None, ): plugins = [] plugin_folder = settings.getBaseFolder("plugins") @@ -2102,7 +2253,10 @@ class PluginManagerPlugin( # ignore bundled or from the plugins folder already included in the backup continue - plugins.append({"key": plugin.key, "name": plugin.name, "url": plugin.url}) + data = {"key": plugin.key, "name": plugin.name, "url": plugin.url} + if repo_plugins and plugin.key in repo_plugins: + data["archive"] = repo_plugins[plugin.key]["archive"] + plugins.append(data) return plugins def _to_external_plugin(self, plugin): diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 6afae8e33..d7f79dd42 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -212,6 +212,7 @@ $(function () { self.online = ko.observable(); self.supportedArchiveExtensions = ko.observableArray([]); self.supportedPythonExtensions = ko.observableArray([]); + self.supportedJsonExtensions = ko.observableArray([]); var createExtensionsHelp = function (extensions) { return _.reduce( @@ -235,15 +236,21 @@ $(function () { self.supportedExtensionsHelp = ko.pureComputed(function () { var archiveExts = createExtensionsHelp(self.supportedArchiveExtensions()); var pythonExts = createExtensionsHelp(self.supportedPythonExtensions()); + var jsonExts = createExtensionsHelp(self.supportedJsonExtensions()); return _.sprintf( gettext( "This does not look like a valid plugin. Valid plugins should be " + "either archives installable via pip that " + "have the extension %(archiveExtensions)s, or single file python " + - "plugins with the extension %(pythonExtensions)s." + "plugins with the extension %(pythonExtensions)s, or a plugin list " + + "export with the extension %(jsonExtensions)s." ), - {archiveExtensions: archiveExts, pythonExtensions: pythonExts} + { + archiveExtensions: archiveExts, + pythonExtensions: pythonExts, + jsonExtensions: jsonExts + } ); }); @@ -432,7 +439,8 @@ $(function () { self.invalidFile = ko.pureComputed(function () { var allowedFileExtensions = self .supportedArchiveExtensions() - .concat(self.supportedPythonExtensions()); + .concat(self.supportedPythonExtensions()) + .concat(self.supportedJsonExtensions()); var name = self.uploadFilename(); var lowerName = name !== undefined ? name.toLocaleLowerCase() : undefined; @@ -736,6 +744,7 @@ $(function () { if (!data) return; self.supportedArchiveExtensions(data.archive || []); self.supportedPythonExtensions(data.python || []); + self.supportedJsonExtensions(data.json || []); }; self.dataPluginsDeferred = undefined; @@ -1618,7 +1627,9 @@ $(function () { self._processPluginManagementResult = function (response, action, plugin) { if (response.result) { - if (self.queuedInstalls().length > 0 && action === "install") { + if (response.subResults) { + self._markDone(); + } else if (self.queuedInstalls().length > 0 && action === "install") { var plugin_dequeue = ko.utils.arrayFirst( self.queuedInstalls(), function (item) { @@ -1642,10 +1653,35 @@ $(function () { self._markDone(response.reason, response.faq); } - self._displayPluginManagementNotification(response, action, plugin); + if (response.sub_results) { + _.each(response.sub_results, (result) => { + var {action, name} = self._extractActionAndNameFromResult(result); + self._addPluginManagementLog(result, action, name); + }); + self._displayPluginManagementNotification(); + } else { + self._addPluginManagementLog(response, action, plugin); + self._displayPluginManagementNotification(); + } }; - self._displayPluginManagementNotification = function (response, action, plugin) { + self._extractActionAndNameFromResult = function (result) { + var action = result.action; + var name = "Unknown"; + if (result.hasOwnProperty("plugin")) { + if (result.plugin !== "unknown") { + if (_.isPlainObject(result.plugin)) { + name = result.plugin.name; + } else { + name = result.plugin; + } + } + } + + return {action: action, name: name}; + }; + + self._addPluginManagementLog = function (response, action, plugin) { self.logContents.action.restart = self.logContents.action.restart || response.needs_restart; self.logContents.action.refresh = @@ -1658,7 +1694,9 @@ $(function () { result: response.result, faq: response.faq }); + }; + self._displayPluginManagementNotification = function () { var title = gettext("Plugin management log"); var text = "