44from datetime import datetime
55
66import requests
7- from PyQt5 .QtCore import Qt
7+ from PyQt5 .QtCore import Qt , QThread , pyqtSignal
88from PyQt5 .QtWidgets import QApplication , QMainWindow , QWidget , QVBoxLayout , QHBoxLayout , QLabel , QLineEdit , \
9- QPushButton , QFileDialog , QMessageBox , QComboBox , QProgressDialog
9+ QPushButton , QFileDialog , QMessageBox , QComboBox , QProgressDialog , QDialog , QTextEdit
1010from convertdate import hebrew
1111from titlecase import titlecase
1212
1313SERVER_URL_CONFIG_KEY = 'SERVER_URL'
1414FILE_FILTER = "Divrei Torah (*.pdf)"
1515FILE_CONTENT_TYPE = 'application/pdf'
1616
17- parshas_url = "https://raw.githubusercontent.com/CompuGenius-Programs/RadmashUploader /main/parshas.json"
17+ parshas_url = "https://raw.githubusercontent.com/CompuGenius-Programs/Radmash /main/parshas.json"
1818parshas = requests .get (parshas_url ).json ()["parshas" ]
1919
2020
21+ class UploadThread (QThread ):
22+ finished = pyqtSignal (object ) # Signal to emit the response or exception
23+
24+ def __init__ (self , url , files , data ):
25+ super ().__init__ ()
26+ self .url = url
27+ self .files = files
28+ self .data = data
29+
30+ def run (self ):
31+ try :
32+ response = requests .post (self .url , files = self .files , data = self .data )
33+ self .finished .emit (response )
34+ except Exception as e :
35+ self .finished .emit (e )
36+
37+
2138class FileEntryWidget (QWidget ):
2239 def __init__ (self , file_path , main_window ):
2340 super ().__init__ ()
@@ -51,8 +68,8 @@ def __init__(self, file_path, main_window):
5168 self .parsha_dropdown = QComboBox ()
5269 self .parsha_dropdown .addItems (parshas )
5370 for parsha in parshas :
54- if (parsha .lower () in filename .lower () and
55- (( parsha .lower () + ' ' ) in filename .lower () or (parsha .lower () + '_' ) in filename .lower ())):
71+ if (parsha .lower () in filename .lower () and (
72+ (parsha .lower () + ' ' ) in filename .lower () or (parsha .lower () + '_' ) in filename .lower ())):
5673 self .parsha_dropdown .setCurrentText (parsha )
5774 break
5875
@@ -61,8 +78,9 @@ def __init__(self, file_path, main_window):
6178 try :
6279 gregorian_year = filename .split ('20' )[- 1 ].split ('.' )[0 ]
6380 file_creation_date = datetime .fromtimestamp (os .path .getctime (file_path ))
64- year = str (hebrew .from_gregorian (
65- int ('20' + gregorian_year ), file_creation_date .month , file_creation_date .day )[0 ])
81+ year = str (
82+ hebrew .from_gregorian (int ('20' + gregorian_year ), file_creation_date .month , file_creation_date .day )[
83+ 0 ])
6684 except ValueError :
6785 year = ''
6886 else :
@@ -96,6 +114,31 @@ def remove_self(self):
96114 self .deleteLater ()
97115
98116
117+ class ErrorDialog (QDialog ):
118+ def __init__ (self , parent = None , error_message = "Error" , detailed_text = "" ):
119+ super ().__init__ (parent )
120+ self .setWindowFlags (self .windowFlags () | Qt .WindowSystemMenuHint | Qt .WindowMaximizeButtonHint )
121+ self .setWindowTitle ("Error" )
122+ self .init_ui (error_message , detailed_text )
123+
124+ def init_ui (self , error_message , detailed_text ):
125+ layout = QVBoxLayout ()
126+
127+ error_label = QLabel (error_message )
128+ layout .addWidget (error_label )
129+
130+ detailed_text_edit = QTextEdit ()
131+ detailed_text_edit .setReadOnly (True )
132+ detailed_text_edit .setText (detailed_text )
133+ layout .addWidget (detailed_text_edit )
134+
135+ close_button = QPushButton ("Close" )
136+ close_button .clicked .connect (self .close )
137+ layout .addWidget (close_button )
138+
139+ self .setLayout (layout )
140+
141+
99142class MainWindow (QMainWindow ):
100143 def __init__ (self ):
101144 super ().__init__ ()
@@ -137,6 +180,8 @@ def __init__(self):
137180 self .submit_button = QPushButton ("Submit" )
138181 self .submit_button .clicked .connect (self .upload_files )
139182
183+ self .progress = None
184+
140185 main_layout .addLayout (server_url_layout )
141186 main_layout .addWidget (self .select_button )
142187 main_layout .addLayout (self .files_layout )
@@ -146,14 +191,28 @@ def toggle_editable(self, event):
146191 self .server_url_entry .setReadOnly (False )
147192
148193 def select_files (self ):
194+ try :
195+ with open ('config.json' ) as config_file :
196+ config = json .load (config_file )
197+ last_directory = config .get ("LAST_DIRECTORY" , "" )
198+ except (FileNotFoundError , json .decoder .JSONDecodeError ):
199+ last_directory = ""
200+
149201 file_dialog = QFileDialog ()
202+ file_dialog .setDirectory (last_directory )
150203 file_dialog .setFileMode (QFileDialog .ExistingFiles )
151204 file_dialog .setNameFilter (FILE_FILTER )
152205 if file_dialog .exec_ ():
153206 file_paths = file_dialog .selectedFiles ()
154207 for file_path in file_paths :
155208 self .add_file_entry (file_path )
156209
210+ if file_paths :
211+ selected_directory = os .path .dirname (file_paths [0 ])
212+ config ["LAST_DIRECTORY" ] = selected_directory
213+ with open ('config.json' , 'w' ) as config_file :
214+ json .dump (config , config_file )
215+
157216 def add_file_entry (self , file_path ):
158217 file_entry_widget = FileEntryWidget (file_path , self )
159218 self .files_layout .addWidget (file_entry_widget )
@@ -174,25 +233,34 @@ def upload_files(self):
174233 QMessageBox .warning (self , "Warning" , "Please enter a server URL" )
175234 return
176235
177- progress = QProgressDialog ("Uploading files..." , None , 0 , 0 , self )
178- progress .setWindowFlags (progress .windowFlags () & ~ (Qt .WindowCloseButtonHint | Qt .WindowContextHelpButtonHint ))
179- progress .setWindowTitle ("Radmash Uploader" )
180- progress .show ()
181-
182- try :
183- response = requests .post (server_url + '/upload' , files = self .get_files_payload (),
184- data = self .get_data_payload ())
185- self .handle_upload_response (response )
186- except requests .exceptions .RequestException as e :
187- QMessageBox .critical (self , "Error" , str (e ))
188- progress .close ()
236+ self .progress = QProgressDialog ("Uploading files..." , None , 0 , 0 , self )
237+ self .progress .setWindowFlags (
238+ self .progress .windowFlags () & ~ (Qt .WindowCloseButtonHint | Qt .WindowContextHelpButtonHint ))
239+ self .progress .setWindowTitle ("Radmash Uploader" )
240+ self .progress .show ()
241+
242+ self .upload_thread = UploadThread (server_url + '/upload' , self .get_files_payload (), self .get_data_payload ())
243+ self .upload_thread .finished .connect (self .handle_upload_response_thread )
244+ self .upload_thread .start ()
245+
246+ def handle_upload_response_thread (self , result ):
247+ if isinstance (result , requests .Response ) and result .status_code == 200 :
248+ if result .status_code == 200 :
249+ QMessageBox .information (self , "Success" , "Files uploaded successfully" )
250+ else :
251+ dialog = ErrorDialog (error_message = "Error uploading files" , detailed_text = result .text )
252+ dialog .exec_ ()
253+ else :
254+ dialog = ErrorDialog (error_message = "Error uploading files" , detailed_text = str (result ))
255+ dialog .exec_ ()
256+ self .progress .close ()
189257
190258 def get_files_payload (self ):
191259 files = []
192260 for file_entry in self .file_entries :
193261 file_path = file_entry .file_path
194- file_name = (file_entry .parsha_dropdown .currentText ().lower ().replace (' ' , '_' ) +
195- "_" + file_entry .year_input .text () + ".pdf" )
262+ file_name = (file_entry .parsha_dropdown .currentText ().lower ().replace (' ' ,
263+ '_' ) + "_" + file_entry .year_input .text () + ".pdf" )
196264 # file_name = file_path.split("/")[-1]
197265 with open (file_path , 'rb' ) as file :
198266 file_content = file .read ()
0 commit comments