CuraPackageManager.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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, QUrl
  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. def __init__(self, parent = None):
  17. super().__init__(parent)
  18. self._application = Application.getInstance()
  19. self._container_registry = self._application.getContainerRegistry()
  20. self._plugin_registry = self._application.getPluginRegistry()
  21. #JSON files that keep track of all installed packages.
  22. self._user_package_management_file_path = None
  23. self._bundled_package_management_file_path = None
  24. for search_path in Resources.getSearchPaths():
  25. candidate_bundled_path = os.path.join(search_path, "bundled_packages.json")
  26. if os.path.exists(candidate_bundled_path):
  27. self._bundled_package_management_file_path = candidate_bundled_path
  28. for search_path in (Resources.getDataStoragePath(), Resources.getConfigStoragePath()):
  29. candidate_user_path = os.path.join(search_path, "packages.json")
  30. if os.path.exists(candidate_user_path):
  31. self._user_package_management_file_path = candidate_user_path
  32. if self._user_package_management_file_path is None: #Doesn't exist yet.
  33. self._user_package_management_file_path = os.path.join(Resources.getDataStoragePath(), "packages.json")
  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. # The bundles package management file should always be there
  46. if not os.path.exists(self._bundled_package_management_file_path):
  47. Logger.log("w", "Bundled package management file could not be found!")
  48. return
  49. # Load the bundled packages:
  50. with open(self._bundled_package_management_file_path, "r", encoding = "utf-8") as f:
  51. self._bundled_package_dict = json.load(f, encoding = "utf-8")
  52. Logger.log("i", "Loaded bundled packages data from %s", self._bundled_package_management_file_path)
  53. # Load the user package management file
  54. if not os.path.exists(self._user_package_management_file_path):
  55. Logger.log("i", "User package management file %s doesn't exist, do nothing", self._user_package_management_file_path)
  56. return
  57. # Need to use the file lock here to prevent concurrent I/O from other processes/threads
  58. container_registry = self._application.getContainerRegistry()
  59. with container_registry.lockFile():
  60. # Load the user packages:
  61. with open(self._user_package_management_file_path, "r", encoding="utf-8") as f:
  62. management_dict = json.load(f, encoding="utf-8")
  63. self._installed_package_dict = management_dict.get("installed", {})
  64. self._to_remove_package_set = set(management_dict.get("to_remove", []))
  65. self._to_install_package_dict = management_dict.get("to_install", {})
  66. Logger.log("i", "Loaded user packages management file from %s", self._user_package_management_file_path)
  67. def _saveManagementData(self) -> None:
  68. # Need to use the file lock here to prevent concurrent I/O from other processes/threads
  69. container_registry = self._application.getContainerRegistry()
  70. with container_registry.lockFile():
  71. with open(self._user_package_management_file_path, "w", encoding = "utf-8") as f:
  72. data_dict = {"version": CuraPackageManager.Version,
  73. "installed": self._installed_package_dict,
  74. "to_remove": list(self._to_remove_package_set),
  75. "to_install": self._to_install_package_dict}
  76. json.dump(data_dict, f, sort_keys = True, indent = 4)
  77. Logger.log("i", "Package management file %s was saved", self._user_package_management_file_path)
  78. # (for initialize) Removes all packages that have been scheduled to be removed.
  79. def _removeAllScheduledPackages(self) -> None:
  80. remove_failures = set()
  81. for package_id in self._to_remove_package_set:
  82. try:
  83. self._purgePackage(package_id)
  84. del self._installed_package_dict[package_id]
  85. except:
  86. remove_failures.add(package_id)
  87. Logger.log("e", "There was an error uninstalling the package {package}".format(package = package_id))
  88. self._to_remove_package_set = remove_failures
  89. self._saveManagementData()
  90. # (for initialize) Installs all packages that have been scheduled to be installed.
  91. def _installAllScheduledPackages(self) -> None:
  92. while self._to_install_package_dict:
  93. package_id, package_info = list(self._to_install_package_dict.items())[0]
  94. self._installPackage(package_info)
  95. del self._to_install_package_dict[package_id]
  96. self._saveManagementData()
  97. def getBundledPackageInfo(self, package_id: str) -> Optional[dict]:
  98. package_info = None
  99. if package_id in self._bundled_package_dict:
  100. package_info = self._bundled_package_dict[package_id]["package_info"]
  101. return package_info
  102. # Checks the given package is installed. If so, return a dictionary that contains the package's information.
  103. def getInstalledPackageInfo(self, package_id: str) -> Optional[dict]:
  104. if package_id in self._to_remove_package_set:
  105. return None
  106. if package_id in self._to_install_package_dict:
  107. package_info = self._to_install_package_dict[package_id]["package_info"]
  108. return package_info
  109. if package_id in self._installed_package_dict:
  110. package_info = self._installed_package_dict[package_id]["package_info"]
  111. return package_info
  112. if package_id in self._bundled_package_dict:
  113. package_info = self._bundled_package_dict[package_id]["package_info"]
  114. return package_info
  115. return None
  116. def getAllInstalledPackageIDs(self) -> set:
  117. # Add bundled, installed, and to-install packages to the set of installed package IDs
  118. all_installed_ids = set()
  119. if self._bundled_package_dict.keys():
  120. all_installed_ids = all_installed_ids.union(set(self._bundled_package_dict.keys()))
  121. if self._installed_package_dict.keys():
  122. all_installed_ids = all_installed_ids.union(set(self._installed_package_dict.keys()))
  123. all_installed_ids = all_installed_ids.difference(self._to_remove_package_set)
  124. # If it's going to be installed and to be removed, then the package is being updated and it should be listed.
  125. if self._to_install_package_dict.keys():
  126. all_installed_ids = all_installed_ids.union(set(self._to_install_package_dict.keys()))
  127. return all_installed_ids
  128. def getAllInstalledPackagesInfo(self) -> dict:
  129. all_installed_ids = self.getAllInstalledPackageIDs()
  130. # map of <package_type> -> <package_id> -> <package_info>
  131. installed_packages_dict = {}
  132. for package_id in all_installed_ids:
  133. # Skip required plugins as they should not be tampered with
  134. if package_id in Application.getInstance().getRequiredPlugins():
  135. continue
  136. package_info = None
  137. # Add bundled plugins
  138. if package_id in self._bundled_package_dict:
  139. package_info = self._bundled_package_dict[package_id]["package_info"]
  140. package_info["is_installed"] = True
  141. # Add installed plugins
  142. if package_id in self._installed_package_dict:
  143. package_info = self._installed_package_dict[package_id]["package_info"]
  144. package_info["is_installed"] = True
  145. # Add to install plugins
  146. if package_id in self._to_install_package_dict:
  147. package_info = self._to_install_package_dict[package_id]["package_info"]
  148. package_info["is_installed"] = False
  149. if package_info is None:
  150. continue
  151. # We also need to get information from the plugin registry such as if a plugin is active
  152. package_info["is_active"] = self._plugin_registry.isActivePlugin(package_id)
  153. # If the package ID is in bundled, label it as such
  154. package_info["is_bundled"] = package_info["package_id"] in self._bundled_package_dict.keys() and not self.isUserInstalledPackage(package_info["package_id"])
  155. # If there is not a section in the dict for this type, add it
  156. if package_info["package_type"] not in installed_packages_dict:
  157. installed_packages_dict[package_info["package_type"]] = []
  158. # Finally, add the data
  159. installed_packages_dict[package_info["package_type"]].append(package_info)
  160. return installed_packages_dict
  161. # Checks if the given package is installed (at all).
  162. def isPackageInstalled(self, package_id: str) -> bool:
  163. return self.getInstalledPackageInfo(package_id) is not None
  164. # This is called by drag-and-dropping curapackage files.
  165. @pyqtSlot(QUrl)
  166. def installPackageViaDragAndDrop(self, file_url: str) -> None:
  167. filename = QUrl(file_url).toLocalFile()
  168. return self.installPackage(filename)
  169. # Schedules the given package file to be installed upon the next start.
  170. @pyqtSlot(str)
  171. def installPackage(self, filename: str) -> None:
  172. has_changes = False
  173. try:
  174. # Get package information
  175. package_info = self.getPackageInfo(filename)
  176. if not package_info:
  177. return
  178. package_id = package_info["package_id"]
  179. # Check if it is installed
  180. installed_package_info = self.getInstalledPackageInfo(package_info["package_id"])
  181. to_install_package = installed_package_info is None # Install if the package has not been installed
  182. if installed_package_info is not None:
  183. # Compare versions and only schedule the installation if the given package is newer
  184. new_version = package_info["package_version"]
  185. installed_version = installed_package_info["package_version"]
  186. if Version(new_version) > Version(installed_version):
  187. Logger.log("i", "Package [%s] version [%s] is newer than the installed version [%s], update it.",
  188. package_id, new_version, installed_version)
  189. to_install_package = True
  190. if to_install_package:
  191. # Need to use the lock file to prevent concurrent I/O issues.
  192. with self._container_registry.lockFile():
  193. Logger.log("i", "Package [%s] version [%s] is scheduled to be installed.",
  194. package_id, package_info["package_version"])
  195. # Copy the file to cache dir so we don't need to rely on the original file to be present
  196. package_cache_dir = os.path.join(os.path.abspath(Resources.getCacheStoragePath()), "cura_packages")
  197. if not os.path.exists(package_cache_dir):
  198. os.makedirs(package_cache_dir, exist_ok=True)
  199. target_file_path = os.path.join(package_cache_dir, package_id + ".curapackage")
  200. shutil.copy2(filename, target_file_path)
  201. self._to_install_package_dict[package_id] = {"package_info": package_info,
  202. "filename": target_file_path}
  203. has_changes = True
  204. except:
  205. Logger.logException("c", "Failed to install package file '%s'", filename)
  206. finally:
  207. self._saveManagementData()
  208. if has_changes:
  209. self.installedPackagesChanged.emit()
  210. # Schedules the given package to be removed upon the next start.
  211. # \param package_id id of the package
  212. # \param force_add is used when updating. In that case you actually want to uninstall & install
  213. @pyqtSlot(str)
  214. def removePackage(self, package_id: str, force_add: bool = False) -> None:
  215. # Check the delayed installation and removal lists first
  216. if not self.isPackageInstalled(package_id):
  217. Logger.log("i", "Attempt to remove package [%s] that is not installed, do nothing.", package_id)
  218. return
  219. # Extra safety check
  220. if package_id not in self._installed_package_dict and package_id in self._bundled_package_dict:
  221. Logger.log("i", "Not uninstalling [%s] because it is a bundled package.")
  222. return
  223. if package_id not in self._to_install_package_dict or force_add:
  224. # Schedule for a delayed removal:
  225. self._to_remove_package_set.add(package_id)
  226. else:
  227. if package_id in self._to_install_package_dict:
  228. # Remove from the delayed installation list if present
  229. del self._to_install_package_dict[package_id]
  230. self._saveManagementData()
  231. self.installedPackagesChanged.emit()
  232. ## Is the package an user installed package?
  233. def isUserInstalledPackage(self, package_id: str):
  234. return package_id in self._installed_package_dict
  235. ## Removes everything associated with the given package ID.
  236. # \return It may produce an exception if the user has no permissions to delete this files (on Windows).
  237. # This exception must be catched.
  238. def _purgePackage(self, package_id: str) -> None:
  239. # Iterate through all directories in the data storage directory and look for sub-directories that belong to
  240. # the package we need to remove, that is the sub-dirs with the package_id as names, and remove all those dirs.
  241. data_storage_dir = os.path.abspath(Resources.getDataStoragePath())
  242. for root, dir_names, _ in os.walk(data_storage_dir):
  243. for dir_name in dir_names:
  244. package_dir = os.path.join(root, dir_name, package_id)
  245. if os.path.exists(package_dir):
  246. Logger.log("i", "Removing '%s' for package [%s]", package_dir, package_id)
  247. shutil.rmtree(package_dir)
  248. break
  249. # Installs all files associated with the given package.
  250. def _installPackage(self, installation_package_data: dict):
  251. package_info = installation_package_data["package_info"]
  252. filename = installation_package_data["filename"]
  253. package_id = package_info["package_id"]
  254. Logger.log("i", "Installing package [%s] from file [%s]", package_id, filename)
  255. # Load the cached package file and extract all contents to a temporary directory
  256. if not os.path.exists(filename):
  257. Logger.log("w", "Package [%s] file '%s' is missing, cannot install this package", package_id, filename)
  258. return
  259. try:
  260. with zipfile.ZipFile(filename, "r") as archive:
  261. temp_dir = tempfile.TemporaryDirectory()
  262. archive.extractall(temp_dir.name)
  263. except Exception:
  264. Logger.logException("e", "Failed to install package from file [%s]", filename)
  265. return
  266. from cura.CuraApplication import CuraApplication
  267. installation_dirs_dict = {
  268. "materials": Resources.getStoragePath(CuraApplication.ResourceTypes.MaterialInstanceContainer),
  269. "qualities": Resources.getStoragePath(CuraApplication.ResourceTypes.QualityInstanceContainer),
  270. "plugins": os.path.abspath(Resources.getStoragePath(Resources.Plugins)),
  271. }
  272. # Remove it first and then install
  273. try:
  274. self._purgePackage(package_id)
  275. except:
  276. Logger.log("e", "There was an error deleting the package {package} during updating.".format(package = package_id))
  277. return
  278. # Copy the folders there
  279. for sub_dir_name, installation_root_dir in installation_dirs_dict.items():
  280. src_dir_path = os.path.join(temp_dir.name, "files", sub_dir_name)
  281. dst_dir_path = os.path.join(installation_root_dir, package_id)
  282. if not os.path.exists(src_dir_path):
  283. continue
  284. self.__installPackageFiles(package_id, src_dir_path, dst_dir_path)
  285. # Remove the file
  286. try:
  287. os.remove(filename)
  288. except Exception:
  289. Logger.log("w", "Tried to delete file [%s], but it failed", filename)
  290. # Move the info to the installed list of packages only when it succeeds
  291. self._installed_package_dict[package_id] = self._to_install_package_dict[package_id]
  292. def __installPackageFiles(self, package_id: str, src_dir: str, dst_dir: str) -> None:
  293. Logger.log("i", "Moving package {package_id} from {src_dir} to {dst_dir}".format(package_id=package_id, src_dir=src_dir, dst_dir=dst_dir))
  294. shutil.move(src_dir, dst_dir)
  295. # Gets package information from the given file.
  296. def getPackageInfo(self, filename: str) -> Dict[str, Any]:
  297. if not os.path.exists(filename):
  298. Logger.log("w", "Package file '%s' is missing, cannot get info from this package", filename)
  299. return {}
  300. with zipfile.ZipFile(filename) as archive:
  301. try:
  302. # All information is in package.json
  303. with archive.open("package.json") as f:
  304. package_info_dict = json.loads(f.read().decode("utf-8"))
  305. return package_info_dict
  306. except Exception as e:
  307. Logger.logException("w", "Could not get package information from file '%s': %s" % (filename, e))
  308. return {}
  309. # Gets the license file content if present in the given package file.
  310. # Returns None if there is no license file found.
  311. def getPackageLicense(self, filename: str) -> Optional[str]:
  312. if not os.path.exists(filename):
  313. Logger.log("w", "Package file '%s' is missing, cannot get license from this package", filename)
  314. return None
  315. license_string = None
  316. with zipfile.ZipFile(filename) as archive:
  317. # Go through all the files and use the first successful read as the result
  318. for file_info in archive.infolist():
  319. if file_info.filename.endswith("LICENSE"):
  320. Logger.log("d", "Found potential license file '%s'", file_info.filename)
  321. try:
  322. with archive.open(file_info.filename, "r") as f:
  323. data = f.read()
  324. license_string = data.decode("utf-8")
  325. break
  326. except:
  327. Logger.logException("e", "Failed to load potential license file '%s' as text file.",
  328. file_info.filename)
  329. license_string = None
  330. return license_string