RemotePackageList.py 6.8 KB

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