Skip to content

Commit 03bac8a

Browse files
committed
Cleanup
1 parent 2f07248 commit 03bac8a

File tree

9 files changed

+81
-50
lines changed

9 files changed

+81
-50
lines changed

src/core/archive.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
parser.add_argument("-u", "--unpack", help="Unpack archive", type=str)
77
args = parser.parse_args()
88

9+
# Get password entered in the "Create a new password" dialog from the temporary file
910
def get_password():
1011
temp_file = f"{CACHE}/temp_file"
1112
if os.path.exists(temp_file):
@@ -14,6 +15,7 @@ def get_password():
1415
else:
1516
return None
1617

18+
# Remove above temporary file
1719
def remove_temp_file():
1820
try:
1921
os.remove(f"{CACHE}/temp_file")
@@ -39,8 +41,8 @@ def start_saving(self):
3941
print("Configuration saved successfully.")
4042
remove_temp_file()
4143

44+
# Cleanup the cache dir before saving
4245
def _cleanup_cache_dir(self):
43-
# Cleanup the cache dir before importing
4446
print("Cleaning up the cache directory")
4547
save_cache_dir = f"{CACHE}/save_config"
4648
try:
@@ -50,6 +52,7 @@ def _cleanup_cache_dir(self):
5052
os.makedirs(save_cache_dir, exist_ok=True)
5153
os.chdir(save_cache_dir)
5254

55+
# Copy the configuration folder to the user-defined directory
5356
def _copy_config_to_folder(self):
5457
open(f"{CACHE}/save_config/.folder.sd", "w").close()
5558

@@ -58,6 +61,7 @@ def _copy_config_to_folder(self):
5861

5962
shutil.move(f"{CACHE}/save_config", f"{args.create}")
6063

64+
# Create a new ZIP archive with 7-Zip
6165
def _create_archive(self):
6266
password = get_password()
6367
cmd = ['7z', 'a', '-tzip', '-mx=3', '-x!*.zip', '-x!saving_status', 'cfg.sd.zip', '.']
@@ -84,16 +88,6 @@ def start_importing(self):
8488
self._cleanup_cache_dir()
8589
self._check_config_type()
8690

87-
# Check, if the input is folder or not
88-
if self.is_folder:
89-
self._copy_folder_to_cache()
90-
else:
91-
if self.import_file.endswith(".sd.zip"):
92-
self._unpack_zip_archive()
93-
94-
elif ".sd.tar.gz" in self.import_file:
95-
self._unpack_tar_archive()
96-
9791
self._replace_home_in_files(".", home)
9892
subprocess.run([sys.executable, "-m", "savedesktop.core.config", "--import_"], check=True, env={**os.environ, "PYTHONPATH": f"{app_prefix}"})
9993

@@ -116,15 +110,29 @@ def _cleanup_cache_dir(self):
116110
# Create a txt file to prevent removing the cache's content after closing the app window
117111
open("import_status", "w").close()
118112

113+
# Check, if the input is archive or folder
119114
def _check_config_type(self):
120115
if self.import_file.endswith(".sd.zip") or self.import_file.endswith(".sd.tar.gz"):
121116
self.is_folder = False
122117
else:
123118
self.is_folder = True
124119

120+
# Check, if the input is folder or not
121+
if self.is_folder:
122+
self._copy_folder_to_cache()
123+
else:
124+
if self.import_file.endswith(".sd.zip"):
125+
self._unpack_zip_archive()
126+
elif self.import_file.endswith(".sd.tar.gz"):
127+
self._unpack_tar_archive()
128+
else:
129+
pass
130+
131+
# Copy the user-defined folder to the cache directory
125132
def _copy_folder_to_cache(self):
126133
shutil.copytree(self.import_folder, f"{CACHE}/import_config", dirs_exist_ok=True, ignore_dangling_symlinks=True)
127134

135+
# Unpack the ZIP archive with 7-Zip
128136
def _unpack_zip_archive(self):
129137
password = get_password()
130138

@@ -144,6 +152,7 @@ def _unpack_zip_archive(self):
144152
capture_output=False, text=True, check=True
145153
)
146154

155+
# Unpack a legacy archive with Tarball (for backward compatibility)
147156
def _unpack_tar_archive(self):
148157
subprocess.run(["tar", "-xzf", self.import_file, "-C", f"{CACHE}/import_config"],capture_output=True, text=True, check=True)
149158

@@ -162,6 +171,7 @@ def _replace_home_in_files(self, root, home, patterns=(".xml", ".ini")):
162171
f.write(new_text)
163172
print(f"Updated /home/$USER path in: {path}")
164173

174+
# Remove the "import_status" file if the condition is met
165175
def _remove_status_file(self):
166176
if all(not os.path.exists(p) for p in [
167177
f"{CACHE}/import_config/app",

src/core/periodic_saving.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class PeriodicBackups:
1818
def __init__(self):
1919
self.last_backup_date = self.load_last_backup_date()
2020

21+
# Load last backup date from the {DATA}/periodic-saving.json file
2122
def load_last_backup_date(self):
2223
backup_file = f"{DATA}/periodic-saving.json"
2324
if os.path.exists(backup_file):
@@ -26,6 +27,8 @@ def load_last_backup_date(self):
2627
return date.fromisoformat(jp.get("last-saved", "2000-01-01"))
2728
return date(2000, 1, 1)
2829

30+
# Start periodic saving without checking last backup date (with --now parameter)
31+
# or with checking it
2932
def run(self, now: bool) -> None:
3033
self.pbfolder = f'{settings["periodic-saving-folder"].format(download_dir)}'
3134

@@ -35,6 +38,7 @@ def run(self, now: bool) -> None:
3538
else:
3639
self.get_interval()
3740

41+
# Get the periodic saving interval from GSettings
3842
def get_interval(self):
3943
if settings["periodic-saving"] == 'Never':
4044
print("Periodic saving is not set up.")
@@ -45,6 +49,7 @@ def get_interval(self):
4549
elif settings["periodic-saving"] == 'Monthly':
4650
self.check_and_backup(30)
4751

52+
# Check the number of days since the last backup
4853
def check_and_backup(self, interval):
4954
today = date.today()
5055
if (today - self.last_backup_date).days >= interval:
@@ -79,6 +84,7 @@ def backup(self):
7984
self.save_last_backup_date()
8085
self.config_saved()
8186

87+
# Get an encrypted password from the {DATA}/password file
8288
def get_password_from_file(self):
8389
try:
8490
ps = PasswordStore()
@@ -91,6 +97,7 @@ def get_password_from_file(self):
9197
subprocess.run(['7z', 'a', '-tzip', '-mx=6', '-x!*.zip', '-x!saving_status', 'cfg.sd.zip', '.'], check=True)
9298
shutil.copyfile('cfg.sd.zip', f'{self.pbfolder}/{self.filename}.sd.zip')
9399

100+
# Save today's date to the {DATA}/periodic-saving.json file
94101
def save_last_backup_date(self):
95102
with open(f"{DATA}/periodic-saving.json", "w") as pb:
96103
json.dump({"last-saved": date.today().isoformat()}, pb)

src/core/synchronization.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ def download_config(self):
7777
print("extracting the archive")
7878
self.get_zip_file_status()
7979

80+
# Send a notification about the started synchronization
8081
def _send_notification_at_startup(self):
8182
orig_str = _("<big><b>Importing configuration …</b></big>\nImporting configuration from:\n<i>{}</i>\n")
8283
status_str = orig_str

src/core/synchronization_setup.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,12 @@ def set_up_auto_mount(mount_type):
1919

2020
if not cfile_subtitle == "none":
2121
if "gvfs" in cfile_subtitle:
22-
pattern = r'.*/gvfs/([^:]*):host=([^,]*),user=([^/]*).*' if "google-drive" in cfile_subtitle else r'.*/gvfs/([^:]+):host=([^,]+),user=([^/]+)' if "onedrive" in cfile_subtitle else r'.*/gvfs/([^:]*):host=([^,]*),ssl=([^,]*),user=([^,]*),prefix=([^/]*).*'
22+
if "google-drive" in cfile_subtitle:
23+
pattern = r'.*/gvfs/([^:]*):host=([^,]*),user=([^/]*).*'
24+
elif "onedrive" in cfile_subtitle:
25+
pattern = r'.*/gvfs/([^:]+):host=([^,]+),user=([^/]+)'
26+
else:
27+
pattern = r'.*/gvfs/([^:]*):host=([^,]*),ssl=([^,]*),user=([^,]*),prefix=([^/]*).*'
2328

2429
match = re.search(pattern, cfile_subtitle)
2530

src/globals.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ def get_app_environment():
1010
if os.path.exists("/.flatpak-info"):
1111
return {
1212
'type': 'flatpak',
13-
'home': Path(os.getenv('HOME', Path.home())),
1413
'run_cmd': 'flatpak run io.github.vikdevelop.SaveDesktop',
1514
'cache': f'{GLib.get_user_cache_dir()}/tmp',
1615
'data': f'{GLib.get_user_data_dir()}'
@@ -19,15 +18,14 @@ def get_app_environment():
1918
else:
2019
return {
2120
'type': 'native',
22-
'home': Path.home(),
2321
'run_cmd': 'savedesktop',
2422
'cache': os.path.join(f'{GLib.get_user_cache_dir()}', 'io.github.vikdevelop.SaveDesktop'),
2523
'data': os.path.join(f'{GLib.get_user_data_dir()}', 'io.github.vikdevelop.SaveDesktop')
2624
}
2725

2826
env = get_app_environment()
2927

30-
home = env['home']
28+
home = Path.home()
3129

3230
# System paths
3331
download_dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOWNLOAD)
@@ -40,6 +38,9 @@ def get_app_environment():
4038
CACHE = env['cache']
4139
DATA = env['data']
4240

41+
os.makedirs(CACHE, exist_ok=True)
42+
os.makedirs(DATA, exist_ok=True)
43+
4344
# Commands
4445
periodic_saving_cmd = f'{env["run_cmd"]} --background'
4546
sync_cmd = f'{env["run_cmd"]} --sync'

src/gui/more_options_dialog.py

Lines changed: 36 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
class MoreOptionsDialog(Adw.AlertDialog):
99
def __init__(self, parent):
1010
super().__init__()
11-
self.parent = parent
11+
self.parent = parent # Connect this dialog with MainWindow class
12+
1213
self.set_heading(_("More options"))
1314

1415
# Box for this dialog
@@ -18,6 +19,21 @@ def __init__(self, parent):
1819
self.set_extra_child(self.msBox)
1920

2021
# Periodic saving section
22+
self.load_periodic_saving_section()
23+
24+
# Manual saving section
25+
self.load_manual_saving_section()
26+
27+
# Call _expand_periodic_row() method to expand "Periodic saving" section
28+
self._expand_periodic_row()
29+
30+
# add response of this dialog
31+
self.add_response('cancel', _("Cancel"))
32+
self.add_response('ok', _("Apply"))
33+
self.set_response_appearance('ok', Adw.ResponseAppearance.SUGGESTED)
34+
self.connect('response', self.msDialog_closed)
35+
36+
def load_periodic_saving_section(self):
2137
# Expander row for showing options of the periodic saving
2238
self.periodic_row = Adw.ExpanderRow.new()
2339
self.periodic_row.set_title(_("Periodic saving"))
@@ -50,7 +66,7 @@ def __init__(self, parent):
5066
self.filefrmtButton.add_css_class('destructive-action')
5167
self.filefrmtButton.set_valign(Gtk.Align.CENTER)
5268
self.filefrmtButton.set_tooltip_text(_("Reset to default"))
53-
self.filefrmtButton.connect("clicked", self.reset_fileformat)
69+
self.filefrmtButton.connect("clicked", self._reset_fileformat)
5470

5571
# Entry for selecting file name format
5672
self.filefrmtEntry = Adw.EntryRow.new()
@@ -63,7 +79,7 @@ def __init__(self, parent):
6379
self.folderButton = Gtk.Button.new_from_icon_name("document-open-symbolic")
6480
self.folderButton.set_valign(Gtk.Align.CENTER)
6581
self.folderButton.set_tooltip_text(_("Choose another folder"))
66-
self.folderButton.connect("clicked", self.open_file_dialog)
82+
self.folderButton.connect("clicked", self._open_file_dialog)
6783

6884
# Adw.ActionRow for showing folder for periodic saving
6985
self.dirRow = Adw.ActionRow.new()
@@ -87,7 +103,7 @@ def __init__(self, parent):
87103
self.pswdgenButton.connect("clicked", self._get_generated_password)
88104
self.cpwdRow.add_suffix(self.pswdgenButton)
89105

90-
# Manual saving section
106+
def load_manual_saving_section(self):
91107
self.manRow = Adw.ExpanderRow.new()
92108
self.manRow.set_title(_("Manual saving"))
93109
self.manRow.set_expanded(True)
@@ -97,7 +113,7 @@ def __init__(self, parent):
97113
self.encryptSwitch = Gtk.Switch.new()
98114
self.archSwitch = Gtk.Switch.new()
99115
self.encryptSwitch.set_valign(Gtk.Align.CENTER)
100-
self.encryptSwitch.connect('notify::active', self.set_encryptswitch_sensitivity)
116+
self.encryptSwitch.connect('notify::active', self._set_encryptswitch_sensitivity)
101117
if settings["enable-encryption"] == True:
102118
self.encryptSwitch.set_active(True)
103119
self.archSwitch.set_sensitive(False)
@@ -112,7 +128,7 @@ def __init__(self, parent):
112128

113129
# action row and switch for showing the "Save a configuration without creating the archive" option
114130
self.archSwitch.set_valign(Gtk.Align.CENTER)
115-
self.archSwitch.connect('notify::active', self.set_archswitch_sensitivity)
131+
self.archSwitch.connect('notify::active', self._set_archswitch_sensitivity)
116132
if settings["save-without-archive"] == True:
117133
self.archSwitch.set_active(True)
118134
self.encryptSwitch.set_sensitive(False)
@@ -123,46 +139,43 @@ def __init__(self, parent):
123139
self.archRow.set_activatable_widget(self.archSwitch)
124140
self.manRow.add_row(self.archRow)
125141

126-
self._expand_periodic_row()
127-
128-
# add response of this dialog
129-
self.add_response('cancel', _("Cancel"))
130-
self.add_response('ok', _("Apply"))
131-
self.set_response_appearance('ok', Adw.ResponseAppearance.SUGGESTED)
132-
self.connect('response', self.msDialog_closed)
133-
142+
# Get an encrypted password from the {DATA}/password file
134143
def _get_password_from_file(self):
135144
if os.path.exists(f"{DATA}/password"):
136145
p = PasswordStore()
137146
self.cpwdRow.set_text(p.password)
138147
else:
139148
self.cpwdRow.set_text("")
140149

150+
# Call MainWindow's method (self.parent) to get auto-generated password
141151
def _get_generated_password(self, w):
142152
self.password = self.parent._password_generator()
143153
self.cpwdRow.set_text(self.password)
144154

145-
def open_file_dialog(self, w):
155+
# Open the file chooser dialog for selecting the periodic saving folder
156+
# by calling the MainWindow's method (self.parent)
157+
def _open_file_dialog(self, w):
146158
self.parent.select_pb_folder(w="")
147159

148-
# reset the file name format entry to the default value
149-
def reset_fileformat(self, w):
160+
# Reset the file name format entry to the default value
161+
def _reset_fileformat(self, w):
150162
self.filefrmtEntry.set_text("Latest_configuration")
151163

152-
# set sensitivity of the encryptSwitch
153-
def set_encryptswitch_sensitivity(self, GParamBoolean, encryptSwitch):
164+
# Set sensitivity of the encryptSwitch
165+
def _set_encryptswitch_sensitivity(self, GParamBoolean, encryptSwitch):
154166
if self.encryptSwitch.get_active():
155167
self.archSwitch.set_sensitive(False)
156168
else:
157169
self.archSwitch.set_sensitive(True)
158170

159-
# set sensitivity of the archSwitch
160-
def set_archswitch_sensitivity(self, GParamBoolean, archSwitch):
171+
# Set sensitivity of the archSwitch
172+
def _set_archswitch_sensitivity(self, GParamBoolean, archSwitch):
161173
if self.archSwitch.get_active():
162174
self.encryptSwitch.set_sensitive(False)
163175
else:
164176
self.encryptSwitch.set_sensitive(True)
165177

178+
# Expand "Periodic saving" row if the below file exists
166179
def _expand_periodic_row(self):
167180
if os.path.exists(f"{CACHE}/expand_pb_row"):
168181
self.periodic_row.set_expanded(True)
@@ -206,6 +219,8 @@ def _save_password(self):
206219
except:
207220
pass
208221

222+
# Open the "Set up the sync file" dialog after clicking on the Apply button
223+
# in this dialog, if the below file exists
209224
def _call_set_dialog(self):
210225
if os.path.exists(f"{CACHE}/expand_pb_row"):
211226
self.parent._open_SetDialog()

src/gui/password_checker.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ def __init__(self, *args, **kwargs):
6565
self.applyButton.set_sensitive(False)
6666
self.winBox.append(self.applyButton)
6767

68+
# Set sensitivity of the Apply button based on the Password entry status
6869
def _empty_check(self, passEntry):
6970
if self.passEntry.get_text() == "":
7071
self.applyButton.set_sensitive(False)
@@ -86,7 +87,7 @@ def __init__(self, **kwargs):
8687
application_id="io.github.vikdevelop.SaveDesktop")
8788
self.connect('activate', self.on_activate)
8889

89-
# Show the main window of the application
90+
# Show the app window
9091
def on_activate(self, app):
9192
self.win = PasswordWindow(application=app)
9293
self.win.present()

0 commit comments

Comments
 (0)