-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgmailmanager.py
1243 lines (1032 loc) · 52.2 KB
/
gmailmanager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import re
import logging
import json
import pytz
import base64
import mimetypes
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from email.message import EmailMessage
from datetime import datetime
from email.utils import parsedate_to_datetime
from tzlocal import get_localzone
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import QPushButton, QProgressBar
from PyQt5.QtCore import Qt, QTimer, QUrl
from PyQt5.QtGui import QDesktopServices
#logging.basicConfig(level=logging.DEBUG)
# We need full access to delete emails
SCOPES = ["https://mail.google.com/"]
# SCOPES = ["https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.modify"]
def get_real_date(date_string):
if date_string == 'No Date':
return date_string
try:
# Attempt to parse the date with the specific format YYYY.MM.DD-HH.MM.SS.
parsed_date = datetime.strptime(date_string, '%Y.%m.%d-%H.%M.%S')
except ValueError:
# If the specific format fails, try with the standard format.
try:
parsed_date = parsedate_to_datetime(date_string)
except ValueError:
parsed_date = None
if parsed_date:
# Convert the date to the user's local time
local_tz = get_localzone()
local_date = parsed_date.astimezone(local_tz)
# Format the date according to a specific format
formatted_date = local_date.strftime("%Y-%m-%d %H:%M:%S %Z")
return formatted_date
else:
return 'Invalid Date'
def convert_expiry_to_local_time(expiry_utc):
local_timezone = get_localzone()
utc_timezone = pytz.utc
expiry_utc = utc_timezone.localize(expiry_utc)
expiry_local = expiry_utc.astimezone(local_timezone)
return expiry_local
def authenticate():
creds = None
token_path = "token.json"
if os.path.exists(token_path):
creds = Credentials.from_authorized_user_file(token_path, SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
try:
creds.refresh(Request())
print("Token refreshed:")
print(f"Access Token: {creds.token}")
print(f"Refresh Token: {creds.refresh_token}")
print("Expiry:", convert_expiry_to_local_time(creds.expiry))
except Exception as e:
print(f"Error refreshing token: {e}")
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
print("New authorization:")
print(f"Access Token: {creds.token}")
print(f"Refresh Token: {creds.refresh_token}")
print("Expiry:", convert_expiry_to_local_time(creds.expiry))
else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
print("New authorization:")
print(f"Access Token: {creds.token}")
print(f"Refresh Token: {creds.refresh_token}")
print("Expiry:", convert_expiry_to_local_time(creds.expiry))
with open(token_path, "w") as token:
token.write(creds.to_json())
else:
print("Existing token:")
print(f"Access Token: {creds.token}")
print(f"Refresh Token: {creds.refresh_token}")
print("Expiry:", convert_expiry_to_local_time(creds.expiry))
return creds
def load_icons():
icon_ids = {
'INBOX': 'icons/inbox.png',
'SENT': 'icons/sent.png',
'STARRED': 'icons/starred.png',
'IMPORTANT': 'icons/important.png',
'UNREAD': 'icons/unread.png',
'DRAFT': 'icons/draft.png',
'TRASH': 'icons/trash.png',
'SPAM': 'icons/spam.png',
}
icons = {}
for label, icon_path in icon_ids.items():
icon = QtGui.QIcon(icon_path)
icons[label] = icon
return icons
def list_labels(service):
try:
response = service.users().labels().list(userId='me').execute()
labels = response['labels']
label_order = {
'INBOX': 1,
'SENT': 2,
'STARRED': 3,
'IMPORTANT': 4,
'UNREAD': 5,
'DRAFT': 6,
'TRASH': 7,
'SPAM': 8,
'system': 100,
'user': 200
}
def sort_key(label):
# Get the sorting order by name and by type
order = label_order.get(label['name'].upper(), float('inf'))
type_order = label_order.get(label['type'], float('inf'))
# If the type is 'user', sort by name and sub-label depth
if label['type'] == 'user':
parts = label['name'].split('/')
# Use an iterative loop to get the depth of the sub-label
depth = len(parts)
# Create a sorting key combining name and depth
return type_order, parts[0], depth, label['name']
return type_order, order
sorted_labels = sorted(labels, key=sort_key)
label_data = []
unread_message_subjects = []
# Collect the subjects of the UNREAD messages
unread_label_id = None
for label in sorted_labels:
if label['name'].upper() == 'UNREAD':
unread_label_id = label['id']
break
if unread_label_id:
unread_messages = list_messages(service, unread_label_id)
unread_message_subjects = [get_message_subject(service, message['id']) for message in unread_messages]
for label in sorted_labels:
messages = list_messages(service, label['id'])
num_messages = len(messages)
label_name = f"{label['name']} ({num_messages})" if num_messages > 0 else label['name']
has_unread_messages = any(subject in unread_message_subjects for subject in [get_message_subject(service, message['id']) for message in messages])
unread_messages_count = sum(1 for message in messages if get_message_subject(service, message['id']) in unread_message_subjects)
if has_unread_messages:
if unread_messages_count > 0:
if not re.search(r'\bUNREAD\b', label['name'], re.IGNORECASE):
label_name += f" | Unread {unread_messages_count}"
color = QtGui.QColor(0, 0, 139) # Dark blue
font = QtGui.QFont()
font.setBold(True)
else:
color = QtGui.QColor(0, 0, 0)
font = QtGui.QFont()
font.setBold(False)
label_data.append((label_name, color, label['id'], font))
return label_data
except HttpError as error:
QtWidgets.QMessageBox.critical(None, "Error", f"An error occurred: {error}")
def list_messages(service, label_id):
try:
response = service.users().messages().list(userId='me', labelIds=[label_id]).execute()
messages = response.get('messages', [])
return messages
except HttpError as error:
QtWidgets.QMessageBox.critical(None, "Error", f"An error occurred: {error}")
return []
def get_message_subject(service, message_id):
try:
msg = service.users().messages().get(userId='me', id=message_id).execute()
headers = msg['payload']['headers']
subject = next((header['value'] for header in headers if header['name'] == 'Subject'), 'No Subject')
return subject
except HttpError as error:
QtWidgets.QMessageBox.critical(None, "Error", f"An error occurred: {error}")
return 'No Subject'
class GmailManager(QtWidgets.QMainWindow):
custom_interval = None
def __init__(self, service):
super().__init__()
self.downloaded_images = []
self.image_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'downloaded_images')
if not os.path.exists(self.image_directory):
os.makedirs(self.image_directory)
self.downloaded_pdf = []
self.pdf_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'downloaded_pdf')
if not os.path.exists(self.pdf_directory):
os.makedirs(self.pdf_directory)
self.service = service
self.check_frequency = 180000 # Initialize the default check frequency
self.timer_active = True
self.current_action = None
self.action_objects = []
self.setup_menu()
# Create and start QTimer
self.timer = QTimer(self)
self.timer.timeout.connect(self.check_for_new_and_unread_messages)
self.update_timer()
self.progress_bar = QProgressBar()
self.initUI()
self.check_for_new_and_unread_messages() # Start automatically checking for new messages
def initUI(self):
self.setWindowTitle('Gmail Manager')
self.setGeometry(100, 100, 1200, 800)
toolbar = self.addToolBar('Toolbar')
new_message = QPushButton("New Message")
toolbar.addWidget(new_message)
new_message.clicked.connect(self.new_message)
refresh_action = QPushButton('Refresh', self)
toolbar.addWidget(refresh_action)
refresh_action.clicked.connect(self.refresh_labels)
delete_action = QPushButton('Delete', self)
toolbar.addWidget(delete_action)
delete_action.clicked.connect(self.delete_message)
mark_as_read_action = QPushButton('Mark as Read', self)
toolbar.addWidget(mark_as_read_action)
mark_as_read_action.clicked.connect(self.mark_message_as_read_from_button)
mark_as_not_read_action = QPushButton('Mark as Not Read', self)
toolbar.addWidget(mark_as_not_read_action)
mark_as_not_read_action.clicked.connect(self.mark_message_as_not_read_from_button)
empty_trash_action = QPushButton('Empty Trash', self)
toolbar.addWidget(empty_trash_action)
empty_trash_action.clicked.connect(self.empty_trash)
quit_action = QPushButton('Quit', self)
toolbar.addWidget(quit_action)
quit_action.clicked.connect(self.close)
# Create an icon to indicate UNREAD messages
self.unread_message_icon = QtGui.QIcon("icons/unread_message_notif.png")
# Create the action to indicate UNREAD messages in the toolbar
self.unread_message_action = QtWidgets.QAction(self.unread_message_icon, "(No UNREAD messages)", self)
toolbar.addAction(self.unread_message_action)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
layout = QtWidgets.QVBoxLayout(central_widget)
self.progress_bar = QtWidgets.QProgressBar()
self.progress_bar.setFixedHeight(20)
self.progress_bar.setFormat(" Refreshing labels & messages... %p%")
self.progress_bar.setStyleSheet("QProgressBar {border: 2px solid grey; border-radius: 5px; background-color: #FFFFFF;} QProgressBar::chunk {background-color: #37c9e1;}")
layout.addWidget(self.progress_bar)
self.progress_bar.setVisible(False)
self.label_list = QtWidgets.QListWidget()
self.message_list = QtWidgets.QListWidget()
self.message_content = QWebEngineView()
# Enable multiple selection in the messages list
self.message_list.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.label_list.itemSelectionChanged.connect(self.on_label_selected)
self.message_list.itemSelectionChanged.connect(self.on_message_selected)
self.splitter1 = QtWidgets.QSplitter(Qt.Horizontal)
self.splitter2 = QtWidgets.QSplitter(Qt.Vertical)
self.splitter1.addWidget(self.label_list)
self.splitter1.addWidget(self.splitter2)
self.splitter2.addWidget(self.message_list)
self.splitter2.addWidget(self.message_content)
layout.addWidget(self.splitter1)
self.refresh_labels()
# Default to selecting the label "INBOX" on widget startup
inbox_item = self.find_label_item(r'^INBOX\b.*')
if inbox_item:
inbox_index = self.label_list.indexFromItem(inbox_item).row()
self.label_list.setCurrentRow(inbox_index)
@staticmethod
def get_label_id_by_name(service, label_name):
labels = service.users().labels().list(userId='me').execute()
for label in labels['labels']:
if label['name'] == label_name:
return label['id']
return None
def setup_menu(self):
menubar = self.menuBar()
self.frequency_menu = menubar.addMenu('Set Check Frequency')
self.actions = [
('1 minute', 60000),
('2 minutes', 120000),
('3 minutes', 180000),
('Custom interval', None),
('Disable timer', None)
]
self.action_objects = []
for text, frequency in self.actions:
action = QtWidgets.QAction(text, self)
if frequency is not None:
action.triggered.connect(lambda _, f=frequency, a=action: self.set_check_frequency(f, a))
else:
action.triggered.connect(lambda _, a=action: self.handle_special_action(a))
self.frequency_menu.addAction(action)
self.action_objects.append(action)
# Select the default action based on the default check_frequency
default_action_index = 2 # Index for 3 minutes
self.update_selected_action(self.frequency_menu.actions()[default_action_index])
def handle_special_action(self, action):
action_text = action.text()
if action_text == 'Custom interval':
self.set_custom_interval()
elif action_text == 'Disable timer':
self.disable_timer()
self.update_selected_action(action)
def set_check_frequency(self, frequency, action):
self.check_frequency = frequency
self.timer.stop()
self.update_timer()
print(f"Check frequency set to {frequency} milliseconds")
if not self.timer_active:
self.timer_active = True
self.update_timer()
self.update_selected_action(action)
def set_custom_interval(self):
interval, ok = QtWidgets.QInputDialog.getInt(self, 'Custom Interval', 'Enter interval in minutes:', 1, 1, 1440)
if ok:
self.check_frequency = interval * 60000
if not self.timer_active:
self.timer_active = True
self.update_timer()
print(f"Check frequency set to {self.check_frequency} milliseconds")
self.update_selected_action(self.action_objects[3]) # Custom interval is at index 3
else:
self.update_selected_action(self.current_action) # Keep the current action selected if canceled
def disable_timer(self):
self.timer_active = False
self.update_timer()
print("Timer disabled")
self.update_selected_action(self.action_objects[4]) # Disable timer is at index 4
def update_timer(self):
if self.timer_active:
self.timer.start(self.check_frequency)
else:
self.timer.stop()
def update_selected_action(self, action):
if self.current_action:
if 'Custom interval' in self.current_action.text():
self.current_action.setText('Custom interval')
else:
self.current_action.setText(self.current_action.text().replace(' [Selected]', ''))
self.current_action = action
action_text = action.text()
if 'Custom interval' in action_text:
action_text = f'Custom interval ({self.check_frequency // 60000} minutes)'
self.current_action.setText(f"{action_text} [Selected]")
def check_for_new_and_unread_messages(self):
# Logic to check UNREAD messages
# Use QTimer to schedule periodic checks
self.refresh_labels()
# Check UNREAD messages in the UNREAD label
label_name = 'UNREAD'
label_id = self.get_label_id_by_name(self.service, label_name)
if label_id:
unread_messages = list_messages(self.service, label_id)
if unread_messages:
# If UNREAD messages are found in the UNREAD label, update the notification icon
self.unread_message_action.setEnabled(True)
self.unread_message_action.setText(f"UNREAD Messages Received")
else:
# Disable the action if no UNREAD messages are detected
self.unread_message_action.setEnabled(False)
else:
print("Label '{}' not found.".format(label_name))
def refresh_labels(self, select_label=None):
# Display the progress bar before processing.
self.process_data_with_progress()
# Save the index of the previously selected row and the label name
previous_index = self.label_list.currentRow()
previous_label_name = None
selected_items = self.label_list.selectedItems()
if selected_items:
previous_label_name = selected_items[0].text() # Save the name of the previous label
#print("Label before :", previous_label_name)
#else:
#print("No label selected before refreshing")
#print("Index of the previously selected row before refreshing :", previous_index)
self.label_list.clear()
self.labels = list_labels(self.service)
# Load the icons
icons = load_icons()
for label_name, label_color, label_id, font in self.labels:
item = QtWidgets.QListWidgetItem()
item.setData(Qt.UserRole, label_id)
base_label_name = label_name.split()[0]
if base_label_name in icons:
icon = icons[base_label_name]
item.setIcon(icon)
item.setText(label_name)
if label_color:
item.setForeground(label_color)
if font:
item.setFont(font)
self.label_list.addItem(item)
# Adjust the size of splitter1 based on the maximum length of the labels
max_label_length = max([self.label_list.fontMetrics().boundingRect(label[0]).width() for label in self.labels])
self.label_list.setFixedWidth(max_label_length + 50) # Add a margin for some extra space.
self.splitter1.setSizes([max_label_length + 20, self.width() - max_label_length - 20])
# Try to retrieve the label by its name
if previous_label_name:
#print("Name of the previously active label :", previous_label_name)
escaped_previous_label_name = re.escape(previous_label_name)
escaped_previous_label_name = escaped_previous_label_name.replace('\\(', '\\(').replace('\\)', '\\)')
previous_item = self.find_label_item(escaped_previous_label_name)
if previous_item:
previous_index = self.label_list.indexFromItem(previous_item).row()
# Restore the selection of the previously active label by index
#print("Index of the restored row after refreshing :", previous_index)
self.label_list.setCurrentRow(previous_index)
# Search for and select the specified label
if select_label:
label_item = self.find_label_item(select_label)
if not label_item:
# If the specified label is not found, try to find a matching label
# with a regular pattern (e.g., "SENT (number)")
pattern = re.compile(rf"{re.escape(select_label)}(?:\s*\(\d+\))?$")
for item in self.label_list.findItems(pattern.pattern, Qt.MatchRegExp):
label_item = item
break
if label_item:
label_index = self.label_list.indexFromItem(label_item).row()
self.label_list.setCurrentRow(label_index)
else:
print(f"Le libellé '{select_label}' n'a pas été trouvé.")
# # Debug - Get the name of the selected label after refreshing
# selected_items = self.label_list.selectedItems()
# if selected_items:
# current_label_name = selected_items[0].text()
# print("Label after :", current_label_name)
# else:
# print("No label selected after refreshing")
# # End Debug
# Check if there are any messages left in the list of UNREAD
# Search for the first label starting with "UNREAD" in the list of labels in the user interface
unread_label_id = None
for index in range(self.label_list.count()):
label_item = self.label_list.item(index)
label_name = label_item.text()
if re.match(r'^UNREAD', label_name, re.IGNORECASE):
unread_label_id = label_item.data(Qt.UserRole)
break
if unread_label_id:
unread_messages = list_messages(self.service, unread_label_id)
if len(unread_messages) > 0:
# If UNREAD messages are found in the UNREAD label, update the notification icon
self.unread_message_action.setEnabled(True)
self.unread_message_action.setText(f"UNREAD Messages Received")
def show_progress_bar(self):
self.progress_bar.setVisible(True)
def hide_progress_bar(self):
self.progress_bar.setVisible(False)
def process_data_with_progress(self):
self.show_progress_bar()
total_steps = 100
for i in range(total_steps):
progress_value = (i + 1) * 100 / total_steps
self.progress_bar.setValue(int(progress_value))
QtCore.QThread.msleep(100)
self.hide_progress_bar()
def find_label_item(self, label_name):
for item in self.label_list.findItems(label_name, Qt.MatchRegExp):
return item
return None
def clear_web_view(self):
self.message_content.setUrl(QtCore.QUrl("about:blank"))
def on_label_selected(self):
self.message_list.clear()
selected_items = self.label_list.selectedItems()
if not selected_items:
return
label_id = selected_items[0].data(Qt.UserRole)
messages = list_messages(self.service, label_id)
# Search for the first label starting with "UNREAD" in the list of labels in the user interface
unread_label_id = None
for index in range(self.label_list.count()):
label_item = self.label_list.item(index)
label_name = label_item.text()
if re.match(r'^UNREAD', label_name, re.IGNORECASE):
unread_label_id = label_item.data(Qt.UserRole)
break
if unread_label_id:
unread_messages = list_messages(self.service, unread_label_id)
unread_message_subjects = [get_message_subject(self.service, message['id']) for message in unread_messages]
else:
unread_message_subjects = []
for message in messages:
subject = get_message_subject(self.service, message['id'])
item = QtWidgets.QListWidgetItem(subject)
item.setData(Qt.UserRole, message['id'])
# Check if the subject of the message is in the list of subjects of unread messages
if subject in unread_message_subjects:
item.setForeground(QtGui.QColor(0, 0, 139)) # Dark blue for unread messages
font = item.font() # Get the current font of the item.
font.setBold(True)
item.setFont(font) # Apply the modified font to the item.
self.message_list.addItem(item)
# Clear the message content if there are no messages for the selected label
if not messages:
self.clear_web_view()
# Select the first item in the list of messages
if self.message_list.count() > 0:
self.message_list.setCurrentRow(0)
def on_message_selected(self):
selected_items = self.message_list.selectedItems()
if not selected_items:
return
# Delete the previously downloaded PNG files and PDF files .
self.delete_downloaded_images()
self.delete_downloaded_pdf()
# Clear the list of downloaded PNG files and PDF files.
self.downloaded_images = []
self.downloaded_pdf = []
message_id = selected_items[0].data(Qt.UserRole)
message = self.service.users().messages().get(userId='me', id=message_id, format="full").execute()
#print(json.dumps(self.service.users().messages().get(userId='me', id=message_id, format="full").execute(), indent=2))
payload = message.get('payload', {})
parts = payload.get('parts', [])
headers = {header['name']: header['value'] for header in payload.get('headers', [])}
subject = headers.get('Subject', 'No Subject')
date = headers.get('Date', 'No Date')
from_email = headers.get('From', 'No Sender')
to_emails = headers.get('To', 'No Recipient')
# Use regular expressions to clean up email addresses
from_email_cleaned = re.findall(r'<([^>]+)>', from_email)
if from_email_cleaned:
from_email = from_email_cleaned[0].strip('"')
else:
from_email = from_email.strip('"')
to_emails_cleaned = re.findall(r'<([^>]+)>', to_emails)
if to_emails_cleaned:
to_emails = ', '.join(to_emails_cleaned)
else:
to_emails = to_emails # In case there are no angle brackets
real_date = get_real_date(date)
date_str = f"<strong>Date:</strong> {real_date}"
from_email_str = f"<strong>From:</strong> {from_email}"
to_emails_str = f"<strong>To:</strong> {to_emails}"
if 'text/html' in [part.get('mimeType') for part in parts]:
attachments = GmailManager.get_attachments(self, message_id)
cid_to_path = {} # Dictionary to map CIDs to local paths
for attachment in attachments:
saved_path = self.save_attachment(self.image_directory, attachment)
if saved_path:
cid_to_path[attachment['filename']] = saved_path
self.downloaded_images.append(saved_path) # Add the file path to the list
#print(f"Mapping cid '{attachment['filename']}' to local path '{saved_path}'")
else:
print(f"Failed to save attachment '{attachment['filename']}'.")
content = self.extract_html([payload])
script_dir = os.path.dirname(os.path.abspath(__file__))
for cid, path in cid_to_path.items():
#print(f"Replacing src for cid '{cid}' with local path '{path}'")
# Add the prefix file:// and the absolute path of the script's directory to the image path.
absolute_path = f"file://{path}"
content = re.sub(r'src=["\']cid:{}["\']'.format(re.escape(cid)), f'src="{absolute_path}"', content)
if self.downloaded_pdf:
if len(self.downloaded_pdf) > 1:
content += "<p><strong>PDF Attachments:</strong></p>"
for filename in self.downloaded_pdf:
file_path = os.path.join(self.pdf_directory, filename)
file_pdf = f"file://{file_path}"
content += f"<p>• <a href=\"{file_pdf}\">{filename}</a></p>"
else:
filename = self.downloaded_pdf[0]
file_path = os.path.join(self.pdf_directory, filename)
file_pdf = f"file://{file_path}"
content += f"<p><strong>PDF Attachment:</strong> <a href=\"{file_pdf}\">{filename}</a></p>"
# logic to detect links to PDF files and open them in the browser.
self.message_content.page().profile().downloadRequested.connect(self.on_pdf_requested)
#print(content)
# Construct full HTML content
full_content = f"""
<html>
<body>
<h2 style='margin-top: 10px;'>{subject}</h2>
<div>{date_str}</div>
<div>{from_email_str}</div>
<div>{to_emails_str}</div>
<hr>
{content}
</body>
</html>
"""
#print(full_content)
base_url = QtCore.QUrl.fromLocalFile(script_dir + '/')
self.message_content.setHtml(full_content, base_url)
else:
attachments = GmailManager.get_attachments(self, message_id)
cid_to_path = {} # Dictionary to map CIDs to local paths
for attachment in attachments:
saved_path = self.save_attachment(self.image_directory, attachment)
if saved_path:
cid_to_path[attachment['filename']] = saved_path
self.downloaded_images.append(saved_path) # Add the file path to the list
#print(f"Mapping cid '{attachment['filename']}' to local path '{saved_path}'")
else:
print(f"Failed to save attachment '{attachment['filename']}'.")
content = self.extract_data([payload])
script_dir = os.path.dirname(os.path.abspath(__file__))
for cid, path in cid_to_path.items():
#print(f"Replacing src for cid '{cid}' with local path '{path}'")
# Add the prefix file:// and the absolute path of the script's directory to the image path.
absolute_path = f"file://{path}"
content = re.sub(r'src=["\']cid:{}["\']'.format(re.escape(cid)), f'src="{absolute_path}"', content)
if self.downloaded_pdf:
if len(self.downloaded_pdf) > 1:
content += "<p><strong>PDF Attachments:</strong></p>"
for filename in self.downloaded_pdf:
file_path = os.path.join(self.pdf_directory, filename)
file_pdf = f"file://{file_path}"
content += f"<p>• <a href=\"{file_pdf}\">{filename}</a></p>"
else:
filename = self.downloaded_pdf[0]
file_path = os.path.join(self.pdf_directory, filename)
file_pdf = f"file://{file_path}"
content += f"<p><strong>PDF Attachment:</strong> <a href=\"{file_pdf}\">{filename}</a></p>"
# logic to detect links to PDF files and open them in the browser.
self.message_content.page().profile().downloadRequested.connect(self.on_pdf_requested)
#print(content)
# Construct full HTML content
full_content = f"""
<html>
<body>
<h2 style='margin-top: 10px;'>{subject}</h2>
<div>{date_str}</div>
<div>{from_email_str}</div>
<div>{to_emails_str}</div>
<hr>
{content}
</body>
</html>
"""
#print(full_content)
base_url = QtCore.QUrl.fromLocalFile(script_dir + '/')
self.message_content.setHtml(full_content, base_url)
def mark_message_as_read_from_button(self):
# Retrieve IDs of selected messages in the list of messages
selected_items = self.message_list.selectedItems()
if not selected_items:
return
message_ids = [item.data(Qt.UserRole) for item in selected_items]
#print("Selected message IDs:", message_ids)
# Call the method to mark the messages as read
self.mark_messages_as_read(message_ids)
def mark_messages_as_read(self, message_ids):
try:
for message_id in message_ids:
modify_request = {'removeLabelIds': ['UNREAD']}
self.service.users().messages().modify(userId='me', id=message_id, body=modify_request).execute()
#print(f"Message with ID {message_id} marked as read successfully.")
self.check_for_new_and_unread_messages()
# Check if there are any messages left in the list of UNREAD
# Search for the first label starting with "UNREAD" in the list of labels in the user interface
unread_label_id = None
for index in range(self.label_list.count()):
label_item = self.label_list.item(index)
label_name = label_item.text()
if re.match(r'^UNREAD', label_name, re.IGNORECASE):
unread_label_id = label_item.data(Qt.UserRole)
break
if unread_label_id:
unread_messages = list_messages(self.service, unread_label_id)
if len(unread_messages) == 0:
# Disable the action if no UNREAD messages are detected
self.unread_message_action.setEnabled(False)
except HttpError as error:
QtWidgets.QMessageBox.critical(None, "Error", f"An error occurred while marking the messages as read: {error}")
def mark_message_as_not_read_from_button(self):
# Retrieve IDs of selected messages in the list of messages
selected_items = self.message_list.selectedItems()
if not selected_items:
return
message_ids = [item.data(Qt.UserRole) for item in selected_items]
#print("Selected message IDs:", message_ids) # Print selected message IDs for debugging
# Call the method to mark the messages as unread
self.mark_messages_as_not_read(message_ids)
def mark_messages_as_not_read(self, message_ids):
try:
for message_id in message_ids:
modify_request = {'addLabelIds': ['UNREAD']}
self.service.users().messages().modify(userId='me', id=message_id, body=modify_request).execute()
#print(f"Message with ID {message_id} marked as not read successfully.")
self.check_for_new_and_unread_messages()
except HttpError as error:
QtWidgets.QMessageBox.critical(None, "Error", f"An error occurred while marking the messages as not read: {error}")
def delete_downloaded_images(self):
#print("Deleting downloaded images...")
for file_path in self.downloaded_images:
try:
if os.path.exists(file_path):
os.remove(file_path)
#print(f"Deleted file '{file_path}'")
except Exception as e:
print(f"Failed to delete file '{file_path}': {e}")
def delete_downloaded_pdf(self):
#print("Deleting downloaded PDFs...")
for file_name in self.downloaded_pdf:
file_path = os.path.join(self.pdf_directory, file_name) # Construct the full file path
try:
if os.path.exists(file_path):
os.remove(file_path)
#print(f"Deleted file '{file_path}'")
except Exception as e:
print(f"Failed to delete file '{file_path}': {e}")
@staticmethod
def get_content_id(headers):
for header in headers:
if header['name'].lower() == 'content-id':
return header['value'].strip('<>')
return None
@staticmethod
def get_attachments(self, message_id):
try:
#print("Fetching message attachments...")
message = self.service.users().messages().get(userId='me', id=message_id).execute()
attachments = []
if 'parts' in message['payload']:
#print("Processing message parts for attachments...")
for part in message['payload']['parts']:
if 'body' in part and 'attachmentId' in part['body']:
#print(f"Downloading attachment: {part['filename']}")
attachment_data = self.service.users().messages().attachments().get(
userId='me', messageId=message_id, id=part['body']['attachmentId']
).execute()
if 'data' in attachment_data:
content_id = self.get_content_id(part['headers'])
if content_id:
attachments.append({'filename': content_id, 'data': attachment_data['data']})
#print(f"Attachment '{content_id}' downloaded.")
else:
print("No Content-ID found.")
else:
print("No attachment data found.")
else:
print("No parts found in message.")
return attachments
except Exception as e:
print('An error occurred:', e)
return []
@staticmethod
def save_attachment(directory, attachment_data):
try:
filename = attachment_data['filename']
filename = re.sub(r'[\\/*?:"<>|]', "", filename) + ".png"
if directory and not os.path.exists(directory):
os.makedirs(directory)
filepath = os.path.join(directory, filename)
with open(filepath, 'wb') as f:
f.write(base64.urlsafe_b64decode(attachment_data['data']))
#print(f"Attachment '{filename}' saved to '{directory}'.")
return filepath
except Exception as e:
print("An error occurred while saving attachment:", e)
return None
@staticmethod
def open_pdf_in_browser(pdf_path):
QDesktopServices.openUrl(QUrl(pdf_path))
def on_pdf_requested(self, download):
url = download.url().toString()
if url.lower().endswith('.pdf'):
self.open_pdf_in_browser(url)
def extract_data(self, parts):
result = ""
max_size = 0
pdf_ids_downloaded = set()
for part in parts:
if 'body' in part:
body_size = part['body']['size']
if body_size > max_size:
max_size = body_size
if 'data' in part['body']:
data = part['body']['data']
result = GmailManager.decode_base64(data).decode("utf-8")
elif 'parts' in part:
sub_data = self.extract_data(part['parts'])
sub_size = len(sub_data)
if sub_size > max_size:
result = sub_data
max_size = sub_size
# Check if the part contains a PDF; if so, download it
if part.get('mimeType') == 'application/pdf' and part.get('filename'):
part_id = part.get('partId')
if part_id not in pdf_ids_downloaded:
filename = part['filename']
selected_items = self.message_list.selectedItems()
if not selected_items:
return
message_id = selected_items[0].data(Qt.UserRole)
attachment = self.service.users().messages().attachments().get(userId='me', messageId=message_id, id=part['body']['attachmentId']).execute()
file_data = base64.urlsafe_b64decode(attachment['data'])
pdf_path = os.path.join(self.pdf_directory, filename)
with open(pdf_path, 'wb') as f:
f.write(file_data)
pdf_ids_downloaded.add(part_id)
self.downloaded_pdf.append(filename)
#print(f"Downloaded PDF part_id: {part_id}")
#print(f"PDF part IDs downloaded: {pdf_ids_downloaded}")
return result
def find_matching_part(self, parts, mime_type, max_depth, current_depth=0):
matching_part = None
max_size = 0
pdf_ids_downloaded = set()
for part in parts:
if 'mimeType' in part and part['mimeType'] == mime_type:
if 'body' in part and part['body'] and 'data' in part['body']:
if part['body']['size'] > max_size:
matching_part = part
max_size = part['body']['size']
if 'parts' in part and current_depth < max_depth:
matched_part = self.find_matching_part(part['parts'], mime_type, max_depth, current_depth=current_depth+1)
if matched_part:
if matched_part['body']['size'] > max_size:
matching_part = matched_part
max_size = matched_part['body']['size']
# Check if the part contains a PDF; if so, download it
if part.get('mimeType') == 'application/pdf' and part.get('filename'):
part_id = part.get('partId')
if part_id not in pdf_ids_downloaded:
filename = part['filename']
selected_items = self.message_list.selectedItems()
if not selected_items:
return
message_id = selected_items[0].data(Qt.UserRole)
attachment = self.service.users().messages().attachments().get(userId='me', messageId=message_id, id=part['body']['attachmentId']).execute()
file_data = base64.urlsafe_b64decode(attachment['data'])
pdf_path = os.path.join(self.pdf_directory, filename)
with open(pdf_path, 'wb') as f:
f.write(file_data)
pdf_ids_downloaded.add(part_id)
self.downloaded_pdf.append(filename)
#print(f"Downloaded PDF part_id: {part_id}")
#print(f"PDF part IDs downloaded: {pdf_ids_downloaded}")
return matching_part
def extract_html(self, parts, max_depth=3):
matching_part = self.find_matching_part(parts, 'text/html', max_depth)
if not matching_part:
return ""
if 'body' in matching_part and matching_part['body']:
if 'data' in matching_part['body']:
data = matching_part['body']['data']
# Decode the data in UTF-8
html_data = GmailManager.decode_base64(data).decode('utf-8')