DigitalFactoryApiClient.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. from json import JSONDecodeError
  5. from time import time
  6. from typing import List, Any, Optional, Union, Type, Tuple, Dict, cast, TypeVar, Callable
  7. from PyQt6.QtNetwork import QNetworkReply, QNetworkRequest
  8. from UM.Logger import Logger
  9. from UM.TaskManagement.HttpRequestManager import HttpRequestManager
  10. from UM.TaskManagement.HttpRequestScope import JsonDecoratorScope
  11. from cura.CuraApplication import CuraApplication
  12. from cura.UltimakerCloud import UltimakerCloudConstants
  13. from cura.UltimakerCloud.UltimakerCloudScope import UltimakerCloudScope
  14. from .DFPrintJobUploadResponse import DFPrintJobUploadResponse
  15. from .BaseModel import BaseModel
  16. from .CloudError import CloudError
  17. from .DFFileUploader import DFFileUploader
  18. from .DFLibraryFileUploadRequest import DFLibraryFileUploadRequest
  19. from .DFLibraryFileUploadResponse import DFLibraryFileUploadResponse
  20. from .DFPrintJobUploadRequest import DFPrintJobUploadRequest
  21. from .DigitalFactoryFeatureBudgetResponse import DigitalFactoryFeatureBudgetResponse
  22. from .DigitalFactoryFileResponse import DigitalFactoryFileResponse
  23. from .DigitalFactoryProjectResponse import DigitalFactoryProjectResponse
  24. from .PaginationLinks import PaginationLinks
  25. from .PaginationManager import PaginationManager
  26. CloudApiClientModel = TypeVar("CloudApiClientModel", bound=BaseModel)
  27. """The generic type variable used to document the methods below."""
  28. class DigitalFactoryApiClient:
  29. # The URL to access the digital factory.
  30. ROOT_PATH = UltimakerCloudConstants.CuraCloudAPIRoot
  31. CURA_API_ROOT = "{}/cura/v1".format(ROOT_PATH)
  32. DEFAULT_REQUEST_TIMEOUT = 10 # seconds
  33. # In order to avoid garbage collection we keep the callbacks in this list.
  34. _anti_gc_callbacks: List[Callable[[Any], None]] = []
  35. def __init__(self, application: CuraApplication, on_error: Callable[[List[CloudError]], None], projects_limit_per_page: Optional[int] = None) -> None:
  36. """Initializes a new digital factory API client.
  37. :param application:
  38. :param on_error: The callback to be called whenever we receive errors from the server.
  39. """
  40. super().__init__()
  41. self._application = application
  42. self._account = application.getCuraAPI().account
  43. self._scope = JsonDecoratorScope(UltimakerCloudScope(application))
  44. self._http = HttpRequestManager.getInstance()
  45. self._on_error = on_error
  46. self._file_uploader: Optional[DFFileUploader] = None
  47. self._library_max_private_projects: Optional[int] = None
  48. self._projects_pagination_mgr = PaginationManager(limit = projects_limit_per_page) if projects_limit_per_page else None # type: Optional[PaginationManager]
  49. def checkUserHasAccess(self, callback: Callable) -> None:
  50. """Checks if the user has any sort of access to the digital library.
  51. A user is considered to have access if the max-# of private projects is greater then 0 (or -1 for unlimited).
  52. """
  53. def callbackWrap(response: Optional[Any] = None, *args, **kwargs) -> None:
  54. if (response is not None and isinstance(response, DigitalFactoryFeatureBudgetResponse) and
  55. response.library_max_private_projects is not None):
  56. # A user has DF access when library_max_private_projects is either -1 (unlimited) or bigger then 0
  57. has_access = response.library_max_private_projects == -1 or response.library_max_private_projects > 0
  58. callback(has_access)
  59. self._library_max_private_projects = response.library_max_private_projects
  60. else:
  61. Logger.warning(f"Digital Factory: Response is not a feature budget, likely an error: {str(response)}")
  62. callback(False)
  63. self._http.get(f"{self.CURA_API_ROOT}/feature_budgets",
  64. scope = self._scope,
  65. callback = self._parseCallback(callbackWrap, DigitalFactoryFeatureBudgetResponse, callbackWrap),
  66. error_callback = callbackWrap,
  67. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  68. def checkUserCanCreateNewLibraryProject(self, callback: Callable) -> None:
  69. """
  70. Checks if the user is allowed to create new library projects.
  71. A user is allowed to create new library projects if the haven't reached their maximum allowed private projects.
  72. """
  73. def callbackWrap(response: Optional[Any] = None, *args, **kwargs) -> None:
  74. if response is not None:
  75. if isinstance(response, DigitalFactoryProjectResponse): # The user has only one private project
  76. callback(True)
  77. elif isinstance(response, list) and all(isinstance(r, DigitalFactoryProjectResponse) for r in response):
  78. callback(len(response) < cast(int, self._library_max_private_projects))
  79. else:
  80. Logger.warning(f"Digital Factory: Incorrect response type received when requesting private projects: {str(response)}")
  81. callback(False)
  82. else:
  83. Logger.warning(f"Digital Factory: Response is empty, likely an error: {str(response)}")
  84. callback(False)
  85. if self._library_max_private_projects is not None and self._library_max_private_projects > 0:
  86. # The user has a limit in the number of private projects they can create. Check whether they have already
  87. # reached that limit.
  88. # Note: Set the pagination manager to None when doing this get request, or else the next/previous links
  89. # of the pagination will become corrupted
  90. url = f"{self.CURA_API_ROOT}/projects?shared=false&limit={self._library_max_private_projects}"
  91. self._http.get(url,
  92. scope = self._scope,
  93. callback = self._parseCallback(callbackWrap, DigitalFactoryProjectResponse, callbackWrap, pagination_manager = None),
  94. error_callback = callbackWrap,
  95. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  96. else:
  97. # If the limit is -1, then the user is allowed unlimited projects. If its 0 then they are not allowed to
  98. # create any projects
  99. callback(self._library_max_private_projects == -1)
  100. def getProject(self, library_project_id: str, on_finished: Callable[[DigitalFactoryProjectResponse], Any], failed: Callable) -> None:
  101. """
  102. Retrieves a digital factory project by its library project id.
  103. :param library_project_id: The id of the library project
  104. :param on_finished: The function to be called after the result is parsed.
  105. :param failed: The function to be called if the request fails.
  106. """
  107. url = "{}/projects/{}".format(self.CURA_API_ROOT, library_project_id)
  108. self._http.get(url,
  109. scope = self._scope,
  110. callback = self._parseCallback(on_finished, DigitalFactoryProjectResponse, failed),
  111. error_callback = failed,
  112. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  113. def getProjectsFirstPage(self, search_filter: str, on_finished: Callable[[List[DigitalFactoryProjectResponse]], Any], failed: Callable) -> None:
  114. """
  115. Retrieves digital factory projects for the user that is currently logged in.
  116. If a projects pagination manager exists, then it attempts to get the first page of the paginated projects list,
  117. according to the limit set in the pagination manager. If there is no projects pagination manager, this function
  118. leaves the project limit to the default set on the server side (999999).
  119. :param search_filter: Text to filter the search results. If given an empty string, results are not filtered.
  120. :param on_finished: The function to be called after the result is parsed.
  121. :param failed: The function to be called if the request fails.
  122. """
  123. url = f"{self.CURA_API_ROOT}/projects"
  124. query_character = "?"
  125. if self._projects_pagination_mgr:
  126. self._projects_pagination_mgr.reset() # reset to clear all the links and response metadata
  127. url += f"{query_character}limit={self._projects_pagination_mgr.limit}"
  128. query_character = "&"
  129. if search_filter != "":
  130. url += f"{query_character}search={search_filter}"
  131. self._http.get(url,
  132. scope = self._scope,
  133. callback = self._parseCallback(on_finished, DigitalFactoryProjectResponse, failed, pagination_manager = self._projects_pagination_mgr),
  134. error_callback = failed,
  135. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  136. def getMoreProjects(self,
  137. on_finished: Callable[[List[DigitalFactoryProjectResponse]], Any],
  138. failed: Callable) -> None:
  139. """Retrieves the next page of the paginated projects list from the API, provided that there is any.
  140. :param on_finished: The function to be called after the result is parsed.
  141. :param failed: The function to be called if the request fails.
  142. """
  143. if self.hasMoreProjectsToLoad():
  144. url = cast(PaginationLinks, cast(PaginationManager, self._projects_pagination_mgr).links).next_page
  145. self._http.get(url,
  146. scope = self._scope,
  147. callback = self._parseCallback(on_finished, DigitalFactoryProjectResponse, failed, pagination_manager = self._projects_pagination_mgr),
  148. error_callback = failed,
  149. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  150. else:
  151. Logger.log("d", "There are no more projects to load.")
  152. def hasMoreProjectsToLoad(self) -> bool:
  153. """
  154. Determines whether the client can get more pages of projects list from the API.
  155. :return: Whether there are more pages in the projects list available to be retrieved from the API.
  156. """
  157. return self._projects_pagination_mgr is not None and self._projects_pagination_mgr.links is not None and self._projects_pagination_mgr.links.next_page is not None
  158. def getListOfFilesInProject(self, library_project_id: str, on_finished: Callable[[List[DigitalFactoryFileResponse]], Any], failed: Callable) -> None:
  159. """Retrieves the list of files contained in the project with library_project_id from the Digital Factory Library.
  160. :param library_project_id: The id of the digital factory library project in which the files are included
  161. :param on_finished: The function to be called after the result is parsed.
  162. :param failed: The function to be called if the request fails.
  163. """
  164. url = "{}/projects/{}/files".format(self.CURA_API_ROOT, library_project_id)
  165. self._http.get(url,
  166. scope = self._scope,
  167. callback = self._parseCallback(on_finished, DigitalFactoryFileResponse, failed),
  168. error_callback = failed,
  169. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  170. def _parseCallback(self,
  171. on_finished: Union[Callable[[CloudApiClientModel], Any],
  172. Callable[[List[CloudApiClientModel]], Any]],
  173. model: Type[CloudApiClientModel],
  174. on_error: Optional[Callable] = None,
  175. pagination_manager: Optional[PaginationManager] = None) -> Callable[[QNetworkReply], None]:
  176. """
  177. Creates a callback function so that it includes the parsing of the response into the correct model.
  178. The callback is added to the 'finished' signal of the reply. If a paginated request was made and a pagination
  179. manager is given, the pagination metadata will be held there.
  180. :param on_finished: The callback in case the response is successful. Depending on the endpoint it will be either
  181. a list or a single item.
  182. :param model: The type of the model to convert the response to.
  183. :param on_error: The callback in case the response is ... less successful.
  184. :param pagination_manager: Holds the pagination links and metadata contained in paginated responses.
  185. If no pagination manager is provided, the pagination metadata is ignored.
  186. """
  187. def parse(reply: QNetworkReply) -> None:
  188. self._anti_gc_callbacks.remove(parse)
  189. # Don't try to parse the reply if we didn't get one
  190. if reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) is None:
  191. if on_error is not None:
  192. on_error()
  193. return
  194. status_code, response = self._parseReply(reply)
  195. if status_code >= 300 and on_error is not None:
  196. on_error()
  197. else:
  198. self._parseModels(response, on_finished, model, pagination_manager = pagination_manager)
  199. self._anti_gc_callbacks.append(parse)
  200. return parse
  201. @staticmethod
  202. def _parseReply(reply: QNetworkReply) -> Tuple[int, Dict[str, Any]]:
  203. """Parses the given JSON network reply into a status code and a dictionary, handling unexpected errors as well.
  204. :param reply: The reply from the server.
  205. :return: A tuple with a status code and a dictionary.
  206. """
  207. status_code = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute)
  208. try:
  209. response = bytes(reply.readAll()).decode()
  210. return status_code, json.loads(response)
  211. except (UnicodeDecodeError, JSONDecodeError, ValueError) as err:
  212. error = CloudError(code = type(err).__name__, title = str(err), http_code = str(status_code),
  213. id = str(time()), http_status = "500")
  214. Logger.logException("e", "Could not parse the stardust response: %s", error.toDict())
  215. return status_code, {"errors": [error.toDict()]}
  216. def _parseModels(self,
  217. response: Dict[str, Any],
  218. on_finished: Union[Callable[[CloudApiClientModel], Any],
  219. Callable[[List[CloudApiClientModel]], Any]],
  220. model_class: Type[CloudApiClientModel],
  221. pagination_manager: Optional[PaginationManager] = None) -> None:
  222. """Parses the given models and calls the correct callback depending on the result.
  223. :param response: The response from the server, after being converted to a dict.
  224. :param on_finished: The callback in case the response is successful.
  225. :param model_class: The type of the model to convert the response to. It may either be a single record or a list.
  226. :param pagination_manager: Holds the pagination links and metadata contained in paginated responses.
  227. If no pagination manager is provided, the pagination metadata is ignored.
  228. """
  229. if "data" in response:
  230. data = response["data"]
  231. if "meta" in response and pagination_manager:
  232. pagination_manager.setResponseMeta(response["meta"])
  233. if "links" in response and pagination_manager:
  234. pagination_manager.setLinks(response["links"])
  235. if isinstance(data, list):
  236. results = [model_class(**c) for c in data] # type: List[CloudApiClientModel]
  237. on_finished_list = cast(Callable[[List[CloudApiClientModel]], Any], on_finished)
  238. on_finished_list(results)
  239. else:
  240. result = model_class(**data) # type: CloudApiClientModel
  241. on_finished_item = cast(Callable[[CloudApiClientModel], Any], on_finished)
  242. on_finished_item(result)
  243. elif "errors" in response:
  244. self._on_error([CloudError(**error) for error in response["errors"]])
  245. else:
  246. Logger.log("e", "Cannot find data or errors in the cloud response: %s", response)
  247. def requestUpload3MF(self, request: DFLibraryFileUploadRequest,
  248. on_finished: Callable[[DFLibraryFileUploadResponse], Any],
  249. on_error: Optional[Callable[["QNetworkReply", "QNetworkReply.NetworkError"], None]] = None) -> None:
  250. """Requests the Digital Factory to register the upload of a file in a library project.
  251. :param request: The request object.
  252. :param on_finished: The function to be called after the result is parsed.
  253. :param on_error: The callback in case the request fails.
  254. """
  255. url = "{}/files/upload".format(self.CURA_API_ROOT)
  256. data = json.dumps({"data": request.toDict()}).encode()
  257. self._http.put(url,
  258. scope = self._scope,
  259. data = data,
  260. callback = self._parseCallback(on_finished, DFLibraryFileUploadResponse),
  261. error_callback = on_error,
  262. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  263. def requestUploadMeshFile(self, request: DFPrintJobUploadRequest,
  264. on_finished: Callable[[DFPrintJobUploadResponse], Any],
  265. on_error: Optional[Callable[["QNetworkReply", "QNetworkReply.NetworkError"], None]] = None) -> None:
  266. """Requests the Digital Factory to register the upload of a file in a library project.
  267. :param request: The request object.
  268. :param on_finished: The function to be called after the result is parsed.
  269. :param on_error: The callback in case the request fails.
  270. """
  271. url = "{}/jobs/upload".format(self.CURA_API_ROOT)
  272. data = json.dumps({"data": request.toDict()}).encode()
  273. self._http.put(url,
  274. scope = self._scope,
  275. data = data,
  276. callback = self._parseCallback(on_finished, DFPrintJobUploadResponse),
  277. error_callback = on_error,
  278. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  279. def uploadExportedFileData(self,
  280. df_file_upload_response: Union[DFLibraryFileUploadResponse, DFPrintJobUploadResponse],
  281. mesh: bytes,
  282. on_finished: Callable[[str], Any],
  283. on_success: Callable[[str], Any],
  284. on_progress: Callable[[str, int], Any],
  285. on_error: Callable[[str, "QNetworkReply", "QNetworkReply.NetworkError"], Any]) -> None:
  286. """Uploads an exported file (in bytes) to the Digital Factory Library.
  287. :param df_file_upload_response: The response received after requesting an upload with `self.requestUpload`.
  288. :param mesh: The mesh data (in bytes) to be uploaded.
  289. :param on_finished: The function to be called after the upload has finished. Called both after on_success and on_error.
  290. It receives the name of the file that has finished uploading.
  291. :param on_success: The function to be called if the upload was successful.
  292. It receives the name of the file that was uploaded successfully.
  293. :param on_progress: A function to be called during upload progress. It receives a percentage (0-100).
  294. It receives the name of the file for which the upload progress should be updated.
  295. :param on_error: A function to be called if the upload fails.
  296. It receives the name of the file that produced errors during the upload process.
  297. """
  298. self._file_uploader = DFFileUploader(self._http, df_file_upload_response, mesh, on_finished, on_success, on_progress, on_error)
  299. self._file_uploader.start()
  300. def createNewProject(self, project_name: str, on_finished: Callable[[DigitalFactoryProjectResponse], Any], on_error: Callable) -> None:
  301. """ Create a new project in the Digital Factory.
  302. :param project_name: Name of the new to be created project.
  303. :param on_finished: The function to be called after the result is parsed.
  304. :param on_error: The function to be called if anything goes wrong.
  305. """
  306. Logger.log("i", "Attempt to create new DF project '{}'.".format(project_name))
  307. url = "{}/projects".format(self.CURA_API_ROOT)
  308. data = json.dumps({"data": {"display_name": project_name}}).encode()
  309. self._http.put(url,
  310. scope = self._scope,
  311. data = data,
  312. callback = self._parseCallback(on_finished, DigitalFactoryProjectResponse),
  313. error_callback = on_error,
  314. timeout = self.DEFAULT_REQUEST_TIMEOUT)
  315. def clear(self) -> None:
  316. if self._projects_pagination_mgr is not None:
  317. self._projects_pagination_mgr.reset()