CloudMaterialSync.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 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.show()
  52. def _showSyncNewMaterialsMessage(self) -> None:
  53. sync_materials_message = Message(
  54. text = catalog.i18nc("@action:button",
  55. "Please sync the material profiles with your printers before starting to print."),
  56. title = catalog.i18nc("@action:button", "New materials installed"),
  57. message_type = Message.MessageType.WARNING,
  58. lifetime = 0
  59. )
  60. sync_materials_message.addAction(
  61. "sync",
  62. name = catalog.i18nc("@action:button", "Sync materials with printers"),
  63. icon = "",
  64. description = "Sync your newly installed materials with your printers.",
  65. button_align = Message.ActionButtonAlignment.ALIGN_RIGHT
  66. )
  67. sync_materials_message.addAction(
  68. "learn_more",
  69. name = catalog.i18nc("@action:button", "Learn more"),
  70. icon = "",
  71. description = "Learn more about syncing your newly installed materials with your printers.",
  72. button_align = Message.ActionButtonAlignment.ALIGN_LEFT,
  73. button_style = Message.ActionButtonStyle.LINK
  74. )
  75. sync_materials_message.actionTriggered.connect(self._onSyncMaterialsMessageActionTriggered)
  76. # Show the message only if there are printers that support material export
  77. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  78. global_stacks = container_registry.findContainerStacks(type = "machine")
  79. if any([stack.supportsMaterialExport for stack in global_stacks]):
  80. sync_materials_message.show()
  81. def _onSyncMaterialsMessageActionTriggered(self, sync_message: Message, sync_message_action: str):
  82. if sync_message_action == "sync":
  83. self.openSyncAllWindow()
  84. sync_message.hide()
  85. elif sync_message_action == "learn_more":
  86. QDesktopServices.openUrl(QUrl("https://support.ultimaker.com/hc/en-us/articles/360013137919?utm_source=cura&utm_medium=software&utm_campaign=sync-material-printer-message"))
  87. @pyqtSlot(result = QUrl)
  88. def getPreferredExportAllPath(self) -> QUrl:
  89. """
  90. Get the preferred path to export materials to.
  91. If there is a removable drive, that should be the preferred path. Otherwise it should be the most recent local
  92. file path.
  93. :return: The preferred path to export all materials to.
  94. """
  95. cura_application = cura.CuraApplication.CuraApplication.getInstance()
  96. device_manager = cura_application.getOutputDeviceManager()
  97. devices = device_manager.getOutputDevices()
  98. for device in devices:
  99. if device.__class__.__name__ == "RemovableDriveOutputDevice":
  100. return QUrl.fromLocalFile(device.getId())
  101. else: # No removable drives? Use local path.
  102. return cura_application.getDefaultPath("dialog_material_path")
  103. @pyqtSlot(QUrl)
  104. def exportAll(self, file_path: QUrl, notify_progress: Optional["Signal"] = None) -> None:
  105. """
  106. Export all materials to a certain file path.
  107. :param file_path: The path to export the materials to.
  108. """
  109. registry = CuraContainerRegistry.getInstance()
  110. # Create empty archive.
  111. try:
  112. archive = zipfile.ZipFile(file_path.toLocalFile(), "w", compression = zipfile.ZIP_DEFLATED)
  113. except OSError as e:
  114. Logger.log("e", f"Can't write to destination {file_path.toLocalFile()}: {type(e)} - {str(e)}")
  115. error_message = Message(
  116. text = catalog.i18nc("@message:text", "Could not save material archive to {}:").format(file_path.toLocalFile()) + " " + str(e),
  117. title = catalog.i18nc("@message:title", "Failed to save material archive"),
  118. message_type = Message.MessageType.ERROR
  119. )
  120. error_message.show()
  121. return
  122. materials_metadata = registry.findInstanceContainersMetadata(type = "material")
  123. for index, metadata in enumerate(materials_metadata):
  124. if notify_progress is not None:
  125. progress = index / len(materials_metadata)
  126. notify_progress.emit(progress)
  127. if metadata["base_file"] != metadata["id"]: # Only process base files.
  128. continue
  129. if metadata["id"] == "empty_material": # Don't export the empty material.
  130. continue
  131. material = registry.findContainers(id = metadata["id"])[0]
  132. suffix = registry.getMimeTypeForContainer(type(material)).preferredSuffix
  133. filename = metadata["id"] + "." + suffix
  134. try:
  135. archive.writestr(filename, material.serialize())
  136. except OSError as e:
  137. Logger.log("e", f"An error has occurred while writing the material \'{metadata['id']}\' in the file \'{filename}\': {e}.")
  138. exportUploadStatusChanged = pyqtSignal()
  139. @pyqtProperty(str, notify = exportUploadStatusChanged)
  140. def exportUploadStatus(self) -> str:
  141. return self._export_upload_status
  142. @pyqtSlot()
  143. def exportUpload(self) -> None:
  144. """
  145. Export all materials and upload them to the user's account.
  146. """
  147. self._export_upload_status = "uploading"
  148. self.exportUploadStatusChanged.emit()
  149. job = UploadMaterialsJob(self)
  150. job.uploadProgressChanged.connect(self._onUploadProgressChanged)
  151. job.uploadCompleted.connect(self.exportUploadCompleted)
  152. job.start()
  153. def _onUploadProgressChanged(self, progress: float, printers_status: Dict[str, str]):
  154. self.setExportProgress(progress)
  155. self.setPrinterStatus(printers_status)
  156. def exportUploadCompleted(self, job_result: UploadMaterialsJob.Result, job_error: Optional[Exception]):
  157. if not self.sync_all_dialog: # Shouldn't get triggered before the dialog is open, but better to check anyway.
  158. return
  159. if job_result == UploadMaterialsJob.Result.FAILED:
  160. if isinstance(job_error, UploadMaterialsError):
  161. self.sync_all_dialog.setProperty("syncStatusText", str(job_error))
  162. else: # Could be "None"
  163. self.sync_all_dialog.setProperty("syncStatusText", catalog.i18nc("@text", "Unknown error."))
  164. self._export_upload_status = "error"
  165. else:
  166. self._export_upload_status = "success"
  167. self.exportUploadStatusChanged.emit()
  168. exportProgressChanged = pyqtSignal(float)
  169. def setExportProgress(self, progress: float) -> None:
  170. self._export_progress = progress
  171. self.exportProgressChanged.emit(self._export_progress)
  172. @pyqtProperty(float, fset = setExportProgress, notify = exportProgressChanged)
  173. def exportProgress(self) -> float:
  174. return self._export_progress
  175. printerStatusChanged = pyqtSignal()
  176. def setPrinterStatus(self, new_status: Dict[str, str]) -> None:
  177. self._printer_status = new_status
  178. self.printerStatusChanged.emit()
  179. @pyqtProperty("QVariantMap", fset = setPrinterStatus, notify = printerStatusChanged)
  180. def printerStatus(self) -> Dict[str, str]:
  181. return self._printer_status
  182. def reset(self) -> None:
  183. self.setPrinterStatus({})
  184. self.setExportProgress(0.0)
  185. self._export_upload_status = "idle"
  186. self.exportUploadStatusChanged.emit()