CloudMaterialSync.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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.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. material = registry.findContainers(id = metadata["id"])[0]
  133. suffix = registry.getMimeTypeForContainer(type(material)).preferredSuffix
  134. filename = metadata["id"] + "." + suffix
  135. try:
  136. archive.writestr(filename, material.serialize())
  137. except OSError as e:
  138. Logger.log("e", f"An error has occurred while writing the material \'{metadata['id']}\' in the file \'{filename}\': {e}.")
  139. exportUploadStatusChanged = pyqtSignal()
  140. @pyqtProperty(str, notify = exportUploadStatusChanged)
  141. def exportUploadStatus(self) -> str:
  142. return self._export_upload_status
  143. @pyqtSlot()
  144. def exportUpload(self) -> None:
  145. """
  146. Export all materials and upload them to the user's account.
  147. """
  148. self._export_upload_status = "uploading"
  149. self.exportUploadStatusChanged.emit()
  150. job = UploadMaterialsJob(self)
  151. job.uploadProgressChanged.connect(self._onUploadProgressChanged)
  152. job.uploadCompleted.connect(self.exportUploadCompleted)
  153. job.start()
  154. def _onUploadProgressChanged(self, progress: float, printers_status: Dict[str, str]):
  155. self.setExportProgress(progress)
  156. self.setPrinterStatus(printers_status)
  157. def exportUploadCompleted(self, job_result: UploadMaterialsJob.Result, job_error: Optional[Exception]):
  158. if not self.sync_all_dialog: # Shouldn't get triggered before the dialog is open, but better to check anyway.
  159. return
  160. if job_result == UploadMaterialsJob.Result.FAILED:
  161. if isinstance(job_error, UploadMaterialsError):
  162. self.sync_all_dialog.setProperty("syncStatusText", str(job_error))
  163. else: # Could be "None"
  164. self.sync_all_dialog.setProperty("syncStatusText", catalog.i18nc("@text", "Unknown error."))
  165. self._export_upload_status = "error"
  166. else:
  167. self._export_upload_status = "success"
  168. self.exportUploadStatusChanged.emit()
  169. exportProgressChanged = pyqtSignal(float)
  170. def setExportProgress(self, progress: float) -> None:
  171. self._export_progress = progress
  172. self.exportProgressChanged.emit(self._export_progress)
  173. @pyqtProperty(float, fset = setExportProgress, notify = exportProgressChanged)
  174. def exportProgress(self) -> float:
  175. return self._export_progress
  176. printerStatusChanged = pyqtSignal()
  177. def setPrinterStatus(self, new_status: Dict[str, str]) -> None:
  178. self._printer_status = new_status
  179. self.printerStatusChanged.emit()
  180. @pyqtProperty("QVariantMap", fset = setPrinterStatus, notify = printerStatusChanged)
  181. def printerStatus(self) -> Dict[str, str]:
  182. return self._printer_status
  183. def reset(self) -> None:
  184. self.setPrinterStatus({})
  185. self.setExportProgress(0.0)
  186. self._export_upload_status = "idle"
  187. self.exportUploadStatusChanged.emit()