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