Backup.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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 copy import deepcopy
  8. from zipfile import ZipFile, ZIP_DEFLATED, BadZipfile
  9. from typing import Dict, Optional, TYPE_CHECKING
  10. from UM import i18nCatalog
  11. from UM.Logger import Logger
  12. from UM.Message import Message
  13. from UM.Platform import Platform
  14. from UM.Resources import Resources
  15. if TYPE_CHECKING:
  16. from cura.CuraApplication import CuraApplication
  17. class Backup:
  18. """The back-up class holds all data about a back-up.
  19. It is also responsible for reading and writing the zip file to the user data folder.
  20. """
  21. IGNORED_FILES = [r"cura\.log", r"plugins\.json", r"cache", r"__pycache__", r"\.qmlc", r"\.pyc"]
  22. """These files should be ignored when making a backup."""
  23. SECRETS_SETTINGS = ["general/ultimaker_auth_data"]
  24. """Secret preferences that need to obfuscated when making a backup of Cura"""
  25. catalog = i18nCatalog("cura")
  26. """Re-use translation catalog"""
  27. def __init__(self, application: "CuraApplication", zip_file: bytes = None, meta_data: Dict[str, str] = None) -> None:
  28. self._application = application
  29. self.zip_file = zip_file # type: Optional[bytes]
  30. self.meta_data = meta_data # type: Optional[Dict[str, str]]
  31. def makeFromCurrent(self) -> None:
  32. """Create a back-up from the current user config folder."""
  33. cura_release = self._application.getVersion()
  34. version_data_dir = Resources.getDataStoragePath()
  35. Logger.log("d", "Creating backup for Cura %s, using folder %s", cura_release, version_data_dir)
  36. # obfuscate sensitive secrets
  37. secrets = self._obfuscate()
  38. # Ensure all current settings are saved.
  39. self._application.saveSettings()
  40. # We copy the preferences file to the user data directory in Linux as it's in a different location there.
  41. # When restoring a backup on Linux, we move it back.
  42. 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.
  43. preferences_file_name = self._application.getApplicationName()
  44. preferences_file = Resources.getPath(Resources.Preferences, "{}.cfg".format(preferences_file_name))
  45. backup_preferences_file = os.path.join(version_data_dir, "{}.cfg".format(preferences_file_name))
  46. if os.path.exists(preferences_file) and (not os.path.exists(backup_preferences_file) or not os.path.samefile(preferences_file, backup_preferences_file)):
  47. Logger.log("d", "Copying preferences file from %s to %s", preferences_file, backup_preferences_file)
  48. shutil.copyfile(preferences_file, backup_preferences_file)
  49. # Create an empty buffer and write the archive to it.
  50. buffer = io.BytesIO()
  51. archive = self._makeArchive(buffer, version_data_dir)
  52. if archive is None:
  53. return
  54. files = archive.namelist()
  55. # Count the metadata items. We do this in a rather naive way at the moment.
  56. machine_count = max(len([s for s in files if "machine_instances/" in s]) - 1, 0) # If people delete their profiles but not their preferences, it can still make a backup, and report -1 profiles. Server crashes on this.
  57. material_count = max(len([s for s in files if "materials/" in s]) - 1, 0)
  58. profile_count = max(len([s for s in files if "quality_changes/" in s]) - 1, 0)
  59. plugin_count = len([s for s in files if "plugin.json" in s])
  60. # Store the archive and metadata so the BackupManager can fetch them when needed.
  61. self.zip_file = buffer.getvalue()
  62. self.meta_data = {
  63. "cura_release": cura_release,
  64. "machine_count": str(machine_count),
  65. "material_count": str(material_count),
  66. "profile_count": str(profile_count),
  67. "plugin_count": str(plugin_count)
  68. }
  69. # Restore the obfuscated settings
  70. self._illuminate(**secrets)
  71. def _makeArchive(self, buffer: "io.BytesIO", root_path: str) -> Optional[ZipFile]:
  72. """Make a full archive from the given root path with the given name.
  73. :param root_path: The root directory to archive recursively.
  74. :return: The archive as bytes.
  75. """
  76. ignore_string = re.compile("|".join(self.IGNORED_FILES))
  77. try:
  78. archive = ZipFile(buffer, "w", ZIP_DEFLATED)
  79. for root, folders, files in os.walk(root_path):
  80. for item_name in folders + files:
  81. absolute_path = os.path.join(root, item_name)
  82. if ignore_string.search(absolute_path):
  83. continue
  84. archive.write(absolute_path, absolute_path[len(root_path) + len(os.sep):])
  85. archive.close()
  86. return archive
  87. except (IOError, OSError, BadZipfile) as error:
  88. Logger.log("e", "Could not create archive from user data directory: %s", error)
  89. self._showMessage(
  90. self.catalog.i18nc("@info:backup_failed",
  91. "Could not create archive from user data directory: {}".format(error)))
  92. return None
  93. def _showMessage(self, message: str) -> None:
  94. """Show a UI message."""
  95. Message(message, title=self.catalog.i18nc("@info:title", "Backup"), lifetime=30).show()
  96. def restore(self) -> bool:
  97. """Restore this back-up.
  98. :return: Whether we had success or not.
  99. """
  100. if not self.zip_file or not self.meta_data or not self.meta_data.get("cura_release", None):
  101. # We can restore without the minimum required information.
  102. Logger.log("w", "Tried to restore a Cura backup without having proper data or meta data.")
  103. self._showMessage(
  104. self.catalog.i18nc("@info:backup_failed",
  105. "Tried to restore a Cura backup without having proper data or meta data."))
  106. return False
  107. current_version = self._application.getVersion()
  108. version_to_restore = self.meta_data.get("cura_release", "master")
  109. if current_version < version_to_restore:
  110. # Cannot restore version newer than current because settings might have changed.
  111. 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))
  112. self._showMessage(
  113. self.catalog.i18nc("@info:backup_failed",
  114. "Tried to restore a Cura backup that is higher than the current version."))
  115. return False
  116. # Get the current secrets and store since the back-up doesn't contain those
  117. secrets = self._obfuscate()
  118. version_data_dir = Resources.getDataStoragePath()
  119. archive = ZipFile(io.BytesIO(self.zip_file), "r")
  120. extracted = self._extractArchive(archive, version_data_dir)
  121. # Under Linux, preferences are stored elsewhere, so we copy the file to there.
  122. if Platform.isLinux():
  123. preferences_file_name = self._application.getApplicationName()
  124. preferences_file = Resources.getPath(Resources.Preferences, "{}.cfg".format(preferences_file_name))
  125. backup_preferences_file = os.path.join(version_data_dir, "{}.cfg".format(preferences_file_name))
  126. Logger.log("d", "Moving preferences file from %s to %s", backup_preferences_file, preferences_file)
  127. shutil.move(backup_preferences_file, preferences_file)
  128. # Restore the obfuscated settings
  129. self._illuminate(**secrets)
  130. return extracted
  131. @staticmethod
  132. def _extractArchive(archive: "ZipFile", target_path: str) -> bool:
  133. """Extract the whole archive to the given target path.
  134. :param archive: The archive as ZipFile.
  135. :param target_path: The target path.
  136. :return: Whether we had success or not.
  137. """
  138. # Implement security recommendations: Sanity check on zip files will make it harder to spoof.
  139. from cura.CuraApplication import CuraApplication
  140. config_filename = CuraApplication.getInstance().getApplicationName() + ".cfg" # Should be there if valid.
  141. if config_filename not in [file.filename for file in archive.filelist]:
  142. Logger.logException("e", "Unable to extract the backup due to corruption of compressed file(s).")
  143. return False
  144. Logger.log("d", "Removing current data in location: %s", target_path)
  145. Resources.factoryReset()
  146. Logger.log("d", "Extracting backup to location: %s", target_path)
  147. try:
  148. archive.extractall(target_path)
  149. except (PermissionError, EnvironmentError):
  150. Logger.logException("e", "Unable to extract the backup due to permission or file system errors.")
  151. return False
  152. return True
  153. def _obfuscate(self) -> Dict[str, str]:
  154. """
  155. Obfuscate and remove the secret preferences that are specified in SECRETS_SETTINGS
  156. :return: a dictionary of the removed secrets. Note: the '/' is replaced by '__'
  157. """
  158. preferences = self._application.getPreferences()
  159. secrets = {}
  160. for secret in self.SECRETS_SETTINGS:
  161. secrets[secret.replace("/", "__")] = deepcopy(preferences.getValue(secret))
  162. preferences.setValue(secret, None)
  163. self._application.savePreferences()
  164. return secrets
  165. def _illuminate(self, **kwargs) -> None:
  166. """
  167. Restore the obfuscated settings
  168. :param kwargs: a dict of obscured preferences. Note: the '__' of the keys will be replaced by '/'
  169. """
  170. preferences = self._application.getPreferences()
  171. for key, value in kwargs.items():
  172. preferences.setValue(key.replace("__", "/"), value)
  173. self._application.savePreferences()