Toolbox.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Toolbox is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import os
  5. import tempfile
  6. import platform
  7. from typing import cast, Any, Dict, List, Set, TYPE_CHECKING, Tuple, Optional, Union
  8. from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, pyqtSlot
  9. from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
  10. from UM.Logger import Logger
  11. from UM.PluginRegistry import PluginRegistry
  12. from UM.Extension import Extension
  13. from UM.i18n import i18nCatalog
  14. from UM.Version import Version
  15. from UM.Message import Message
  16. from cura import ApplicationMetadata
  17. from cura import UltimakerCloudAuthentication
  18. from cura.CuraApplication import CuraApplication
  19. from cura.Machines.ContainerTree import ContainerTree
  20. from .AuthorsModel import AuthorsModel
  21. from .PackagesModel import PackagesModel
  22. from .SubscribedPackagesModel import SubscribedPackagesModel
  23. if TYPE_CHECKING:
  24. from UM.TaskManagement.HttpRequestData import HttpRequestData
  25. from cura.Settings.GlobalStack import GlobalStack
  26. i18n_catalog = i18nCatalog("cura")
  27. ## The Toolbox class is responsible of communicating with the server through the API
  28. class Toolbox(QObject, Extension):
  29. def __init__(self, application: CuraApplication) -> None:
  30. super().__init__()
  31. self._application = application # type: CuraApplication
  32. self._sdk_version = ApplicationMetadata.CuraSDKVersion # type: Union[str, int]
  33. self._cloud_api_version = UltimakerCloudAuthentication.CuraCloudAPIVersion # type: str
  34. self._cloud_api_root = UltimakerCloudAuthentication.CuraCloudAPIRoot # type: str
  35. self._api_url = None # type: Optional[str]
  36. # Network:
  37. self._download_request_data = None # type: Optional[HttpRequestData]
  38. self._download_progress = 0 # type: float
  39. self._is_downloading = False # type: bool
  40. self._request_headers = dict() # type: Dict[str, str]
  41. self._updateRequestHeader()
  42. self._request_urls = {} # type: Dict[str, str]
  43. self._to_update = [] # type: List[str] # Package_ids that are waiting to be updated
  44. self._old_plugin_ids = set() # type: Set[str]
  45. self._old_plugin_metadata = dict() # type: Dict[str, Dict[str, Any]]
  46. # The responses as given by the server parsed to a list.
  47. self._server_response_data = {
  48. "authors": [],
  49. "packages": [],
  50. "updates": [],
  51. "subscribed_packages": [],
  52. } # type: Dict[str, List[Any]]
  53. # Models:
  54. self._models = {
  55. "authors": AuthorsModel(self),
  56. "packages": PackagesModel(self),
  57. "updates": PackagesModel(self),
  58. "subscribed_packages": SubscribedPackagesModel(self),
  59. } # type: Dict[str, Union[AuthorsModel, PackagesModel, SubscribedPackagesModel]]
  60. self._plugins_showcase_model = PackagesModel(self)
  61. self._plugins_available_model = PackagesModel(self)
  62. self._plugins_installed_model = PackagesModel(self)
  63. self._materials_showcase_model = AuthorsModel(self)
  64. self._materials_available_model = AuthorsModel(self)
  65. self._materials_installed_model = PackagesModel(self)
  66. self._materials_generic_model = PackagesModel(self)
  67. # These properties are for keeping track of the UI state:
  68. # ----------------------------------------------------------------------
  69. # View category defines which filter to use, and therefore effectively
  70. # which category is currently being displayed. For example, possible
  71. # values include "plugin" or "material", but also "installed".
  72. self._view_category = "plugin" # type: str
  73. # View page defines which type of page layout to use. For example,
  74. # possible values include "overview", "detail" or "author".
  75. self._view_page = "welcome" # type: str
  76. # Active package refers to which package is currently being downloaded,
  77. # installed, or otherwise modified.
  78. self._active_package = None # type: Optional[Dict[str, Any]]
  79. self._dialog = None # type: Optional[QObject]
  80. self._confirm_reset_dialog = None # type: Optional[QObject]
  81. self._resetUninstallVariables()
  82. self._restart_required = False # type: bool
  83. # variables for the license agreement dialog
  84. self._license_dialog_plugin_name = "" # type: str
  85. self._license_dialog_license_content = "" # type: str
  86. self._license_dialog_plugin_file_location = "" # type: str
  87. self._restart_dialog_message = "" # type: str
  88. self._application.initializationFinished.connect(self._onAppInitialized)
  89. self._application.getCuraAPI().account.accessTokenChanged.connect(self._updateRequestHeader)
  90. # Signals:
  91. # --------------------------------------------------------------------------
  92. # Downloading changes
  93. activePackageChanged = pyqtSignal()
  94. onDownloadProgressChanged = pyqtSignal()
  95. onIsDownloadingChanged = pyqtSignal()
  96. restartRequiredChanged = pyqtSignal()
  97. installChanged = pyqtSignal()
  98. enabledChanged = pyqtSignal()
  99. # UI changes
  100. viewChanged = pyqtSignal()
  101. detailViewChanged = pyqtSignal()
  102. filterChanged = pyqtSignal()
  103. metadataChanged = pyqtSignal()
  104. showLicenseDialog = pyqtSignal()
  105. uninstallVariablesChanged = pyqtSignal()
  106. ## Go back to the start state (welcome screen or loading if no login required)
  107. def _restart(self):
  108. self._updateRequestHeader()
  109. # For an Essentials build, login is mandatory
  110. if not self._application.getCuraAPI().account.isLoggedIn and ApplicationMetadata.IsEnterpriseVersion:
  111. self.setViewPage("welcome")
  112. else:
  113. self.setViewPage("loading")
  114. self._fetchPackageData()
  115. def _updateRequestHeader(self):
  116. self._request_headers = {
  117. "User-Agent": "%s/%s (%s %s)" % (self._application.getApplicationName(),
  118. self._application.getVersion(),
  119. platform.system(),
  120. platform.machine())
  121. }
  122. access_token = self._application.getCuraAPI().account.accessToken
  123. if access_token:
  124. self._request_headers["Authorization"] = "Bearer {}".format(access_token)
  125. def _resetUninstallVariables(self) -> None:
  126. self._package_id_to_uninstall = None # type: Optional[str]
  127. self._package_name_to_uninstall = ""
  128. self._package_used_materials = [] # type: List[Tuple[GlobalStack, str, str]]
  129. self._package_used_qualities = [] # type: List[Tuple[GlobalStack, str, str]]
  130. @pyqtSlot(str, int)
  131. def ratePackage(self, package_id: str, rating: int) -> None:
  132. url = "{base_url}/packages/{package_id}/ratings".format(base_url = self._api_url, package_id = package_id)
  133. data = "{\"data\": {\"cura_version\": \"%s\", \"rating\": %i}}" % (Version(self._application.getVersion()), rating)
  134. self._application.getHttpRequestManager().put(url, headers_dict = self._request_headers,
  135. data = data.encode())
  136. @pyqtSlot(str)
  137. def subscribe(self, package_id: str) -> None:
  138. if self._application.getCuraAPI().account.isLoggedIn:
  139. data = "{\"data\": {\"package_id\": \"%s\", \"sdk_version\": \"%s\"}}" % (package_id, self._sdk_version)
  140. self._application.getHttpRequestManager().put(url=self._api_url_user_packages,
  141. headers_dict=self._request_headers,
  142. data=data.encode()
  143. )
  144. @pyqtSlot(result = str)
  145. def getLicenseDialogPluginName(self) -> str:
  146. return self._license_dialog_plugin_name
  147. @pyqtSlot(result = str)
  148. def getLicenseDialogPluginFileLocation(self) -> str:
  149. return self._license_dialog_plugin_file_location
  150. @pyqtSlot(result = str)
  151. def getLicenseDialogLicenseContent(self) -> str:
  152. return self._license_dialog_license_content
  153. def openLicenseDialog(self, plugin_name: str, license_content: str, plugin_file_location: str) -> None:
  154. self._license_dialog_plugin_name = plugin_name
  155. self._license_dialog_license_content = license_content
  156. self._license_dialog_plugin_file_location = plugin_file_location
  157. self.showLicenseDialog.emit()
  158. # This is a plugin, so most of the components required are not ready when
  159. # this is initialized. Therefore, we wait until the application is ready.
  160. def _onAppInitialized(self) -> None:
  161. self._plugin_registry = self._application.getPluginRegistry()
  162. self._package_manager = self._application.getPackageManager()
  163. self._api_url = "{cloud_api_root}/cura-packages/v{cloud_api_version}/cura/v{sdk_version}".format(
  164. cloud_api_root = self._cloud_api_root,
  165. cloud_api_version = self._cloud_api_version,
  166. sdk_version = self._sdk_version
  167. )
  168. # https://api.ultimaker.com/cura-packages/v1/user/packages
  169. self._api_url_user_packages = "{cloud_api_root}/cura-packages/v{cloud_api_version}/user/packages".format(
  170. cloud_api_root = self._cloud_api_root,
  171. cloud_api_version = self._cloud_api_version,
  172. )
  173. # We need to construct a query like installed_packages=ID:VERSION&installed_packages=ID:VERSION, etc.
  174. installed_package_ids_with_versions = [":".join(items) for items in
  175. self._package_manager.getAllInstalledPackageIdsAndVersions()]
  176. installed_packages_query = "&installed_packages=".join(installed_package_ids_with_versions)
  177. self._request_urls = {
  178. "authors": "{base_url}/authors".format(base_url = self._api_url),
  179. "packages": "{base_url}/packages".format(base_url = self._api_url),
  180. "updates": "{base_url}/packages/package-updates?installed_packages={query}".format(
  181. base_url = self._api_url, query = installed_packages_query),
  182. "subscribed_packages": self._api_url_user_packages,
  183. }
  184. self._application.getCuraAPI().account.loginStateChanged.connect(self._restart)
  185. self._application.getCuraAPI().account.loginStateChanged.connect(self._fetchUserSubscribedPackages)
  186. # On boot we check which packages have updates.
  187. if CuraApplication.getInstance().getPreferences().getValue("info/automatic_update_check") and len(installed_package_ids_with_versions) > 0:
  188. # Request the latest and greatest!
  189. self._makeRequestByType("updates")
  190. self._fetchUserSubscribedPackages()
  191. def _fetchUserSubscribedPackages(self):
  192. if self._application.getCuraAPI().account.isLoggedIn:
  193. self._makeRequestByType("subscribed_packages")
  194. def _fetchPackageData(self) -> None:
  195. self._makeRequestByType("packages")
  196. self._makeRequestByType("authors")
  197. self._updateInstalledModels()
  198. # Displays the toolbox
  199. @pyqtSlot()
  200. def launch(self) -> None:
  201. if not self._dialog:
  202. self._dialog = self._createDialog("Toolbox.qml")
  203. if not self._dialog:
  204. Logger.log("e", "Unexpected error trying to create the 'Marketplace' dialog.")
  205. return
  206. self._restart()
  207. self._dialog.show()
  208. # Apply enabled/disabled state to installed plugins
  209. self.enabledChanged.emit()
  210. def _createDialog(self, qml_name: str) -> Optional[QObject]:
  211. Logger.log("d", "Marketplace: Creating dialog [%s].", qml_name)
  212. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  213. if not plugin_path:
  214. return None
  215. path = os.path.join(plugin_path, "resources", "qml", qml_name)
  216. dialog = self._application.createQmlComponent(path, {"toolbox": self})
  217. if not dialog:
  218. raise Exception("Failed to create Marketplace dialog")
  219. return dialog
  220. def _convertPluginMetadata(self, plugin_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  221. try:
  222. highest_sdk_version_supported = Version(0)
  223. for supported_version in plugin_data["plugin"]["supported_sdk_versions"]:
  224. if supported_version > highest_sdk_version_supported:
  225. highest_sdk_version_supported = supported_version
  226. formatted = {
  227. "package_id": plugin_data["id"],
  228. "package_type": "plugin",
  229. "display_name": plugin_data["plugin"]["name"],
  230. "package_version": plugin_data["plugin"]["version"],
  231. "sdk_version": highest_sdk_version_supported,
  232. "author": {
  233. "author_id": plugin_data["plugin"]["author"],
  234. "display_name": plugin_data["plugin"]["author"]
  235. },
  236. "is_installed": True,
  237. "description": plugin_data["plugin"]["description"]
  238. }
  239. return formatted
  240. except KeyError:
  241. Logger.log("w", "Unable to convert plugin meta data %s", str(plugin_data))
  242. return None
  243. @pyqtSlot()
  244. def _updateInstalledModels(self) -> None:
  245. # This is moved here to avoid code duplication and so that after installing plugins they get removed from the
  246. # list of old plugins
  247. old_plugin_ids = self._plugin_registry.getInstalledPlugins()
  248. installed_package_ids = self._package_manager.getAllInstalledPackageIDs()
  249. scheduled_to_remove_package_ids = self._package_manager.getToRemovePackageIDs()
  250. self._old_plugin_ids = set()
  251. self._old_plugin_metadata = dict()
  252. for plugin_id in old_plugin_ids:
  253. # Neither the installed packages nor the packages that are scheduled to remove are old plugins
  254. if plugin_id not in installed_package_ids and plugin_id not in scheduled_to_remove_package_ids:
  255. Logger.log("d", "Found a plugin that was installed with the old plugin browser: %s", plugin_id)
  256. old_metadata = self._plugin_registry.getMetaData(plugin_id)
  257. new_metadata = self._convertPluginMetadata(old_metadata)
  258. if new_metadata is None:
  259. # Something went wrong converting it.
  260. continue
  261. self._old_plugin_ids.add(plugin_id)
  262. self._old_plugin_metadata[new_metadata["package_id"]] = new_metadata
  263. all_packages = self._package_manager.getAllInstalledPackagesInfo()
  264. if "plugin" in all_packages:
  265. # For old plugins, we only want to include the old custom plugin that were installed via the old toolbox.
  266. # The bundled plugins will be included in JSON files in the "bundled_packages" folder, so the bundled
  267. # plugins should be excluded from the old plugins list/dict.
  268. all_plugin_package_ids = set(package["package_id"] for package in all_packages["plugin"])
  269. self._old_plugin_ids = set(plugin_id for plugin_id in self._old_plugin_ids
  270. if plugin_id not in all_plugin_package_ids)
  271. self._old_plugin_metadata = {k: v for k, v in self._old_plugin_metadata.items() if k in self._old_plugin_ids}
  272. self._plugins_installed_model.setMetadata(all_packages["plugin"] + list(self._old_plugin_metadata.values()))
  273. self.metadataChanged.emit()
  274. if "material" in all_packages:
  275. self._materials_installed_model.setMetadata(all_packages["material"])
  276. self.metadataChanged.emit()
  277. @pyqtSlot(str)
  278. def install(self, file_path: str) -> None:
  279. self._package_manager.installPackage(file_path)
  280. self.installChanged.emit()
  281. self._updateInstalledModels()
  282. self.metadataChanged.emit()
  283. self._restart_required = True
  284. self.restartRequiredChanged.emit()
  285. ## Check package usage and uninstall
  286. # If the package is in use, you'll get a confirmation dialog to set everything to default
  287. @pyqtSlot(str)
  288. def checkPackageUsageAndUninstall(self, package_id: str) -> None:
  289. package_used_materials, package_used_qualities = self._package_manager.getMachinesUsingPackage(package_id)
  290. if package_used_materials or package_used_qualities:
  291. # Set up "uninstall variables" for resetMaterialsQualitiesAndUninstall
  292. self._package_id_to_uninstall = package_id
  293. package_info = self._package_manager.getInstalledPackageInfo(package_id)
  294. self._package_name_to_uninstall = package_info.get("display_name", package_info.get("package_id"))
  295. self._package_used_materials = package_used_materials
  296. self._package_used_qualities = package_used_qualities
  297. # Ask change to default material / profile
  298. if self._confirm_reset_dialog is None:
  299. self._confirm_reset_dialog = self._createDialog("dialogs/ToolboxConfirmUninstallResetDialog.qml")
  300. self.uninstallVariablesChanged.emit()
  301. if self._confirm_reset_dialog is None:
  302. Logger.log("e", "ToolboxConfirmUninstallResetDialog should have been initialized, but it is not. Not showing dialog and not uninstalling package.")
  303. else:
  304. self._confirm_reset_dialog.show()
  305. else:
  306. # Plain uninstall
  307. self.uninstall(package_id)
  308. @pyqtProperty(str, notify = uninstallVariablesChanged)
  309. def pluginToUninstall(self) -> str:
  310. return self._package_name_to_uninstall
  311. @pyqtProperty(str, notify = uninstallVariablesChanged)
  312. def uninstallUsedMaterials(self) -> str:
  313. return "\n".join(["%s (%s)" % (str(global_stack.getName()), material) for global_stack, extruder_nr, material in self._package_used_materials])
  314. @pyqtProperty(str, notify = uninstallVariablesChanged)
  315. def uninstallUsedQualities(self) -> str:
  316. return "\n".join(["%s (%s)" % (str(global_stack.getName()), quality) for global_stack, extruder_nr, quality in self._package_used_qualities])
  317. @pyqtSlot()
  318. def closeConfirmResetDialog(self) -> None:
  319. if self._confirm_reset_dialog is not None:
  320. self._confirm_reset_dialog.close()
  321. ## Uses "uninstall variables" to reset qualities and materials, then uninstall
  322. # It's used as an action on Confirm reset on Uninstall
  323. @pyqtSlot()
  324. def resetMaterialsQualitiesAndUninstall(self) -> None:
  325. application = CuraApplication.getInstance()
  326. machine_manager = application.getMachineManager()
  327. container_tree = ContainerTree.getInstance()
  328. for global_stack, extruder_nr, container_id in self._package_used_materials:
  329. extruder = global_stack.extruderList[int(extruder_nr)]
  330. approximate_diameter = extruder.getApproximateMaterialDiameter()
  331. variant_node = container_tree.machines[global_stack.definition.getId()].variants[extruder.variant.getName()]
  332. default_material_node = variant_node.preferredMaterial(approximate_diameter)
  333. machine_manager.setMaterial(extruder_nr, default_material_node, global_stack = global_stack)
  334. for global_stack, extruder_nr, container_id in self._package_used_qualities:
  335. variant_names = [extruder.variant.getName() for extruder in global_stack.extruderList]
  336. material_bases = [extruder.material.getMetaDataEntry("base_file") for extruder in global_stack.extruderList]
  337. extruder_enabled = [extruder.isEnabled for extruder in global_stack.extruderList]
  338. definition_id = global_stack.definition.getId()
  339. machine_node = container_tree.machines[definition_id]
  340. default_quality_group = machine_node.getQualityGroups(variant_names, material_bases, extruder_enabled)[machine_node.preferred_quality_type]
  341. machine_manager.setQualityGroup(default_quality_group, global_stack = global_stack)
  342. if self._package_id_to_uninstall is not None:
  343. self._markPackageMaterialsAsToBeUninstalled(self._package_id_to_uninstall)
  344. self.uninstall(self._package_id_to_uninstall)
  345. self._resetUninstallVariables()
  346. self.closeConfirmResetDialog()
  347. def _markPackageMaterialsAsToBeUninstalled(self, package_id: str) -> None:
  348. container_registry = self._application.getContainerRegistry()
  349. all_containers = self._package_manager.getPackageContainerIds(package_id)
  350. for container_id in all_containers:
  351. containers = container_registry.findInstanceContainers(id = container_id)
  352. if not containers:
  353. continue
  354. container = containers[0]
  355. if container.getMetaDataEntry("type") != "material":
  356. continue
  357. root_material_id = container.getMetaDataEntry("base_file")
  358. root_material_containers = container_registry.findInstanceContainers(id = root_material_id)
  359. if not root_material_containers:
  360. continue
  361. root_material_container = root_material_containers[0]
  362. root_material_container.setMetaDataEntry("removed", True)
  363. @pyqtSlot(str)
  364. def uninstall(self, package_id: str) -> None:
  365. self._package_manager.removePackage(package_id, force_add = True)
  366. self.installChanged.emit()
  367. self._updateInstalledModels()
  368. self.metadataChanged.emit()
  369. self._restart_required = True
  370. self.restartRequiredChanged.emit()
  371. ## Actual update packages that are in self._to_update
  372. def _update(self) -> None:
  373. if self._to_update:
  374. plugin_id = self._to_update.pop(0)
  375. remote_package = self.getRemotePackage(plugin_id)
  376. if remote_package:
  377. download_url = remote_package["download_url"]
  378. Logger.log("d", "Updating package [%s]..." % plugin_id)
  379. self.startDownload(download_url)
  380. else:
  381. Logger.log("e", "Could not update package [%s] because there is no remote package info available.", plugin_id)
  382. if self._to_update:
  383. self._application.callLater(self._update)
  384. ## Update a plugin by plugin_id
  385. @pyqtSlot(str)
  386. def update(self, plugin_id: str) -> None:
  387. self._to_update.append(plugin_id)
  388. self._application.callLater(self._update)
  389. @pyqtSlot(str)
  390. def enable(self, plugin_id: str) -> None:
  391. self._plugin_registry.enablePlugin(plugin_id)
  392. self.enabledChanged.emit()
  393. Logger.log("i", "%s was set as 'active'.", plugin_id)
  394. self._restart_required = True
  395. self.restartRequiredChanged.emit()
  396. @pyqtSlot(str)
  397. def disable(self, plugin_id: str) -> None:
  398. self._plugin_registry.disablePlugin(plugin_id)
  399. self.enabledChanged.emit()
  400. Logger.log("i", "%s was set as 'deactive'.", plugin_id)
  401. self._restart_required = True
  402. self.restartRequiredChanged.emit()
  403. @pyqtProperty(bool, notify = metadataChanged)
  404. def dataReady(self) -> bool:
  405. return self._packages_model is not None
  406. @pyqtProperty(bool, notify = restartRequiredChanged)
  407. def restartRequired(self) -> bool:
  408. return self._restart_required
  409. @pyqtSlot()
  410. def restart(self) -> None:
  411. self._application.windowClosed()
  412. def getRemotePackage(self, package_id: str) -> Optional[Dict]:
  413. # TODO: make the lookup in a dict, not a loop. canUpdate is called for every item.
  414. remote_package = None
  415. for package in self._server_response_data["packages"]:
  416. if package["package_id"] == package_id:
  417. remote_package = package
  418. break
  419. return remote_package
  420. @pyqtSlot(str, result = bool)
  421. def canDowngrade(self, package_id: str) -> bool:
  422. # If the currently installed version is higher than the bundled version (if present), the we can downgrade
  423. # this package.
  424. local_package = self._package_manager.getInstalledPackageInfo(package_id)
  425. if local_package is None:
  426. return False
  427. bundled_package = self._package_manager.getBundledPackageInfo(package_id)
  428. if bundled_package is None:
  429. return False
  430. local_version = Version(local_package["package_version"])
  431. bundled_version = Version(bundled_package["package_version"])
  432. return bundled_version < local_version
  433. @pyqtSlot(str, result = bool)
  434. def isInstalled(self, package_id: str) -> bool:
  435. result = self._package_manager.isPackageInstalled(package_id)
  436. # Also check the old plugins list if it's not found in the package manager.
  437. if not result:
  438. result = self.isOldPlugin(package_id)
  439. return result
  440. @pyqtSlot(str, result = int)
  441. def getNumberOfInstalledPackagesByAuthor(self, author_id: str) -> int:
  442. count = 0
  443. for package in self._materials_installed_model.items:
  444. if package["author_id"] == author_id:
  445. count += 1
  446. return count
  447. # This slot is only used to get the number of material packages by author, not any other type of packages.
  448. @pyqtSlot(str, result = int)
  449. def getTotalNumberOfMaterialPackagesByAuthor(self, author_id: str) -> int:
  450. count = 0
  451. for package in self._server_response_data["packages"]:
  452. if package["package_type"] == "material":
  453. if package["author"]["author_id"] == author_id:
  454. count += 1
  455. return count
  456. @pyqtSlot(str, result = bool)
  457. def isEnabled(self, package_id: str) -> bool:
  458. return package_id in self._plugin_registry.getActivePlugins()
  459. # Check for plugins that were installed with the old plugin browser
  460. def isOldPlugin(self, plugin_id: str) -> bool:
  461. return plugin_id in self._old_plugin_ids
  462. def getOldPluginPackageMetadata(self, plugin_id: str) -> Optional[Dict[str, Any]]:
  463. return self._old_plugin_metadata.get(plugin_id)
  464. def isLoadingComplete(self) -> bool:
  465. populated = 0
  466. for metadata_list in self._server_response_data.items():
  467. if metadata_list:
  468. populated += 1
  469. return populated == len(self._server_response_data.items())
  470. # Make API Calls
  471. # --------------------------------------------------------------------------
  472. def _makeRequestByType(self, request_type: str) -> None:
  473. Logger.log("d", "Requesting [%s] metadata from server.", request_type)
  474. self._updateRequestHeader()
  475. url = self._request_urls[request_type]
  476. callback = lambda r, rt = request_type: self._onDataRequestFinished(rt, r)
  477. error_callback = lambda r, e, rt = request_type: self._onDataRequestError(rt, r, e)
  478. self._application.getHttpRequestManager().get(url,
  479. headers_dict = self._request_headers,
  480. callback = callback,
  481. error_callback = error_callback)
  482. @pyqtSlot(str)
  483. def startDownload(self, url: str) -> None:
  484. Logger.log("i", "Attempting to download & install package from %s.", url)
  485. callback = lambda r: self._onDownloadFinished(r)
  486. error_callback = lambda r, e: self._onDownloadFailed(r, e)
  487. download_progress_callback = self._onDownloadProgress
  488. request_data = self._application.getHttpRequestManager().get(url, headers_dict = self._request_headers,
  489. callback = callback,
  490. error_callback = error_callback,
  491. download_progress_callback = download_progress_callback)
  492. self._download_request_data = request_data
  493. self.setDownloadProgress(0)
  494. self.setIsDownloading(True)
  495. @pyqtSlot()
  496. def cancelDownload(self) -> None:
  497. Logger.log("i", "User cancelled the download of a package. request %s", self._download_request_data)
  498. if self._download_request_data is not None:
  499. self._application.getHttpRequestManager().abortRequest(self._download_request_data)
  500. self._download_request_data = None
  501. self.resetDownload()
  502. def resetDownload(self) -> None:
  503. self.setDownloadProgress(0)
  504. self.setIsDownloading(False)
  505. # Handlers for Network Events
  506. # --------------------------------------------------------------------------
  507. def _onDataRequestError(self, request_type: str, reply: "QNetworkReply", error: "QNetworkReply.NetworkError") -> None:
  508. Logger.log("e", "Request [%s] failed due to error [%s]: %s", request_type, error, reply.errorString())
  509. self.setViewPage("errored")
  510. def _onDataRequestFinished(self, request_type: str, reply: "QNetworkReply") -> None:
  511. if reply.operation() != QNetworkAccessManager.GetOperation:
  512. Logger.log("e", "_onDataRequestFinished() only handles GET requests but got [%s] instead", reply.operation())
  513. return
  514. http_status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
  515. if http_status_code != 200:
  516. Logger.log("e", "Request type [%s] got non-200 HTTP response: [%s]", http_status_code)
  517. self.setViewPage("errored")
  518. return
  519. data = bytes(reply.readAll())
  520. try:
  521. json_data = json.loads(data.decode("utf-8"))
  522. except json.decoder.JSONDecodeError:
  523. Logger.log("e", "Failed to decode response data as JSON for request type [%s], response data [%s]",
  524. request_type, data)
  525. self.setViewPage("errored")
  526. return
  527. # Check for errors:
  528. if "errors" in json_data:
  529. for error in json_data["errors"]:
  530. Logger.log("e", "Request type [%s] got response showing error: %s", error["title"])
  531. self.setViewPage("errored")
  532. return
  533. # Create model and apply metadata:
  534. if not self._models[request_type]:
  535. Logger.log("e", "Could not find the model for request type [%s].", request_type)
  536. self.setViewPage("errored")
  537. return
  538. self._server_response_data[request_type] = json_data["data"]
  539. self._models[request_type].setMetadata(self._server_response_data[request_type])
  540. if request_type == "packages":
  541. self._models[request_type].setFilter({"type": "plugin"})
  542. self.reBuildMaterialsModels()
  543. self.reBuildPluginsModels()
  544. self._notifyPackageManager()
  545. elif request_type == "authors":
  546. self._models[request_type].setFilter({"package_types": "material"})
  547. self._models[request_type].setFilter({"tags": "generic"})
  548. elif request_type == "updates":
  549. # Tell the package manager that there's a new set of updates available.
  550. packages = set([pkg["package_id"] for pkg in self._server_response_data[request_type]])
  551. self._package_manager.setPackagesWithUpdate(packages)
  552. elif request_type == "subscribed_packages":
  553. self._checkCompatibilities(json_data["data"])
  554. self.metadataChanged.emit()
  555. if self.isLoadingComplete():
  556. self.setViewPage("overview")
  557. def _checkCompatibilities(self, json_data) -> None:
  558. user_subscribed_packages = [plugin["package_id"] for plugin in json_data]
  559. user_installed_packages = self._package_manager.getUserInstalledPackages()
  560. # We check if there are packages installed in Cloud Marketplace but not in Cura marketplace (discrepancy)
  561. package_discrepancy = list(set(user_subscribed_packages).difference(user_installed_packages))
  562. if package_discrepancy:
  563. self._models["subscribed_packages"].addValue(package_discrepancy)
  564. self._models["subscribed_packages"].update()
  565. Logger.log("d", "Discrepancy found between Cloud subscribed packages and Cura installed packages")
  566. sync_message = Message(i18n_catalog.i18nc(
  567. "@info:generic",
  568. "\nDo you want to sync material and software packages with your account?"),
  569. lifetime=0,
  570. title=i18n_catalog.i18nc("@info:title", "Changes detected from your Ultimaker account", ))
  571. sync_message.addAction("sync",
  572. name=i18n_catalog.i18nc("@action:button", "Sync"),
  573. icon="",
  574. description="Sync your Cloud subscribed packages to your local environment.",
  575. button_align=Message.ActionButtonAlignment.ALIGN_RIGHT)
  576. sync_message.actionTriggered.connect(self._onSyncButtonClicked)
  577. sync_message.show()
  578. def _onSyncButtonClicked(self, sync_message: Message, sync_message_action: str) -> None:
  579. sync_message.hide()
  580. compatibility_dialog_path = "resources/qml/dialogs/CompatibilityDialog.qml"
  581. plugin_path_prefix = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  582. if plugin_path_prefix:
  583. path = os.path.join(plugin_path_prefix, compatibility_dialog_path)
  584. self.compatibility_dialog_view = self._application.getInstance().createQmlComponent(path, {"toolbox": self})
  585. # This function goes through all known remote versions of a package and notifies the package manager of this change
  586. def _notifyPackageManager(self):
  587. for package in self._server_response_data["packages"]:
  588. self._package_manager.addAvailablePackageVersion(package["package_id"], Version(package["package_version"]))
  589. def _onDownloadFinished(self, reply: "QNetworkReply") -> None:
  590. self.resetDownload()
  591. if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200:
  592. Logger.log("w", "Failed to download package. The following error was returned: %s",
  593. json.loads(reply.readAll().data().decode("utf-8")))
  594. return
  595. # Must not delete the temporary file on Windows
  596. self._temp_plugin_file = tempfile.NamedTemporaryFile(mode = "w+b", suffix = ".curapackage", delete = False)
  597. file_path = self._temp_plugin_file.name
  598. # Write first and close, otherwise on Windows, it cannot read the file
  599. self._temp_plugin_file.write(reply.readAll())
  600. self._temp_plugin_file.close()
  601. self._onDownloadComplete(file_path)
  602. def _onDownloadFailed(self, reply: "QNetworkReply", error: "QNetworkReply.NetworkError") -> None:
  603. Logger.log("w", "Failed to download package. The following error was returned: %s", error)
  604. self.resetDownload()
  605. def _onDownloadProgress(self, bytes_sent: int, bytes_total: int) -> None:
  606. if bytes_total > 0:
  607. new_progress = bytes_sent / bytes_total * 100
  608. self.setDownloadProgress(new_progress)
  609. Logger.log("d", "new download progress %s / %s : %s%%", bytes_sent, bytes_total, new_progress)
  610. def _onDownloadComplete(self, file_path: str) -> None:
  611. Logger.log("i", "Download complete.")
  612. package_info = self._package_manager.getPackageInfo(file_path)
  613. if not package_info:
  614. Logger.log("w", "Package file [%s] was not a valid CuraPackage.", file_path)
  615. return
  616. license_content = self._package_manager.getPackageLicense(file_path)
  617. if license_content is not None:
  618. self.openLicenseDialog(package_info["package_id"], license_content, file_path)
  619. return
  620. self.install(file_path)
  621. self.subscribe(package_info["package_id"])
  622. # Getter & Setters for Properties:
  623. # --------------------------------------------------------------------------
  624. def setDownloadProgress(self, progress: float) -> None:
  625. if progress != self._download_progress:
  626. self._download_progress = progress
  627. self.onDownloadProgressChanged.emit()
  628. @pyqtProperty(int, fset = setDownloadProgress, notify = onDownloadProgressChanged)
  629. def downloadProgress(self) -> float:
  630. return self._download_progress
  631. def setIsDownloading(self, is_downloading: bool) -> None:
  632. if self._is_downloading != is_downloading:
  633. self._is_downloading = is_downloading
  634. self.onIsDownloadingChanged.emit()
  635. @pyqtProperty(bool, fset = setIsDownloading, notify = onIsDownloadingChanged)
  636. def isDownloading(self) -> bool:
  637. return self._is_downloading
  638. def setActivePackage(self, package: Dict[str, Any]) -> None:
  639. if self._active_package != package:
  640. self._active_package = package
  641. self.activePackageChanged.emit()
  642. ## The active package is the package that is currently being downloaded
  643. @pyqtProperty(QObject, fset = setActivePackage, notify = activePackageChanged)
  644. def activePackage(self) -> Optional[Dict[str, Any]]:
  645. return self._active_package
  646. def setViewCategory(self, category: str = "plugin") -> None:
  647. if self._view_category != category:
  648. self._view_category = category
  649. self.viewChanged.emit()
  650. @pyqtProperty(str, fset = setViewCategory, notify = viewChanged)
  651. def viewCategory(self) -> str:
  652. return self._view_category
  653. def setViewPage(self, page: str = "overview") -> None:
  654. if self._view_page != page:
  655. self._view_page = page
  656. self.viewChanged.emit()
  657. @pyqtProperty(str, fset = setViewPage, notify = viewChanged)
  658. def viewPage(self) -> str:
  659. return self._view_page
  660. # Exposed Models:
  661. # --------------------------------------------------------------------------
  662. @pyqtProperty(QObject, constant = True)
  663. def authorsModel(self) -> AuthorsModel:
  664. return cast(AuthorsModel, self._models["authors"])
  665. @pyqtProperty(QObject, constant = True)
  666. def subscribedPackagesModel(self) -> SubscribedPackagesModel:
  667. return cast(SubscribedPackagesModel, self._models["subscribed_packages"])
  668. @pyqtProperty(bool, constant=True)
  669. def has_compatible_packages(self) -> bool:
  670. return self._models["subscribed_packages"].hasCompatiblePackages()
  671. @pyqtProperty(bool, constant=True)
  672. def has_incompatible_packages(self) -> bool:
  673. return self._models["subscribed_packages"].hasIncompatiblePackages()
  674. @pyqtProperty(QObject, constant = True)
  675. def packagesModel(self) -> PackagesModel:
  676. return cast(PackagesModel, self._models["packages"])
  677. @pyqtProperty(QObject, constant = True)
  678. def pluginsShowcaseModel(self) -> PackagesModel:
  679. return self._plugins_showcase_model
  680. @pyqtProperty(QObject, constant = True)
  681. def pluginsAvailableModel(self) -> PackagesModel:
  682. return self._plugins_available_model
  683. @pyqtProperty(QObject, constant = True)
  684. def pluginsInstalledModel(self) -> PackagesModel:
  685. return self._plugins_installed_model
  686. @pyqtProperty(QObject, constant = True)
  687. def materialsShowcaseModel(self) -> AuthorsModel:
  688. return self._materials_showcase_model
  689. @pyqtProperty(QObject, constant = True)
  690. def materialsAvailableModel(self) -> AuthorsModel:
  691. return self._materials_available_model
  692. @pyqtProperty(QObject, constant = True)
  693. def materialsInstalledModel(self) -> PackagesModel:
  694. return self._materials_installed_model
  695. @pyqtProperty(QObject, constant = True)
  696. def materialsGenericModel(self) -> PackagesModel:
  697. return self._materials_generic_model
  698. # Filter Models:
  699. # --------------------------------------------------------------------------
  700. @pyqtSlot(str, str, str)
  701. def filterModelByProp(self, model_type: str, filter_type: str, parameter: str) -> None:
  702. if not self._models[model_type]:
  703. Logger.log("w", "Couldn't filter %s model because it doesn't exist.", model_type)
  704. return
  705. self._models[model_type].setFilter({filter_type: parameter})
  706. self.filterChanged.emit()
  707. @pyqtSlot(str, "QVariantMap")
  708. def setFilters(self, model_type: str, filter_dict: dict) -> None:
  709. if not self._models[model_type]:
  710. Logger.log("w", "Couldn't filter %s model because it doesn't exist.", model_type)
  711. return
  712. self._models[model_type].setFilter(filter_dict)
  713. self.filterChanged.emit()
  714. @pyqtSlot(str)
  715. def removeFilters(self, model_type: str) -> None:
  716. if not self._models[model_type]:
  717. Logger.log("w", "Couldn't remove filters on %s model because it doesn't exist.", model_type)
  718. return
  719. self._models[model_type].setFilter({})
  720. self.filterChanged.emit()
  721. # HACK(S):
  722. # --------------------------------------------------------------------------
  723. def reBuildMaterialsModels(self) -> None:
  724. materials_showcase_metadata = []
  725. materials_available_metadata = []
  726. materials_generic_metadata = []
  727. processed_authors = [] # type: List[str]
  728. for item in self._server_response_data["packages"]:
  729. if item["package_type"] == "material":
  730. author = item["author"]
  731. if author["author_id"] in processed_authors:
  732. continue
  733. # Generic materials to be in the same section
  734. if "generic" in item["tags"]:
  735. materials_generic_metadata.append(item)
  736. else:
  737. if "showcase" in item["tags"]:
  738. materials_showcase_metadata.append(author)
  739. else:
  740. materials_available_metadata.append(author)
  741. processed_authors.append(author["author_id"])
  742. self._materials_showcase_model.setMetadata(materials_showcase_metadata)
  743. self._materials_available_model.setMetadata(materials_available_metadata)
  744. self._materials_generic_model.setMetadata(materials_generic_metadata)
  745. def reBuildPluginsModels(self) -> None:
  746. plugins_showcase_metadata = []
  747. plugins_available_metadata = []
  748. for item in self._server_response_data["packages"]:
  749. if item["package_type"] == "plugin":
  750. if "showcase" in item["tags"]:
  751. plugins_showcase_metadata.append(item)
  752. else:
  753. plugins_available_metadata.append(item)
  754. self._plugins_showcase_model.setMetadata(plugins_showcase_metadata)
  755. self._plugins_available_model.setMetadata(plugins_available_metadata)