Backup.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 zipfile import ZipFile, ZIP_DEFLATED, BadZipfile
  8. from typing import Dict, Optional, TYPE_CHECKING
  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. if TYPE_CHECKING:
  15. from cura.CuraApplication import CuraApplication
  16. ## The back-up class holds all data about a back-up.
  17. #
  18. # It is also responsible for reading and writing the zip file to the user data
  19. # folder.
  20. class Backup:
  21. # These files should be ignored when making a backup.
  22. IGNORED_FILES = [r"cura\.log", r"plugins\.json", r"cache", r"__pycache__", r"\.qmlc", r"\.pyc"]
  23. # Re-use translation catalog.
  24. catalog = i18nCatalog("cura")
  25. def __init__(self, application: "CuraApplication", zip_file: bytes = None, meta_data: Dict[str, str] = None) -> None:
  26. self._application = application
  27. self.zip_file = zip_file # type: Optional[bytes]
  28. self.meta_data = meta_data # type: Optional[Dict[str, str]]
  29. ## Create a back-up from the current user config folder.
  30. def makeFromCurrent(self) -> None:
  31. cura_release = self._application.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. self._application.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(): #TODO: This should check for the config directory not being the same as the data directory, rather than hard-coding that to Linux systems.
  39. preferences_file_name = self._application.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. if os.path.exists(preferences_file) and (not os.path.exists(backup_preferences_file) or not os.path.samefile(preferences_file, backup_preferences_file)):
  43. Logger.log("d", "Copying preferences file from %s to %s", preferences_file, backup_preferences_file)
  44. shutil.copyfile(preferences_file, backup_preferences_file)
  45. # Create an empty buffer and write the archive to it.
  46. buffer = io.BytesIO()
  47. archive = self._makeArchive(buffer, version_data_dir)
  48. if archive is None:
  49. return
  50. files = archive.namelist()
  51. # Count the metadata items. We do this in a rather naive way at the moment.
  52. machine_count = len([s for s in files if "machine_instances/" in s]) - 1
  53. material_count = len([s for s in files if "materials/" in s]) - 1
  54. profile_count = len([s for s in files if "quality_changes/" in s]) - 1
  55. plugin_count = len([s for s in files if "plugin.json" in s])
  56. # Store the archive and metadata so the BackupManager can fetch them when needed.
  57. self.zip_file = buffer.getvalue()
  58. self.meta_data = {
  59. "cura_release": cura_release,
  60. "machine_count": str(machine_count),
  61. "material_count": str(material_count),
  62. "profile_count": str(profile_count),
  63. "plugin_count": str(plugin_count)
  64. }
  65. ## Make a full archive from the given root path with the given name.
  66. # \param root_path The root directory to archive recursively.
  67. # \return The archive as bytes.
  68. def _makeArchive(self, buffer: "io.BytesIO", root_path: str) -> Optional[ZipFile]:
  69. ignore_string = re.compile("|".join(self.IGNORED_FILES))
  70. try:
  71. archive = ZipFile(buffer, "w", ZIP_DEFLATED)
  72. for root, folders, files in os.walk(root_path):
  73. for item_name in folders + files:
  74. absolute_path = os.path.join(root, item_name)
  75. if ignore_string.search(absolute_path):
  76. continue
  77. archive.write(absolute_path, absolute_path[len(root_path) + len(os.sep):])
  78. archive.close()
  79. return archive
  80. except (IOError, OSError, BadZipfile) as error:
  81. Logger.log("e", "Could not create archive from user data directory: %s", error)
  82. self._showMessage(
  83. self.catalog.i18nc("@info:backup_failed",
  84. "Could not create archive from user data directory: {}".format(error)))
  85. return None
  86. ## Show a UI message.
  87. def _showMessage(self, message: str) -> None:
  88. Message(message, title=self.catalog.i18nc("@info:title", "Backup"), lifetime=30).show()
  89. ## Restore this back-up.
  90. # \return Whether we had success or not.
  91. def restore(self) -> bool:
  92. if not self.zip_file or not self.meta_data or not self.meta_data.get("cura_release", None):
  93. # We can restore without the minimum required information.
  94. Logger.log("w", "Tried to restore a Cura backup without having proper data or meta data.")
  95. self._showMessage(
  96. self.catalog.i18nc("@info:backup_failed",
  97. "Tried to restore a Cura backup without having proper data or meta data."))
  98. return False
  99. current_version = self._application.getVersion()
  100. version_to_restore = self.meta_data.get("cura_release", "master")
  101. if current_version < version_to_restore:
  102. # Cannot restore version newer than current because settings might have changed.
  103. Logger.log("d", "Tried to restore a Cura backup of version {version_to_restore} with cura version {current_version}".format(version_to_restore = version_to_restore, current_version = current_version))
  104. self._showMessage(
  105. self.catalog.i18nc("@info:backup_failed",
  106. "Tried to restore a Cura backup that is higher than the current version."))
  107. return False
  108. version_data_dir = Resources.getDataStoragePath()
  109. archive = ZipFile(io.BytesIO(self.zip_file), "r")
  110. extracted = self._extractArchive(archive, version_data_dir)
  111. # Under Linux, preferences are stored elsewhere, so we copy the file to there.
  112. if Platform.isLinux():
  113. preferences_file_name = self._application.getApplicationName()
  114. preferences_file = Resources.getPath(Resources.Preferences, "{}.cfg".format(preferences_file_name))
  115. backup_preferences_file = os.path.join(version_data_dir, "{}.cfg".format(preferences_file_name))
  116. Logger.log("d", "Moving preferences file from %s to %s", backup_preferences_file, preferences_file)
  117. shutil.move(backup_preferences_file, preferences_file)
  118. return extracted
  119. ## Extract the whole archive to the given target path.
  120. # \param archive The archive as ZipFile.
  121. # \param target_path The target path.
  122. # \return Whether we had success or not.
  123. @staticmethod
  124. def _extractArchive(archive: "ZipFile", target_path: str) -> bool:
  125. # Implement security recommendations: Sanity check on zip files will make it harder to spoof.
  126. from cura.CuraApplication import CuraApplication
  127. config_filename = CuraApplication.getInstance().getApplicationName() + ".cfg" # Should be there if valid.
  128. if config_filename not in [file.filename for file in archive.filelist]:
  129. Logger.logException("e", "Unable to extract the backup due to corruption of compressed file(s).")
  130. return False
  131. Logger.log("d", "Removing current data in location: %s", target_path)
  132. Resources.factoryReset()
  133. Logger.log("d", "Extracting backup to location: %s", target_path)
  134. try:
  135. archive.extractall(target_path)
  136. except PermissionError:
  137. Logger.logException("e", "Unable to extract the backup due to permission errors")
  138. return False
  139. return True