SafePDF 1.0.11__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.
Files changed (48) hide show
  1. SafePDF/__init__.py +10 -0
  2. SafePDF/ctrl/__init__.py +0 -0
  3. SafePDF/ctrl/language_manager.py +69 -0
  4. SafePDF/ctrl/safe_pdf_controller.py +469 -0
  5. SafePDF/logger/__init__.py +0 -0
  6. SafePDF/logger/logging_config.py +94 -0
  7. SafePDF/ops/__init__.py +0 -0
  8. SafePDF/ops/license_manager.py +247 -0
  9. SafePDF/ops/pdf2docx.py +157 -0
  10. SafePDF/ops/pdf2jpeg.py +116 -0
  11. SafePDF/ops/pdf_compress.py +282 -0
  12. SafePDF/ops/pdf_merge.py +104 -0
  13. SafePDF/ops/pdf_operations.py +563 -0
  14. SafePDF/ops/pdf_rotate.py +102 -0
  15. SafePDF/ops/pdf_split.py +178 -0
  16. SafePDF/ops/updates.py +308 -0
  17. SafePDF/safe_pdf_app.py +121 -0
  18. SafePDF/test/__init__.py +0 -0
  19. SafePDF/test/test_compression.py +79 -0
  20. SafePDF/test/test_pro_dialog.py +45 -0
  21. SafePDF/text/de/help_content.txt +58 -0
  22. SafePDF/text/de/pro_features.txt +9 -0
  23. SafePDF/text/de/ui.json +260 -0
  24. SafePDF/text/de/welcome_content.txt +24 -0
  25. SafePDF/text/en/help_content.txt +42 -0
  26. SafePDF/text/en/pro_features.txt +8 -0
  27. SafePDF/text/en/ui.json +260 -0
  28. SafePDF/text/en/welcome_content.txt +25 -0
  29. SafePDF/text/tr/help_content.txt +53 -0
  30. SafePDF/text/tr/pro_features.txt +8 -0
  31. SafePDF/text/tr/ui.json +260 -0
  32. SafePDF/text/tr/welcome_content.txt +24 -0
  33. SafePDF/ui/__init__.py +11 -0
  34. SafePDF/ui/common_elements.py +40 -0
  35. SafePDF/ui/help_ui.py +233 -0
  36. SafePDF/ui/language_elements.py +9 -0
  37. SafePDF/ui/operation_settings.py +377 -0
  38. SafePDF/ui/safe_pdf_ui.py +3497 -0
  39. SafePDF/ui/settings_ui.py +394 -0
  40. SafePDF/ui/tabs_manager.py +235 -0
  41. SafePDF/ui/update_ui.py +717 -0
  42. SafePDF/version.txt +34 -0
  43. safepdf-1.0.11.dist-info/METADATA +162 -0
  44. safepdf-1.0.11.dist-info/RECORD +48 -0
  45. safepdf-1.0.11.dist-info/WHEEL +5 -0
  46. safepdf-1.0.11.dist-info/entry_points.txt +2 -0
  47. safepdf-1.0.11.dist-info/licenses/LICENSE +674 -0
  48. safepdf-1.0.11.dist-info/top_level.txt +1 -0
SafePDF/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """
2
+ SafePDF package initializer.
3
+
4
+ This file makes the `SafePDF` directory a proper Python package so
5
+ absolute imports like `from SafePDF.ui...` work consistently.
6
+ """
7
+
8
+ __version__ = "1.0.11"
9
+
10
+ __all__ = []
File without changes
@@ -0,0 +1,69 @@
1
+ """
2
+ Language Manager - Loads localized UI strings and content from JSON and text files.
3
+ Supports language switching without restart by reloading language data.
4
+ """
5
+
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Optional
10
+
11
+
12
+ class LanguageManager:
13
+ """Simple language manager to load localized UI strings and content files.
14
+
15
+ It looks under `text/{lang}/` for `ui.json` and content files like
16
+ `welcome_content.txt`, `help_content.txt`, `pro_features.txt`, etc.
17
+ Falls back to top-level `text/` files when localized ones are missing.
18
+ """
19
+
20
+ def __init__(self, lang: str = "en"):
21
+ # Get the base directory - handle both Python and PyInstaller executables
22
+ if getattr(sys, "frozen", False):
23
+ # Running in PyInstaller bundle
24
+ base_dir = Path(sys._MEIPASS)
25
+ else:
26
+ # Running as Python script
27
+ base_dir = Path(__file__).parent.parent
28
+
29
+ self.base = base_dir / "text"
30
+ self.lang = lang or "en"
31
+ self.ui_strings = {}
32
+ self.load(self.lang)
33
+
34
+ def load(self, lang: str):
35
+ """Load UI strings for a language (non-fatal)."""
36
+ self.lang = lang or "en"
37
+ self.ui_strings = {}
38
+ ui_path = self.base / self.lang / "ui.json"
39
+ fallback = self.base / "ui.json"
40
+ try:
41
+ if ui_path.exists():
42
+ with open(ui_path, "r", encoding="utf-8") as f:
43
+ self.ui_strings = json.load(f)
44
+ elif fallback.exists():
45
+ with open(fallback, "r", encoding="utf-8") as f:
46
+ self.ui_strings = json.load(f)
47
+ except Exception:
48
+ self.ui_strings = {}
49
+
50
+ def get(self, key: str, default: Optional[str] = None) -> Optional[str]:
51
+ """Get a UI string for the current language, with optional default."""
52
+ return self.ui_strings.get(key) or default
53
+
54
+ def get_text_file(self, name: str) -> Optional[str]:
55
+ """Return contents of a text file under text/{lang}/{name}.txt or fallback.
56
+
57
+ Example: name='welcome_content' -> looks for welcome_content.txt
58
+ """
59
+ candidates = [
60
+ self.base / self.lang / f"{name}.txt",
61
+ self.base / f"{name}.txt",
62
+ ]
63
+ for p in candidates:
64
+ try:
65
+ if p.exists():
66
+ return p.read_text(encoding="utf-8")
67
+ except Exception:
68
+ continue
69
+ return None
@@ -0,0 +1,469 @@
1
+ """
2
+ SafePDF Controller - Core Logic
3
+ by mcagriaksoy - 2025
4
+
5
+ This module handles the core application logic, state management,
6
+ and coordination of PDF operations.
7
+ """
8
+
9
+ import os
10
+ import shutil
11
+ from datetime import datetime, timedelta
12
+ from os import makedirs
13
+ from os import path as os_path
14
+ from threading import Thread
15
+
16
+ from SafePDF.logger.logging_config import get_logger
17
+ from SafePDF.ops.license_manager import LicenseManager
18
+ from SafePDF.ops.pdf_operations import PDFOperations
19
+ from SafePDF.ops.updates import SafePDFUpdates
20
+
21
+
22
+ class SafePDFController:
23
+ """Controller class that manages application state and logic"""
24
+
25
+ def __init__(self, progress_callback=None, language_manager=None):
26
+ # Application state
27
+ self.selected_files = []
28
+ self.selected_file = None
29
+ self.selected_operation = None
30
+ self.current_tab = 0
31
+ self.operation_settings = {}
32
+ self.operation_running = False
33
+ self.output_path = None
34
+ self.output_dir = None
35
+ self.current_output = None
36
+
37
+ # Activation state
38
+ self.is_pro_activated = False
39
+ self.activation_key = None
40
+ self.pro_expiry_date = None
41
+
42
+ # Module logger (needed for _load_pro_status)
43
+ self.logger = get_logger("SafePDF.Controller")
44
+
45
+ # Language manager for localization
46
+ self.language_manager = language_manager
47
+
48
+ # License manager for verification (must be initialized BEFORE _load_pro_status)
49
+ self.license_manager = LicenseManager(logger=self.logger)
50
+
51
+ # Load saved pro status
52
+ self._load_pro_status()
53
+
54
+ # PDF operations handler
55
+ self.pdf_ops = PDFOperations(progress_callback=progress_callback, language_manager=language_manager)
56
+
57
+ # Updates handler for GitHub releases and signed keys
58
+ self.updates = SafePDFUpdates()
59
+
60
+ # Callbacks for UI updates
61
+ self.progress_callback = progress_callback
62
+ self.update_ui_callback = None
63
+ self.completion_callback = None
64
+
65
+ def set_ui_callbacks(self, update_ui_callback=None, completion_callback=None):
66
+ """Set callback functions for UI updates"""
67
+ self.update_ui_callback = update_ui_callback
68
+ self.completion_callback = completion_callback
69
+
70
+ def select_file(self, file_path):
71
+ """Select and validate PDF file(s)"""
72
+ if isinstance(file_path, list):
73
+ self.selected_files = file_path
74
+ else:
75
+ self.selected_files = [file_path]
76
+
77
+ self.selected_file = self.selected_files[0] if self.selected_files else None
78
+
79
+ # Validate all files
80
+ for f in self.selected_files:
81
+ if not os_path.exists(f):
82
+ return False, f"File does not exist: {f}"
83
+ if not f.lower().endswith(".pdf"):
84
+ return False, f"Please select PDF files only. Invalid: {os_path.basename(f)}"
85
+
86
+ filenames = [os_path.basename(f) for f in self.selected_files]
87
+ return True, f"Selected: {', '.join(filenames)}"
88
+
89
+ def get_pdf_info(self):
90
+ """Get information about the selected PDF file"""
91
+ if not self.selected_file:
92
+ return None
93
+
94
+ return self.pdf_ops.get_pdf_info(self.selected_file)
95
+
96
+ def select_operation(self, operation):
97
+ """Select a PDF operation"""
98
+ valid_operations = [
99
+ "compress",
100
+ "split",
101
+ "merge",
102
+ "to_jpg",
103
+ "rotate",
104
+ "repair",
105
+ "to_word",
106
+ "to_txt",
107
+ "extract_info",
108
+ ]
109
+ if operation in valid_operations:
110
+ self.selected_operation = operation
111
+ return True
112
+ return False
113
+
114
+ def set_operation_settings(self, settings_dict):
115
+ """Set operation-specific settings"""
116
+ self.operation_settings.update(settings_dict)
117
+
118
+ def can_proceed_to_tab(self, tab_index):
119
+ """Check if the user can proceed to a specific tab"""
120
+ if tab_index == 3: # File selection tab
121
+ if not self.selected_operation:
122
+ return False, "Please select an operation first!"
123
+ elif tab_index == 4: # Settings tab - no additional validation needed
124
+ if not self.selected_file:
125
+ return False, "Please select a file first!"
126
+ if self.selected_operation == "merge" and len(self.selected_files) < 2:
127
+ return False, "Merge requires at least two files. Please select more files."
128
+
129
+ return True, ""
130
+
131
+ def prepare_output_paths(self, custom_output_path=None, use_default=True):
132
+ """Optimized output path preparation"""
133
+ if not use_default and custom_output_path:
134
+ if self.selected_operation in ["split", "to_jpg"]:
135
+ return None, custom_output_path
136
+ else:
137
+ return custom_output_path, None
138
+
139
+ # Default paths with minimal processing
140
+ if self.selected_operation in ["compress", "rotate", "repair", "to_word", "to_txt", "extract_info", "merge"]:
141
+ base_name = os_path.splitext(self.selected_file)[0]
142
+ if self.selected_operation == "to_word":
143
+ return f"{base_name}.docx", None
144
+ elif self.selected_operation == "to_txt":
145
+ return f"{base_name}.txt", None
146
+ elif self.selected_operation == "extract_info":
147
+ return f"{base_name}_info.txt", None
148
+ elif self.selected_operation == "merge":
149
+ return f"{base_name}_merged.pdf", None
150
+ else:
151
+ return f"{base_name}_{self.selected_operation}.pdf", None
152
+ else:
153
+ base_dir = os_path.dirname(self.selected_file)
154
+ base_name = os_path.splitext(os_path.basename(self.selected_file))[0]
155
+ output_dir = os_path.join(base_dir, f"{base_name}_{self.selected_operation}")
156
+ makedirs(output_dir, exist_ok=True)
157
+ return None, output_dir
158
+
159
+ def execute_operation_async(self, output_path=None, output_dir=None):
160
+ """Execute the selected operation asynchronously"""
161
+ if not self.selected_file or not self.selected_operation:
162
+ return False, "Please select a file and operation first!"
163
+
164
+ if self.operation_running:
165
+ return False, "Operation is already running!"
166
+
167
+ # Start operation in a separate thread
168
+ self.operation_running = True
169
+ thread = Thread(target=self._run_operation_thread, args=(output_path, output_dir), daemon=True)
170
+ thread.start()
171
+ return True, "Operation started"
172
+
173
+ def _run_operation_thread(self, output_path, output_dir):
174
+ """Run the PDF operation in a separate thread"""
175
+ try:
176
+ success = False
177
+ message = ""
178
+
179
+ # Execute operation based on type
180
+ if self.selected_operation == "compress":
181
+ quality = self.operation_settings.get("quality", "medium")
182
+ success, message = self.pdf_ops.compress_pdf(self.selected_file, output_path, quality)
183
+
184
+ elif self.selected_operation == "split":
185
+ method = self.operation_settings.get("method", "pages")
186
+ page_range = self.operation_settings.get("page_range", None)
187
+ success, message = self.pdf_ops.split_pdf(self.selected_file, output_dir, method, page_range)
188
+
189
+ elif self.selected_operation == "rotate":
190
+ angle = int(self.operation_settings.get("angle", 90))
191
+ success, message = self.pdf_ops.rotate_pdf(self.selected_file, output_path, angle)
192
+
193
+ elif self.selected_operation == "repair":
194
+ success, message = self.pdf_ops.repair_pdf(self.selected_file, output_path)
195
+
196
+ elif self.selected_operation == "to_jpg":
197
+ dpi = int(self.operation_settings.get("dpi", 200))
198
+ success, message = self.pdf_ops.pdf_to_jpg(self.selected_file, output_dir, dpi)
199
+
200
+ elif self.selected_operation == "merge":
201
+ # Merge operation: use all selected files
202
+ if len(self.selected_files) < 2:
203
+ success = False
204
+ message = "Merge requires at least 2 PDF files to be selected."
205
+ else:
206
+ # Use all selected files in order
207
+ input_paths = self.selected_files
208
+
209
+ # Prepare output file path (single file)
210
+ output_path, _ = self.prepare_output_paths(custom_output_path=None, use_default=True)
211
+
212
+ try:
213
+ success, message = self.pdf_ops.merge_pdfs(input_paths, output_path)
214
+ if success:
215
+ self.current_output = output_path
216
+ except Exception as e:
217
+ success = False
218
+ message = f"Merge failed: {e}"
219
+
220
+ elif self.selected_operation == "to_word":
221
+ # PDF to Word conversion
222
+ base_name = os_path.splitext(self.selected_file)[0]
223
+ output_path = f"{base_name}.docx"
224
+ success, message = self.pdf_ops.pdf_to_word(self.selected_file, output_path)
225
+
226
+ elif self.selected_operation == "to_txt":
227
+ # PDF to TXT conversion
228
+ base_name = os_path.splitext(self.selected_file)[0]
229
+ output_path = f"{base_name}.txt"
230
+ success, message = self.pdf_ops.pdf_to_txt(self.selected_file, output_path)
231
+
232
+ elif self.selected_operation == "extract_info":
233
+ # Extract hidden information
234
+ base_name = os_path.splitext(self.selected_file)[0]
235
+ output_path = f"{base_name}_info.txt"
236
+ success, message = self.pdf_ops.extract_hidden_info(self.selected_file, output_path)
237
+
238
+ # Store current output location
239
+ self.current_output = output_path or output_dir if success else None
240
+
241
+ # Notify completion
242
+ if self.completion_callback:
243
+ self.completion_callback(success, message, self.current_output)
244
+
245
+ except Exception as e:
246
+ error_msg = f"Operation failed with error: {str(e)}"
247
+ if self.completion_callback:
248
+ self.completion_callback(False, error_msg, None)
249
+ finally:
250
+ self.operation_running = False
251
+
252
+ def cancel_operation(self):
253
+ """Cancel the current operation (if possible)"""
254
+ # Cooperative cancellation: ask pdf_ops to cancel and clear flags
255
+ try:
256
+ if hasattr(self.pdf_ops, "request_cancel"):
257
+ self.pdf_ops.request_cancel()
258
+ except Exception:
259
+ self.logger.debug("Error requesting operation cancellation", exc_info=True)
260
+ pass
261
+
262
+ # Wait briefly for operation to observe cancel request
263
+ # Do not block indefinitely; poll a few times
264
+ for _ in range(20):
265
+ if not self.operation_running:
266
+ break
267
+ import time
268
+
269
+ time.sleep(0.05)
270
+
271
+ # Force-clear running flag as last resort
272
+ self.operation_running = False
273
+
274
+ def activate_pro_features(self, license_file_path):
275
+ """Activate pro features by verifying and copying the license file"""
276
+ try:
277
+ if not os_path.exists(license_file_path):
278
+ return False, "License file not found."
279
+
280
+ # Verify the license file using license manager
281
+ success, message, license_data = self.license_manager.verify_license(license_file_path)
282
+
283
+ if not success:
284
+ self.logger.warning(f"License verification failed: {message}")
285
+ return False, f"License verification failed: {message}"
286
+
287
+ # Setup config directory
288
+ config_dir = os_path.join(os_path.expanduser("~"), ".safepdf")
289
+ makedirs(config_dir, exist_ok=True)
290
+
291
+ # Copy verified license file to config directory
292
+ license_filename = os_path.basename(license_file_path)
293
+ dest_license_path = os_path.join(config_dir, license_filename)
294
+
295
+ self.logger.debug(f"Copying verified license from {license_file_path} to {dest_license_path}")
296
+ shutil.copy2(license_file_path, dest_license_path)
297
+
298
+ # Verify the copy was successful
299
+ if not os_path.exists(dest_license_path):
300
+ self.logger.error(f"License file copy failed: {dest_license_path} does not exist")
301
+ return False, "Failed to copy license file to config directory."
302
+
303
+ # Extract expiry date from license data
304
+ try:
305
+ expiry_date = datetime.strptime(license_data["expires"], "%Y-%m-%d")
306
+ except (ValueError, KeyError):
307
+ expiry_date = datetime.now() + timedelta(days=365) # Fallback to 1 year
308
+
309
+ self.is_pro_activated = True
310
+ self.activation_key = dest_license_path
311
+ self.pro_expiry_date = expiry_date
312
+ self.logger.info(f"✓ Pro features activated successfully: {dest_license_path}")
313
+ return True, "Pro features activated successfully!"
314
+
315
+ except Exception as e:
316
+ self.logger.error(f"Error activating pro features: {e}", exc_info=True)
317
+ return False, f"Activation failed: {str(e)}"
318
+
319
+ def deactivate_pro_features(self):
320
+ """Deactivate pro features by deleting the license file"""
321
+ try:
322
+ # Delete license file from config directory
323
+ if self.activation_key and os_path.exists(self.activation_key):
324
+ os.remove(self.activation_key)
325
+ self.logger.info(f"License file deleted: {self.activation_key}")
326
+ except Exception as e:
327
+ self.logger.error(f"Error deleting license file: {e}")
328
+
329
+ self.is_pro_activated = False
330
+ self.activation_key = None
331
+ self.pro_expiry_date = None
332
+ self.logger.info("Pro features deactivated")
333
+
334
+ def is_pro_feature_enabled(self, feature_name=None):
335
+ """Check if pro features are enabled, optionally for a specific feature"""
336
+ return self.is_pro_activated
337
+
338
+ def check_for_updates(self):
339
+ """Check for available updates from GitHub Releases"""
340
+ return self.updates.check_for_updates()
341
+
342
+ def download_update(self, download_url, signature_url):
343
+ """Download and verify an update"""
344
+ return self.updates.download_and_verify(download_url, signature_url)
345
+
346
+ def get_release_info(self, version=None):
347
+ """Get information about a specific release"""
348
+ return self.updates.get_release_info(version)
349
+
350
+ def apply_settings(self, settings_dict):
351
+ """Apply application settings"""
352
+ # Store settings for persistence (could save to file)
353
+ self.app_settings = settings_dict
354
+ self.logger.debug(f"Applied settings: {settings_dict}")
355
+
356
+ def set_app_settings(self, settings_dict):
357
+ """Set application settings (alias for apply_settings)"""
358
+ self.apply_settings(settings_dict)
359
+
360
+ def reset_state(self):
361
+ """Reset the application state completely"""
362
+ # Cancel any running operation first
363
+ self.cancel_operation()
364
+
365
+ # Reset all state variables
366
+ self.selected_files = []
367
+ self.selected_file = None
368
+ self.selected_operation = None
369
+ self.operation_settings = {}
370
+ self.operation_running = False
371
+ self.current_output = None
372
+ self.current_tab = 0
373
+
374
+ # Clear operation settings dictionary completely
375
+ self.operation_settings.clear()
376
+
377
+ # Reset PDF operations handler (clears any cached data)
378
+ if hasattr(self.pdf_ops, "_fitz"):
379
+ setattr(self.pdf_ops, "_fitz", None)
380
+ if hasattr(self.pdf_ops, "_imagetk"):
381
+ setattr(self.pdf_ops, "_imagetk", None)
382
+
383
+ def get_state_summary(self):
384
+ """Get a summary of the current application state"""
385
+ return {
386
+ "selected_files": self.selected_files,
387
+ "selected_file": self.selected_file,
388
+ "selected_operation": self.selected_operation,
389
+ "current_tab": self.current_tab,
390
+ "operation_running": self.operation_running,
391
+ "has_output": bool(self.current_output),
392
+ "output_location": self.current_output,
393
+ }
394
+
395
+ def _load_pro_status(self):
396
+ """Load and verify pro activation status on startup"""
397
+ try:
398
+ config_dir = os_path.join(os_path.expanduser("~"), ".safepdf")
399
+ makedirs(config_dir, exist_ok=True)
400
+
401
+ self.logger.info(f"[STARTUP] Checking for license files in: {config_dir}")
402
+
403
+ # Look for license files (.lic extension only)
404
+ license_files = []
405
+
406
+ if os_path.exists(config_dir):
407
+ for filename in os.listdir(config_dir):
408
+ _, ext = os_path.splitext(filename)
409
+ if ext.lower() == ".lic":
410
+ license_files.append(os_path.join(config_dir, filename))
411
+
412
+ if license_files:
413
+ self.logger.info(f"[STARTUP] Found {len(license_files)} license file(s)")
414
+
415
+ # Verify each license file found
416
+ for idx, license_file_path in enumerate(license_files, 1):
417
+ self.logger.info(
418
+ f"[STARTUP] Verifying license {idx}/{len(license_files)}: {os_path.basename(license_file_path)}"
419
+ )
420
+
421
+ # Verify the license file using license manager
422
+ success, message, license_data = self.license_manager.verify_license(license_file_path)
423
+
424
+ if success:
425
+ # Extract expiry date from verified license
426
+ try:
427
+ expiry_date = datetime.strptime(license_data["expires"], "%Y-%m-%d")
428
+ remaining_days = (expiry_date - datetime.now()).days
429
+ except (ValueError, KeyError):
430
+ expiry_date = datetime.now() + timedelta(days=365)
431
+ remaining_days = 365
432
+
433
+ self.is_pro_activated = True
434
+ self.activation_key = license_file_path
435
+ self.pro_expiry_date = expiry_date
436
+ self.logger.info("[STARTUP] ✓ License verified successfully!")
437
+ self.logger.info(f"[STARTUP] ✓ User: {license_data.get('user', 'N/A')}")
438
+ self.logger.info(f"[STARTUP] ✓ Type: {license_data.get('type', 'N/A')}")
439
+ self.logger.info(f"[STARTUP] ✓ Expires: {license_data.get('expires', 'N/A')}")
440
+ self.logger.info(f"[STARTUP] ✓ Remaining: {remaining_days} days")
441
+ self.logger.info("[STARTUP] ✓ Pro features ACTIVATED")
442
+ return
443
+ else:
444
+ self.logger.warning(f"[STARTUP] ✗ License verification failed: {message}")
445
+ self.logger.warning(f"[STARTUP] License file: {license_file_path}")
446
+ else:
447
+ self.logger.info(f"[STARTUP] No license files found in {config_dir}")
448
+
449
+ # No valid license file found - reset pro status
450
+ self.logger.info("[STARTUP] Running in FREE mode")
451
+ self.is_pro_activated = False
452
+ self.activation_key = None
453
+ self.pro_expiry_date = None
454
+
455
+ except Exception as e:
456
+ self.logger.error(f"[STARTUP] Error loading pro status: {e}", exc_info=True)
457
+ # Reset to defaults on error
458
+ self.is_pro_activated = False
459
+ self.pro_expiry_date = None
460
+ self.activation_key = None
461
+ self.logger.info("[STARTUP] Running in FREE mode (error occurred)")
462
+
463
+ def get_pro_remaining_days(self):
464
+ """Get remaining days for pro license"""
465
+ if not self.is_pro_activated or not self.pro_expiry_date:
466
+ return 0
467
+
468
+ remaining = self.pro_expiry_date - datetime.now()
469
+ return max(0, remaining.days)
File without changes
@@ -0,0 +1,94 @@
1
+ """Central logging setup for SafePDF.
2
+
3
+ Place this file inside the `SafePDF/` package and call
4
+ `from SafePDF.logging_config import setup_logging` early in the
5
+ application startup (for example in `safe_pdf_app.py`) so the
6
+ root logger and file handlers are configured before other modules
7
+ obtain loggers.
8
+
9
+ Usage:
10
+ from SafePDF.logging_config import setup_logging, get_logger
11
+ setup_logging() # call once at startup
12
+ logger = get_logger(__name__)
13
+ logger.info("Ready")
14
+ """
15
+
16
+ import logging
17
+ from logging.handlers import RotatingFileHandler
18
+ from pathlib import Path
19
+
20
+ DEFAULT_LOG_DIR_NAME = ".safepdf"
21
+ DEFAULT_LOG_FILE = "safepdf.log"
22
+
23
+ _configured = False
24
+ _log_file_path = None
25
+
26
+
27
+ def setup_logging(log_dir: str | None = None, max_bytes: int = 5 * 1024 * 1024, backup_count: int = 3):
28
+ """Configure root logger with a rotating file handler.
29
+
30
+ Call this once early in application startup (before other modules
31
+ obtain module loggers).
32
+
33
+ Returns the `Path` to the log file.
34
+ """
35
+ global _configured, _log_file_path
36
+
37
+ if _configured:
38
+ return _log_file_path
39
+
40
+ # Determine log directory
41
+ if log_dir:
42
+ log_dir_path = Path(log_dir).expanduser()
43
+ else:
44
+ log_dir_path = Path.home() / DEFAULT_LOG_DIR_NAME
45
+
46
+ try:
47
+ log_dir_path.mkdir(parents=True, exist_ok=True)
48
+ except Exception:
49
+ logging.error(
50
+ f"Failed to create log directory at {log_dir_path}, falling back to current working directory.",
51
+ exc_info=True,
52
+ )
53
+ # Fall back to current working directory
54
+ log_dir_path = Path.cwd()
55
+
56
+ _log_file_path = log_dir_path / DEFAULT_LOG_FILE
57
+
58
+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
59
+
60
+ handler = RotatingFileHandler(str(_log_file_path), maxBytes=max_bytes, backupCount=backup_count, encoding="utf-8")
61
+ handler.setFormatter(formatter)
62
+ handler.setLevel(logging.DEBUG)
63
+
64
+ root = logging.getLogger()
65
+ root.setLevel(logging.DEBUG)
66
+ # Avoid adding multiple handlers when setup_logging is called more than once
67
+ if not any(
68
+ isinstance(h, RotatingFileHandler) and getattr(h, "baseFilename", None) == str(_log_file_path)
69
+ for h in root.handlers
70
+ ):
71
+ root.addHandler(handler)
72
+
73
+ # Optional: also emit warnings to console in development
74
+ # if not any(isinstance(h, logging.StreamHandler) for h in root.handlers):
75
+ # console = logging.StreamHandler()
76
+ # console.setFormatter(formatter)
77
+ # console.setLevel(logging.INFO)
78
+ # root.addHandler(console)
79
+
80
+ _configured = True
81
+ return _log_file_path
82
+
83
+
84
+ def get_logger(name: str):
85
+ """Return a logger for the given name. Call `setup_logging()` first.
86
+
87
+ If `setup_logging()` was not called, this still returns a logger
88
+ but logs will follow the default logging behaviour.
89
+ """
90
+ return logging.getLogger(name)
91
+
92
+
93
+ def get_log_file_path():
94
+ return _log_file_path
File without changes