Backup.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. class Backup:
  17. """The back-up class holds all data about a back-up.
  18. It is also responsible for reading and writing the zip file to the user data folder.
  19. """
  20. IGNORED_FILES = [r"cura\.log", r"plugins\.json", r"cache", r"__pycache__", r"\.qmlc", r"\.pyc"]
  21. """These files should be ignored when making a backup."""
  22. catalog = i18nCatalog("cura")
  23. """Re-use translation catalog"""
  24. def __init__(self, application: "CuraApplication", zip_file: bytes = None, meta_data: Dict[str, str] = None) -> None:
  25. self._application = application
  26. self.zip_file = zip_file # type: Optional[bytes]
  27. self.meta_data = meta_data # type: Optional[Dict[str, str]]
  28. def makeFromCurrent(self) -> None:
  29. """Create a back-up from the current user config folder."""
  30. cura_release = self._application.getVersion()
  31. version_data_dir = Resources.getDataStoragePath()
  32. Logger.log("d", "Creating backup for Cura %s, using folder %s", cura_release, version_data_dir)
  33. # Ensure all current settings are saved.
  34. self._application.saveSettings()
  35. # We copy the preferences file to the user data directory in Linux as it's in a different location there.
  36. # When restoring a backup on Linux, we move it back.
  37. 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.
  38. preferences_file_name = self._application.getApplicationName()
  39. preferences_file = Resources.getPath(Resources.Preferences, "{}.cfg".format(preferences_file_name))
  40. backup_preferences_file = os.path.join(version_data_dir, "{}.cfg".format(preferences_file_name))
  41. if os.path.exists(preferences_file) and (not os.path.exists(backup_preferences_file) or not os.path.samefile(preferences_file, backup_preferences_file)):
  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. if archive is None:
  48. return
  49. files = archive.namelist()
  50. # Count the metadata items. We do this in a rather naive way at the moment.
  51. 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.
  52. material_count = max(len([s for s in files if "materials/" in s]) - 1, 0)
  53. profile_count = max(len([s for s in files if "quality_changes/" in s]) - 1, 0)
  54. plugin_count = len([s for s in files if "plugin.json" in s])
  55. # Store the archive and metadata so the BackupManager can fetch them when needed.
  56. self.zip_file = buffer.getvalue()
  57. self.meta_data = {
  58. "cura_release": cura_release,
  59. "machine_count": str(machine_count),
  60. "material_count": str(material_count),
  61. "profile_count": str(profile_count),
  62. "plugin_count": str(plugin_count)
  63. }
  64. def _makeArchive(self, buffer: "io.BytesIO", root_path: str) -> Optional[ZipFile]:
  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. """
  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. def _showMessage(self, message: str) -> None:
  87. """Show a UI message."""
  88. Message(message, title=self.catalog.i18nc("@info:title", "Backup"), lifetime=30).show()
  89. def restore(self) -> bool:
  90. """Restore this back-up.
  91. :return: 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 = self._application.getVersion()
  101. version_to_restore = self.meta_data.get("cura_release", "master")
  102. if current_version < version_to_restore:
  103. # Cannot restore version newer than current because settings might have changed.
  104. 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))
  105. self._showMessage(
  106. self.catalog.i18nc("@info:backup_failed",
  107. "Tried to restore a Cura backup that is higher than the 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 = self._application.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. """Extract the whole archive to the given target path.
  123. :param archive: The archive as ZipFile.
  124. :param target_path: The target path.
  125. :return: Whether we had success or not.
  126. """
  127. # Implement security recommendations: Sanity check on zip files will make it harder to spoof.
  128. from cura.CuraApplication import CuraApplication
  129. config_filename = CuraApplication.getInstance().getApplicationName() + ".cfg" # Should be there if valid.
  130. if config_filename not in [file.filename for file in archive.filelist]:
  131. Logger.logException("e", "Unable to extract the backup due to corruption of compressed file(s).")
  132. return False
  133. Logger.log("d", "Removing current data in location: %s", target_path)
  134. Resources.factoryReset()
  135. Logger.log("d", "Extracting backup to location: %s", target_path)
  136. try:
  137. archive.extractall(target_path)
  138. except (PermissionError, EnvironmentError):
  139. Logger.logException("e", "Unable to extract the backup due to permission or file system errors.")
  140. return False
  141. return True