RemotePackageList.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt6.QtCore import pyqtProperty, pyqtSignal, pyqtSlot
  4. from PyQt6.QtNetwork import QNetworkReply
  5. from typing import Optional, TYPE_CHECKING
  6. from UM.i18n import i18nCatalog
  7. from UM.Logger import Logger
  8. from UM.TaskManagement.HttpRequestManager import HttpRequestManager # To request the package list from the API.
  9. from .Constants import PACKAGES_URL # To get the list of packages. Imported this way to prevent circular imports.
  10. from .PackageList import PackageList
  11. from .PackageModel import PackageModel # The contents of this list.
  12. if TYPE_CHECKING:
  13. from PyQt6.QtCore import QObject
  14. catalog = i18nCatalog("cura")
  15. class RemotePackageList(PackageList):
  16. ITEMS_PER_PAGE = 20 # Pagination of number of elements to download at once.
  17. def __init__(self, parent: Optional["QObject"] = None) -> None:
  18. super().__init__(parent)
  19. self._package_type_filter = ""
  20. self._requested_search_string = ""
  21. self._current_search_string = ""
  22. self._request_url = self._initialRequestUrl()
  23. self._ongoing_requests["get_packages"] = None
  24. self.isLoadingChanged.connect(self._onLoadingChanged)
  25. self.isLoadingChanged.emit()
  26. @pyqtSlot()
  27. def updatePackages(self) -> None:
  28. """
  29. Make a request for the first paginated page of packages.
  30. When the request is done, the list will get updated with the new package models.
  31. """
  32. self.setErrorMessage("") # Clear any previous errors.
  33. self.setIsLoading(True)
  34. self._ongoing_requests["get_packages"] = HttpRequestManager.getInstance().get(
  35. self._request_url,
  36. scope = self._scope,
  37. callback = self._parseResponse,
  38. error_callback = self._onError
  39. )
  40. def reset(self) -> None:
  41. self.clear()
  42. self._request_url = self._initialRequestUrl()
  43. packageTypeFilterChanged = pyqtSignal()
  44. searchStringChanged = pyqtSignal()
  45. def setPackageTypeFilter(self, new_filter: str) -> None:
  46. if new_filter != self._package_type_filter:
  47. self._package_type_filter = new_filter
  48. self.reset()
  49. self.packageTypeFilterChanged.emit()
  50. def setSearchString(self, new_search: str) -> None:
  51. self._requested_search_string = new_search
  52. self._onLoadingChanged()
  53. @pyqtProperty(str, fset = setPackageTypeFilter, notify = packageTypeFilterChanged)
  54. def packageTypeFilter(self) -> str:
  55. """
  56. Get the package type this package list is filtering on, like ``plugin`` or ``material``.
  57. :return: The package type this list is filtering on.
  58. """
  59. return self._package_type_filter
  60. @pyqtProperty(str, fset = setSearchString, notify = searchStringChanged)
  61. def searchString(self) -> str:
  62. """
  63. Get the string the user is currently searching for (as in: the list is updating) within the packages,
  64. or an empty string if no extra search filter has to be applied. Does not override package-type filter!
  65. :return: String the user is searching for. Empty denotes 'no search filter'.
  66. """
  67. return self._current_search_string
  68. def _onLoadingChanged(self) -> None:
  69. if self._requested_search_string != self._current_search_string and not self._is_loading:
  70. self._current_search_string = self._requested_search_string
  71. self.reset()
  72. self.updatePackages()
  73. self.searchStringChanged.emit()
  74. def _initialRequestUrl(self) -> str:
  75. """
  76. Get the URL to request the first paginated page with.
  77. :return: A URL to request.
  78. """
  79. request_url = f"{PACKAGES_URL}?limit={self.ITEMS_PER_PAGE}"
  80. if self._package_type_filter != "":
  81. request_url += f"&package_type={self._package_type_filter}"
  82. if self._current_search_string != "":
  83. request_url += f"&search={self._current_search_string}"
  84. return request_url
  85. def _parseResponse(self, reply: "QNetworkReply") -> None:
  86. """
  87. Parse the response from the package list API request.
  88. This converts that response into PackageModels, and triggers the ListModel to update.
  89. :param reply: A reply containing information about a number of packages.
  90. """
  91. response_data = HttpRequestManager.readJSON(reply)
  92. if "data" not in response_data or "links" not in response_data:
  93. Logger.error(f"Could not interpret the server's response. Missing 'data' or 'links' from response data. Keys in response: {response_data.keys()}")
  94. self.setErrorMessage(catalog.i18nc("@info:error", "Could not interpret the server's response."))
  95. return
  96. for package_data in response_data["data"]:
  97. try:
  98. package = PackageModel(package_data, parent = self)
  99. self._connectManageButtonSignals(package)
  100. self.appendItem({"package": package}) # Add it to this list model.
  101. except RuntimeError:
  102. # Setting the ownership of this object to not qml can still result in a RuntimeError. Which can occur when quickly toggling
  103. # between de-/constructing RemotePackageLists. This try-except is here to prevent a hard crash when the wrapped C++ object
  104. # was deleted when it was still parsing the response
  105. continue
  106. self._request_url = response_data["links"].get("next", "") # Use empty string to signify that there is no next page.
  107. self._ongoing_requests["get_packages"] = None
  108. self.setIsLoading(False)
  109. self.setHasMore(self._request_url != "")
  110. def _onError(self, reply: "QNetworkReply", error: Optional[QNetworkReply.NetworkError]) -> None:
  111. """
  112. Handles networking and server errors when requesting the list of packages.
  113. :param reply: The reply with packages. This will most likely be incomplete and should be ignored.
  114. :param error: The error status of the request.
  115. """
  116. if error == QNetworkReply.NetworkError.OperationCanceledError or error == QNetworkReply.NetworkError.ProtocolUnknownError:
  117. Logger.debug("Cancelled request for packages.")
  118. self._ongoing_requests["get_packages"] = None
  119. self.setIsLoading(False)
  120. return # Don't show an error about this to the user.
  121. Logger.error("Could not reach Marketplace server.")
  122. self.setErrorMessage(catalog.i18nc("@info:error", "Could not reach Marketplace."))
  123. self._ongoing_requests["get_packages"] = None
  124. self.setIsLoading(False)