CloudMaterialSync.py 10 KB

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