CuraPackageManager.py 18 KB

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