CuraPackageManager.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Optional
  4. import json
  5. import os
  6. import shutil
  7. import zipfile
  8. import tempfile
  9. from PyQt5.QtCore import pyqtSlot, QObject, pyqtSignal
  10. from UM.Application import Application
  11. from UM.Logger import Logger
  12. from UM.Resources import Resources
  13. from UM.Version import Version
  14. class CuraPackageManager(QObject):
  15. Version = 1
  16. # The prefix that's added to all files for an installed package to avoid naming conflicts with user created
  17. # files.
  18. PREFIX_PLACE_HOLDER = "-CP;"
  19. def __init__(self, parent = None):
  20. super().__init__(parent)
  21. self._application = parent
  22. self._container_registry = self._application.getContainerRegistry()
  23. self._plugin_registry = self._application.getPluginRegistry()
  24. # JSON file that keeps track of all installed packages.
  25. self._package_management_file_path = os.path.join(os.path.abspath(Resources.getDataStoragePath()),
  26. "packages.json")
  27. self._installed_package_dict = {} # a dict of all installed packages
  28. self._to_remove_package_set = set() # a set of packages that need to be removed at the next start
  29. self._to_install_package_dict = {} # a dict of packages that need to be installed at the next start
  30. installedPackagesChanged = pyqtSignal() # Emitted whenever the installed packages collection have been changed.
  31. def initialize(self):
  32. self._loadManagementData()
  33. self._removeAllScheduledPackages()
  34. self._installAllScheduledPackages()
  35. # (for initialize) Loads the package management file if exists
  36. def _loadManagementData(self) -> None:
  37. if not os.path.exists(self._package_management_file_path):
  38. Logger.log("i", "Package management file %s doesn't exist, do nothing", self._package_management_file_path)
  39. return
  40. # Need to use the file lock here to prevent concurrent I/O from other processes/threads
  41. container_registry = self._application.getContainerRegistry()
  42. with container_registry.lockFile():
  43. with open(self._package_management_file_path, "r", encoding = "utf-8") as f:
  44. management_dict = json.load(f, encoding = "utf-8")
  45. self._installed_package_dict = management_dict.get("installed", {})
  46. self._to_remove_package_set = set(management_dict.get("to_remove", []))
  47. self._to_install_package_dict = management_dict.get("to_install", {})
  48. Logger.log("i", "Package management file %s is loaded", self._package_management_file_path)
  49. def _saveManagementData(self) -> None:
  50. # Need to use the file lock here to prevent concurrent I/O from other processes/threads
  51. container_registry = self._application.getContainerRegistry()
  52. with container_registry.lockFile():
  53. with open(self._package_management_file_path, "w", encoding = "utf-8") as f:
  54. data_dict = {"version": CuraPackageManager.Version,
  55. "installed": self._installed_package_dict,
  56. "to_remove": list(self._to_remove_package_set),
  57. "to_install": self._to_install_package_dict}
  58. data_dict["to_remove"] = list(data_dict["to_remove"])
  59. json.dump(data_dict, f)
  60. Logger.log("i", "Package management file %s is saved", self._package_management_file_path)
  61. # (for initialize) Removes all packages that have been scheduled to be removed.
  62. def _removeAllScheduledPackages(self) -> None:
  63. for package_id in self._to_remove_package_set:
  64. self._purgePackage(package_id)
  65. self._to_remove_package_set.clear()
  66. self._saveManagementData()
  67. # (for initialize) Installs all packages that have been scheduled to be installed.
  68. def _installAllScheduledPackages(self) -> None:
  69. for package_id, installation_package_data in self._to_install_package_dict.items():
  70. self._installPackage(installation_package_data)
  71. self._to_install_package_dict.clear()
  72. self._saveManagementData()
  73. # Checks the given package is installed. If so, return a dictionary that contains the package's information.
  74. def getInstalledPackageInfo(self, package_id: str) -> Optional[dict]:
  75. if package_id in self._to_remove_package_set:
  76. return None
  77. if package_id in self._to_install_package_dict:
  78. package_info = self._to_install_package_dict[package_id]["package_info"]
  79. package_info["is_bundled"] = False
  80. return package_info
  81. if package_id in self._installed_package_dict:
  82. package_info = self._installed_package_dict.get(package_id)
  83. package_info["is_bundled"] = False
  84. return package_info
  85. for section, packages in self.getAllInstalledPackagesInfo().items():
  86. for package in packages:
  87. if package["package_id"] == package_id:
  88. package_info = package
  89. return package_info
  90. return None
  91. def getAllInstalledPackagesInfo(self) -> dict:
  92. installed_package_id_set = set(self._installed_package_dict.keys()) | set(self._to_install_package_dict.keys())
  93. installed_package_id_set = installed_package_id_set.difference(self._to_remove_package_set)
  94. managed_package_id_set = set(installed_package_id_set) | self._to_remove_package_set
  95. # TODO: For absolutely no reason, this function seems to run in a loop
  96. # even though no loop is ever called with it.
  97. # map of <package_type> -> <package_id> -> <package_info>
  98. installed_packages_dict = {}
  99. for package_id in installed_package_id_set:
  100. if package_id in Application.getInstance().getRequiredPlugins():
  101. continue
  102. if package_id in self._to_install_package_dict:
  103. package_info = self._to_install_package_dict[package_id]["package_info"]
  104. else:
  105. package_info = self._installed_package_dict[package_id]
  106. package_info["is_bundled"] = False
  107. package_type = package_info["package_type"]
  108. if package_type not in installed_packages_dict:
  109. installed_packages_dict[package_type] = []
  110. installed_packages_dict[package_type].append( package_info )
  111. # We also need to get information from the plugin registry such as if a plugin is active
  112. package_info["is_active"] = self._plugin_registry.isActivePlugin(package_id)
  113. # Also get all bundled plugins
  114. all_metadata = self._plugin_registry.getAllMetaData()
  115. for item in all_metadata:
  116. plugin_package_info = self.__convertPluginMetadataToPackageMetadata(item)
  117. # Only gather the bundled plugins here.
  118. package_id = plugin_package_info["package_id"]
  119. if package_id in managed_package_id_set:
  120. continue
  121. if package_id in Application.getInstance().getRequiredPlugins():
  122. continue
  123. plugin_package_info["is_bundled"] = True if plugin_package_info["author"]["display_name"] == "Ultimaker B.V." else False
  124. plugin_package_info["is_active"] = self._plugin_registry.isActivePlugin(package_id)
  125. package_type = "plugin"
  126. if package_type not in installed_packages_dict:
  127. installed_packages_dict[package_type] = []
  128. installed_packages_dict[package_type].append( plugin_package_info )
  129. return installed_packages_dict
  130. def __convertPluginMetadataToPackageMetadata(self, plugin_metadata: dict) -> dict:
  131. package_metadata = {
  132. "package_id": plugin_metadata["id"],
  133. "package_type": "plugin",
  134. "display_name": plugin_metadata["plugin"]["name"],
  135. "description": plugin_metadata["plugin"].get("description"),
  136. "package_version": plugin_metadata["plugin"]["version"],
  137. "cura_version": int(plugin_metadata["plugin"]["api"]),
  138. "website": "",
  139. "author_id": plugin_metadata["plugin"].get("author", "UnknownID"),
  140. "author": {
  141. "author_id": plugin_metadata["plugin"].get("author", "UnknownID"),
  142. "display_name": plugin_metadata["plugin"].get("author", ""),
  143. "email": "",
  144. "website": "",
  145. },
  146. "tags": ["plugin"],
  147. }
  148. return package_metadata
  149. # Checks if the given package is installed.
  150. def isPackageInstalled(self, package_id: str) -> bool:
  151. return self.getInstalledPackageInfo(package_id) is not None
  152. # Schedules the given package file to be installed upon the next start.
  153. @pyqtSlot(str)
  154. def installPackage(self, filename: str) -> None:
  155. # Get package information
  156. package_info = self.getPackageInfo(filename)
  157. package_id = package_info["package_id"]
  158. has_changes = False
  159. # Check the delayed installation and removal lists first
  160. if package_id in self._to_remove_package_set:
  161. self._to_remove_package_set.remove(package_id)
  162. has_changes = True
  163. # Check if it is installed
  164. installed_package_info = self.getInstalledPackageInfo(package_info["package_id"])
  165. to_install_package = installed_package_info is None # Install if the package has not been installed
  166. if installed_package_info is not None:
  167. # Compare versions and only schedule the installation if the given package is newer
  168. new_version = package_info["package_version"]
  169. installed_version = installed_package_info["package_version"]
  170. if Version(new_version) > Version(installed_version):
  171. Logger.log("i", "Package [%s] version [%s] is newer than the installed version [%s], update it.",
  172. package_id, new_version, installed_version)
  173. to_install_package = True
  174. if to_install_package:
  175. Logger.log("i", "Package [%s] version [%s] is scheduled to be installed.",
  176. package_id, package_info["package_version"])
  177. # Copy the file to cache dir so we don't need to rely on the original file to be present
  178. package_cache_dir = os.path.join(os.path.abspath(Resources.getCacheStoragePath()), "cura_packages")
  179. if not os.path.exists(package_cache_dir):
  180. os.makedirs(package_cache_dir, exist_ok=True)
  181. target_file_path = os.path.join(package_cache_dir, package_id + ".curapackage")
  182. shutil.copy2(filename, target_file_path)
  183. self._to_install_package_dict[package_id] = {"package_info": package_info,
  184. "filename": target_file_path}
  185. has_changes = True
  186. self._saveManagementData()
  187. if has_changes:
  188. self.installedPackagesChanged.emit()
  189. # Schedules the given package to be removed upon the next start.
  190. @pyqtSlot(str)
  191. def removePackage(self, package_id: str) -> None:
  192. # Check the delayed installation and removal lists first
  193. if not self.isPackageInstalled(package_id):
  194. Logger.log("i", "Attempt to remove package [%s] that is not installed, do nothing.", package_id)
  195. return
  196. # Remove from the delayed installation list if present
  197. if package_id in self._to_install_package_dict:
  198. del self._to_install_package_dict[package_id]
  199. # Schedule for a delayed removal:
  200. self._to_remove_package_set.add(package_id)
  201. self._saveManagementData()
  202. self.installedPackagesChanged.emit()
  203. # Removes everything associated with the given package ID.
  204. def _purgePackage(self, package_id: str) -> None:
  205. # Iterate through all directories in the data storage directory and look for sub-directories that belong to
  206. # the package we need to remove, that is the sub-dirs with the package_id as names, and remove all those dirs.
  207. data_storage_dir = os.path.abspath(Resources.getDataStoragePath())
  208. for root, dir_names, _ in os.walk(data_storage_dir):
  209. for dir_name in dir_names:
  210. package_dir = os.path.join(root, dir_name, package_id)
  211. if os.path.exists(package_dir):
  212. Logger.log("i", "Removing '%s' for package [%s]", package_dir, package_id)
  213. shutil.rmtree(package_dir)
  214. break
  215. # Installs all files associated with the given package.
  216. def _installPackage(self, installation_package_data: dict):
  217. package_info = installation_package_data["package_info"]
  218. filename = installation_package_data["filename"]
  219. package_id = package_info["package_id"]
  220. if not os.path.exists(filename):
  221. Logger.log("w", "Package [%s] file '%s' is missing, cannot install this package", package_id, filename)
  222. return
  223. Logger.log("i", "Installing package [%s] from file [%s]", package_id, filename)
  224. # If it's installed, remove it first and then install
  225. if package_id in self._installed_package_dict:
  226. self._purgePackage(package_id)
  227. # Install the package
  228. archive = zipfile.ZipFile(filename, "r")
  229. temp_dir = tempfile.TemporaryDirectory()
  230. archive.extractall(temp_dir.name)
  231. from cura.CuraApplication import CuraApplication
  232. installation_dirs_dict = {
  233. "materials": Resources.getStoragePath(CuraApplication.ResourceTypes.MaterialInstanceContainer),
  234. "quality": Resources.getStoragePath(CuraApplication.ResourceTypes.QualityInstanceContainer),
  235. "plugins": os.path.abspath(Resources.getStoragePath(Resources.Plugins)),
  236. }
  237. for sub_dir_name, installation_root_dir in installation_dirs_dict.items():
  238. src_dir_path = os.path.join(temp_dir.name, "files", sub_dir_name)
  239. dst_dir_path = os.path.join(installation_root_dir, package_id)
  240. if not os.path.exists(src_dir_path):
  241. continue
  242. # Need to rename the container files so they don't get ID conflicts
  243. to_rename_files = sub_dir_name not in ("plugins",)
  244. self.__installPackageFiles(package_id, src_dir_path, dst_dir_path, need_to_rename_files= to_rename_files)
  245. archive.close()
  246. # Remove the file
  247. os.remove(filename)
  248. def __installPackageFiles(self, package_id: str, src_dir: str, dst_dir: str, need_to_rename_files: bool = True) -> None:
  249. shutil.move(src_dir, dst_dir)
  250. # Rename files if needed
  251. if not need_to_rename_files:
  252. return
  253. for root, _, file_names in os.walk(dst_dir):
  254. for filename in file_names:
  255. new_filename = self.PREFIX_PLACE_HOLDER + package_id + "-" + filename
  256. old_file_path = os.path.join(root, filename)
  257. new_file_path = os.path.join(root, new_filename)
  258. os.rename(old_file_path, new_file_path)
  259. # Gets package information from the given file.
  260. def getPackageInfo(self, filename: str) -> dict:
  261. archive = zipfile.ZipFile(filename, "r")
  262. try:
  263. # All information is in package.json
  264. with archive.open("package.json", "r") as f:
  265. package_info_dict = json.loads(f.read().decode("utf-8"))
  266. return package_info_dict
  267. except Exception as e:
  268. raise RuntimeError("Could not get package information from file '%s': %s" % (filename, e))
  269. finally:
  270. archive.close()
  271. # Gets the license file content if present in the given package file.
  272. # Returns None if there is no license file found.
  273. def getPackageLicense(self, filename: str) -> Optional[str]:
  274. license_string = None
  275. archive = zipfile.ZipFile(filename)
  276. try:
  277. # Go through all the files and use the first successful read as the result
  278. for file_info in archive.infolist():
  279. if file_info.is_dir() or not file_info.filename.startswith("files/"):
  280. continue
  281. filename_parts = os.path.basename(file_info.filename.lower()).split(".")
  282. stripped_filename = filename_parts[0]
  283. if stripped_filename in ("license", "licence"):
  284. Logger.log("i", "Found potential license file '%s'", file_info.filename)
  285. try:
  286. with archive.open(file_info.filename, "r") as f:
  287. data = f.read()
  288. license_string = data.decode("utf-8")
  289. break
  290. except:
  291. Logger.logException("e", "Failed to load potential license file '%s' as text file.",
  292. file_info.filename)
  293. license_string = None
  294. except Exception as e:
  295. raise RuntimeError("Could not get package license from file '%s': %s" % (filename, e))
  296. finally:
  297. archive.close()
  298. return license_string