CloudMaterialSync.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject, QUrl
  4. from PyQt5.QtGui import QDesktopServices
  5. from typing import Dict, Optional, TYPE_CHECKING
  6. import zipfile # To export all materials in a .zip archive.
  7. import cura.CuraApplication # Imported like this to prevent circular imports.
  8. from cura.PrinterOutput.UploadMaterialsJob import UploadMaterialsJob, UploadMaterialsError # To export materials to the output printer.
  9. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry
  10. from UM.i18n import i18nCatalog
  11. from UM.Logger import Logger
  12. from UM.Message import Message
  13. if TYPE_CHECKING:
  14. from UM.Signal import Signal
  15. catalog = i18nCatalog("cura")
  16. class CloudMaterialSync(QObject):
  17. """
  18. Handles the synchronisation of material profiles with cloud accounts.
  19. """
  20. def __init__(self, parent: QObject = None):
  21. super().__init__(parent)
  22. self.sync_all_dialog = None # type: Optional[QObject]
  23. self._export_upload_status = "idle"
  24. self._checkIfNewMaterialsWereInstalled()
  25. self._export_progress = 0.0
  26. self._printer_status = {} # type: Dict[str, str]
  27. def _checkIfNewMaterialsWereInstalled(self) -> None:
  28. """
  29. Checks whether new material packages were installed in the latest startup. If there were, then it shows
  30. a message prompting the user to sync the materials with their printers.
  31. """
  32. application = cura.CuraApplication.CuraApplication.getInstance()
  33. for package_id, package_data in application.getPackageManager().getPackagesInstalledOnStartup().items():
  34. if package_data["package_info"]["package_type"] == "material":
  35. # At least one new material was installed
  36. self._showSyncNewMaterialsMessage()
  37. break
  38. def _showSyncNewMaterialsMessage(self) -> None:
  39. sync_materials_message = Message(
  40. text = catalog.i18nc("@action:button",
  41. "Please sync the material profiles with your printers before starting to print."),
  42. title = catalog.i18nc("@action:button", "New materials installed"),
  43. message_type = Message.MessageType.WARNING,
  44. lifetime = 0
  45. )
  46. sync_materials_message.addAction(
  47. "sync",
  48. name = catalog.i18nc("@action:button", "Sync materials with printers"),
  49. icon = "",
  50. description = "Sync your newly installed materials with your printers.",
  51. button_align = Message.ActionButtonAlignment.ALIGN_RIGHT
  52. )
  53. sync_materials_message.addAction(
  54. "learn_more",
  55. name = catalog.i18nc("@action:button", "Learn more"),
  56. icon = "",
  57. description = "Learn more about syncing your newly installed materials with your printers.",
  58. button_align = Message.ActionButtonAlignment.ALIGN_LEFT,
  59. button_style = Message.ActionButtonStyle.LINK
  60. )
  61. sync_materials_message.actionTriggered.connect(self._onSyncMaterialsMessageActionTriggered)
  62. # Show the message only if there are printers that support material export
  63. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  64. global_stacks = container_registry.findContainerStacks(type = "machine")
  65. if any([stack.supportsMaterialExport for stack in global_stacks]):
  66. sync_materials_message.show()
  67. def _onSyncMaterialsMessageActionTriggered(self, sync_message: Message, sync_message_action: str):
  68. if sync_message_action == "sync":
  69. self.openSyncAllWindow()
  70. sync_message.hide()
  71. elif sync_message_action == "learn_more":
  72. QDesktopServices.openUrl(QUrl("https://support.ultimaker.com/hc/en-us/articles/360013137919?utm_source=cura&utm_medium=software&utm_campaign=sync-material-printer-message"))
  73. @pyqtSlot(result = QUrl)
  74. def getPreferredExportAllPath(self) -> QUrl:
  75. """
  76. Get the preferred path to export materials to.
  77. If there is a removable drive, that should be the preferred path. Otherwise it should be the most recent local
  78. file path.
  79. :return: The preferred path to export all materials to.
  80. """
  81. cura_application = cura.CuraApplication.CuraApplication.getInstance()
  82. device_manager = cura_application.getOutputDeviceManager()
  83. devices = device_manager.getOutputDevices()
  84. for device in devices:
  85. if device.__class__.__name__ == "RemovableDriveOutputDevice":
  86. return QUrl.fromLocalFile(device.getId())
  87. else: # No removable drives? Use local path.
  88. return cura_application.getDefaultPath("dialog_material_path")
  89. @pyqtSlot(QUrl)
  90. def exportAll(self, file_path: QUrl, notify_progress: Optional["Signal"] = None) -> None:
  91. """
  92. Export all materials to a certain file path.
  93. :param file_path: The path to export the materials to.
  94. """
  95. registry = CuraContainerRegistry.getInstance()
  96. # Create empty archive.
  97. try:
  98. archive = zipfile.ZipFile(file_path.toLocalFile(), "w", compression = zipfile.ZIP_DEFLATED)
  99. except OSError as e:
  100. Logger.log("e", f"Can't write to destination {file_path.toLocalFile()}: {type(e)} - {str(e)}")
  101. error_message = Message(
  102. text = catalog.i18nc("@message:text", "Could not save material archive to {}:").format(file_path.toLocalFile()) + " " + str(e),
  103. title = catalog.i18nc("@message:title", "Failed to save material archive"),
  104. message_type = Message.MessageType.ERROR
  105. )
  106. error_message.show()
  107. return
  108. materials_metadata = registry.findInstanceContainersMetadata(type = "material")
  109. for index, metadata in enumerate(materials_metadata):
  110. if notify_progress is not None:
  111. progress = index / len(materials_metadata)
  112. notify_progress.emit(progress)
  113. if metadata["base_file"] != metadata["id"]: # Only process base files.
  114. continue
  115. if metadata["id"] == "empty_material": # Don't export the empty material.
  116. continue
  117. material = registry.findContainers(id = metadata["id"])[0]
  118. suffix = registry.getMimeTypeForContainer(type(material)).preferredSuffix
  119. filename = metadata["id"] + "." + suffix
  120. try:
  121. archive.writestr(filename, material.serialize())
  122. except OSError as e:
  123. Logger.log("e", f"An error has occurred while writing the material \'{metadata['id']}\' in the file \'{filename}\': {e}.")
  124. exportUploadStatusChanged = pyqtSignal()
  125. @pyqtProperty(str, notify = exportUploadStatusChanged)
  126. def exportUploadStatus(self) -> str:
  127. return self._export_upload_status
  128. @pyqtSlot()
  129. def exportUpload(self) -> None:
  130. """
  131. Export all materials and upload them to the user's account.
  132. """
  133. self._export_upload_status = "uploading"
  134. self.exportUploadStatusChanged.emit()
  135. job = UploadMaterialsJob(self)
  136. job.uploadProgressChanged.connect(self._onUploadProgressChanged)
  137. job.uploadCompleted.connect(self.exportUploadCompleted)
  138. job.start()
  139. def _onUploadProgressChanged(self, progress: float, printers_status: Dict[str, str]):
  140. self.setExportProgress(progress)
  141. self.setPrinterStatus(printers_status)
  142. def exportUploadCompleted(self, job_result: UploadMaterialsJob.Result, job_error: Optional[Exception]):
  143. if not self.sync_all_dialog: # Shouldn't get triggered before the dialog is open, but better to check anyway.
  144. return
  145. if job_result == UploadMaterialsJob.Result.FAILED:
  146. if isinstance(job_error, UploadMaterialsError):
  147. self.sync_all_dialog.setProperty("syncStatusText", catalog.i18nc("@text", "Error sending materials to the Digital Factory:") + " " + str(job_error))
  148. else: # Could be "None"
  149. self.sync_all_dialog.setProperty("syncStatusText", catalog.i18nc("@text", "Unknown error."))
  150. self._export_upload_status = "error"
  151. else:
  152. self._export_upload_status = "success"
  153. self.exportUploadStatusChanged.emit()
  154. exportProgressChanged = pyqtSignal(float)
  155. def setExportProgress(self, progress: float) -> None:
  156. self._export_progress = progress
  157. self.exportProgressChanged.emit(self._export_progress)
  158. @pyqtProperty(float, fset = setExportProgress, notify = exportProgressChanged)
  159. def exportProgress(self) -> float:
  160. return self._export_progress
  161. printerStatusChanged = pyqtSignal()
  162. def setPrinterStatus(self, new_status: Dict[str, str]) -> None:
  163. self._printer_status = new_status
  164. self.printerStatusChanged.emit()
  165. @pyqtProperty("QVariantMap", fset = setPrinterStatus, notify = printerStatusChanged)
  166. def printerStatus(self) -> Dict[str, str]:
  167. return self._printer_status
  168. def reset(self) -> None:
  169. self.setPrinterStatus({})
  170. self.setExportProgress(0.0)
  171. self._export_upload_status = "idle"
  172. self.exportUploadStatusChanged.emit()