Backup.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import io
  4. import os
  5. import re
  6. import shutil
  7. from typing import Optional
  8. from zipfile import ZipFile, ZIP_DEFLATED, BadZipfile
  9. from UM import i18nCatalog
  10. from UM.Logger import Logger
  11. from UM.Message import Message
  12. from UM.Platform import Platform
  13. from UM.Resources import Resources
  14. from cura.CuraApplication import CuraApplication
  15. class Backup:
  16. """
  17. The backup class holds all data about a backup.
  18. It is also responsible for reading and writing the zip file to the user data folder.
  19. """
  20. # These files should be ignored when making a backup.
  21. IGNORED_FILES = [r"cura\.log", r"plugins\.json", r"cache", r"__pycache__", r"\.qmlc", r"\.pyc"]
  22. # Re-use translation catalog.
  23. catalog = i18nCatalog("cura")
  24. def __init__(self, zip_file: bytes = None, meta_data: dict = None):
  25. self.zip_file = zip_file # type: Optional[bytes]
  26. self.meta_data = meta_data # type: Optional[dict]
  27. def makeFromCurrent(self) -> (bool, Optional[str]):
  28. """
  29. Create a backup from the current user config folder.
  30. """
  31. cura_release = CuraApplication.getInstance().getVersion()
  32. version_data_dir = Resources.getDataStoragePath()
  33. Logger.log("d", "Creating backup for Cura %s, using folder %s", cura_release, version_data_dir)
  34. # Ensure all current settings are saved.
  35. CuraApplication.getInstance().saveSettings()
  36. # We copy the preferences file to the user data directory in Linux as it's in a different location there.
  37. # When restoring a backup on Linux, we move it back.
  38. if Platform.isLinux():
  39. preferences_file_name = CuraApplication.getInstance().getApplicationName()
  40. preferences_file = Resources.getPath(Resources.Preferences, "{}.cfg".format(preferences_file_name))
  41. backup_preferences_file = os.path.join(version_data_dir, "{}.cfg".format(preferences_file_name))
  42. Logger.log("d", "Copying preferences file from %s to %s", preferences_file, backup_preferences_file)
  43. shutil.copyfile(preferences_file, backup_preferences_file)
  44. # Create an empty buffer and write the archive to it.
  45. buffer = io.BytesIO()
  46. archive = self._makeArchive(buffer, version_data_dir)
  47. files = archive.namelist()
  48. # Count the metadata items. We do this in a rather naive way at the moment.
  49. machine_count = len([s for s in files if "machine_instances/" in s]) - 1
  50. material_count = len([s for s in files if "materials/" in s]) - 1
  51. profile_count = len([s for s in files if "quality_changes/" in s]) - 1
  52. plugin_count = len([s for s in files if "plugin.json" in s])
  53. # Store the archive and metadata so the BackupManager can fetch them when needed.
  54. self.zip_file = buffer.getvalue()
  55. self.meta_data = {
  56. "cura_release": cura_release,
  57. "machine_count": str(machine_count),
  58. "material_count": str(material_count),
  59. "profile_count": str(profile_count),
  60. "plugin_count": str(plugin_count)
  61. }
  62. def _makeArchive(self, buffer: "io.BytesIO", root_path: str) -> Optional[ZipFile]:
  63. """
  64. Make a full archive from the given root path with the given name.
  65. :param root_path: The root directory to archive recursively.
  66. :return: The archive as bytes.
  67. """
  68. ignore_string = re.compile("|".join(self.IGNORED_FILES))
  69. try:
  70. archive = ZipFile(buffer, "w", ZIP_DEFLATED)
  71. for root, folders, files in os.walk(root_path):
  72. for item_name in folders + files:
  73. absolute_path = os.path.join(root, item_name)
  74. if ignore_string.search(absolute_path):
  75. continue
  76. archive.write(absolute_path, absolute_path[len(root_path) + len(os.sep):])
  77. archive.close()
  78. return archive
  79. except (IOError, OSError, BadZipfile) as error:
  80. Logger.log("e", "Could not create archive from user data directory: %s", error)
  81. self._showMessage(
  82. self.catalog.i18nc("@info:backup_failed",
  83. "Could not create archive from user data directory: {}".format(error)))
  84. return None
  85. def _showMessage(self, message: str) -> None:
  86. """Show a UI message"""
  87. Message(message, title=self.catalog.i18nc("@info:title", "Backup"), lifetime=30).show()
  88. def restore(self) -> bool:
  89. """
  90. Restore this backups
  91. :return: A boolean whether we had success or not.
  92. """
  93. if not self.zip_file or not self.meta_data or not self.meta_data.get("cura_release", None):
  94. # We can restore without the minimum required information.
  95. Logger.log("w", "Tried to restore a Cura backup without having proper data or meta data.")
  96. self._showMessage(
  97. self.catalog.i18nc("@info:backup_failed",
  98. "Tried to restore a Cura backup without having proper data or meta data."))
  99. return False
  100. current_version = CuraApplication.getInstance().getVersion()
  101. version_to_restore = self.meta_data.get("cura_release", "master")
  102. if current_version != version_to_restore:
  103. # Cannot restore version older or newer than current because settings might have changed.
  104. # Restoring this will cause a lot of issues so we don't allow this for now.
  105. self._showMessage(
  106. self.catalog.i18nc("@info:backup_failed",
  107. "Tried to restore a Cura backup that does not match your current version."))
  108. return False
  109. version_data_dir = Resources.getDataStoragePath()
  110. archive = ZipFile(io.BytesIO(self.zip_file), "r")
  111. extracted = self._extractArchive(archive, version_data_dir)
  112. # Under Linux, preferences are stored elsewhere, so we copy the file to there.
  113. if Platform.isLinux():
  114. preferences_file_name = CuraApplication.getInstance().getApplicationName()
  115. preferences_file = Resources.getPath(Resources.Preferences, "{}.cfg".format(preferences_file_name))
  116. backup_preferences_file = os.path.join(version_data_dir, "{}.cfg".format(preferences_file_name))
  117. Logger.log("d", "Moving preferences file from %s to %s", backup_preferences_file, preferences_file)
  118. shutil.move(backup_preferences_file, preferences_file)
  119. return extracted
  120. @staticmethod
  121. def _extractArchive(archive: "ZipFile", target_path: str) -> bool:
  122. """
  123. Extract the whole archive to the given target path.
  124. :param archive: The archive as ZipFile.
  125. :param target_path: The target path.
  126. :return: A boolean whether we had success or not.
  127. """
  128. Logger.log("d", "Removing current data in location: %s", target_path)
  129. Resources.factoryReset()
  130. Logger.log("d", "Extracting backup to location: %s", target_path)
  131. archive.extractall(target_path)
  132. return True