CloudPackageChecker.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # Copyright (c) 2022 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. from typing import List, Dict, Any, Set
  5. from typing import Optional
  6. from PyQt6.QtCore import QObject
  7. from PyQt6.QtNetwork import QNetworkReply
  8. from UM import i18nCatalog
  9. from UM.Logger import Logger
  10. from UM.Message import Message
  11. from UM.Signal import Signal
  12. from UM.TaskManagement.HttpRequestManager import HttpRequestManager
  13. from UM.TaskManagement.HttpRequestScope import JsonDecoratorScope
  14. from cura.API.Account import SyncState
  15. from cura.CuraApplication import CuraApplication, ApplicationMetadata
  16. from cura.UltimakerCloud.UltimakerCloudScope import UltimakerCloudScope
  17. from .SubscribedPackagesModel import SubscribedPackagesModel
  18. from ..CloudApiModel import CloudApiModel
  19. class CloudPackageChecker(QObject):
  20. SYNC_SERVICE_NAME = "CloudPackageChecker"
  21. def __init__(self, application: CuraApplication) -> None:
  22. super().__init__()
  23. self.discrepancies = Signal() # Emits SubscribedPackagesModel
  24. self._application: CuraApplication = application
  25. self._scope = JsonDecoratorScope(UltimakerCloudScope(application))
  26. self._model = SubscribedPackagesModel()
  27. self._message: Optional[Message] = None
  28. self._application.initializationFinished.connect(self._onAppInitialized)
  29. self._i18n_catalog = i18nCatalog("cura")
  30. self._sdk_version = ApplicationMetadata.CuraSDKVersion
  31. self._last_notified_packages = set() # type: Set[str]
  32. """Packages for which a notification has been shown. No need to bother the user twice for equal content"""
  33. # This is a plugin, so most of the components required are not ready when
  34. # this is initialized. Therefore, we wait until the application is ready.
  35. def _onAppInitialized(self) -> None:
  36. self._package_manager = self._application.getPackageManager()
  37. # initial check
  38. self._getPackagesIfLoggedIn()
  39. self._application.getCuraAPI().account.loginStateChanged.connect(self._onLoginStateChanged)
  40. self._application.getCuraAPI().account.syncRequested.connect(self._getPackagesIfLoggedIn)
  41. def _onLoginStateChanged(self) -> None:
  42. # reset session
  43. self._last_notified_packages = set()
  44. self._getPackagesIfLoggedIn()
  45. def _getPackagesIfLoggedIn(self) -> None:
  46. if self._application.getCuraAPI().account.isLoggedIn:
  47. self._getUserSubscribedPackages()
  48. else:
  49. self._hideSyncMessage()
  50. def _getUserSubscribedPackages(self) -> None:
  51. self._application.getCuraAPI().account.setSyncState(self.SYNC_SERVICE_NAME, SyncState.SYNCING)
  52. url = CloudApiModel.api_url_user_packages
  53. self._application.getHttpRequestManager().get(url,
  54. callback = self._onUserPackagesRequestFinished,
  55. error_callback = self._onUserPackagesRequestFinished,
  56. timeout = 10,
  57. scope = self._scope)
  58. def _onUserPackagesRequestFinished(self, reply: "QNetworkReply", error: Optional["QNetworkReply.NetworkError"] = None) -> None:
  59. if error is not None or HttpRequestManager.safeHttpStatus(reply) != 200:
  60. Logger.log("w",
  61. "Requesting user packages failed, response code %s while trying to connect to %s",
  62. HttpRequestManager.safeHttpStatus(reply), reply.url())
  63. self._application.getCuraAPI().account.setSyncState(self.SYNC_SERVICE_NAME, SyncState.ERROR)
  64. return
  65. try:
  66. json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
  67. # Check for errors:
  68. if "errors" in json_data:
  69. for error in json_data["errors"]:
  70. Logger.log("e", "%s", error["title"])
  71. self._application.getCuraAPI().account.setSyncState(self.SYNC_SERVICE_NAME, SyncState.ERROR)
  72. return
  73. self._handleCompatibilityData(json_data["data"])
  74. except json.decoder.JSONDecodeError:
  75. Logger.log("w", "Received invalid JSON for user subscribed packages from the Web Marketplace")
  76. self._application.getCuraAPI().account.setSyncState(self.SYNC_SERVICE_NAME, SyncState.SUCCESS)
  77. def _handleCompatibilityData(self, subscribed_packages_payload: List[Dict[str, Any]]) -> None:
  78. user_subscribed_packages = {plugin["package_id"] for plugin in subscribed_packages_payload}
  79. user_installed_packages = self._package_manager.getAllInstalledPackageIDs()
  80. # We need to re-evaluate the dismissed packages
  81. # (i.e. some package might got updated to the correct SDK version in the meantime,
  82. # hence remove them from the Dismissed Incompatible list)
  83. self._package_manager.reEvaluateDismissedPackages(subscribed_packages_payload, self._sdk_version)
  84. user_dismissed_packages = self._package_manager.getDismissedPackages()
  85. if user_dismissed_packages:
  86. user_installed_packages.update(user_dismissed_packages)
  87. # We check if there are packages installed in Web Marketplace but not in Cura marketplace
  88. package_discrepancy = list(user_subscribed_packages.difference(user_installed_packages))
  89. if user_subscribed_packages != self._last_notified_packages:
  90. # scenario:
  91. # 1. user subscribes to a package
  92. # 2. dismisses the license/unsubscribes
  93. # 3. subscribes to the same package again
  94. # in this scenario we want to notify the user again. To capture that there was a change during
  95. # step 2, we clear the last_notified after step 2. This way, the user will be notified after
  96. # step 3 even though the list of packages for step 1 and 3 are equal
  97. self._last_notified_packages = set()
  98. if package_discrepancy:
  99. account = self._application.getCuraAPI().account
  100. account.setUpdatePackagesAction(lambda: self._onSyncButtonClicked(None, None))
  101. if user_subscribed_packages == self._last_notified_packages:
  102. # already notified user about these
  103. return
  104. Logger.log("d", "Discrepancy found between Cloud subscribed packages and Cura installed packages")
  105. self._model.addDiscrepancies(package_discrepancy)
  106. self._model.initialize(self._package_manager, subscribed_packages_payload)
  107. self._showSyncMessage()
  108. self._last_notified_packages = user_subscribed_packages
  109. def _showSyncMessage(self) -> None:
  110. """Show the message if it is not already shown"""
  111. if self._message is not None:
  112. self._message.show()
  113. return
  114. sync_message = Message(self._i18n_catalog.i18nc(
  115. "@info:generic",
  116. "Do you want to sync material and software packages with your account?"),
  117. title = self._i18n_catalog.i18nc("@info:title", "Changes detected from your UltiMaker account", ))
  118. sync_message.addAction("sync",
  119. name = self._i18n_catalog.i18nc("@action:button", "Sync"),
  120. icon = "",
  121. description = "Sync your plugins and print profiles to Ultimaker Cura.",
  122. button_align = Message.ActionButtonAlignment.ALIGN_RIGHT)
  123. sync_message.actionTriggered.connect(self._onSyncButtonClicked)
  124. sync_message.show()
  125. self._message = sync_message
  126. def _hideSyncMessage(self) -> None:
  127. """Hide the message if it is showing"""
  128. if self._message is not None:
  129. self._message.hide()
  130. self._message = None
  131. def _onSyncButtonClicked(self, sync_message: Optional[Message], sync_message_action: Optional[str]) -> None:
  132. if sync_message is not None:
  133. sync_message.hide()
  134. self._hideSyncMessage() # Should be the same message, but also sets _message to None
  135. self.discrepancies.emit(self._model)