RemotePackageList.py 6.6 KB

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