-
Notifications
You must be signed in to change notification settings - Fork 25
/
nsf2x.py
1479 lines (1279 loc) · 71.5 KB
/
nsf2x.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
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Copyright (C) 2016 Free Software Foundation
# Author : David Bateman <dbateman@free.fr>
"""NSF2X : A Python/Tkinter application for Lotus Lotus NSF to MBOX,
EML and PST converter
"""
# Very loosely based on nlconverter (https://code.google.com/p/nlconverter/)
# by Hugues Bernard <hugues.bernard@gmail.com>
# Place the PyLint warning to disable globally in this file here
# Ignore variable/function/Method naming conventions of PEP8. I like my names
# pylint: disable=C0103
# Ignore line length conventions (lines less than 100 characters)
# pylint: disable=C0301
import gettext
import locale
import traceback
import tempfile
import datetime
import codecs
import os
import sys
import io
import platform
import subprocess
import shutil
import pywintypes
import win32crypt
import win32cryptcon
import winreg
import win32com.client #NB : Calls to COM are starting with an uppercase
import ctypes
try:
# Python 3.x
import tkinter
import tkinter.ttk as ttk
except ImportError:
# Python 2.7
import Tkinter as tkinter
import ttk
import mapiex
# This list should be extended to match regular install paths
notesDllPathList = [r'c:/notes', r'd:/notes', r'c:/program files/notes', r'd:/program files/notes',
r'c:/program files (x86)/notes', r'd:/program files (x86)/notes',
r'c:/program files/ibm/notes', r'd:/program files/ibm/notes',
r'c:/program files (x86)/ibm/notes', r'd:/program files (x86)/ibm/notes']
# Setup i8n. This has to stay here rather than at the end of the file so that
# "_" is defined
lang = locale.windows_locale.get(ctypes.windll.kernel32.GetUserDefaultLCID())
localedir = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'locale')
translate = gettext.translation('nsf2x', localedir, languages=[lang], fallback=True)
_ = translate.gettext
translate.install()
# The following classes are a means of creating a simple ENUM functionality
# Use list(range()) for Python 2.7 and 3.x compatibility
class Format: # pylint: disable=R0903
"""Enum for format to write to"""
EML, MBOX, PST = list(range(3))
class EncryptionType: # pylint: disable=R0903
"""Enum for re-encryption type"""
NONE, RC2CBC, DES, AES128, AES256 = list(range(5))
class SubdirectoryMBOX: # pylint: disable=R0903
"""Enum for the treatment of subfolder for the MBOX format"""
NO, YES = list(range(2))
class ErrorLevel: # pylint: disable=R0903
"""Enum for the error reporting level"""
NORMAL, ERROR, WARN, INFO = list(range(4))
class Exceptions: # pylint: disable=R0903
"""Enum for the number of exceptions allowed before quitting"""
EX_1, EX_10, EX_100, EX_INF = list(range(4))
class Helper: # pylint: disable=R0903
"""Enum to flag whether the use of an external PST import is to be forced"""
NO, YES = list(range(2))
def OutlookPath():
"""Function to retrieve the path to Outlook from the registry"""
aReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
aKey = winreg.OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\OUTLOOK.EXE")
# prepend unused variables with "dummy_" to keep PyLint happy
dummy_n, v, dummy_t = winreg.EnumValue(aKey, 0)
winreg.CloseKey(aKey)
winreg.CloseKey(aReg)
return v
class NotesEntries(object):
"""Wrapper to nnotes.dll for access to ConvertMime not exposed through COM interface"""
OPEN_RAW_RFC822_TEXT = ctypes.c_uint32(0x01000000)
OPEN_RAW_MIME_PART = ctypes.c_uint32(0x02000000)
OPEN_RAW_MIME = ctypes.c_uint32(0x03000000) # OPEN_RAW_RFC822_TEXT | OPEN_RAW_MIME_PART
nnotesdll = None
hDb = ctypes.c_void_p(0)
def __init__(self, fp=None):
"""NoteEntries initialisation method"""
self.__loaddll(fp)
self.__isLoaded(True, False) # Throw an error if the DLL didn't load
self.__SetDLLReturnTypes()
stat = self.nnotesdll.NotesInitExtended(0, ctypes.c_void_p(0))
if stat != 0:
raise NameError(_("NNOTES DLL can not be initialized (ErrorID %d)") % stat)
def __delete__(self, instance):
""""NotesEntries destructor"""
self.__isLoaded(True, False)
self.nnotesdll.NotesTerm()
def __loaddll(self, fp=None):
if fp != None:
if os.path.exists(fp):
self.nnotesdll = ctypes.WinDLL(fp)
else:
self.nnotesdll = None
else:
self.nnotesdll = None
try:
# If we already have the COM/DDE interface to Notes, then nlsxbe.dll
# is already loaded, so we can just try and get nnotes.dll leaving
# Windows to search in its default search path
self.nnotesdll = ctypes.WinDLL('nnotes.dll')
except OSError:
# Try harder
for p in notesDllPathList:
fp = os.path.join(p, 'nnotes.dll')
if os.path.exists(fp):
self.nnotesdll = ctypes.WinDLL(fp)
break
def __isLoaded(self, raiseError=True, TestDb=True):
if raiseError:
if self.nnotesdll is None:
raise NameError(_("NNOTES DLL not loaded"))
elif TestDb and self.hDb is None:
raise NameError(_("NNOTES DLL : Database not loaded"))
else:
return self.nnotesdll != None and self.hDb != None
def __SetDLLReturnTypes(self):
self.nnotesdll.NotesInitExtended.restype = ctypes.c_uint16
self.nnotesdll.NotesTerm.restype = ctypes.c_uint16
self.nnotesdll.NSFDbOpen.restype = ctypes.c_uint16
self.nnotesdll.NSFDbClose.restype = ctypes.c_uint16
self.nnotesdll.NSFNoteOpenExt.restype = ctypes.c_uint16
self.nnotesdll.NSFNoteOpenByUNID.restype = ctypes.c_uint16
self.nnotesdll.NSFNoteClose.restype = ctypes.c_uint16
self.nnotesdll.NSFNoteCopy.restype = ctypes.c_uint16
self.nnotesdll.NSFNoteGetInfo.restype = None
self.nnotesdll.NSFNoteIsSignedOrSealed.restype = ctypes.c_bool
self.nnotesdll.NSFNoteDecrypt.restype = ctypes.c_uint16
self.nnotesdll.NSFItemDelete.restype = ctypes.c_uint16
self.nnotesdll.NSFNoteHasMIMEPart.restype = ctypes.c_bool
self.nnotesdll.NSFNoteHasMIME.restype = ctypes.c_bool
self.nnotesdll.NSFNoteHasComposite.restype = ctypes.c_bool
self.nnotesdll.MMCreateConvControls.restype = ctypes.c_uint16
self.nnotesdll.MMDestroyConvControls.restype = ctypes.c_uint16
self.nnotesdll.MMSetMessageContentEncoding.restype = None
self.nnotesdll.MIMEConvertCDParts.restype = ctypes.c_uint16
self.nnotesdll.MIMEConvertMIMEPartCC.restype = ctypes.c_uint16
self.nnotesdll.NSFNoteUpdate.restype = ctypes.c_uint16
def NSFDbOpen(self, path):
self.__isLoaded(True, False)
# Conversion UNICODE to LMBCS to allow Lotus to open databases with
# accents in their names.
# OS_TRANSLATE_UTF8_TO_LMBCS = 24
maxpath = 1024
astr1 = path.encode('utf-8')
astr2 = ctypes.create_string_buffer(maxpath)
self.nnotesdll.OSTranslate(24, astr1, len(astr1), ctypes.byref(astr2), maxpath)
return self.nnotesdll.NSFDbOpen(ctypes.c_char_p(astr2.value), ctypes.byref(self.hDb))
def NSFDbClose(self):
self.__isLoaded()
return self.nnotesdll.NSFDbClose(self.hDb)
def NSFNoteCopy(self, hNote):
self.__isLoaded()
hNoteNew = ctypes.c_void_p(0)
retval = self.nnotesdll.NSFDbClose(hNote, ctypes.byref(hNoteNew))
return retval, hNoteNew
def NSFNoteOpenExt(self, nid, flags):
self.__isLoaded()
hNote = ctypes.c_void_p(0)
retval = self.nnotesdll.NSFNoteOpenExt(self.hDb, nid, flags, ctypes.byref(hNote))
return retval, hNote
def NSFNoteOpenByUNID(self, unid, flags):
self.__isLoaded()
hNote = ctypes.c_void_p(0)
retval = self.nnotesdll.NSFNoteOpenByUNID(self.hDb, unid, flags, ctypes.byref(hNote))
return retval, hNote
def NSFNoteClose(self, hNote):
self.__isLoaded()
return self.nnotesdll.NSFNoteClose(hNote)
def NSFNoteGetInfo(self, hNote, flags):
self.__isLoaded()
retval = ctypes.c_uint16(0)
self.nnotesdll.NSFNoteGetInfo(hNote, flags, ctypes.byref(retval))
return retval
def NSFNoteIsSignedOrSealed(self, hNote):
self.__isLoaded()
isSigned = ctypes.c_bool(False)
isSealed = ctypes.c_bool(False)
retval = self.nnotesdll.NSFNoteIsSignedOrSealed(hNote, ctypes.byref(isSigned),
ctypes.byref(isSealed))
return retval, isSigned.value, isSealed.value
def NSFNoteDecrypt(self, hNote, flags):
self.__isLoaded()
return self.nnotesdll.NSFNoteDecrypt(hNote, flags, ctypes.c_void_p(0))
def NSFItemDelete(self, hNote, iname):
self.__isLoaded()
return self.nnotesdll.NSFItemDelete(hNote, iname, len(iname))
def NSFNoteHasMIMEPart(self, hNote):
self.__isLoaded()
return self.nnotesdll.NSFNoteHasMIMEPart(hNote)
def NSFNoteHasMIME(self, hNote):
self.__isLoaded()
return self.nnotesdll.NSFNoteHasMIME(hNote)
def NSFNoteHasComposite(self, hNote):
self.__isLoaded()
return self.nnotesdll.NSFNoteHasComposite(hNote)
def MMCreateConvControls(self):
self.__isLoaded()
hCC = ctypes.c_void_p(0)
stat = self.nnotesdll.MMCreateConvControls(ctypes.byref(hCC))
return(stat, hCC)
def MMDestroyConvControls(self, hCC):
self.__isLoaded()
return self.nnotesdll.MMDestroyConvControls(hCC)
def MMSetMessageContentEncoding(self, hCC, flags):
self.__isLoaded()
self.nnotesdll.MMSetMessageContentEncoding(hCC, flags)
def MIMEConvertCDParts(self, hNote, bcanon, bisMime, hCC):
self.__isLoaded()
return self.nnotesdll.MIMEConvertCDParts(hNote, bcanon, bisMime, hCC)
def MIMEConvertMIMEPartsCC(self, hNote, bcanon, hCC):
self.__isLoaded()
return self.nnotesdll.MIMEConvertCDParts(hNote, bcanon, hCC)
def NSFNoteUpdate(self, hNote, flags):
self.__isLoaded()
return self.nnotesdll.NSFNoteUpdate(hNote, flags)
class Gui(tkinter.Frame):
"""Basic Gui for NSF to EML, MBOX, PST export"""
def __init__(self):
"""Gui init function"""
# Setup the Tk frame including the manner in which the row/columns are
# expanded. IE. Expand all columns equally, but only expand in height
# the message area
tkinter.Frame.__init__(self)
self.master.title(_("Lotus Notes Converter"))
self.master.grid_rowconfigure(4, weight=1)
self.master.grid_columnconfigure(1, weight=1)
self.master.grid_columnconfigure(2, weight=1)
self.master.grid_columnconfigure(3, weight=1)
self.master.grid_columnconfigure(4, weight=1)
self.nsfPath = "."
self.destPath = os.path.join(os.path.expanduser('~'), 'Documents')
self.checked = False
self.Lotus = None
self.running = False
self.dialog = None
self.certificate = None
self.hCryptoProv = None
self.EML2PST = None
# Initialize the default values of the Radio buttons
self.Format = tkinter.IntVar()
self.Format.set(Format.PST)
self.Encrypt = tkinter.IntVar()
self.Encrypt.set(EncryptionType.AES256)
self.MBOXType = tkinter.IntVar()
self.MBOXType.set(SubdirectoryMBOX.YES)
self.ErrorLevel = tkinter.IntVar()
self.ErrorLevel.set(ErrorLevel.ERROR)
self.Exceptions = tkinter.IntVar()
self.Exceptions.set(Exceptions.EX_100)
self.Helper = tkinter.IntVar()
self.Helper.set(Helper.NO)
# Lotus Password
self.entryPassword = tkinter.Entry(self.master, relief=tkinter.GROOVE)
self.entryPassword.insert(0, _("Enter Lotus Notes password"))
self.entryPassword.grid(row=1, column=1, columnspan=2, sticky=tkinter.E+tkinter.W)
self.entryPassword.bind("<FocusIn>", self.bindEntry)
# Action button
self.startButton = tkinter.Button(self.master, text=_("Open Session"),
command=self.doConvert, relief=tkinter.GROOVE)
self.startButton.grid(row=1, column=3, columnspan=2, sticky=tkinter.E+tkinter.W)
# Conversion Type
self.formatTypeEML = tkinter.Radiobutton(self.master, text="EML",
variable=self.Format, value=Format.EML)
self.formatTypeEML.grid(row=2, column=1, sticky=tkinter.E+tkinter.W)
self.formatTypeMBOX = tkinter.Radiobutton(self.master, text="MBOX",
variable=self.Format, value=Format.MBOX)
self.formatTypeMBOX.grid(row=2, column=2, sticky=tkinter.E+tkinter.W)
self.formatTypePST = tkinter.Radiobutton(self.master, text="PST",
variable=self.Format, value=Format.PST)
self.formatTypePST.grid(row=2, column=3, sticky=tkinter.E+tkinter.W)
# Options button
self.optionsButton = tkinter.Button(self.master, text=_("Options"),
command=self.doOptions, relief=tkinter.GROOVE,
state=tkinter.DISABLED)
self.optionsButton.grid(row=2, column=4, sticky=tkinter.E+tkinter.W)
# Source chooser
self.chooseNsfButton = tkinter.Button(self.master,
text=_("Select Directory of SOURCE nsf files"),
command=self.openSource, relief=tkinter.GROOVE,
state=tkinter.DISABLED)
self.chooseNsfButton.grid(row=3, column=1, columnspan=2, sticky=tkinter.E+tkinter.W)
# Destination chooser
self.chooseDestButton = tkinter.Button(self.master,
text=_("Select Directory of DESTINATION files"),
command=self.openDestination,
relief=tkinter.GROOVE, state=tkinter.DISABLED)
self.chooseDestButton.grid(row=3, column=3, columnspan=2, sticky=tkinter.E+tkinter.W)
# Message Area
frame = tkinter.Frame(self.master)
frame.grid(row=4, column=1, columnspan=4, sticky=tkinter.E+tkinter.W+tkinter.N+tkinter.S)
self.messageWidget = tkinter.Text(frame, width=80, height=20,
state=tkinter.DISABLED, wrap=tkinter.NONE)
scrollY = tkinter.Scrollbar(frame, orient=tkinter.VERTICAL,
command=self.messageWidget.yview)
self.messageWidget['yscrollcommand'] = scrollY.set
scrollY.pack(side=tkinter.RIGHT, expand=tkinter.NO, fill=tkinter.Y)
scrollX = tkinter.Scrollbar(frame, orient=tkinter.HORIZONTAL,
command=self.messageWidget.xview)
self.messageWidget['xscrollcommand'] = scrollX.set
scrollX.pack(side=tkinter.BOTTOM, expand=tkinter.NO, fill=tkinter.X)
self.messageWidget.pack(side=tkinter.RIGHT, expand=tkinter.YES, fill=tkinter.BOTH)
self.log(ErrorLevel.NORMAL, _("Lotus Notes NSF file to EML, MBOX and PST file converter."))
self.log(ErrorLevel.NORMAL, _("Contact dbateman@free.fr for more information.\n"))
def openSource(self):
"""Gui Open Source Action Callback"""
dirname = self.tk.call('tk_chooseDirectory', '-initialdir', self.nsfPath,
'-mustexist', True)
if dirname != "":
self.nsfPath = dirname.replace('/', '\\')
self.chooseNsfButton.config(text=_("Source directory is : %s") % self.nsfPath)
def openDestination(self):
"""Gui Open Destinaion Action Callback"""
dirname = self.tk.call('tk_chooseDirectory', '-initialdir',
self.destPath, '-mustexist', True)
if dirname != "" and type(dirname) is not tuple and str(dirname) != "":
self.destPath = dirname.replace('/', '\\')
self.chooseDestButton.config(text=_("Destination directory is : %s") % self.destPath)
def bindEntry(self, dummy_event=None):
"""Blank the password field and set it in password mode"""
self.entryPassword.delete(0, tkinter.END)
self.entryPassword.config(show="*")
self.entryPassword.unbind("<FocusIn>") #not needed anymore
self.unchecked()
def check(self):
"""Method to chack that Lotus Notes COM interface is loaded"""
if self.Lotus != None:
self.checked = True
self.log(ErrorLevel.NORMAL, _("Connection to Notes established\n"))
else:
self.unchecked()
self.log(ErrorLevel.ERROR, _("Check the Notes password and that NSF2X and Notes use the same architecture\n"))
return self.checked
def unchecked(self):
"""Method to reinitialise NSF2X startup state"""
self.startButton.config(text=_("Open Session"))
self.checked = False
self.configPasswordEntry()
def configStop(self, AllowButton=True, ActionText=_("Stop")):
"""Gui Stop Button Configuration"""
self.chooseNsfButton.config(state=tkinter.DISABLED)
self.chooseDestButton.config(state=tkinter.DISABLED)
self.entryPassword.config(state=tkinter.DISABLED)
if AllowButton:
self.startButton.config(text=ActionText, state=tkinter.NORMAL)
else:
self.startButton.config(text=ActionText, state=tkinter.DISABLED)
self.optionsButton.config(state=tkinter.DISABLED)
self.formatTypeEML.config(state=tkinter.DISABLED)
self.formatTypeMBOX.config(state=tkinter.DISABLED)
self.formatTypePST.config(state=tkinter.DISABLED)
def configPasswordEntry(self):
"""Gui Password Entry Configuration"""
self.startButton.config(text=_("Open Sessions"), state=tkinter.NORMAL)
self.chooseNsfButton.config(text=_("Select Directory of SOURCE nsf files"),
state=tkinter.DISABLED)
self.chooseDestButton.config(text=_("Select Directory of DESTINATION files"),
state=tkinter.DISABLED)
self.entryPassword.config(state=tkinter.NORMAL)
self.formatTypeEML.config(state=tkinter.DISABLED)
self.formatTypeMBOX.config(state=tkinter.DISABLED)
self.formatTypePST.config(state=tkinter.DISABLED)
self.optionsButton.config(state=tkinter.DISABLED)
def configDirectoryEntry(self, SetDefaultPath=True):
"""Gui Directory Entry Configuration"""
self.startButton.config(text=_("Convert"), state=tkinter.NORMAL)
self.entryPassword.config(state=tkinter.DISABLED)
self.formatTypeEML.config(state=tkinter.NORMAL)
self.formatTypeMBOX.config(state=tkinter.NORMAL)
self.formatTypePST.config(state=tkinter.NORMAL)
self.optionsButton.config(state=tkinter.NORMAL)
if SetDefaultPath:
op = None
try:
op = os.path.join(os.path.dirname(self.Lotus.URLDatabase.FilePath), 'archive')
except (pywintypes.com_error, OSError): # pylint: disable=E1101
try:
op = os.path.join(os.path.expanduser('~'), 'archive')
except OSError:
op = None
finally:
if os.path.exists(op):
self.nsfPath = op
else:
self.nsfPath = '.'
sp = os.path.join(os.path.expanduser('~'), 'Documents')
if os.path.exists(sp):
self.destPath = sp
else:
self.destPath = '.'
self.chooseNsfButton.config(text=_("Source directory is : %s") % self.nsfPath)
self.chooseNsfButton.config(state=tkinter.NORMAL)
self.chooseDestButton.config(text=_("Destination directory is %s") % self.destPath)
self.chooseDestButton.config(state=tkinter.NORMAL)
def doOptions(self):
"""Gui Options Action Callback"""
self.configStop(False, _("Convert"))
self.dialog = tkinter.Toplevel(master=self.winfo_toplevel())
self.dialog.title(_("NSF2X Options"))
self.dialog.protocol("WM_DELETE_WINDOW", self.closeOptions)
self.dialog.resizable(0, 0)
L1 = tkinter.Label(self.dialog, text=_("Use different MBOXes for each sub-folder :"))
L1.grid(row=1, column=1, columnspan=4, sticky=tkinter.W)
R1 = tkinter.Radiobutton(self.dialog, text=_("No"), variable=self.MBOXType,
value=SubdirectoryMBOX.NO)
R1.grid(row=2, column=1, columnspan=2, sticky=tkinter.W)
R2 = tkinter.Radiobutton(self.dialog, text=_("Yes"), variable=self.MBOXType,
value=SubdirectoryMBOX.YES)
R2.grid(row=2, column=3, columnspan=2, sticky=tkinter.W)
ttk.Separator(self.dialog, orient=tkinter.HORIZONTAL).grid(row=3, columnspan=5,
sticky=tkinter.E+tkinter.W)
L2 = tkinter.Label(self.dialog, text=_("Re-encryption of encrypted Notes messages :"))
L2.grid(row=4, column=1, columnspan=4, sticky=tkinter.W)
R3 = tkinter.Radiobutton(self.dialog, text=_("None"), variable=self.Encrypt,
value=EncryptionType.NONE)
R3.grid(row=5, column=1, sticky=tkinter.W)
R4 = tkinter.Radiobutton(self.dialog, text=_("RC2 40bit"), variable=self.Encrypt,
value=EncryptionType.RC2CBC)
R4.grid(row=5, column=2, sticky=tkinter.W)
R5 = tkinter.Radiobutton(self.dialog, text=_("3DES 168bit"), variable=self.Encrypt,
value=EncryptionType.DES)
R5.grid(row=5, column=3, columnspan=2, sticky=tkinter.W)
R6 = tkinter.Radiobutton(self.dialog, text=_("AES 128bit"), variable=self.Encrypt,
value=EncryptionType.AES128)
R6.grid(row=6, column=1, columnspan=2, sticky=tkinter.W)
R7 = tkinter.Radiobutton(self.dialog, text=_("AES 256bit"), variable=self.Encrypt,
value=EncryptionType.AES256)
R7.grid(row=6, column=3, columnspan=2, sticky=tkinter.W)
ttk.Separator(self.dialog, orient=tkinter.HORIZONTAL).grid(row=7, columnspan=5,
sticky=tkinter.E+tkinter.W)
L3 = tkinter.Label(self.dialog, text=_("Error logging level :"))
L3.grid(row=8, column=1, columnspan=4, sticky=tkinter.W)
R8 = tkinter.Radiobutton(self.dialog, text=_("Error"), variable=self.ErrorLevel,
value=ErrorLevel.ERROR)
R8.grid(row=9, column=1, sticky=tkinter.W)
R9 = tkinter.Radiobutton(self.dialog, text=_("Warning"), variable=self.ErrorLevel,
value=ErrorLevel.WARN)
R9.grid(row=9, column=2, sticky=tkinter.W)
R10 = tkinter.Radiobutton(self.dialog, text=_("Information"),
variable=self.ErrorLevel, value=ErrorLevel.INFO)
R10.grid(row=9, column=3, columnspan=2, sticky=tkinter.W)
ttk.Separator(self.dialog, orient=tkinter.HORIZONTAL).grid(row=10, columnspan=5,
sticky=tkinter.E+tkinter.W)
L4 = tkinter.Label(self.dialog, text=_("Number of exceptions before giving up :"))
L4.grid(row=11, column=1, columnspan=4, sticky=tkinter.W)
R11 = tkinter.Radiobutton(self.dialog, text="1", variable=self.Exceptions,
value=Exceptions.EX_1)
R11.grid(row=12, column=1, sticky=tkinter.W)
R12 = tkinter.Radiobutton(self.dialog, text="10", variable=self.Exceptions,
value=Exceptions.EX_10)
R12.grid(row=12, column=2, sticky=tkinter.W)
R13 = tkinter.Radiobutton(self.dialog, text="100", variable=self.Exceptions,
value=Exceptions.EX_100)
R13.grid(row=12, column=3, sticky=tkinter.W)
R14 = tkinter.Radiobutton(self.dialog, text=_("Infinite"),
variable=self.Exceptions, value=Exceptions.EX_INF)
R14.grid(row=12, column=4, sticky=tkinter.W)
ttk.Separator(self.dialog, orient=tkinter.HORIZONTAL).grid(row=13, columnspan=5,
sticky=tkinter.E+tkinter.W)
L5 = tkinter.Label(self.dialog, text=_("Always use external PST helper function :"))
L5.grid(row=14, column=1, columnspan=4, sticky=tkinter.W)
R15 = tkinter.Radiobutton(self.dialog, text=_("No"), variable=self.Helper,
value=Helper.NO)
R15.grid(row=15, column=1, columnspan=2, sticky=tkinter.W)
R16 = tkinter.Radiobutton(self.dialog, text=_("Yes"), variable=self.Helper,
value=Helper.YES)
R16.grid(row=15, column=3, columnspan=2, sticky=tkinter.W)
B1 = tkinter.Button(self.dialog, text=_("Close"), command=self.closeOptions,
relief=tkinter.GROOVE)
B1.grid(row=16, column=2, columnspan=2, sticky=tkinter.E+tkinter.W)
self.dialog.focus_force()
def closeOptions(self):
"""GUI Close Options action callback"""
self.configDirectoryEntry(False)
if self.dialog != None:
self.dialog.destroy()
def doConvert(self):
"""GUI Convert action callback"""
if self.checked:
if self.running:
self.running = False
self.configStop(False)
self.log(ErrorLevel.NORMAL, _("Waiting for sub processes to terminate"))
else:
self.running = True
self.configStop()
self.master.after(0, self.doConvertDirectory())
else: #Check if all is OK
try:
self.Lotus = win32com.client.Dispatch(r'Lotus.NotesSession')
# Use rstrip to remove trailing whitespace as not part of the password
self.Lotus.Initialize(self.entryPassword.get().rstrip())
self.Lotus.ConvertMime = False
except pywintypes.com_error as ex: # pylint: disable=E1101
self.log(ErrorLevel.ERROR, _("Error connecting to Lotus !"))
self.log(ErrorLevel.ERROR, _("Exception %s :") % ex)
# Try to force loading of Notes, but only do it if the COM
# interface wasn't found.
if self.Lotus is None:
for p in notesDllPathList:
fp = os.path.join(p, 'nlsxbe.dll')
if os.path.exists(fp) and os.system('regsvr32 /s "%s"' % fp) == 0:
break
self.Lotus = None
self.check()
if self.checked:
self.configDirectoryEntry()
def doConvertDirectory(self):
"""Method to convert all NSF files in a directory"""
tl = self.winfo_toplevel()
self.log(ErrorLevel.NORMAL, _("Starting Convert : %s\n") % datetime.datetime.now())
if self.Format.get() == Format.MBOX and self.MBOXType.get() == SubdirectoryMBOX.NO:
self.log(ErrorLevel.WARN, _("The MBOX file will not have the directory hierarchies present in NSF file\n"))
if self.Format.get() == Format.PST:
# Check if our Outlook is 64bit, and adapt the importation
# strategy accoridngly. The MAPI interface must have the
# same bitness as the version of Outlook, so the EML2PST option
# forces a call an external helper program of the right bitness
# to do the importation. See
# https://msdn.microsoft.com/en-us/library/office/dd941355.aspx?f=255&MSPPError=-2147217396
if platform.architecture()[0] == "32bit":
# NSF2X is running as a 32bit application
if platform.architecture(executable=OutlookPath())[0] != "32bit":
# Need to use the 64bit helper function
self.EML2PST = "helper64/eml2pst.exe"
self.log(ErrorLevel.NORMAL, _("Detected 32bit NFS2X and 64bit Outlook"))
elif self.Helper.get() == Helper.YES:
self.EML2PST = "helper32/eml2pst.exe"
self.log(ErrorLevel.NORMAL, _("Forcing use of external helper function"))
else:
# NSF2X is running as a 64bit application
if platform.architecture(executable=OutlookPath())[0] == '32bit':
# Need to use the 32bit helper function
self.EML2PST = 'helper32/eml2pst.exe'
self.log(ErrorLevel.NORMAL, _("Detected 64bit NFS2X and 32bit Outlook"))
elif self.Helper.get() == Helper.YES:
self.EML2PST = "helper64/eml2pst.exe"
self.log(ErrorLevel.NORMAL, _("Forcing use of external helper function"))
if self.EML2PST:
self.log(ErrorLevel.NORMAL, _("Using external helper function '%s' for importation of the EML files") % self.EML2PST)
for src in os.listdir(self.nsfPath):
if not self.running:
break
abssrc = os.path.join(self.nsfPath, src)
if os.path.isfile(abssrc) and src.lower().endswith('.nsf'):
dest = src[:-4]
try:
self.realConvert(src, dest)
except (pywintypes.com_error, OSError) as ex: # pylint: disable=E1101
self.log(ErrorLevel.ERROR, _("Error converting database %s") % src)
self.log(ErrorLevel.ERROR, _("Exception %s :") % ex)
self.log(ErrorLevel.ERROR, "%s" % traceback.format_exc())
self.log(ErrorLevel.NORMAL, _("End of convert : %s\n") % datetime.datetime.now())
tl.title(_("Lotus Notes Converter"))
self.update()
self.running = False
self.configDirectoryEntry(False)
def realConvert(self, src, dest):
"""Method to perform the translation from NSF to X on a single file"""
c = 0 #document counter
e = 0 #exception counter
ac = 0 # all message count, though only an upper bounds as some documents not in folders
tl = self.winfo_toplevel()
# Setup the permitted number of exceptions
if self.Exceptions.get() == Exceptions.EX_1:
nex = 1
elif self.Exceptions.get() == Exceptions.EX_10:
nex = 10
elif self.Exceptions.get() == Exceptions.EX_100:
nex = 100
else:
nex = -1
if self.Format.get() == Format.PST and self.EML2PST:
ph = 3
else:
ph = 2
path = os.path.join(self.nsfPath, src)
self.log(ErrorLevel.NORMAL, _("Converting : %s ") % path)
if self.Lotus != None:
try:
dBNotes = self.Lotus.GetDatabase("", path)
ac = dBNotes.AllDocuments.Count
except pywintypes.com_error as ex: # pylint: disable=E1101
self.log(ErrorLevel.ERROR, _("Error connecting to Lotus !"))
self.log(ErrorLevel.ERROR, _("Exception %s :") % ex)
else:
raise ValueError(_("Empty Lotus session"))
if ac <= 0:
raise ValueError(_("The database %s appears to be empty. Returning") % src)
# Preconvert all messages to MIME before writing EML files as the
# C DLL might not be finished saving the message before the COM
# interface tries to access the MIME body. Also the call to mapiex.mapi()
# must come after the conversion, as if it doesn't all the call to
# MIMEConvertCDParts will raise a "File does not exist error (259)".
# ?*#! -> Weird interaction MAPI to Notes
# This also means that the NotesEntries class that loads nnotes.dll must
# be called here rather that only once when starting NSF2X so that it is
# reloaded after using mapîex.mapi() for multiple NSF files.
#
# If "File not found (259)" errors from MIMEConvertCDParts persist then
# the call to "win32com.client.Dispatch(r'Lotus.NotesSession')" probably
# needs to be in the method realConvert as well, though that will need
# thought about reworking the UI. If after that there are still 259 errors
# then NSF2X should be rewritten to force the user to relaunch after each
# conversion, though that will prevent batch conversion of multiple NSF
# files !!
_NotesEntries = NotesEntries()
stat = _NotesEntries.NSFDbOpen(path)
if stat != 0:
raise ValueError(_("Can not open Lotus database %s with C API (ErrorID %d)") %
(path, stat))
self.log(ErrorLevel.NORMAL, _("Starting MIME encoding of messages"))
for fld in dBNotes.Views:
try:
# If the NSF file is from an older version of Lotus the View might be invalid.
# So in case of an error here, warn the user and continue, rather than raising
# an error
if not (fld.Name == "($Sent)" or fld.IsFolder) or fld.EntryCount <= 0:
if fld.EntryCount > 0:
tl.title(_("Lotus Notes Converter - Phase 1/%d Converting MIME (%.1f%%)") %
(ph, float(10.*c/ac)))
self.update()
if not self.running:
return False
continue
doc = fld.GetFirstDocument()
except:
# FIXME : Can I ensure that fld.Name is always valid ?
self.log(ErrorLevel.WARN, _("Invalid View '%s' in NSF file. Skipping") % fld.Name)
if not self.running:
return False
continue
while doc and (nex < 0 or e < nex): #stop after XXX exceptions...
if not self.running:
return False
subject = doc.GetFirstItem("Subject")
try:
if not self.ConvertToMIME(doc, _NotesEntries):
e += 1
self.log(ErrorLevel.ERROR, _("Can not convert message %d to MIME") % c)
if subject:
self.log(ErrorLevel.ERROR, _("#### Subject : %s") % subject.Text)
except (pywintypes.com_error, OSError) as ex: # pylint: disable=E1101
e += 1
self.log(ErrorLevel.ERROR, _("Exception converting message %d to MIME : %s") %
(c, ex))
if subject:
self.log(ErrorLevel.ERROR, _("#### Subject : %s") % subject.Text)
doc = fld.GetNextDocument(doc)
c += 1
if (c % 20) == 0:
tl.title(_("Lotus Notes Converter - Phase 1/%d Converting MIME (%.1f%%)") %
(ph, float(10.*c/ac)))
self.update()
if e == nex:
self.log(ErrorLevel.ERROR, _("Too many exceptions during MIME conversion. Stopping\n"))
return False
if c <= 0:
raise ValueError(_("The database %s appears to be empty. Returning") % src)
f = None
MAPIrootFolder = None
if self.Format.get() == Format.MBOX and self.MBOXType.get() == SubdirectoryMBOX.NO:
mbox = os.path.join(self.destPath, (dest + ".mbox"))
self.log(ErrorLevel.NORMAL, _("Opening MBOX file - %s") % mbox)
f = open(mbox, "wb")
elif self.Format.get() == Format.PST and not self.EML2PST:
pst = os.path.join(self.destPath, (dest + ".pst"))
# Can't guarantee that MAPISVC.INF contains the service "MSPST MS" and so
# can't use MAPI to create PST. This is now the only place the Outlook
# Object Model is used, and it would be great to get rid of it.
try:
Outlook = win32com.client.Dispatch(r'Outlook.Application')
except pywintypes.com_error as ex: # pylint: disable=E1101
self.log(ErrorLevel.ERROR, _("Could not connect to Outlook !"))
self.log(ErrorLevel.ERROR, _("Exception %s :") % ex)
Outlook = None
ns = Outlook.GetNamespace(r'MAPI')
self.log(ErrorLevel.NORMAL, _("Opening PST file - %s") % pst)
ns.AddStore(pst)
rootFolder = ns.Folders.GetLast()
rootFolder.Name = dest
# Reopen the message store created with OOM and only use MAPI from here
# on out.
try:
MAPI = mapiex.mapi()
MAPI.OpenMessageStore(dest)
MAPIrootFolder = MAPI.OpenRootFolder()
except Exception as ex:
self.log(ErrorLevel.ERROR, _("Could not connect to MAPI !"))
self.log(ErrorLevel.ERROR, _("Exception %s :") % ex)
raise
if self.Format.get() == Format.PST and self.EML2PST:
self.log(ErrorLevel.NORMAL, _("Starting exportation to temporary EML messages"))
else:
self.log(ErrorLevel.NORMAL, _("Starting importation of EML messages into mailbox"))
ac = c # Update all message count
c = 0
e = 0
for fld in dBNotes.Views:
try:
# If the NSF file is from an older version of Lotus the View might be invalid.
# So in case of an error here, warn the user and continue, rather than raising
# an error
if not (fld.Name == "($Sent)" or fld.IsFolder) or fld.EntryCount <= 0:
if fld.EntryCount > 0:
if ph == 3:
tl.title(_("Lotus Notes Converter - Phase 2/3 Export Message %d of %d (%.1f%%)") %
(c, ac, float(10.*(ac + 6.*c)/ac)))
else:
tl.title(_("Lotus Notes Converter - Phase 2/2 Import Message %d of %d (%.1f%%)") %
(c, ac, float(10.*(ac + 9.*c)/ac)))
self.update()
if not self.running:
return False
continue
except:
# FIXME : Can I ensure that fld.Name is always valid ?
self.log(ErrorLevel.WARN, _("Invalid View '%s' in NSF file. Skipping") % fld.Name)
if not self.running:
return False
continue
pstfld = None
if self.Format.get() == Format.EML or (self.Format.get() == Format.PST
and self.EML2PST):
if fld.Name == "($Sent)":
path = os.path.join(self.destPath, dest, _("Sent"))
elif fld.Name == "($Inbox)":
path = os.path.join(self.destPath, dest, _("Inbox"))
else:
path = os.path.join(self.destPath, dest, fld.Name)
try:
if not os.path.exists(path):
os.makedirs(path, 0x755)
self.log(ErrorLevel.NORMAL, _("Creating directory %s") % path)
except OSError as ex:
self.log(ErrorLevel.ERROR, _("Can not create directory %s") % path)
self.log(ErrorLevel.ERROR, "%s :" % ex)
continue
elif self.Format.get() == Format.PST and not self.EML2PST:
if fld.Name == "($Sent)":
pstfld = MAPIrootFolder.CreateSubFolder(_("Sent"))
elif fld.Name == "($Inbox)":
pstfld = MAPIrootFolder.CreateSubFolder(_("Inbox"))
else:
pstfld = MAPIrootFolder.CreateSubFolder(fld.Name)
if not pstfld:
self.log(ErrorLevel.ERROR, _("Could not open folder : %s") % fld.Name)
continue
elif self.Format.get() == Format.MBOX and self.MBOXType.get() == SubdirectoryMBOX.YES:
if fld.Name == "($Sent)":
mbox = os.path.join(self.destPath, dest, (_("Sent") + ".mbox"))
elif fld.Name == "($Inbox)":
mbox = os.path.join(self.destPath, dest, (_("Inbox") + ".mbox"))
else:
mbox = os.path.join(self.destPath, dest, (fld.Name + ".mbox"))
try:
mboxdir = os.path.dirname(mbox)
if not os.path.exists(mboxdir):
os.makedirs(mboxdir, 0x755)
self.log(ErrorLevel.NORMAL, _("Creating directory %s") % mboxdir)
except OSError as ex:
self.log(ErrorLevel.ERROR, _("Can not create directory %s") % mboxdir)
self.log(ErrorLevel.ERROR, "%s :" % ex)
self.log(ErrorLevel.NORMAL, _("Opening MBOX file - %s") % mbox)
f = open(mbox, "wb")
doc = fld.GetFirstDocument()
d = 1
while doc and (nex < 0 or e < nex): #stop after XXX exceptions...
if not self.running:
return False
try:
eml = None
if doc.GetFirstItem("Body") is None:
# This allows the export of message that contain no
# body, as the subject, date and recipients contain
# useful information
self.log(ErrorLevel.INFO, _("Creating Body in message %d") % c)
doc.CreateMIMEEntity()
if doc.GetMIMEEntity("Body") is None:
subject = doc.GetFirstItem("Subject")
form = doc.GetFirstItem("Form")
if not form:
form = "None"
else:
form = form.Text
empty = False
if form in ("Appointment", "Task", "Notice", "Return Receipt",
"Trace Report", "Delivery Report"):
# These are clearly not messages, so ok to ignore them
errlvl = ErrorLevel.WARN
else:
body = doc.GetFirstItem("Body")
if not body or body.ValueLength <= 0:
# This shouldn't be possible after creation of body above
errlvl = ErrorLevel.WARN
empty = True
else:
errlvl = ErrorLevel.ERROR
e += 1
if empty:
self.log(errlvl, _("Ignoring message %d of form '%s' with empty body") % (c, form))
else:
self.log(errlvl, _("Ignoring message %d of form '%s' without MIME body") % (c, form))
if subject:
self.log(errlvl, _("#### Subject : %s") % subject.Text)
if errlvl == ErrorLevel.WARN:
self.log(errlvl, _("Skipping as probably not a message"))
else:
if self.Format.get() != Format.MBOX:
if self.Format.get() == Format.EML or (self.Format.get() == Format.PST
and self.EML2PST):
if fld.Name == "($Sent)":
eml = os.path.join(self.destPath, dest, _("Sent"),
(str(d) + ".eml"))
elif fld.Name == "($Inbox)":
eml = os.path.join(self.destPath, dest, _("Inbox"),
(str(d) + ".eml"))
else:
eml = os.path.join(self.destPath, dest, fld.Name,
(str(d) + ".eml"))
# Need to treat as binary so that windows doesn't convert
# \n\r to \n\n\r
f = open(eml, "wb")
elif self.Format.get() == Format.PST and not self.EML2PST:
(fd, eml) = tempfile.mkstemp(suffix=".eml")
f = os.fdopen(fd, "wb")
if self.WriteMIMEOutput(f, doc):
d += 1
if self.Format.get() == Format.PST and not self.EML2PST:
f.close()
pstfld.ImportEML(eml)
# Done with the temporary EML file. Remove it
if eml != None:
os.remove(eml)