DFFileExportAndUploadManager.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. # Copyright (c) 2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import threading
  5. from json import JSONDecodeError
  6. from typing import List, Dict, Any, Callable, Union, Optional
  7. from PyQt6.QtCore import QUrl
  8. from PyQt6.QtGui import QDesktopServices
  9. from PyQt6.QtNetwork import QNetworkReply
  10. from UM.FileHandler.FileHandler import FileHandler
  11. from UM.Logger import Logger
  12. from UM.Message import Message
  13. from UM.Scene.SceneNode import SceneNode
  14. from cura.CuraApplication import CuraApplication
  15. from .BackwardsCompatibleMessage import getBackwardsCompatibleMessage
  16. from .DFLibraryFileUploadRequest import DFLibraryFileUploadRequest
  17. from .DFLibraryFileUploadResponse import DFLibraryFileUploadResponse
  18. from .DFPrintJobUploadRequest import DFPrintJobUploadRequest
  19. from .DFPrintJobUploadResponse import DFPrintJobUploadResponse
  20. from .DigitalFactoryApiClient import DigitalFactoryApiClient
  21. from .ExportFileJob import ExportFileJob
  22. class DFFileExportAndUploadManager:
  23. """
  24. Class responsible for exporting the scene and uploading the exported data to the Digital Factory Library. Since 3mf
  25. and (UFP or makerbot) files may need to be uploaded at the same time, this class keeps a single progress and success message for
  26. both files and updates those messages according to the progress of both the file job uploads.
  27. """
  28. def __init__(self, file_handlers: Dict[str, FileHandler],
  29. nodes: List[SceneNode],
  30. library_project_id: str,
  31. library_project_name: str,
  32. file_name: str,
  33. formats: List[str],
  34. on_upload_error: Callable[[], Any],
  35. on_upload_success: Callable[[], Any],
  36. on_upload_finished: Callable[[], Any],
  37. on_upload_progress: Callable[[int], Any]) -> None:
  38. self._file_handlers: Dict[str, FileHandler] = file_handlers
  39. self._nodes: List[SceneNode] = nodes
  40. self._library_project_id: str = library_project_id
  41. self._library_project_name: str = library_project_name
  42. self._file_name: str = file_name
  43. self._upload_jobs: List[ExportFileJob] = []
  44. self._formats: List[str] = formats
  45. self._api = DigitalFactoryApiClient(application = CuraApplication.getInstance(), on_error = lambda error: Logger.log("e", str(error)))
  46. self._source_file_id: Optional[str] = None
  47. # Functions of the parent class that should be called based on the upload process output
  48. self._on_upload_error = on_upload_error
  49. self._on_upload_success = on_upload_success
  50. self._on_upload_finished = on_upload_finished
  51. self._on_upload_progress = on_upload_progress
  52. # Lock used for updating the progress message (since the progress is changed by two parallel upload jobs) or
  53. # show the success message (once both upload jobs are done)
  54. self._message_lock = threading.Lock()
  55. self._file_upload_job_metadata: Dict[str, Dict[str, Any]] = self.initializeFileUploadJobMetadata()
  56. self.progress_message = Message(
  57. title = "Uploading...",
  58. text = "Uploading files to '{}'".format(self._library_project_name),
  59. progress = -1,
  60. lifetime = 0,
  61. dismissable = False,
  62. use_inactivity_timer = False
  63. )
  64. self._generic_success_message = getBackwardsCompatibleMessage(
  65. text = "Your {} uploaded to '{}'.".format("file was" if len(self._file_upload_job_metadata) <= 1 else "files were", self._library_project_name),
  66. title = "Upload successful",
  67. lifetime = 30,
  68. message_type_str = "POSITIVE"
  69. )
  70. self._generic_success_message.addAction(
  71. "open_df_project",
  72. "Open project",
  73. "open-folder", "Open the project containing the file in Digital Library"
  74. )
  75. self._generic_success_message.actionTriggered.connect(self._onMessageActionTriggered)
  76. def _onCuraProjectFileExported(self, job: ExportFileJob) -> None:
  77. """Handler for when the DF Library workspace file (3MF) has been created locally.
  78. It can now be sent over the Digital Factory API.
  79. """
  80. if not job.getOutput():
  81. self._onJobExportError(job.getFileName())
  82. return
  83. self._file_upload_job_metadata[job.getFileName()]["export_job_output"] = job.getOutput()
  84. request = DFLibraryFileUploadRequest(
  85. content_type = job.getMimeType(),
  86. file_name = job.getFileName(),
  87. file_size = len(job.getOutput()),
  88. library_project_id = self._library_project_id
  89. )
  90. self._api.requestUpload3MF(request, on_finished = self._uploadFileData, on_error = self._onRequestUploadCuraProjectFileFailed)
  91. def _onPrintFileExported(self, job: ExportFileJob) -> None:
  92. """Handler for when the DF Library print job file (UFP) has been created locally.
  93. It can now be sent over the Digital Factory API.
  94. """
  95. if not job.getOutput():
  96. self._onJobExportError(job.getFileName())
  97. return
  98. self._file_upload_job_metadata[job.getFileName()]["export_job_output"] = job.getOutput()
  99. request = DFPrintJobUploadRequest(
  100. content_type = job.getMimeType(),
  101. job_name = job.getFileName(),
  102. file_size = len(job.getOutput()),
  103. library_project_id = self._library_project_id,
  104. source_file_id = self._source_file_id
  105. )
  106. self._api.requestUploadMeshFile(request, on_finished = self._uploadFileData, on_error = self._onRequestUploadPrintFileFailed)
  107. def _uploadFileData(self, file_upload_response: Union[DFLibraryFileUploadResponse, DFPrintJobUploadResponse]) -> None:
  108. """Uploads the exported file data after the file or print job upload has been registered at the Digital Factory
  109. Library API.
  110. :param file_upload_response: The response received from the Digital Factory Library API.
  111. """
  112. if isinstance(file_upload_response, DFLibraryFileUploadResponse):
  113. file_name = file_upload_response.file_name
  114. # store the `file_id` so it can be as `source_file_id` when uploading the print file
  115. self._source_file_id = file_upload_response.file_id
  116. elif isinstance(file_upload_response, DFPrintJobUploadResponse):
  117. file_name = file_upload_response.job_name if file_upload_response.job_name is not None else ""
  118. else:
  119. Logger.log("e", "Wrong response type received. Aborting uploading file to the Digital Library")
  120. getBackwardsCompatibleMessage(
  121. text = "Upload error",
  122. title = f"Failed to upload {file_name}. Received unexpected response from server.",
  123. message_type_str = "ERROR",
  124. lifetime = 0
  125. ).show()
  126. return
  127. if file_name not in self._file_upload_job_metadata:
  128. Logger.error(f"API response for uploading doesn't match the file name we just uploaded: {file_name} was never uploaded.")
  129. getBackwardsCompatibleMessage(
  130. text = "Upload error",
  131. title = f"Failed to upload {file_name}. Name doesn't match the one sent back in confirmation.",
  132. message_type_str = "ERROR",
  133. lifetime = 0
  134. ).show()
  135. return
  136. with self._message_lock:
  137. self.progress_message.show()
  138. self._file_upload_job_metadata[file_name]["file_upload_response"] = file_upload_response
  139. job_output = self._file_upload_job_metadata[file_name]["export_job_output"]
  140. with self._message_lock:
  141. self._file_upload_job_metadata[file_name]["upload_status"] = "uploading"
  142. self._api.uploadExportedFileData(file_upload_response,
  143. job_output,
  144. on_finished = self._onFileUploadFinished,
  145. on_success = self._onUploadSuccess,
  146. on_progress = self._onUploadProgress,
  147. on_error = self._onUploadError)
  148. self._handleNextUploadJob()
  149. def _onUploadProgress(self, filename: str, progress: int) -> None:
  150. """
  151. Updates the progress message according to the total progress of the two files and displays it to the user. It is
  152. made thread-safe with a lock, since the progress can be updated by two separate upload jobs
  153. :param filename: The name of the file for which we have progress (including the extension).
  154. :param progress: The progress percentage
  155. """
  156. with self._message_lock:
  157. self._file_upload_job_metadata[filename]["upload_progress"] = progress
  158. self._file_upload_job_metadata[filename]["upload_status"] = "uploading"
  159. total_progress = self.getTotalProgress()
  160. self.progress_message.setProgress(total_progress)
  161. self.progress_message.show()
  162. self._on_upload_progress(progress)
  163. def _onUploadSuccess(self, filename: str) -> None:
  164. """
  165. Sets the upload status to success and the progress of the file with the given filename to 100%. This function is
  166. should be called only if the file has uploaded all of its data successfully (i.e. no error occurred during the
  167. upload process).
  168. :param filename: The name of the file that was uploaded successfully (including the extension).
  169. """
  170. with self._message_lock:
  171. self._file_upload_job_metadata[filename]["upload_status"] = "success"
  172. self._file_upload_job_metadata[filename]["upload_progress"] = 100
  173. self._on_upload_success()
  174. def _onFileUploadFinished(self, filename: str) -> None:
  175. """
  176. Callback that makes sure the correct messages are displayed according to the statuses of the individual jobs.
  177. This function is called whenever an upload job has finished, regardless if it had errors or was successful.
  178. Both jobs have to have finished for the messages to show.
  179. :param filename: The name of the file that has finished uploading (including the extension).
  180. """
  181. with self._message_lock:
  182. # All files have finished their uploading process
  183. if all([(file_upload_job["upload_progress"] == 100 and file_upload_job["upload_status"] != "uploading") for file_upload_job in self._file_upload_job_metadata.values()]):
  184. # Reset and hide the progress message
  185. self.progress_message.setProgress(-1)
  186. self.progress_message.hide()
  187. # All files were successfully uploaded.
  188. if all([(file_upload_job["upload_status"] == "success") for file_upload_job in self._file_upload_job_metadata.values()]):
  189. # Show a single generic success message for all files
  190. self._generic_success_message.show()
  191. else: # One or more files failed to upload.
  192. # Show individual messages for each file, according to their statuses
  193. for filename, upload_job_metadata in self._file_upload_job_metadata.items():
  194. if upload_job_metadata["upload_status"] == "success":
  195. upload_job_metadata["file_upload_success_message"].show()
  196. else:
  197. upload_job_metadata["file_upload_failed_message"].show()
  198. # Call the parent's finished function
  199. self._on_upload_finished()
  200. def _onJobExportError(self, filename: str) -> None:
  201. """
  202. Displays an appropriate message when the process to export a file fails.
  203. :param filename: The name of the file that failed to be exported (including the extension).
  204. """
  205. Logger.log("d", "Error while exporting file '{}'".format(filename))
  206. with self._message_lock:
  207. # Set the progress to 100% when the upload job fails, to avoid having the progress message stuck
  208. self._file_upload_job_metadata[filename]["upload_status"] = "failed"
  209. self._file_upload_job_metadata[filename]["upload_progress"] = 100
  210. self._file_upload_job_metadata[filename]["file_upload_failed_message"] = getBackwardsCompatibleMessage(
  211. text = "Failed to export the file '{}'. The upload process is aborted.".format(filename),
  212. title = "Export error",
  213. message_type_str = "ERROR",
  214. lifetime = 30
  215. )
  216. self._on_upload_error()
  217. self._onFileUploadFinished(filename)
  218. def _onRequestUploadCuraProjectFileFailed(self, reply: "QNetworkReply", network_error: "QNetworkReply.NetworkError") -> None:
  219. """
  220. Displays an appropriate message when the request to upload the Cura project file (.3mf) to the Digital Library fails.
  221. This means that something went wrong with the initial request to create a "file" entry in the digital library.
  222. """
  223. reply_string = bytes(reply.readAll()).decode()
  224. filename_3mf = self._file_name + ".3mf"
  225. Logger.log("d", "An error occurred while uploading the Cura project file '{}' to the Digital Library project '{}': {}".format(filename_3mf, self._library_project_id, reply_string))
  226. with self._message_lock:
  227. # Set the progress to 100% when the upload job fails, to avoid having the progress message stuck
  228. self._file_upload_job_metadata[filename_3mf]["upload_status"] = "failed"
  229. self._file_upload_job_metadata[filename_3mf]["upload_progress"] = 100
  230. human_readable_error = self.extractErrorTitle(reply_string)
  231. self._file_upload_job_metadata[filename_3mf]["file_upload_failed_message"] = getBackwardsCompatibleMessage(
  232. text = "Failed to upload the file '{}' to '{}'. {}".format(filename_3mf, self._library_project_name, human_readable_error),
  233. title = "File upload error",
  234. message_type_str = "ERROR",
  235. lifetime = 30
  236. )
  237. self._on_upload_error()
  238. self._onFileUploadFinished(filename_3mf)
  239. def _onRequestUploadPrintFileFailed(self, reply: "QNetworkReply", network_error: "QNetworkReply.NetworkError") -> None:
  240. """
  241. Displays an appropriate message when the request to upload the print file (.ufp) to the Digital Library fails.
  242. This means that something went wrong with the initial request to create a "file" entry in the digital library.
  243. """
  244. reply_string = bytes(reply.readAll()).decode()
  245. if "ufp" in self._formats:
  246. filename_meshfile = self._file_name + ".ufp"
  247. elif "makerbot" in self._formats:
  248. filename_meshfile = self._file_name + ".makerbot"
  249. Logger.log("d", "An error occurred while uploading the print job file '{}' to the Digital Library project '{}': {}".format(filename_meshfile, self._library_project_id, reply_string))
  250. with self._message_lock:
  251. # Set the progress to 100% when the upload job fails, to avoid having the progress message stuck
  252. self._file_upload_job_metadata[filename_meshfile]["upload_status"] = "failed"
  253. self._file_upload_job_metadata[filename_meshfile]["upload_progress"] = 100
  254. human_readable_error = self.extractErrorTitle(reply_string)
  255. self._file_upload_job_metadata[filename_meshfile]["file_upload_failed_message"] = getBackwardsCompatibleMessage(
  256. title = "File upload error",
  257. text = "Failed to upload the file '{}' to '{}'. {}".format(filename_meshfile, self._library_project_name, human_readable_error),
  258. message_type_str = "ERROR",
  259. lifetime = 30
  260. )
  261. self._on_upload_error()
  262. self._onFileUploadFinished(filename_meshfile)
  263. @staticmethod
  264. def extractErrorTitle(reply_body: Optional[str]) -> str:
  265. error_title = ""
  266. if reply_body:
  267. try:
  268. reply_dict = json.loads(reply_body)
  269. except JSONDecodeError:
  270. Logger.logException("w", "Unable to extract title from reply body")
  271. return error_title
  272. if "errors" in reply_dict and len(reply_dict["errors"]) >= 1 and "title" in reply_dict["errors"][0]:
  273. error_title = reply_dict["errors"][0]["title"]
  274. return error_title
  275. def _onUploadError(self, filename: str, reply: "QNetworkReply", error: "QNetworkReply.NetworkError") -> None:
  276. """
  277. Displays the given message if uploading the mesh has failed due to a generic error (i.e. lost connection).
  278. If one of the two files fail, this error function will set its progress as finished, to make sure that the
  279. progress message doesn't get stuck.
  280. :param filename: The name of the file that failed to upload (including the extension).
  281. """
  282. reply_string = bytes(reply.readAll()).decode()
  283. Logger.log("d", "Error while uploading '{}' to the Digital Library project '{}'. Reply: {}".format(filename, self._library_project_id, reply_string))
  284. with self._message_lock:
  285. # Set the progress to 100% when the upload job fails, to avoid having the progress message stuck
  286. self._file_upload_job_metadata[filename]["upload_status"] = "failed"
  287. self._file_upload_job_metadata[filename]["upload_progress"] = 100
  288. human_readable_error = self.extractErrorTitle(reply_string)
  289. self._file_upload_job_metadata[filename]["file_upload_failed_message"] = getBackwardsCompatibleMessage(
  290. title = "File upload error",
  291. text = "Failed to upload the file '{}' to '{}'. {}".format(self._file_name, self._library_project_name, human_readable_error),
  292. message_type_str = "ERROR",
  293. lifetime = 30
  294. )
  295. self._on_upload_error()
  296. def getTotalProgress(self) -> int:
  297. """
  298. Returns the total upload progress of all the upload jobs
  299. :return: The average progress percentage
  300. """
  301. return int(sum([file_upload_job["upload_progress"] for file_upload_job in self._file_upload_job_metadata.values()]) / len(self._file_upload_job_metadata.values()))
  302. def _onMessageActionTriggered(self, message, action):
  303. if action == "open_df_project":
  304. project_url = "{}/app/library/project/{}?wait_for_new_files=true&utm_source=cura&utm_medium=software&utm_campaign=saved-library-file-message".format(CuraApplication.getInstance().ultimakerDigitalFactoryUrl, self._library_project_id)
  305. QDesktopServices.openUrl(QUrl(project_url))
  306. message.hide()
  307. def start(self) -> None:
  308. self._handleNextUploadJob()
  309. def _handleNextUploadJob(self):
  310. try:
  311. job = self._upload_jobs.pop(0)
  312. job.start()
  313. except IndexError:
  314. pass # Empty list, do nothing.
  315. def initializeFileUploadJobMetadata(self) -> Dict[str, Any]:
  316. metadata = {}
  317. self._upload_jobs = []
  318. if "3mf" in self._formats and "3mf" in self._file_handlers and self._file_handlers["3mf"]:
  319. filename_3mf = self._file_name + ".3mf"
  320. metadata[filename_3mf] = {
  321. "export_job_output" : None,
  322. "upload_progress" : -1,
  323. "upload_status" : "",
  324. "file_upload_response": None,
  325. "file_upload_success_message": getBackwardsCompatibleMessage(
  326. text = "'{}' was uploaded to '{}'.".format(filename_3mf, self._library_project_name),
  327. title = "Upload successful",
  328. message_type_str = "POSITIVE",
  329. lifetime = 30
  330. ),
  331. "file_upload_failed_message": getBackwardsCompatibleMessage(
  332. text = "Failed to upload the file '{}' to '{}'.".format(filename_3mf, self._library_project_name),
  333. title = "File upload error",
  334. message_type_str = "ERROR",
  335. lifetime = 30
  336. )
  337. }
  338. job_3mf = ExportFileJob(self._file_handlers["3mf"], self._nodes, self._file_name, "3mf")
  339. job_3mf.finished.connect(self._onCuraProjectFileExported)
  340. self._upload_jobs.append(job_3mf)
  341. if "ufp" in self._formats and "ufp" in self._file_handlers and self._file_handlers["ufp"]:
  342. filename_ufp = self._file_name + ".ufp"
  343. metadata[filename_ufp] = {
  344. "export_job_output" : None,
  345. "upload_progress" : -1,
  346. "upload_status" : "",
  347. "file_upload_response": None,
  348. "file_upload_success_message": getBackwardsCompatibleMessage(
  349. text = "'{}' was uploaded to '{}'.".format(filename_ufp, self._library_project_name),
  350. title = "Upload successful",
  351. message_type_str = "POSITIVE",
  352. lifetime = 30,
  353. ),
  354. "file_upload_failed_message": getBackwardsCompatibleMessage(
  355. text = "Failed to upload the file '{}' to '{}'.".format(filename_ufp, self._library_project_name),
  356. title = "File upload error",
  357. message_type_str = "ERROR",
  358. lifetime = 30
  359. )
  360. }
  361. job_ufp = ExportFileJob(self._file_handlers["ufp"], self._nodes, self._file_name, "ufp")
  362. job_ufp.finished.connect(self._onPrintFileExported)
  363. self._upload_jobs.append(job_ufp)
  364. if "makerbot" in self._formats and "makerbot" in self._file_handlers and self._file_handlers["makerbot"]:
  365. filename_makerbot = self._file_name + ".makerbot"
  366. metadata[filename_makerbot] = {
  367. "export_job_output" : None,
  368. "upload_progress" : -1,
  369. "upload_status" : "",
  370. "file_upload_response": None,
  371. "file_upload_success_message": getBackwardsCompatibleMessage(
  372. text = "'{}' was uploaded to '{}'.".format(filename_makerbot, self._library_project_name),
  373. title = "Upload successful",
  374. message_type_str = "POSITIVE",
  375. lifetime = 30,
  376. ),
  377. "file_upload_failed_message": getBackwardsCompatibleMessage(
  378. text = "Failed to upload the file '{}' to '{}'.".format(filename_makerbot, self._library_project_name),
  379. title = "File upload error",
  380. message_type_str = "ERROR",
  381. lifetime = 30
  382. )
  383. }
  384. job_makerbot = ExportFileJob(self._file_handlers["makerbot"], self._nodes, self._file_name, "makerbot")
  385. job_makerbot.finished.connect(self._onPrintFileExported)
  386. self._upload_jobs.append(job_makerbot)
  387. return metadata