-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgui_viewer_v2.py
More file actions
4033 lines (3402 loc) · 158 KB
/
gui_viewer_v2.py
File metadata and controls
4033 lines (3402 loc) · 158 KB
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
#!/usr/bin/env python3
"""
Exchange EDB Content Viewer v2
GUI application with folder tree navigation
"""
import sys
import os
import struct
import re
import time
from datetime import datetime, timezone
from pathlib import Path
from collections import defaultdict
class Profiler:
"""Simple profiler that tracks timing of named operations."""
def __init__(self):
self._starts = {}
self._stats = {} # name -> {'count': int, 'total': float, 'last': float}
self._log = [] # List of (timestamp, name, elapsed_ms)
def start(self, name):
self._starts[name] = time.perf_counter()
def stop(self, name):
if name not in self._starts:
return
elapsed = time.perf_counter() - self._starts.pop(name)
if name not in self._stats:
self._stats[name] = {'count': 0, 'total': 0.0, 'last': 0.0}
self._stats[name]['count'] += 1
self._stats[name]['total'] += elapsed
self._stats[name]['last'] = elapsed
self._log.append((time.time(), name, elapsed * 1000))
def get_stats(self):
"""Return list of (name, count, total_s, avg_ms, last_ms) sorted by total desc."""
result = []
for name, s in self._stats.items():
avg_ms = (s['total'] / s['count'] * 1000) if s['count'] > 0 else 0
result.append((name, s['count'], s['total'], avg_ms, s['last'] * 1000))
result.sort(key=lambda x: x[2], reverse=True)
return result
def get_log(self):
"""Return chronological log of all operations."""
return list(self._log)
def export_csv(self, filepath):
"""Export stats and log to CSV file."""
import csv
with open(filepath, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(["=== PROFILER STATS ==="])
writer.writerow(["Operation", "Calls", "Total (s)", "Avg (ms)", "Last (ms)"])
for name, count, total, avg_ms, last_ms in self.get_stats():
writer.writerow([name, count, round(total, 3), round(avg_ms, 1), round(last_ms, 1)])
writer.writerow([])
writer.writerow(["=== OPERATION LOG ==="])
writer.writerow(["Timestamp", "Operation", "Duration (ms)"])
for ts, name, elapsed_ms in self._log:
dt = datetime.fromtimestamp(ts).strftime("%H:%M:%S.%f")[:-3]
writer.writerow([dt, name, round(elapsed_ms, 2)])
def clear(self):
self._starts.clear()
self._stats.clear()
self._log.clear()
profiler = Profiler()
# Load version from VERSION file
def get_version():
version_file = Path(__file__).parent / "VERSION"
if version_file.exists():
return version_file.read_text().strip()
return "1.000"
VERSION = get_version()
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QFileDialog, QTreeWidget, QTreeWidgetItem,
QSplitter, QTextEdit, QComboBox, QGroupBox, QLineEdit,
QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView,
QStatusBar, QMessageBox, QProgressBar, QMenu, QListWidget,
QListWidgetItem, QCheckBox, QTextBrowser, QDialog, QFormLayout,
QDateEdit, QDialogButtonBox, QGridLayout, QRadioButton
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QUrl, QDate
from PyQt6.QtGui import QFont, QAction, QTextOption, QColor, QPalette, QIcon
# Using QTextBrowser for lightweight HTML rendering (no WebEngine dependency)
# Try to import LZXPRESS decompressor
try:
from core.lzxpress import decompress_exchange_body, extract_text_from_html, extract_body_from_property_blob, get_body_preview, get_html_content
HAS_LZXPRESS = True
except ImportError:
HAS_LZXPRESS = False
# Check if dissect.esedb is available for proper decompression
try:
from dissect.esedb.compression import decompress as dissect_decompress
HAS_DISSECT = True
except ImportError:
HAS_DISSECT = False
# Try to import folder mapping
try:
from core.folder_mapping import get_folder_name as get_mapped_folder_name, SPECIAL_FOLDER_MAP
HAS_FOLDER_MAPPING = True
except ImportError:
HAS_FOLDER_MAPPING = False
SPECIAL_FOLDER_MAP = {}
# Import stable email extraction module
try:
from exporters.email_message import EmailMessage, EmailExtractor, EmailAttachment
HAS_EMAIL_MODULE = True
except ImportError:
HAS_EMAIL_MODULE = False
# Import calendar extraction module
try:
from exporters.calendar_message import CalendarEvent, CalendarExtractor, export_calendar_to_ics, CALENDAR_MESSAGE_CLASSES
HAS_CALENDAR_MODULE = True
except ImportError:
HAS_CALENDAR_MODULE = False
CALENDAR_MESSAGE_CLASSES = []
# Import PST export module
try:
from eml2pst.pst_file import PSTFileBuilder
HAS_PST_MODULE = True
except ImportError:
HAS_PST_MODULE = False
# Supported encodings for text extraction
# ASCII/UTF-8 encodings (for standard text)
ASCII_ENCODINGS = ['ascii', 'utf-8']
# Extended encodings (for non-ASCII characters like Cyrillic)
EXTENDED_ENCODINGS = [
'windows-1251', # Cyrillic (Russian, Bulgarian, Serbian)
'koi8-r', # Cyrillic (Russian)
'koi8-u', # Cyrillic (Ukrainian)
'iso-8859-5', # Cyrillic
'windows-1252', # Western European
'iso-8859-1', # Latin-1
'cp866', # DOS Cyrillic
]
def try_decode(data, encodings=None):
"""Try to decode bytes using multiple encodings with smart detection."""
if not data:
return None
# Check if data is pure ASCII (all bytes < 128)
has_high_bytes = any(b >= 128 for b in data)
if not has_high_bytes:
# Pure ASCII - decode as ASCII or UTF-8
try:
return data.decode('ascii').rstrip('\x00')
except UnicodeDecodeError:
try:
return data.decode('utf-8').rstrip('\x00')
except UnicodeDecodeError:
pass
# Has high bytes - try UTF-8 first (handles multi-byte UTF-8)
try:
text = data.decode('utf-8')
if text:
return text.rstrip('\x00')
except UnicodeDecodeError:
pass
# Try extended encodings (Cyrillic, etc.) only if there are high bytes
if has_high_bytes:
if encodings is None:
encodings = EXTENDED_ENCODINGS
for encoding in encodings:
try:
text = data.decode(encoding)
# Check if result is mostly printable
printable_count = sum(1 for c in text if c.isprintable() or c.isspace())
if printable_count >= len(text) * 0.8:
return text.rstrip('\x00')
except (UnicodeDecodeError, LookupError):
continue
# Final fallback - decode with replacement
try:
return data.decode('utf-8', errors='replace').rstrip('\x00')
except:
return data.decode('latin-1', errors='replace').rstrip('\x00')
def get_column_map(table):
"""Get mapping of column names to indices."""
col_map = {}
for j in range(table.get_number_of_columns()):
col = table.get_column(j)
if col:
col_map[col.name] = j
return col_map
def get_int_value(record, col_idx):
"""Get integer value from record."""
if col_idx < 0:
return None
try:
val = record.get_value_data(col_idx)
if not val:
return None
if len(val) == 4:
return struct.unpack('<I', val)[0]
elif len(val) == 8:
return struct.unpack('<Q', val)[0]
elif len(val) == 2:
return struct.unpack('<H', val)[0]
except:
pass
return None
def get_folder_id(record, col_idx):
"""Get folder ID as hex string (full ID for proper matching)."""
if col_idx < 0:
return None
try:
val = record.get_value_data(col_idx)
if not val:
return None
# Return full hex for matching with Folder table
return val.hex()
except:
pass
return None
def extract_attachment_filename(blob):
"""Extract attachment filename from PropertyBlob."""
if not blob:
return ""
extensions = [b'.txt', b'.xml', b'.doc', b'.docx', b'.pdf', b'.jpg',
b'.png', b'.xlsx', b'.xls', b'.zip', b'.eml', b'.msg',
b'.html', b'.htm', b'.csv']
for ext in extensions:
idx = blob.lower().find(ext)
if idx >= 0:
start = idx
while start > 0 and 0x20 <= blob[start - 1] < 0x7f:
start -= 1
filename = blob[start:idx + len(ext)]
if len(filename) > len(ext):
return filename.decode('ascii', errors='ignore')
return ""
def extract_attachment_content_type(blob):
"""Extract content type from attachment PropertyBlob."""
if not blob:
return "application/octet-stream"
mime_patterns = [
(b'text/plain', 'text/plain'),
(b'text/html', 'text/html'),
(b'text/xml', 'text/xml'),
(b'application/pdf', 'application/pdf'),
(b'application/xml', 'application/xml'),
(b'image/jpeg', 'image/jpeg'),
(b'image/png', 'image/png'),
]
for pattern, mime in mime_patterns:
if pattern in blob:
return mime
return "application/octet-stream"
def is_encrypted_or_binary(data):
"""Check if data looks like encrypted/binary content (not readable text)."""
if not data or len(data) < 2:
return False
# Count control characters and high-bit bytes
control_count = sum(1 for b in data if b < 32 and b not in (9, 10, 13))
high_byte_count = sum(1 for b in data if b >= 128)
printable_count = sum(1 for b in data if 32 <= b < 127)
total = len(data)
# If more than 30% control chars or mixed high-bytes with control chars, likely encrypted
if control_count > total * 0.3:
return True
# If has control chars at start (like 0x12) and high bytes, likely encrypted
if data[0] < 32 and high_byte_count > 0:
return True
# If less than 50% printable ASCII and not valid UTF-16, likely encrypted
if printable_count < total * 0.5:
# Check if it could be UTF-16
has_null_pattern = len(data) >= 4 and data[1] == 0 and data[3] == 0
if not has_null_pattern:
return True
return False
def get_string_value(record, col_idx):
"""Get string value from record with multi-encoding support."""
if col_idx < 0:
return ""
try:
val = record.get_value_data(col_idx)
if not val:
return ""
# Check if data is encrypted/binary
if is_encrypted_or_binary(val):
return "" # Return empty for encrypted fields
# Check for UTF-16-LE BOM or pattern (null bytes between ASCII chars)
is_likely_utf16 = False
if len(val) >= 2:
# Check for BOM
if val[:2] == b'\xff\xfe':
is_likely_utf16 = True
# Check for null-byte pattern typical of UTF-16-LE ASCII
elif len(val) >= 4 and val[1] == 0 and val[3] == 0 and val[0] != 0 and val[2] != 0:
is_likely_utf16 = True
if is_likely_utf16:
try:
text = val.decode('utf-16-le').rstrip('\x00')
if text and all(c.isprintable() or c.isspace() for c in text):
return text
except:
pass
# Try standard decoding
result = try_decode(val)
return result if result else ""
except:
pass
return ""
def get_bytes_value(record, col_idx):
"""Get raw bytes from record."""
if col_idx < 0:
return None
try:
return record.get_value_data(col_idx)
except:
return None
def get_filetime_value(record, col_idx):
"""Get datetime from Windows FILETIME."""
if col_idx < 0:
return None
try:
val = record.get_value_data(col_idx)
if not val or len(val) != 8:
return None
filetime = struct.unpack('<Q', val)[0]
if filetime == 0:
return None
unix_time = (filetime - 116444736000000000) / 10000000
return datetime.fromtimestamp(unix_time, tz=timezone.utc)
except:
return None
class LoadWorker(QThread):
"""Background worker for loading database."""
progress = pyqtSignal(str)
finished = pyqtSignal(object)
error = pyqtSignal(str)
def __init__(self, edb_path):
super().__init__()
# Normalize path for cross-platform compatibility
self.edb_path = os.path.normpath(os.path.abspath(edb_path))
def run(self):
try:
import pyesedb
profiler.start("DB Open")
self.progress.emit("Opening database (this may take 20-30 seconds)...")
db = pyesedb.file()
db.open(self.edb_path)
self.progress.emit("Database opened, scanning tables...")
self.progress.emit("Loading tables...")
result = {
'db': db,
'tables': {},
'mailboxes': []
}
for i in range(db.get_number_of_tables()):
table = db.get_table(i)
if table:
result['tables'][table.name] = table
# Detect mailbox tables
if table.name.startswith("Message_"):
try:
num = int(table.name.split('_')[1])
result['mailboxes'].append({
'number': num,
'message_count': table.get_number_of_records(),
'owner_email': None # Will be populated later
})
except:
pass
# Sort mailboxes
result['mailboxes'].sort(key=lambda x: x['number'])
result['file_size'] = os.path.getsize(self.edb_path)
result['total_messages'] = sum(mb['message_count'] for mb in result['mailboxes'])
# Try to extract mailbox owner email from Sent Items
for mb in result['mailboxes']:
mb['owner_email'] = self._get_mailbox_owner(result['tables'], mb['number'])
profiler.stop("DB Open")
self.finished.emit(result)
except Exception as e:
profiler.stop("DB Open")
self.error.emit(str(e))
def _get_mailbox_owner(self, tables, mailbox_num):
"""Get mailbox owner from Mailbox table."""
profiler.start("Get Mailbox Owner")
try:
mailbox_table = tables.get('Mailbox')
if not mailbox_table:
return None
col_map = get_column_map(mailbox_table)
mb_num_idx = col_map.get('MailboxNumber', -1)
owner_name_idx = col_map.get('MailboxOwnerDisplayName', -1)
display_name_idx = col_map.get('DisplayName', -1)
for rec_idx in range(mailbox_table.get_number_of_records()):
try:
record = mailbox_table.get_record(rec_idx)
if not record:
continue
# Check if this is the requested mailbox
mb_num_data = record.get_value_data(mb_num_idx)
if mb_num_data:
import struct
mb_num = struct.unpack('<I', mb_num_data)[0]
if mb_num != mailbox_num:
continue
# Try to get owner name
for col_idx in [owner_name_idx, display_name_idx]:
if col_idx < 0:
continue
val = record.get_value_data(col_idx)
if val and HAS_DISSECT:
try:
decompressed = dissect_decompress(val)
for enc in ['utf-16-le', 'utf-8']:
try:
text = decompressed.decode(enc).rstrip('\x00')
if text:
profiler.stop("Get Mailbox Owner")
return text
except:
pass
except:
pass
except:
pass
profiler.stop("Get Mailbox Owner")
return None
except:
profiler.stop("Get Mailbox Owner")
return None
class ProfilerDialog(QDialog):
"""Floating profiler window showing operation timing stats."""
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Profiler")
self.setMinimumSize(500, 300)
self.resize(600, 400)
self.setWindowFlags(self.windowFlags() | Qt.WindowType.Tool)
layout = QVBoxLayout(self)
layout.setContentsMargins(4, 4, 4, 4)
self.table = QTableWidget()
self.table.setColumnCount(5)
self.table.setHorizontalHeaderLabels(["Operation", "Calls", "Total (s)", "Avg (ms)", "Last (ms)"])
self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
self.table.setSortingEnabled(True)
layout.addWidget(self.table)
btn_layout = QHBoxLayout()
clear_btn = QPushButton("Clear")
clear_btn.clicked.connect(self._on_clear)
btn_layout.addWidget(clear_btn)
export_btn = QPushButton("Export CSV")
export_btn.clicked.connect(self._on_export_csv)
btn_layout.addWidget(export_btn)
btn_layout.addStretch()
layout.addLayout(btn_layout)
from PyQt6.QtCore import QTimer
self.timer = QTimer(self)
self.timer.timeout.connect(self.refresh)
self.timer.start(2000)
def refresh(self):
stats = profiler.get_stats()
self.table.setSortingEnabled(False)
self.table.setRowCount(len(stats))
for row, (name, count, total, avg_ms, last_ms) in enumerate(stats):
self.table.setItem(row, 0, QTableWidgetItem(name))
item_count = QTableWidgetItem()
item_count.setData(Qt.ItemDataRole.DisplayRole, count)
self.table.setItem(row, 1, item_count)
item_total = QTableWidgetItem()
item_total.setData(Qt.ItemDataRole.DisplayRole, round(total, 3))
self.table.setItem(row, 2, item_total)
item_avg = QTableWidgetItem()
item_avg.setData(Qt.ItemDataRole.DisplayRole, round(avg_ms, 1))
self.table.setItem(row, 3, item_avg)
item_last = QTableWidgetItem()
item_last.setData(Qt.ItemDataRole.DisplayRole, round(last_ms, 1))
self.table.setItem(row, 4, item_last)
self.table.setSortingEnabled(True)
def _on_clear(self):
profiler.clear()
self.refresh()
def _on_export_csv(self):
path, _ = QFileDialog.getSaveFileName(
self, "Export Profiler Data", "profiler_stats.csv",
"CSV Files (*.csv);;All Files (*.*)"
)
if path:
profiler.export_csv(path)
QMessageBox.information(self, "Export", f"Profiler data exported to:\n{path}")
def showEvent(self, event):
super().showEvent(event)
self.refresh()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(f"Exchange EDB Exporter v{VERSION}")
icon_path = Path(__file__).parent / "assets" / "icon.png"
if icon_path.exists():
self.setWindowIcon(QIcon(str(icon_path)))
self.setMinimumSize(1000, 500)
self.resize(1400, 700) # Default size, can be resized smaller
self.db = None
self.tables = {}
self.current_mailbox = None
self.folders = {}
self.messages_by_folder = defaultdict(list)
self.current_record_idx = None
self.current_attachments = [] # List of (filename, content_type, data)
self.current_email_message = None # EmailMessage object for export
self.current_msg_type = 'email' # 'email', 'calendar', or 'contact'
self.current_cal_event = None
self.current_contact = None
self.email_extractor = None # EmailExtractor instance
self.calendar_extractor = None # CalendarExtractor instance
self.folder_messages_cache = {} # Cache: folder_id -> list of message data
self._cached_msg_col_map = None
self._cached_msg_columns = None
self._cached_attach_col_map = None
self._cached_inid_to_record = None
self._cached_msgdocid_to_attach = None
self.debug_mode = False
self.profiler_dialog = None
self._setup_ui()
self._setup_menu()
def _setup_menu(self):
menubar = self.menuBar()
# File menu
file_menu = menubar.addMenu("&File")
open_action = QAction("&Open Database...", self)
open_action.setShortcut("Ctrl+O")
open_action.triggered.connect(self._on_browse)
file_menu.addAction(open_action)
file_menu.addSeparator()
export_action = QAction("&Export Mailbox...", self)
export_action.setShortcut("Ctrl+E")
export_action.triggered.connect(self._on_export)
file_menu.addAction(export_action)
file_menu.addSeparator()
exit_action = QAction("E&xit", self)
exit_action.setShortcut("Ctrl+Q")
exit_action.triggered.connect(self.close)
file_menu.addAction(exit_action)
# View menu
view_menu = menubar.addMenu("&View")
refresh_action = QAction("&Refresh", self)
refresh_action.setShortcut("F5")
refresh_action.triggered.connect(self._on_refresh)
view_menu.addAction(refresh_action)
view_menu.addSeparator()
# Column visibility toggles
self.show_from_email_action = QAction("Show From Email Column", self)
self.show_from_email_action.setCheckable(True)
self.show_from_email_action.setChecked(False)
self.show_from_email_action.triggered.connect(self._toggle_from_email_column)
view_menu.addAction(self.show_from_email_action)
self.show_to_email_action = QAction("Show To Email Column", self)
self.show_to_email_action.setCheckable(True)
self.show_to_email_action.setChecked(False)
self.show_to_email_action.triggered.connect(self._toggle_to_email_column)
view_menu.addAction(self.show_to_email_action)
def _setup_ui(self):
central = QWidget()
self.setCentralWidget(central)
layout = QVBoxLayout(central)
# File and mailbox selection (two rows)
top_widget = QWidget()
top_widget.setFixedHeight(54)
top_vlayout = QVBoxLayout(top_widget)
top_vlayout.setContentsMargins(2, 0, 2, 0)
top_vlayout.setSpacing(2)
# Row 1: DB path, Load, Hidden, About
row1_layout = QHBoxLayout()
row1_layout.setSpacing(3)
lbl_db = QLabel("DB:")
lbl_db.setFixedWidth(20)
row1_layout.addWidget(lbl_db)
self.file_path = QLineEdit()
self.file_path.setReadOnly(True)
self.file_path.setPlaceholderText("Select EDB...")
self.file_path.setMaximumWidth(200)
self.file_path.setFixedHeight(22)
self.file_path.mousePressEvent = lambda e: self._on_browse()
row1_layout.addWidget(self.file_path)
browse_btn = QPushButton("...")
browse_btn.setFixedSize(30, 22)
browse_btn.clicked.connect(self._on_browse)
row1_layout.addWidget(browse_btn)
self.load_btn = QPushButton("Load")
self.load_btn.setFixedSize(50, 22)
self.load_btn.clicked.connect(self._on_load)
self.load_btn.setEnabled(False)
row1_layout.addWidget(self.load_btn)
self.db_info_label = QLabel("")
self.db_info_label.setStyleSheet("color: #969696; font-size: 11px;")
row1_layout.addWidget(self.db_info_label)
row1_layout.addStretch()
# About button in top right corner
self.about_btn = QPushButton("About")
self.about_btn.setFixedSize(70, 22)
self.about_btn.clicked.connect(self._on_about)
self.about_btn.setToolTip("About this application")
self.about_btn.setStyleSheet("QPushButton { font-weight: bold; background-color: #094771; color: #ffffff; border: 1px solid #007acc; }")
row1_layout.addWidget(self.about_btn)
top_vlayout.addLayout(row1_layout)
# Row 2: Mailbox selection
row2_layout = QHBoxLayout()
row2_layout.setSpacing(3)
lbl_mb = QLabel("MB:")
lbl_mb.setFixedWidth(22)
row2_layout.addWidget(lbl_mb)
self.mailbox_combo = QComboBox()
self.mailbox_combo.setMaximumWidth(284)
self.mailbox_combo.setMinimumWidth(284)
self.mailbox_combo.setFixedHeight(22)
self.mailbox_combo.currentIndexChanged.connect(self._on_mailbox_changed)
row2_layout.addWidget(self.mailbox_combo)
self.owner_label = QLabel("")
self.owner_label.setStyleSheet("color: #55aaff; font-weight: bold; font-size: 11px;")
row2_layout.addWidget(self.owner_label)
row2_layout.addStretch()
top_vlayout.addLayout(row2_layout)
layout.addWidget(top_widget)
# Main content splitter
main_splitter = QSplitter(Qt.Orientation.Horizontal)
# Left panel: Folder tree
left_panel = QWidget()
left_layout = QVBoxLayout(left_panel)
left_layout.setContentsMargins(0, 0, 0, 0)
# Export buttons above folder tree
left_btn_layout = QHBoxLayout()
left_btn_layout.setSpacing(4)
self.export_folder_btn = QPushButton("Export Folder")
self.export_folder_btn.clicked.connect(self._on_export_folder)
self.export_folder_btn.setEnabled(False)
left_btn_layout.addWidget(self.export_folder_btn)
self.export_mailbox_btn = QPushButton("Export Mailbox...")
self.export_mailbox_btn.clicked.connect(self._on_export_mailbox)
self.export_mailbox_btn.setEnabled(False)
self.export_mailbox_btn.setToolTip("Export entire mailbox with filters (date, from, to, subject)")
left_btn_layout.addWidget(self.export_mailbox_btn)
left_layout.addLayout(left_btn_layout)
self.folder_tree = QTreeWidget()
self.folder_tree.setHeaderLabels(["Folder", "Messages"])
self.folder_tree.itemSelectionChanged.connect(self._on_folder_selected)
self.folder_tree.setMinimumWidth(250)
left_layout.addWidget(self.folder_tree)
main_splitter.addWidget(left_panel)
# Middle panel: Message list
middle_panel = QWidget()
middle_layout = QVBoxLayout(middle_panel)
middle_layout.setContentsMargins(0, 0, 0, 0)
# Search and filter controls
search_layout = QHBoxLayout()
search_layout.setSpacing(5)
search_layout.addWidget(QLabel("Search:"))
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Type to search subject, from, to...")
self.search_input.textChanged.connect(self._on_search_changed)
self.search_input.setMaximumWidth(200)
search_layout.addWidget(self.search_input)
# Filter: Read status
self.filter_read_combo = QComboBox()
self.filter_read_combo.addItems(["All", "Unread", "Read", "Failed"])
self.filter_read_combo.setMaximumWidth(80)
self.filter_read_combo.currentIndexChanged.connect(self._on_filter_changed)
search_layout.addWidget(QLabel("Status:"))
search_layout.addWidget(self.filter_read_combo)
# Filter: Has attachments
self.filter_attach_cb = QCheckBox("Has Attach")
self.filter_attach_cb.stateChanged.connect(self._on_filter_changed)
search_layout.addWidget(self.filter_attach_cb)
# Filter: Show hidden/system items
self.show_hidden_cb = QCheckBox("Hidden")
self.show_hidden_cb.setToolTip("Show hidden/system items")
self.show_hidden_cb.stateChanged.connect(self._on_show_hidden_changed)
search_layout.addWidget(self.show_hidden_cb)
# Clear filters button
self.clear_filters_btn = QPushButton("Clear")
self.clear_filters_btn.setMaximumWidth(70)
self.clear_filters_btn.clicked.connect(self._on_clear_filters)
search_layout.addWidget(self.clear_filters_btn)
search_layout.addStretch()
# Message count label
self.msg_count_label = QLabel("")
self.msg_count_label.setStyleSheet("color: #969696;")
search_layout.addWidget(self.msg_count_label)
middle_layout.addLayout(search_layout)
# Message list - columns: #, Date, From, To, FromEmail, ToEmail, Subject, Att, Read
self.message_list = QTreeWidget()
self.message_list.setHeaderLabels(["#", "Date", "From", "To", "From Email", "To Email", "Subject", "Att", "Read"])
self.message_list.itemSelectionChanged.connect(self._on_message_selected)
self.message_list.setMinimumWidth(500)
self.message_list.setSortingEnabled(True)
# Set column widths
self.message_list.setColumnWidth(0, 45) # #
self.message_list.setColumnWidth(1, 115) # Date
self.message_list.setColumnWidth(2, 120) # From
self.message_list.setColumnWidth(3, 120) # To
self.message_list.setColumnWidth(4, 150) # From Email (hidden by default)
self.message_list.setColumnWidth(5, 150) # To Email (hidden by default)
self.message_list.setColumnWidth(6, 180) # Subject
self.message_list.setColumnWidth(7, 30) # Att
self.message_list.setColumnWidth(8, 35) # Read
# Hide email columns by default
self.message_list.setColumnHidden(4, True) # From Email
self.message_list.setColumnHidden(5, True) # To Email
middle_layout.addWidget(self.message_list)
# Store all messages for filtering
self.all_messages_cache = []
main_splitter.addWidget(middle_panel)
# Right panel: Content view
right_panel = QWidget()
right_layout = QVBoxLayout(right_panel)
right_layout.setContentsMargins(0, 0, 0, 0)
# Export buttons row at top of right panel
right_export_layout = QHBoxLayout()
right_export_layout.setSpacing(4)
self.export_eml_btn2 = QPushButton("Export Message (.eml)")
self.export_eml_btn2.clicked.connect(self._on_export_message)
self.export_eml_btn2.setEnabled(False)
self.export_eml_btn2.setStyleSheet("QPushButton { padding: 4px 12px; font-weight: bold; background-color: #094771; color: #ffffff; border: 1px solid #007acc; }")
right_export_layout.addWidget(self.export_eml_btn2)
self.export_attach_btn = QPushButton("Export Attachments")
self.export_attach_btn.clicked.connect(self._on_export_attachments)
self.export_attach_btn.setEnabled(False)
right_export_layout.addWidget(self.export_attach_btn)
right_export_layout.addStretch()
right_layout.addLayout(right_export_layout)
# Message header section (Outlook-style labels above tabs)
header_widget = QWidget()
header_widget.setStyleSheet("QWidget { background-color: #252526; border-bottom: 1px solid #3e3e42; }")
header_layout = QGridLayout(header_widget)
header_layout.setContentsMargins(8, 6, 8, 6)
header_layout.setSpacing(2)
# Create labels with bold field names
label_style = "font-weight: bold; color: #969696;"
value_style = "color: #d4d4d4;"
# Row 0: From / Organizer / Name
self.label_row0 = QLabel("From:")
self.label_row0.setStyleSheet(label_style)
self.header_from = QLabel("(none)")
self.header_from.setStyleSheet(value_style)
self.header_from.setWordWrap(True)
header_layout.addWidget(self.label_row0, 0, 0)
header_layout.addWidget(self.header_from, 0, 1)
# Row 1: To / Attendees / Email
self.label_row1 = QLabel("To:")
self.label_row1.setStyleSheet(label_style)
self.header_to = QLabel("(none)")
self.header_to.setStyleSheet(value_style)
self.header_to.setWordWrap(True)
header_layout.addWidget(self.label_row1, 1, 0)
header_layout.addWidget(self.header_to, 1, 1)
# Row 2: Cc / Location / Phone
self.label_row2 = QLabel("Cc:")
self.label_row2.setStyleSheet(label_style)
self.header_cc = QLabel("(none)")
self.header_cc.setStyleSheet(value_style)
self.header_cc.setWordWrap(True)
header_layout.addWidget(self.label_row2, 2, 0)
header_layout.addWidget(self.header_cc, 2, 1)
# Row 3: Bcc / (hidden) / Company
self.label_row3 = QLabel("Bcc:")
self.label_row3.setStyleSheet(label_style)
self.header_bcc = QLabel("(none)")
self.header_bcc.setStyleSheet(value_style)
self.header_bcc.setWordWrap(True)
header_layout.addWidget(self.label_row3, 3, 0)
header_layout.addWidget(self.header_bcc, 3, 1)
# Row 4: Subject / Subject / Title
self.label_row4 = QLabel("Subject:")
self.label_row4.setStyleSheet(label_style)
self.header_subject = QLabel("(No Subject)")
self.header_subject.setStyleSheet(value_style + " font-weight: bold; color: #ffffff;")
self.header_subject.setWordWrap(True)
header_layout.addWidget(self.label_row4, 4, 0)
header_layout.addWidget(self.header_subject, 4, 1)
# Row 5: Date / Start Time / Created
self.label_row5 = QLabel("Date:")
self.label_row5.setStyleSheet(label_style)
self.header_date = QLabel("(none)")
self.header_date.setStyleSheet(value_style)
header_layout.addWidget(self.label_row5, 5, 0)
header_layout.addWidget(self.header_date, 5, 1)
# Make value column stretch
header_layout.setColumnStretch(1, 1)
right_layout.addWidget(header_widget)
self.content_tabs = QTabWidget()
# Body Plain Text tab - with word wrap
self.body_view = QTextEdit()
self.body_view.setReadOnly(True)
self.body_view.setFont(QFont("Arial", 11))
self.body_view.setWordWrapMode(QTextOption.WrapMode.WordWrap)
self.body_view.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth)
self.content_tabs.addTab(self.body_view, "Body (Text)")
# Body HTML tab - lightweight QTextBrowser for HTML rendering
self.html_browser_view = QTextBrowser()
self.html_browser_view.setReadOnly(True)
self.html_browser_view.setOpenExternalLinks(True)
self.html_browser_view.setFont(QFont("Arial", 11))
self.html_browser_view.setStyleSheet("QTextBrowser { background-color: #ffffff; color: #000000; }")
self.content_tabs.addTab(self.html_browser_view, "Body (HTML)")
# Attachments tab (right after Body HTML for easy access)
attach_widget = QWidget()
attach_layout = QVBoxLayout(attach_widget)
self.attach_list = QListWidget()
self.attach_list.itemDoubleClicked.connect(self._on_attachment_double_clicked)
attach_layout.addWidget(self.attach_list)
attach_btn_layout = QHBoxLayout()
self.save_attach_btn = QPushButton("Save Selected Attachment")
self.save_attach_btn.clicked.connect(self._on_save_attachment)
self.save_attach_btn.setEnabled(False)
attach_btn_layout.addWidget(self.save_attach_btn)
self.save_all_attach_btn = QPushButton("Save All Attachments")
self.save_all_attach_btn.clicked.connect(self._on_save_all_attachments)
self.save_all_attach_btn.setEnabled(False)
attach_btn_layout.addWidget(self.save_all_attach_btn)
attach_layout.addLayout(attach_btn_layout)
self.content_tabs.addTab(attach_widget, "Attachments (0)")
# HTML Source tab - shows raw HTML code
self.html_source_view = QTextEdit()
self.html_source_view.setReadOnly(True)
self.html_source_view.setFont(QFont("Consolas", 9))
self.html_source_view.setWordWrapMode(QTextOption.WrapMode.NoWrap)
self.content_tabs.addTab(self.html_source_view, "HTML Source")
# Raw Body tab with compressed/uncompressed toggle
raw_body_widget = QWidget()
raw_body_layout = QVBoxLayout(raw_body_widget)
raw_body_layout.setContentsMargins(0, 0, 0, 0)
# Toggle for compressed/uncompressed view
raw_toggle_layout = QHBoxLayout()
self.raw_compressed_cb = QCheckBox("Show Compressed (Raw)")
self.raw_compressed_cb.setChecked(True)