TonieToolbox 0.5.1__py3-none-any.whl → 0.6.0a2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,437 @@
1
+ # filepath: d:\Repository\TonieToolbox\TonieToolbox\integration_windows.py
2
+ import os
3
+ import sys
4
+ import json
5
+ from .constants import SUPPORTED_EXTENSIONS, CONFIG_TEMPLATE
6
+ from .logger import get_logger
7
+
8
+ logger = get_logger('integration_windows')
9
+
10
+ class WindowsClassicContextMenuIntegration:
11
+ """
12
+ Class to generate Windows registry entries for TonieToolbox "classic" context menu integration.
13
+ Adds a 'TonieToolbox' cascade menu for supported audio files, .taf files, and folders.
14
+ """
15
+ def __init__(self):
16
+ self.exe_path = os.path.join(sys.prefix, 'Scripts', 'tonietoolbox.exe')
17
+ self.exe_path_reg = self.exe_path.replace('\\', r'\\')
18
+ self.output_dir = os.path.join(os.path.expanduser('~'), '.tonietoolbox')
19
+ self.icon_path = os.path.join(self.output_dir, 'icon.ico').replace('\\', r'\\')
20
+ self.cascade_name = 'TonieToolbox'
21
+ self.entry_is_separator = '"CommandFlags"=dword:00000008'
22
+ self.show_uac = '"CommandFlags"=dword:00000010'
23
+ self.separator_below = '"CommandFlags"=dword:00000040'
24
+ self.separator_above = '"CommandFlags"=dword:00000020'
25
+ self.error_handling = r' && if %ERRORLEVEL% neq 0 (echo Error: Command failed with error code %ERRORLEVEL% && pause && exit /b %ERRORLEVEL%) else (echo Command completed successfully && ping -n 2 127.0.0.1 > nul)'
26
+ self.show_info_error_handling = r' && if %ERRORLEVEL% neq 0 (echo Error: Command failed with error code %ERRORLEVEL% && pause && exit /b %ERRORLEVEL%) else (echo. && echo Press any key to close this window... && pause > nul)'
27
+ self.config = self._apply_config_template()
28
+ self.upload_url = ''
29
+ self.log_level = self.config.get('log_level', 'SILENT')
30
+ self.log_to_file = self.config.get('log_to_file', False)
31
+ self.basic_authentication_cmd = ''
32
+ self.client_cert_cmd = ''
33
+ self.upload_enabled = self._setup_upload()
34
+
35
+ print(f"Upload enabled: {self.upload_enabled}")
36
+ print(f"Upload URL: {self.upload_url}")
37
+ print(f"Authentication: {'Basic Authentication' if self.basic_authentication else ('None' if self.none_authentication else ('Client Cert' if self.client_cert_authentication else 'Unknown'))}")
38
+
39
+ self._setup_commands()
40
+
41
+ def _build_cmd(self, base_args, file_placeholder='%1', output_to_source=True ,use_upload=False, use_artwork=False, use_json=False, use_compare=False, use_info=False, is_recursive=False, is_split=False, is_folder=False, shell='cmd.exe', keep_open=False, log_to_file=False):
42
+ """Dynamically build command strings for registry entries."""
43
+ exe = self.exe_path_reg
44
+ cmd = f'{shell} /{"k" if keep_open else "c"} "echo Running TonieToolbox'
45
+ if use_info:
46
+ cmd += ' info'
47
+ elif is_split:
48
+ cmd += ' split'
49
+ elif use_compare:
50
+ cmd += ' compare'
51
+ elif is_recursive:
52
+ cmd += ' recursive folder convert'
53
+ elif is_folder:
54
+ cmd += ' folder convert'
55
+ elif use_upload and use_artwork and use_json:
56
+ cmd += ' convert, upload, artwork and JSON'
57
+ elif use_upload and use_artwork:
58
+ cmd += ' convert, upload and artwork'
59
+ elif use_upload:
60
+ cmd += ' convert and upload'
61
+ else:
62
+ cmd += ' convert'
63
+ cmd += ' command... && "'
64
+ cmd += f'{exe}" {base_args}'
65
+ if log_to_file:
66
+ cmd += ' --log-file'
67
+ if is_recursive:
68
+ cmd += ' --recursive'
69
+ if output_to_source:
70
+ cmd += ' --output-to-source'
71
+ if use_info:
72
+ cmd += ' --info'
73
+ if is_split:
74
+ cmd += ' --split'
75
+ if use_compare:
76
+ cmd += ' --compare "%1" "%2"'
77
+ else:
78
+ cmd += f' "{file_placeholder}"'
79
+ if use_upload:
80
+ cmd += f' --upload "{self.upload_url}"'
81
+ if self.basic_authentication_cmd:
82
+ cmd += f' {self.basic_authentication_cmd}'
83
+ elif self.client_cert_cmd:
84
+ cmd += f' {self.client_cert_cmd}'
85
+ if getattr(self, "ignore_ssl_verify", False):
86
+ cmd += ' --ignore-ssl-verify'
87
+ if use_artwork:
88
+ cmd += ' --include-artwork'
89
+ if use_json:
90
+ cmd += ' --create-custom-json'
91
+ if use_info or use_compare:
92
+ cmd += ' && echo. && pause && exit > nul"'
93
+ else:
94
+ cmd += f'{self.error_handling}"'
95
+ return cmd
96
+
97
+ def _get_log_level_arg(self):
98
+ """Return the correct log level argument for TonieToolbox CLI based on self.log_level."""
99
+ level = str(self.log_level).strip().upper()
100
+ if level == 'DEBUG':
101
+ return '--debug'
102
+ elif level == 'INFO':
103
+ return '--info'
104
+ return '--silent'
105
+
106
+ def _setup_commands(self):
107
+ """Set up all command strings for registry entries dynamically."""
108
+ log_level_arg = self._get_log_level_arg()
109
+ # Audio file commands
110
+ self.convert_cmd = self._build_cmd(f'{log_level_arg}', log_to_file=self.log_to_file)
111
+ self.upload_cmd = self._build_cmd(f'{log_level_arg}', use_upload=True, log_to_file=self.log_to_file)
112
+ self.upload_artwork_cmd = self._build_cmd(f'{log_level_arg}', use_upload=True, use_artwork=True, log_to_file=self.log_to_file)
113
+ self.upload_artwork_json_cmd = self._build_cmd(f'{log_level_arg}', use_upload=True, use_artwork=True, use_json=True, log_to_file=self.log_to_file)
114
+
115
+ # .taf file commands
116
+ self.show_info_cmd = self._build_cmd(log_level_arg, use_info=True, keep_open=True, log_to_file=self.log_to_file)
117
+ self.extract_opus_cmd = self._build_cmd(log_level_arg, is_split=True, log_to_file=self.log_to_file)
118
+ self.upload_taf_cmd = self._build_cmd(log_level_arg, use_upload=True, log_to_file=self.log_to_file)
119
+ self.upload_taf_artwork_cmd = self._build_cmd(log_level_arg, use_upload=True, use_artwork=True, log_to_file=self.log_to_file)
120
+ self.upload_taf_artwork_json_cmd = self._build_cmd(log_level_arg, use_upload=True, use_artwork=True, use_json=True, log_to_file=self.log_to_file)
121
+ self.compare_taf_cmd = self._build_cmd(log_level_arg, use_compare=True, keep_open=True, log_to_file=self.log_to_file)
122
+
123
+ # Folder commands
124
+ self.convert_folder_cmd = self._build_cmd(f'{log_level_arg}', is_recursive=True, is_folder=True, log_to_file=self.log_to_file)
125
+ self.upload_folder_cmd = self._build_cmd(f'{log_level_arg}', is_recursive=True, is_folder=True, use_upload=True, log_to_file=self.log_to_file)
126
+ self.upload_folder_artwork_cmd = self._build_cmd(f'{log_level_arg}', is_recursive=True, is_folder=True, use_upload=True, use_artwork=True, log_to_file=self.log_to_file)
127
+ self.upload_folder_artwork_json_cmd = self._build_cmd(f'{log_level_arg}', is_recursive=True, is_folder=True, use_upload=True, use_artwork=True, use_json=True, log_to_file=self.log_to_file)
128
+
129
+ def _apply_config_template(self):
130
+ """Apply the default configuration template if config.json is missing or invalid."""
131
+ config_path = os.path.join(self.output_dir, 'config.json')
132
+ if not os.path.exists(config_path):
133
+ with open(config_path, 'w') as f:
134
+ json.dump(CONFIG_TEMPLATE, f, indent=4)
135
+ logger.debug(f"Default configuration created at {config_path}")
136
+ return CONFIG_TEMPLATE
137
+ else:
138
+ logger.debug(f"Configuration file found at {config_path}")
139
+ return self._load_config()
140
+
141
+ def _load_config(self):
142
+ """Load configuration settings from config.json"""
143
+ config_path = os.path.join(self.output_dir, 'config.json')
144
+ if not os.path.exists(config_path):
145
+ raise FileNotFoundError(f"Configuration file not found: {config_path}")
146
+
147
+ with open(config_path, 'r') as f:
148
+ config = json.loads(f.read())
149
+
150
+ return config
151
+
152
+ def _setup_upload(self):
153
+ """Set up upload functionality based on config.json settings"""
154
+ # Always initialize authentication flags
155
+ self.basic_authentication = False
156
+ self.client_cert_authentication = False
157
+ self.none_authentication = False
158
+ config = self.config
159
+ try:
160
+ upload_config = config.get('upload', {})
161
+ self.upload_urls = upload_config.get('url', [])
162
+ self.ignore_ssl_verify = upload_config.get('ignore_ssl_verify', False)
163
+ self.username = upload_config.get('username', '')
164
+ self.password = upload_config.get('password', '')
165
+ self.basic_authentication_cmd = ''
166
+ self.client_cert_cmd = ''
167
+ if self.username and self.password:
168
+ self.basic_authentication_cmd = f'--username {self.username} --password {self.password}'
169
+ self.basic_authentication = True
170
+ self.client_cert_path = upload_config.get('client_cert_path', '')
171
+ self.client_cert_key_path = upload_config.get('client_cert_key_path', '')
172
+ if self.client_cert_path and self.client_cert_key_path:
173
+ self.client_cert_cmd = f'--client-cert {self.client_cert_path} --client-cert-key {self.client_cert_key_path}'
174
+ self.client_cert_authentication = True
175
+ if self.client_cert_authentication and self.basic_authentication:
176
+ logger.warning("Both client certificate and basic authentication are set. Only one can be used.")
177
+ return False
178
+ self.upload_url = self.upload_urls[0] if self.upload_urls else ''
179
+ if not self.client_cert_authentication and not self.basic_authentication and self.upload_url:
180
+ self.none_authentication = True
181
+ return bool(self.upload_url)
182
+ except FileNotFoundError:
183
+ logger.debug("Configuration file not found. Skipping upload setup.")
184
+ return False
185
+ except json.JSONDecodeError:
186
+ logger.debug("Error decoding JSON in configuration file. Skipping upload setup.")
187
+ return False
188
+ except Exception as e:
189
+ logger.debug(f"Unexpected error while loading configuration: {e}")
190
+ return False
191
+
192
+ def _reg_escape(self, s):
193
+ """Escape a string for use in a .reg file (escape double quotes)."""
194
+ return s.replace('"', '\\"')
195
+
196
+ def _generate_audio_extensions_entries(self):
197
+ """Generate registry entries for supported audio file extensions"""
198
+ reg_lines = []
199
+ for ext in SUPPORTED_EXTENSIONS:
200
+ ext = ext.lower().lstrip('.')
201
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell]')
202
+ reg_lines.append('')
203
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}]')
204
+ reg_lines.append('"MUIVerb"="TonieToolbox"')
205
+ reg_lines.append(f'"Icon"="{self.icon_path}"')
206
+ reg_lines.append('"subcommands"=""')
207
+ reg_lines.append('')
208
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell]')
209
+ # Convert
210
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell\\a_Convert]')
211
+ reg_lines.append('@="Convert File to .taf"')
212
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell\\a_Convert\\command]')
213
+ reg_lines.append(f'@="{self._reg_escape(self.convert_cmd)}"')
214
+ reg_lines.append('')
215
+ if self.upload_enabled:
216
+ # Upload
217
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell\\b_Upload]')
218
+ reg_lines.append('@="Convert File to .taf and Upload"')
219
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell\\b_Upload\\command]')
220
+ reg_lines.append(f'@="{self._reg_escape(self.upload_cmd)}"')
221
+ reg_lines.append('')
222
+ # Upload + Artwork
223
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell\\c_UploadArtwork]')
224
+ reg_lines.append('@="Convert File to .taf and Upload + Artwork"')
225
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell\\c_UploadArtwork\\command]')
226
+ reg_lines.append(f'@="{self._reg_escape(self.upload_artwork_cmd)}"')
227
+ reg_lines.append('')
228
+ # Upload + Artwork + JSON
229
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell\\d_UploadArtworkJson]')
230
+ reg_lines.append('@="Convert File to .taf and Upload + Artwork + JSON"')
231
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}\\shell\\d_UploadArtworkJson\\command]')
232
+ reg_lines.append(f'@="{self._reg_escape(self.upload_artwork_json_cmd)}"')
233
+ reg_lines.append('')
234
+ return reg_lines
235
+
236
+ def _generate_taf_file_entries(self):
237
+ """Generate registry entries for .taf files"""
238
+ reg_lines = []
239
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell]')
240
+ reg_lines.append('')
241
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}]')
242
+ reg_lines.append('"MUIVerb"="TonieToolbox"')
243
+ reg_lines.append(f'"Icon"="{self.icon_path}"')
244
+ reg_lines.append('"subcommands"=""')
245
+ reg_lines.append('')
246
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell]')
247
+ # Show Info
248
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\a_ShowInfo]')
249
+ reg_lines.append('@="Show Info"')
250
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\a_ShowInfo\\command]')
251
+ reg_lines.append(f'@="{self._reg_escape(self.show_info_cmd)}"')
252
+ reg_lines.append('')
253
+ # Extract Opus Tracks
254
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\b_ExtractOpus]')
255
+ reg_lines.append('@="Extract Opus Tracks"')
256
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\b_ExtractOpus\\command]')
257
+ reg_lines.append(f'@="{self._reg_escape(self.extract_opus_cmd)}"')
258
+ reg_lines.append('')
259
+ if self.upload_enabled:
260
+ # Upload
261
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\c_Upload]')
262
+ reg_lines.append('@="Upload"')
263
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\c_Upload\\command]')
264
+ reg_lines.append(f'@="{self._reg_escape(self.upload_taf_cmd)}"')
265
+ reg_lines.append('')
266
+ # Upload + Artwork
267
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\d_UploadArtwork]')
268
+ reg_lines.append('@="Upload + Artwork"')
269
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\d_UploadArtwork\\command]')
270
+ reg_lines.append(f'@="{self._reg_escape(self.upload_taf_artwork_cmd)}"')
271
+ reg_lines.append('')
272
+ # Upload + Artwork + JSON
273
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\e_UploadArtworkJson]')
274
+ reg_lines.append('@="Upload + Artwork + JSON"')
275
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\e_UploadArtworkJson\\command]')
276
+ reg_lines.append(f'@="{self._reg_escape(self.upload_taf_artwork_json_cmd)}"')
277
+ reg_lines.append('')
278
+ # Compare TAF Files
279
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\f_CompareTaf]')
280
+ reg_lines.append('@="Compare with another .taf file"')
281
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}\\shell\\f_CompareTaf\\command]')
282
+ reg_lines.append(f'@="{self._reg_escape(self.compare_taf_cmd)}"')
283
+ reg_lines.append('')
284
+ return reg_lines
285
+
286
+ def _generate_folder_entries(self):
287
+ """Generate registry entries for folders"""
288
+ reg_lines = []
289
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell]')
290
+ reg_lines.append('')
291
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}]')
292
+ reg_lines.append('"MUIVerb"="TonieToolbox"')
293
+ reg_lines.append(f'"Icon"="{self.icon_path}"')
294
+ reg_lines.append('"subcommands"=""')
295
+ reg_lines.append('')
296
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell]')
297
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell\\a_ConvertFolder]')
298
+ reg_lines.append('@="Convert Folder to .taf (recursive)"')
299
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell\\a_ConvertFolder\\command]')
300
+ reg_lines.append(f'@="{self._reg_escape(self.convert_folder_cmd)}"')
301
+ reg_lines.append('')
302
+ if self.upload_enabled:
303
+ # Upload
304
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell\\b_UploadFolder]')
305
+ reg_lines.append('@="Convert Folder to .taf and Upload (recursive)"')
306
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell\\b_UploadFolder\\command]')
307
+ reg_lines.append(f'@="{self._reg_escape(self.upload_folder_cmd)}"')
308
+ reg_lines.append('')
309
+ # Upload + Artwork
310
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell\\c_UploadFolderArtwork]')
311
+ reg_lines.append('@="Convert Folder to .taf and Upload + Artwork (recursive)"')
312
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell\\c_UploadFolderArtwork\\command]')
313
+ reg_lines.append(f'@="{self._reg_escape(self.upload_folder_artwork_cmd)}"')
314
+ reg_lines.append('')
315
+ # Upload + Artwork + JSON
316
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell\\d_UploadFolderArtworkJson]')
317
+ reg_lines.append('@="Convert Folder to .taf and Upload + Artwork + JSON (recursive)"')
318
+ reg_lines.append(f'[HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}\\shell\\d_UploadFolderArtworkJson\\command]')
319
+ reg_lines.append(f'@="{self._reg_escape(self.upload_folder_artwork_json_cmd)}"')
320
+ reg_lines.append('')
321
+ return reg_lines
322
+
323
+ def _generate_uninstaller_entries(self):
324
+ """Generate registry entries for uninstaller"""
325
+ unreg_lines = [
326
+ 'Windows Registry Editor Version 5.00',
327
+ '',
328
+ ]
329
+
330
+ for ext in SUPPORTED_EXTENSIONS:
331
+ ext = ext.lower().lstrip('.')
332
+ unreg_lines.append(f'[-HKEY_CLASSES_ROOT\\SystemFileAssociations\\.{ext}\\shell\\{self.cascade_name}]')
333
+ unreg_lines.append('')
334
+
335
+ unreg_lines.append(f'[-HKEY_CLASSES_ROOT\\SystemFileAssociations\\.taf\\shell\\{self.cascade_name}]')
336
+ unreg_lines.append('')
337
+ unreg_lines.append(f'[-HKEY_CLASSES_ROOT\\Directory\\shell\\{self.cascade_name}]')
338
+
339
+ return unreg_lines
340
+
341
+ def generate_registry_files(self):
342
+ """
343
+ Generate Windows registry files for TonieToolbox context menu integration.
344
+ Returns the path to the installer registry file.
345
+ """
346
+ os.makedirs(self.output_dir, exist_ok=True)
347
+
348
+ reg_lines = [
349
+ 'Windows Registry Editor Version 5.00',
350
+ '',
351
+ ]
352
+
353
+ # Add entries for audio extensions
354
+ reg_lines.extend(self._generate_audio_extensions_entries())
355
+
356
+ # Add entries for .taf files
357
+ reg_lines.extend(self._generate_taf_file_entries())
358
+
359
+ # Add entries for folders
360
+ reg_lines.extend(self._generate_folder_entries())
361
+
362
+ # Write the installer .reg file
363
+ reg_path = os.path.join(self.output_dir, 'tonietoolbox_context.reg')
364
+ with open(reg_path, 'w', encoding='utf-8') as f:
365
+ f.write('\n'.join(reg_lines))
366
+
367
+ # Generate and write the uninstaller .reg file
368
+ unreg_lines = self._generate_uninstaller_entries()
369
+ unreg_path = os.path.join(self.output_dir, 'remove_tonietoolbox_context.reg')
370
+ with open(unreg_path, 'w', encoding='utf-8') as f:
371
+ f.write('\n'.join(unreg_lines))
372
+
373
+ return reg_path
374
+
375
+ def install_registry_files(self, uninstall=False):
376
+ """
377
+ Import the generated .reg file into the Windows registry with UAC elevation.
378
+ If uninstall is True, imports the uninstaller .reg file.
379
+
380
+ Returns:
381
+ bool: True if registry import was successful, False otherwise.
382
+ """
383
+ import subprocess
384
+ reg_file = os.path.join(
385
+ self.output_dir,
386
+ 'remove_tonietoolbox_context.reg' if uninstall else 'tonietoolbox_context.reg'
387
+ )
388
+ if not os.path.exists(reg_file):
389
+ logger.error(f"Registry file not found: {reg_file}")
390
+ return False
391
+
392
+ ps_command = (
393
+ f"Start-Process reg.exe -ArgumentList @('import', '{reg_file}') -Verb RunAs -Wait -PassThru"
394
+ )
395
+ try:
396
+ result = subprocess.run(["powershell.exe", "-Command", ps_command], check=False,
397
+ capture_output=True, text=True)
398
+
399
+ if result.returncode == 0:
400
+ logger.info(f"{'Uninstallation' if uninstall else 'Installation'} registry import completed.")
401
+ return True
402
+ else:
403
+ logger.error(f"Registry import command failed with return code {result.returncode}")
404
+ logger.error(f"STDERR: {result.stderr}")
405
+ return False
406
+
407
+ except subprocess.SubprocessError as e:
408
+ logger.error(f"Failed to import registry file: {e}")
409
+ return False
410
+
411
+ @classmethod
412
+ def install(cls):
413
+ """
414
+ Generate registry files and install them with UAC elevation.
415
+ """
416
+ instance = cls()
417
+ instance.generate_registry_files()
418
+ if instance.install_registry_files(uninstall=False):
419
+ logger.info("Integration installed successfully.")
420
+ return True
421
+ else:
422
+ logger.error("Integration installation failed.")
423
+ return False
424
+
425
+ @classmethod
426
+ def uninstall(cls):
427
+ """
428
+ Generate registry files and uninstall them with UAC elevation.
429
+ """
430
+ instance = cls()
431
+ instance.generate_registry_files()
432
+ if instance.install_registry_files(uninstall=True):
433
+ logger.info("Integration uninstalled successfully.")
434
+ return True
435
+ else:
436
+ logger.error("Integration uninstallation failed.")
437
+ return False
TonieToolbox/logger.py CHANGED
@@ -13,7 +13,7 @@ TRACE = 5 # Custom level for ultra-verbose debugging
13
13
  logging.addLevelName(TRACE, 'TRACE')
14
14
 
15
15
  # Create a method for the TRACE level
16
- def trace(self, message, *args, **kwargs):
16
+ def trace(self: logging.Logger, message: str, *args, **kwargs) -> None:
17
17
  """Log a message with TRACE level (more detailed than DEBUG)"""
18
18
  if self.isEnabledFor(TRACE):
19
19
  self.log(TRACE, message, *args, **kwargs)
@@ -21,7 +21,7 @@ def trace(self, message, *args, **kwargs):
21
21
  # Add trace method to the Logger class
22
22
  logging.Logger.trace = trace
23
23
 
24
- def get_log_file_path():
24
+ def get_log_file_path() -> Path:
25
25
  """
26
26
  Get the path to the log file in the .tonietoolbox folder with timestamp.
27
27
 
@@ -29,7 +29,7 @@ def get_log_file_path():
29
29
  Path: Path to the log file
30
30
  """
31
31
  # Create .tonietoolbox folder in user's home directory if it doesn't exist
32
- log_dir = Path.home() / '.tonietoolbox'
32
+ log_dir = Path.home() / '.tonietoolbox' / 'logs'
33
33
  log_dir.mkdir(exist_ok=True)
34
34
 
35
35
  # Create timestamp string for the filename
@@ -40,14 +40,13 @@ def get_log_file_path():
40
40
 
41
41
  return log_file
42
42
 
43
- def setup_logging(level=logging.INFO, log_to_file=False):
43
+ def setup_logging(level: int = logging.INFO, log_to_file: bool = False) -> logging.Logger:
44
44
  """
45
45
  Set up logging configuration for the entire application.
46
46
 
47
47
  Args:
48
- level: Logging level (default: logging.INFO)
49
- log_to_file: Whether to log to a file (default: False)
50
-
48
+ level (int): Logging level (default: logging.INFO)
49
+ log_to_file (bool): Whether to log to a file (default: False)
51
50
  Returns:
52
51
  logging.Logger: Root logger instance
53
52
  """
@@ -88,13 +87,12 @@ def setup_logging(level=logging.INFO, log_to_file=False):
88
87
 
89
88
  return root_logger
90
89
 
91
- def get_logger(name):
90
+ def get_logger(name: str) -> logging.Logger:
92
91
  """
93
92
  Get a logger with the specified name.
94
93
 
95
94
  Args:
96
- name: Logger name, typically the module name
97
-
95
+ name (str): Logger name, typically the module name
98
96
  Returns:
99
97
  logging.Logger: Logger instance
100
98
  """