Skip to content

Commit 0915ee4

Browse files
authored
Merge pull request #4 from auax/master
fixed bugs and improved code quality
2 parents 9f5ac9c + 0f0917b commit 0915ee4

File tree

3 files changed

+71
-29
lines changed

3 files changed

+71
-29
lines changed

resources/main.ui

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,8 @@ p, li { white-space: pre-wrap; }
432432
<property name="title">
433433
<string>Options</string>
434434
</property>
435+
<addaction name="clear_log"/>
436+
<addaction name="separator"/>
435437
<addaction name="open_github"/>
436438
<addaction name="report_issue"/>
437439
<addaction name="donate"/>
@@ -459,6 +461,11 @@ p, li { white-space: pre-wrap; }
459461
<string>Donate</string>
460462
</property>
461463
</action>
464+
<action name="clear_log">
465+
<property name="text">
466+
<string>Clear Log</string>
467+
</property>
468+
</action>
462469
</widget>
463470
<resources/>
464471
<connections/>

secauax.py

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pathlib import Path
44
from typing import Union
55

6-
from cryptography.fernet import Fernet
6+
from cryptography.fernet import Fernet, InvalidToken
77

88

99
class Secauax:
@@ -107,12 +107,20 @@ def bulk_encrypt(self,
107107
assert os.path.isdir(pathname), "pathname path doesn't exist"
108108
assert os.path.isdir(output_directory), "output_directory path doesn't exist"
109109

110-
try:
111-
for file in glob.glob(os.path.join(pathname, file_extension)):
112-
self.encrypt_file(file, os.path.join(output_directory, os.path.basename(file)))
113-
except:
114-
return False
115-
return True
110+
files_encrypted = 0
111+
112+
for file in glob.glob(os.path.join(pathname, file_extension)):
113+
try:
114+
filename = os.path.join(output_directory, os.path.basename(file))
115+
if os.path.isdir(file): # Skip folders
116+
continue
117+
self.encrypt_file(file, filename)
118+
files_encrypted += 1
119+
120+
except InvalidToken:
121+
pass
122+
123+
return True if files_encrypted >= 1 else False
116124

117125
def decrypt_file(self, path: Union[Path, str], filename: Union[Path, str] = None) -> bytes:
118126
"""
@@ -138,26 +146,36 @@ def decrypt_file(self, path: Union[Path, str], filename: Union[Path, str] = None
138146
decrypted_file.write(decrypted_data)
139147
decrypted_file.close()
140148

149+
return decrypted_data
150+
141151
def bulk_decrypt(self,
142152
pathname: Union[Path, str],
143153
output_directory: Union[Path, str] = None,
144154
file_extension: str = "*") -> bool:
145155
"""
146156
Decrypt all the files inside a directory and save them into another directory.
147157
Attention: If the output_directory parameter is not specified, the new file(s) will overwrite the original(s).
148-
This method returns a true boolean if the files are saved successfully. Any error will result in a false boolean.
158+
This method returns a true boolean if at least one file was decrypted.
149159
:param pathname: path to encrypted folder
150160
:param output_directory: path to save the decrypted files
151-
:param file_extension: select which files will be decrypted. Format: ".png" or, for all type of files: "*"
161+
:param file_extension: filter files by extension: ".png" / ".txt" / ...
152162
:return: bool
153163
"""
154164

155165
assert os.path.isdir(pathname), "pathname path doesn't exist"
156166
assert os.path.isdir(output_directory), "output_directory path doesn't exist"
157167

158-
try:
159-
for file in glob.glob(os.path.join(pathname, file_extension)):
160-
self.decrypt_file(file, os.path.join(output_directory, os.path.basename(file)))
161-
except:
162-
return False
163-
return True
168+
files_decrypted = 0
169+
170+
for file in glob.glob(os.path.join(pathname, file_extension)):
171+
try:
172+
filename = os.path.join(output_directory, os.path.basename(file))
173+
if os.path.isdir(file): # Skip folders
174+
continue
175+
self.decrypt_file(file, filename)
176+
files_decrypted += 1
177+
178+
except InvalidToken:
179+
pass
180+
181+
return True if files_decrypted >= 1 else False

window.py

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,10 @@
66
from PyQt5 import QtGui
77
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QMessageBox
88
from PyQt5.uic import loadUi
9+
from cryptography.fernet import InvalidToken
910

1011
from secauax import Secauax
1112

12-
log = []
13-
1413

1514
def resource_path(relative_path: str) -> str:
1615
"""
@@ -27,6 +26,8 @@ class MainWindow(QMainWindow):
2726
def __init__(self):
2827
super(MainWindow, self).__init__()
2928

29+
self.log_data = []
30+
3031
# Set Window settings
3132
loadUi(resource_path("resources/main.ui"), self)
3233
self.setWindowTitle("Secauax by Auax")
@@ -35,6 +36,7 @@ def __init__(self):
3536
self.enable = False # Enable the encrypt and decrypt buttons
3637

3738
# Connect Menu
39+
self.clear_log.triggered.connect(self.reset_logger)
3840
self.open_github.triggered.connect(lambda: webbrowser.open("https://github.com/auax"))
3941
self.report_issue.triggered.connect(lambda: webbrowser.open("https://github.com/auax/secauax/issues/new"))
4042
self.donate.triggered.connect(lambda: webbrowser.open("https://paypal.me/zellius"))
@@ -160,16 +162,17 @@ def encrypt(self) -> None:
160162
if self.save_key_path.text():
161163
# Save key to the desired path
162164
secauax.save_key(self.save_key_path.text())
163-
self.logger(f"Key loaded from {self.save_key_path.text()}!")
165+
self.logger(f"Key saved in {self.save_key_path.text()}!")
164166

165167
if self.load_key_path.text():
166168
# Load key from the desired path
167169
secauax.load_key_into_class(self.load_key_path.text())
168-
self.logger(f"Key saved in {self.load_key_path.text()}!")
170+
self.logger(f"Key loaded from {self.load_key_path.text()}!")
169171

170172
if self.mode_cb.isChecked():
171173
# Directory mode
172-
secauax.bulk_encrypt(self.input_path.text(), self.output_path.text())
174+
if not secauax.bulk_encrypt(self.input_path.text(), self.output_path.text()):
175+
raise InvalidToken
173176
else:
174177
# File mode
175178
secauax.encrypt_file(self.input_path.text(), self.output_path.text())
@@ -180,8 +183,11 @@ def encrypt(self) -> None:
180183
# Show a message
181184
MainWindow.create_dialog("File(s) encrypted successfuly!", "", "Success!", QMessageBox.Information)
182185

186+
except InvalidToken:
187+
self.logger("InvalidToken! Make sure to select the correct key.")
188+
183189
except Exception as E:
184-
self.logger("Something went wrong! Please try again.") # Log error
190+
self.logger(f"Unhandled error: {type(E).__name__}")
185191

186192
def decrypt(self) -> None:
187193
"""
@@ -195,16 +201,17 @@ def decrypt(self) -> None:
195201
if self.save_key_path.text():
196202
# Save key to the desired path
197203
secauax.save_key(self.save_key_path.text())
198-
self.logger(f"Key loaded from {self.save_key_path.text()}!")
204+
self.logger(f"Key saved in {self.save_key_path.text()}!")
199205

200206
if self.load_key_path.text():
201207
# Load key from the desired path
202208
secauax.load_key_into_class(self.load_key_path.text())
203-
self.logger(f"Key saved in {self.load_key_path.text()}!")
209+
self.logger(f"Key loaded from {self.load_key_path.text()}!")
204210

205211
if self.mode_cb.isChecked():
206212
# Directory mode
207-
secauax.bulk_decrypt(self.input_path.text(), self.output_path.text())
213+
if not secauax.bulk_decrypt(self.input_path.text(), self.output_path.text()):
214+
raise InvalidToken
208215
else:
209216
# File mode
210217
secauax.decrypt_file(self.input_path.text(), self.output_path.text())
@@ -215,8 +222,11 @@ def decrypt(self) -> None:
215222
# Show message
216223
MainWindow.create_dialog("File(s) decrypted successfuly!", "", "Success!", QMessageBox.Information)
217224

218-
except:
219-
self.logger("Something went wrong! Please try again.") # Log error
225+
except InvalidToken:
226+
self.logger("InvalidToken! Make sure to select the correct key.")
227+
228+
except Exception as E:
229+
self.logger(f"Unhandled error: {type(E).__name__}")
220230

221231
def logger(self, message: str, color: str = "red") -> None:
222232
"""
@@ -225,13 +235,20 @@ def logger(self, message: str, color: str = "red") -> None:
225235
:param color: the color of the message
226236
:return: None
227237
"""
228-
global log
229-
log.append(message)
238+
self.log_data.append(message)
230239
to_html = ""
231-
for i in log:
240+
for i in self.log_data:
232241
to_html += f"<p style='margin: 2px 4px 2px 4px !important;'><code style='color:red'>>></code> {i}</p>"
233242
self.log.setHtml(to_html)
234243

244+
def reset_logger(self) -> None:
245+
"""
246+
Clear all log data
247+
:return: None
248+
"""
249+
self.log_data = []
250+
self.log.setHtml("")
251+
235252
@staticmethod
236253
def create_dialog(message: str, informative_text: str, title: str = "Info", icon=QMessageBox.Critical) -> None:
237254
"""

0 commit comments

Comments
 (0)