/
mboximport.js
1684 lines (1489 loc) · 56.2 KB
/
mboximport.js
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
/*
ImportExportTools NG is a derivative extension for Thunderbird 60+
providing import and export tools for messages and folders.
The derivative extension authors:
Copyright (C) 2021 : John Bieling, Christopher Leidigh
Copyright (C) 2019 : Christopher Leidigh, The Thunderbird Team
The original extension & derivatives, ImportExportTools, by Paolo "Kaosmos",
is covered by the GPLv3 open-source license (see LICENSE file).
Copyright (C) 2007 : Paolo "Kaosmos"
ImportExportTools NG 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 3 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, see <https://www.gnu.org/licenses/>.
*/
// cleidigh - reformat, services, globals, Streamlisteners
/* eslint-disable no-control-regex */
/* eslint-disable no-useless-concat */
/* eslint-disable no-lonely-if */
/* eslint-disable consistent-return */
/* global IETformatWarning,
getPredefinedFolder,
IETwritestatus,
IETstoreFormat,
GetSelectedMsgFolders,
IETgetSelectedMessages,
isMbox,
IETprefs,
IETgetComplexPref,
nametoascii,
getSubjectForHdr,
IETcopyStrToClip,
SelectFolder,
IETremoteWarning,
IETgetPickerModeFolder,
exportVirtualFolder,
IETglobalMsgFoldersExported,
exportIMAPfolder,
IETcleanName,
IETemlx2eml,
IETescapeBeginningFrom,
IOUtils,
PathUtils,
PrintUtils,
strftime,
*/
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { XPCOMUtils } = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
var FileUtils = ChromeUtils.import("resource://gre/modules/FileUtils.jsm").FileUtils;
XPCOMUtils.defineLazyGlobalGetters(this, ["IOUtils", "PathUtils"]);
var MBstrBundleService = Services.strings;
var mboximportbundle = MBstrBundleService.createBundle("chrome://mboximport/locale/mboximport.properties");
var nosub = mboximportbundle.GetStringFromName("nosubjectmsg");
var mboximportbundle2 = MBstrBundleService.createBundle("chrome://messenger/locale/mime.properties");
var gEMLimported;
var gEMLimportedErrs;
var gEMLtotal;
var gFileEMLarray;
var gFileEMLarrayIndex;
var IETtempfilesize;
var IETcount;
var gNeedCompact;
var gMsgFolderImported;
var IETabort;
// cleidigh where do we get this
var gImporting;
// cleidigh create folder fix
var folderCount;
var IETprintPDFmain = {
print: async function (allMessages) {
// New built in Mozilla PDF driver finally works on OSX - enable for Mac
// Addresses #353
try {
let printSvc = Cc["@mozilla.org/gfx/printsettings-service;1"].getService(Ci.nsIPrintSettingsService);
if (printSvc.defaultPrinterName === "") {
alert(mboximportbundle.GetStringFromName("noPDFnoPrinter"));
return;
}
} catch (e) { }
let msgFolders = GetSelectedMsgFolders();
if (msgFolders.length > 1) {
alert(mboximportbundle.GetStringFromName("noPDFmultipleFolders"));
return;
}
let question = IETformatWarning(1);
if (!question)
return;
question = IETformatWarning(0);
if (!question)
return;
if (!allMessages) {
IETprintPDFmain.uris = IETgetSelectedMessages();
} else {
IETprintPDFmain.uris = [];
let msgFolder = msgFolders[0];
let isVirtFol = msgFolder ? msgFolder.flags & 0x0020 : false;
if (isVirtFol) {
var total = msgFolder.getTotalMessages(false);
for (let i = 0; i < total; i++)
// error handling changed in 102
// https://searchfox.org/comm-central/source/mailnews/base/content/junkCommands.js#428
// Resolves #359
try {
IETprintPDFmain.uris.push(gDBView.getURIForViewIndex(i));
} catch (ex) {
continue; // ignore errors for dummy rows
}
} else {
let msgs = msgFolder.messages;
while (msgs.hasMoreElements()) {
let msg = msgs.getNext();
msg = msg.QueryInterface(Ci.nsIMsgDBHdr);
let uri = msgFolder.getUriForMsg(msg);
IETprintPDFmain.uris.push(uri);
}
}
}
if (!IETprintPDFmain.uris)
return;
IETprintPDFmain.total = IETprintPDFmain.uris.length;
let dir = getPredefinedFolder(2);
if (!dir) {
let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
fp.init(window, mboximportbundle.GetStringFromName("filePickerExport"), Ci.nsIFilePicker.modeGetFolder);
let res = await new Promise(resolve => {
fp.open(resolve);
});
if (res !== Ci.nsIFilePicker.returnOK) {
return;
}
dir = fp.file;
}
IETprintPDFmain.file = dir;
await IETprintPDFmain.saveAsPDF();
},
/**
* Runs through IETprintPDFmain.uris and prints all to PDF
*/
saveAsPDF: async function (pageSettings = {}) {
let fileFormat = IETprefs.getIntPref("extensions.importexporttoolsng.printPDF.fileFormat");
let filePath = IETprintPDFmain.file.path;
let psService = Cc[
"@mozilla.org/gfx/printsettings-service;1"
].getService(Ci.nsIPrintSettingsService);
// pdf changes for 102
// newPrintSettings => createNewPrintSettings()
// printSetting.printToFile deprecated in 102, not needed in 91
let printSettings;
if (psService.newPrintSettings) {
printSettings = psService.newPrintSettings;
} else {
printSettings = psService.createNewPrintSettings();
}
printSettings.isInitializedFromPrinter = true;
printSettings.isInitializedFromPrefs = true;
printSettings.printSilent = true;
printSettings.outputFormat = Ci.nsIPrintSettings.kOutputFormatPDF;
// print setup for PDF printing changed somewhere around 102.3
// also on 91.x The change first appeared in Linux
// the printToFile gets deprecated and replaced by
// outputDestination
// As an XPCOM object you must check property existence
// Addresses #351
if (printSettings.outputDestination !== undefined) {
printSettings.outputDestination = Ci.nsIPrintSettings.kOutputDestinationFile;
}
if (printSettings.printToFile !== undefined) {
printSettings.printToFile = true;
}
if (pageSettings.paperSizeUnit)
printSettings.paperSizeUnit = pageSettings.paperSizeUnit;
if (pageSettings.paperWidth)
printSettings.paperWidth = pageSettings.paperWidth;
if (pageSettings.paperHeight)
printSettings.paperHeight = pageSettings.paperHeight;
if (pageSettings.orientation)
printSettings.orientation = pageSettings.orientation;
if (pageSettings.scaling)
printSettings.scaling = pageSettings.scaling;
if (pageSettings.shrinkToFit)
printSettings.shrinkToFit = pageSettings.shrinkToFit;
if (pageSettings.showBackgroundColors)
printSettings.printBGColors = pageSettings.showBackgroundColors;
if (pageSettings.showBackgroundImages)
printSettings.printBGImages = pageSettings.showBackgroundImages;
if (pageSettings.edgeLeft)
printSettings.edgeLeft = pageSettings.edgeLeft;
if (pageSettings.edgeRight)
printSettings.edgeRight = pageSettings.edgeRight;
if (pageSettings.edgeTop)
printSettings.edgeTop = pageSettings.edgeTop;
if (pageSettings.edgeBottom)
printSettings.edgeBottom = pageSettings.edgeBottom;
if (pageSettings.marginLeft)
printSettings.marginLeft = pageSettings.marginLeft;
if (pageSettings.marginRight)
printSettings.marginRight = pageSettings.marginRight;
if (pageSettings.marginTop)
printSettings.marginTop = pageSettings.marginTop;
if (pageSettings.marginBottom)
printSettings.marginBottom = pageSettings.marginBottom;
if (pageSettings.headerLeft)
printSettings.headerStrLeft = pageSettings.headerLeft;
if (pageSettings.headerCenter)
printSettings.headerStrCenter = pageSettings.headerCenter;
if (pageSettings.headerRight)
printSettings.headerStrRight = pageSettings.headerRight;
if (pageSettings.footerLeft)
printSettings.footerStrLeft = pageSettings.footerLeft;
if (pageSettings.footerCenter)
printSettings.footerStrCenter = pageSettings.footerCenter;
if (pageSettings.footerRight)
printSettings.footerStrRight = pageSettings.footerRight;
let customDateFormat = IETgetComplexPref("extensions.importexporttoolsng.export.filename_date_custom_format");
if (customDateFormat !== "") {
let customDate = strftime.strftime(customDateFormat, new Date());
printSettings.headerStrRight = printSettings.headerStrRight.replace("%d", customDate);
printSettings.headerStrLeft = printSettings.headerStrLeft.replace("%d", customDate);
printSettings.headerStrCenter = printSettings.headerStrCenter.replace("%d", customDate);
printSettings.footerStrRight = printSettings.footerStrRight.replace("%d", customDate);
printSettings.footerStrLeft = printSettings.footerStrLeft.replace("%d", customDate);
printSettings.footerStrCenter = printSettings.footerStrCenter.replace("%d", customDate);
}
//console.log("IETNG: Save as PDF: ", new Date());
//console.log("IETNG: message count: ", IETprintPDFmain.uris.length);
// We can simply by using PrintUtils.loadPrintBrowser eliminating
// the fakeBrowser NB: if the printBrowser does not exist we
// can create with PrintUtils as well
var errCounter = 0;
let mainWindow = Services.wm.getMostRecentWindow("mail:3pane");
for (var msgIdx = 0; msgIdx < IETprintPDFmain.uris.length; msgIdx++) {
let uri = IETprintPDFmain.uris[msgIdx];
try {
let messageService = messenger.messageServiceFromURI(uri);
let aMsgHdr = messageService.messageURIToMsgHdr(uri);
let fileName = fileFormat === 2
? getSubjectForHdr(aMsgHdr, filePath) + ".pdf"
: getSubjectForHdr(aMsgHdr, filePath) + ".ps";
printSettings.toFileName = PathUtils.join(filePath, fileName);
//console.log("IETNG: Start: ", msgIdx + 1, fileName, new Date());
await PrintUtils.loadPrintBrowser(messageService.getUrlForUri(uri).spec);
await PrintUtils.printBrowser.browsingContext.print(printSettings);
//console.log("IETNG: End: ", msgIdx + 1, fileName, new Date());
IETwritestatus(mboximportbundle.GetStringFromName("exported") + ": " + fileName);
// When we got here, everything worked, and reset error counter.
errCounter = 0;
} catch (ex) {
// Something went wrong, wait a bit and try again.
// We did not inc i, so we will retry the same file.
//
errCounter++;
console.log(`Re-trying to print message ${msgIdx + 1} (${uri}).`);
if (errCounter > 3) {
console.log(`We retried ${errCounter} times to print message ${msgIdx + 1} and abort.`);
} else {
// dec idx so next loop repeats msg that erred
msgIdx--;
}
await new Promise(r => mainWindow.setTimeout(r, 150));
}
}
//console.log("IETNG: Save as PDF end: ", msgIdx + 1, new Date());
},
};
function openProfileImportWizard() {
var quit = {};
window.openDialog("chrome://mboximport/content/mboximport/profileImportWizard.xhtml", "", "dialog,chrome,modal,centerscreen", quit);
var appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
.getService(Ci.nsIAppStartup);
if (quit.value)
setTimeout(function () {
appStartup.quit(Ci.nsIAppStartup.eAttemptQuit);
}, 1000);
}
async function openMboxDialog() {
if (IETstoreFormat() !== 0) {
alert(mboximportbundle.GetStringFromName("noMboxStorage"));
return;
}
let msgFolder = GetSelectedMsgFolders()[0];
// we don't import the file in imap or nntp accounts
if ((msgFolder.server.type === "imap") || (msgFolder.server.type === "nntp")) {
alert(mboximportbundle.GetStringFromName("badfolder"));
return;
}
var params = { scandir: false, keepstructure: false, openProfDir: false, recursiveMode: false };
window.openDialog("chrome://mboximport/content/mboximport/mboxdialog.xhtml", "", "chrome,modal,centerscreen", params);
if (params.cancel) {
return;
}
// I have no idea why so many setTimeout are in here, but each spins out of the main thread and
// it is hard to keep track of the actual execution flow. Let us return to sequential coding
// using async/await.
await new Promise(resolve => setTimeout(resolve, 800));
await importmbox(params.scandir, params.keepstructure, params.openProfDir, params.recursiveMode, msgFolder);
}
function msgFolder2LocalFile(msgFolder) {
if (msgFolder.filePath)
var LocalFile = msgFolder.filePath;
return LocalFile;
}
function IETupdateFolder(folder) {
var msgDB = folder.msgDatabase;
msgDB.summaryValid = false;
folder.ForceDBClosed();
folder.updateFolder(msgWindow);
}
async function trytocopyMAILDIR() {
if (IETstoreFormat() !== 1) {
alert(mboximportbundle.GetStringFromName("noMaildirStorage"));
return;
}
// initialize variables
let msgFolder = GetSelectedMsgFolders()[0];
// we don't import the file in imap or nntp accounts
if ((msgFolder.server.type === "imap") || (msgFolder.server.type === "nntp")) {
alert(mboximportbundle.GetStringFromName("badfolder"));
return;
}
var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
fp.init(window, mboximportbundle.GetStringFromName("filePickerImport"), Ci.nsIFilePicker.modeGetFolder);
fp.appendFilters(Ci.nsIFilePicker.filterAll);
let res = await new Promise(resolve => {
fp.open(resolve);
});
if (res !== Ci.nsIFilePicker.returnOK) {
return;
}
var destFile = fp.file;
var filename = destFile.leafName;
var newfilename = filename;
var folderFile = msgFolder2LocalFile(msgFolder);
var clonex = folderFile.clone();
var restoreChar = false;
if (newfilename.match(/#/)) {
var safeChar = Math.floor(Math.random() * 99999).toString();
newfilename = newfilename.replace(/#/g, safeChar);
restoreChar = true;
}
clonex.append(newfilename);
// add to the original filename a random number in range 0-999
if (IETprefs.getBoolPref("extensions.importexporttoolsng.import.name_add_number"))
newfilename = newfilename + Math.floor(Math.random() * 999);
var k = 0;
// if exists a subfolder with this name, we change the random number, with max. 500 tests
// while (msgFolder.containsChildNamed(newfilename)) {
while (msgFolder.containsChildNamed(newfilename) || clonex.exists()) {
newfilename = filename + Math.floor(Math.random() * 999);
k++;
if (k > 500) {
alert("Can't find a good name");
return false;
}
clonex = clonex.parent;
clonex.append(newfilename);
}
// 1. add a subfolder with the name of the folder to import
var newFolder = msgFolder.addSubfolder(newfilename);
if (restoreChar) {
var reg = new RegExp(safeChar, "g");
newFolder.name = newfilename.replace(reg, "#");
}
// 2. find the MAILDIR directory created above
var filex = msgFolder2LocalFile(newFolder);
try {
var destFileClone = destFile.clone();
destFileClone.append("cur");
if (!destFileClone.exists() || !destFileClone.isDirectory()) {
alert(mboximportbundle.GetStringFromName("isNotMaildir"));
return;
}
destFileClone = destFileClone.parent;
destFileClone.append("tmp");
if (!destFileClone.exists() || !destFileClone.isDirectory()) {
alert(mboximportbundle.GetStringFromName("isNotMaildir"));
return;
}
var allfiles = destFile.directoryEntries;
// copy all the files inside the MAILDIR directory to import in MAILDIR directory created above
while (allfiles.hasMoreElements()) {
var singlefile = allfiles.getNext();
singlefile = singlefile.QueryInterface(Ci.nsIFile);
singlefile.copyTo(filex, null);
}
} catch (e) {
return false;
}
// 3. update the database by selecting the folder and rebuilding the index
try {
msgFolder.NotifyItemAdded(newFolder);
SelectFolder(newFolder.URI);
IETupdateFolder(newFolder);
} catch (e) { }
}
// The arguments of trytocopy are
// file = the file to import as nsIFile
// filename = the name of the file to import
// msgFolder = the folder as nsImsgFolder
async function trytocopy(file, filename, msgFolder, keepstructure) {
//console.log("IETNG: trytocopy start");
// If the file isn't mbox format, alert, but doesn't exit (it did in pre 0.5.8 version and lower)
// In fact sometimes TB can import also corrupted mbox files
var isMbx = isMbox(file);
if (isMbx !== 1) {
if (isMbx === 0) {
var continuebundle = MBstrBundleService.createBundle("chrome://messenger/locale/filter.properties");
// We take the "Continue" label from another file...
var continuelabel = continuebundle.GetStringFromName("continueButtonLabel");
var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
var flags = prompts.BUTTON_TITLE_CANCEL * prompts.BUTTON_POS_0 +
prompts.BUTTON_TITLE_IS_STRING * prompts.BUTTON_POS_1 + prompts.BUTTON_POS_0_DEFAULT;
var string = ("\"" + filename + "\" " + mboximportbundle.GetStringFromName("nomboxfile"));
var button = prompts.confirmEx(window, "ImportExportTools NG", string, flags, "Button 0", continuelabel, "", null, {});
if (button === 0)
return false;
} else {
if (!confirm(mboximportbundle.GetStringFromName("isNotStandard")))
return false;
}
}
var filex = msgFolder2LocalFile(msgFolder);
var clonex = filex.clone();
var newfilename = filename;
var restoreChar = false;
if (newfilename.match(/#/)) {
var safeChar = Math.floor(Math.random() * 99999).toString();
newfilename = newfilename.replace(/#/g, safeChar);
restoreChar = true;
}
clonex.append(newfilename);
// add to the original filename a random number in range 0-999
if (IETprefs.getBoolPref("extensions.importexporttoolsng.import.name_add_number"))
newfilename = newfilename + Math.floor(Math.random() * 999);
var k = 0;
// if exists a subfolder with this name, we change the random number, with max. 500 tests
// while (msgFolder.containsChildNamed(newfilename)) {
while (msgFolder.containsChildNamed(newfilename) || clonex.exists()) {
newfilename = filename + Math.floor(Math.random() * 999);
k++;
if (k > 500) {
alert("Can't find a good name");
return false;
}
clonex = clonex.parent;
clonex.append(newfilename);
}
// This is a little strange code, but it can find the destintation folder as nsIFile
// without calling nsIFile.initwithPath. This is done creating a new subfolder,
// finding the parent of this temp new subfolder and deleting the subfolder itself.
// The 0.5.3 version did this scanning all the files into the directory, to find the directory
// called "msgfoldername.sbd". But this doesn't work, because there is a case when
// this directory can miss: when you've deleted before all the subfolders from the GUI,
// without restarting.
// This is a dirty hack, I hope to find in the future something better...
//
// 1. add a subfolder with the name of the folder to import
// let msgWindow = Cc["@mozilla.org/messenger/msgwindow;1"].createInstance(Ci.nsIMsgWindow);
var tempfolder = msgFolder.addSubfolder(newfilename);
// console.debug(tempfolder);
// tempfolder = tempfolder.QueryInterface(Ci.nsIMsgLocalMailFolder);
//console.log("IETNG: add subfolder");
if (restoreChar) {
var reg = new RegExp(safeChar, "g");
tempfolder.name = newfilename.replace(reg, "#");
}
// 2. find the nsIFile of the directory where the file will be copied
if (!msgFolder.isServer) {
var tempfolderNS = msgFolder2LocalFile(tempfolder);
filex = tempfolderNS.parent;
}
// 3. delete the new subfolder, to delete all the files inside "msgfoldername.sbd" directory
// tempfolder.Delete();
tempfolder.msgStore.deleteFolder(tempfolder);
if (!filex) {
alert(mboximportbundle.GetStringFromName("internalerror"));
return false;
}
try {
// Finally copy the mbox file in the "msgfoldername.sbd" directory
// file.copyTo(filex, newfilename);
// cleidigh - have to use leafname for truncated internal names
//console.log("IETNG: start copy: ", new Date());
let src = file.path;
let dst = PathUtils.join(filex.path, tempfolder.filePath.leafName);
console.log(src, dst)
let r = await IOUtils.copy(src, dst);
//file.copyTo(filex, tempfolder.filePath.leafName);
//console.log("IETNG: end copy: ", new Date());
// If this is an export with structure, we try also to export the directory mbox-filename.sbd
if (keepstructure) {
var sbd = file.parent;
sbd.append(file.leafName + ".sbd");
if (sbd.exists())
sbd.copyTo(filex, newfilename + ".sbd");
}
} catch (e) {
return false;
}
// inizialize as nsIFile the folder imported in TB and check if it's writable and readable.
// if not (for ex. a file imported from a cdrom), change the permissions
// filex.append(newfilename);
filex.append(tempfolder.filePath.leafName);
if (!filex.isReadable() || !filex.isWritable())
filex.permissions = 420;
// the following code of this subfunction has been written with the help of Frank Ausdilecce
// really thanks for his help
var newFolder = tempfolder;
// At this location was a call to msgFolder.NotifyItemAdded inside a try catch wich was not doing
// anything for ages. The correct call would be msgFolder.notifyFolderAdded(newFolder);
// BUT I think this is too early as the folder is not actually created
//msgFolder.notifyFolderAdded(newFolder);
var forceCompact = addEmptyMessageToForceCompact(newFolder);
if (forceCompact && !gNeedCompact)
gNeedCompact = true;
var obj = {};
obj.msgFolder = newFolder;
obj.forceCompact = forceCompact;
//console.log("IETNG: compacted");
if (keepstructure) {
gMsgFolderImported.push(obj);
if (newFolder.hasSubFolders) {
// I have no idea why so many setTimeout are in here, but each spins
// out of the main thread and it is hard to keep track of the actual
// execution flow. Let us return to sequential coding.
await new Promise(resolve => setTimeout(resolve, 1000));
storeImportedSubFolders(newFolder);
}
} else {
gMsgFolderImported.push(obj);
}
//console.log("IETNG: rebuild foldertree");
gFolderTreeView._rebuild();
//console.log("IETNG: end trytocopy: ", new Date());
return newfilename;
}
function storeImportedSubFolders(msgFolder) {
if (msgFolder.subFolders) {
for (let subfolder of msgFolder.subFolders) {
let obj = {};
obj.msgFolder = subfolder;
obj.forceCompact = false;
gMsgFolderImported.push(obj);
// If the subfolder has subfolders, the function calls itself.
if (subfolder.hasSubFolders)
storeImportedSubFolders(subfolder);
}
}
}
function addEmptyMessageToForceCompact(msgFolder) {
var file = msgFolder2LocalFile(msgFolder);
var istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
istream.init(file, 0x01, 0444, 0);
istream.QueryInterface(Ci.nsILineInputStream);
var line = {};
var first3lines = "";
for (var i = 0; i < 4; i++) {
istream.readLine(line);
first3lines = first3lines + line.value + "\n";
}
istream.close();
if (first3lines.indexOf("X-Mozilla-Status") > -1) {
return false;
}
// Probably this is not a Thunderbird/Mozilla mbox file, because is missing of X-Mozilla-Status fields
// The only way to write X-Mozilla-Status in all messages is to force compacting after import
// Thunderbird will compact just there are bites to expunge, so we add at the end of the mbox file
// a fake deleted message
var foStream = Cc["@mozilla.org/network/file-output-stream;1"].
createInstance(Ci.nsIFileOutputStream);
var data = "\n\nFrom Moon\nX-Mozilla-Status: 0009\nX-Mozilla-Status2: 00800000\nDate: Fri, 08 Feb 2008 10:30:48 +0100\nFrom: nomail@nomail.no\nMIME-Version: 1.0\nTo: nomail@nomail.no\nSubject: empty\nContent-Type: text/plain\n\n\n\n";
foStream.init(file, 0x02 | 0x08 | 0x10, 0666, 0);
foStream.write(data, data.length);
foStream.close();
return true;
}
// these lines *should* create the msf file
async function buildMSGfile(scan) {
for (var i = 0; i < gMsgFolderImported.length; i++) {
try {
var folder = gMsgFolderImported[i].msgFolder;
IETupdateFolder(folder);
} catch (e) { }
// I have no idea why so many setTimeout are in here, but each spins out
// of the main thread and it is hard to keep track of the actual execution
// flow. Let us return to sequential coding.
await new Promise(resolve => setTimeout(resolve, 2000));
await updateImportedFolder(folder, gMsgFolderImported[i].forceCompact);
}
gMsgFolderImported = [];
if (scan)
IETwritestatus(mboximportbundle.GetStringFromName("endscan"));
}
async function updateImportedFolder(msgFolder, forceCompact) {
try {
msgFolder.updateSummaryTotals(true);
} catch (e) { }
try {
msgFolder.summaryChanged();
} catch (e) { }
if (forceCompact)
msgFolder.compact(null, msgWindow);
}
// scandir flag is to know if the function must scan a directory or just import mbox file(s)
async function importmbox(scandir, keepstructure, openProfDir, recursiveMode, msgFolder) {
// mbox import debug #367
/*
console.log("IETNG: mboximport start: ", new Date());
console.log("IETNG: scandir: ", scandir)
console.log("IETNG: keepstructure: ", keepstructure);
console.log("IETNG: openProfDir: ", openProfDir);
console.log("IETNG: recursiveMode: ", recursiveMode);
console.log("IETNG: msgFolder: ", msgFolder.name);
//console.log("IETNG: ")
*/
// initialize variables
gMsgFolderImported = [];
gNeedCompact = false;
var buildMSF = IETprefs.getBoolPref("extensions.importexporttoolsng.import.build_mbox_index");
var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
var profDir;
var filesArray;
var mboxname;
if (!scandir) {
// open the filepicker
fp.init(window, mboximportbundle.GetStringFromName("filePickerImport"), Ci.nsIFilePicker.modeOpenMultiple);
fp.appendFilters(Ci.nsIFilePicker.filterAll);
if (openProfDir) {
profDir = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties)
.get("ProfD", Ci.nsIFile);
fp.displayDirectory = profDir.parent;
}
let res = await new Promise(resolve => {
fp.open(resolve);
});
if (res !== Ci.nsIFilePicker.returnOK) {
return;
}
// thefiles is the nsiSimpleEnumerator with the files selected from the filepicker
var thefiles = fp.files;
//console.log("IETNG: flat import ", thefiles);
while (thefiles.hasMoreElements()) {
var onefile = thefiles.getNext();
onefile = onefile.QueryInterface(Ci.nsIFile);
mboxname = onefile.leafName;
//console.log("IETNG: call trycopy: ", mboxname);
await trytocopy(onefile, mboxname, msgFolder, keepstructure);
}
} else {
// Open the filepicker to choose the directory
fp.init(window, mboximportbundle.GetStringFromName("searchdir"), Ci.nsIFilePicker.modeGetFolder);
if (openProfDir) {
profDir = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties)
.get("ProfD", Ci.nsIFile);
fp.displayDirectory = profDir.parent;
}
let res = await new Promise(resolve => {
fp.open(resolve);
});
if (res !== Ci.nsIFilePicker.returnOK) {
return;
}
if (!recursiveMode) {
// allfiles is the nsiSimpleEnumerator with the files in the directory selected from the filepicker
var allfiles = fp.file.directoryEntries;
filesArray = [];
while (allfiles.hasMoreElements()) {
var singlefile = allfiles.getNext();
singlefile = singlefile.QueryInterface(Ci.nsIFile);
filesArray.push(singlefile);
}
} else {
filesArray = MBOXIMPORTscandir.find(fp.file);
}
var importThis;
// scanning the directory to search files that could be mbox files
for (var i = 0; i < filesArray.length; i++) {
var afile = filesArray[i];
mboxname = afile.leafName;
var mboxpath = afile.path;
if (isMbox(afile) === 1) {
var ask = IETprefs.getBoolPref("extensions.importexporttoolsng.confirm.before_mbox_import");
if (ask) {
var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Ci.nsIPromptService);
var checkObj = {};
checkObj.value = false;
var flags = prompts.BUTTON_TITLE_YES * prompts.BUTTON_POS_0 +
prompts.BUTTON_TITLE_NO * prompts.BUTTON_POS_2 +
prompts.BUTTON_TITLE_CANCEL * prompts.BUTTON_POS_1 +
prompts.BUTTON_POS_0_DEFAULT;
var string = mboximportbundle.GetStringFromName("confirmimport") + ' "' + mboxpath + '" ?';
var button = prompts.confirmEx(window, "ImportExportTools NG", string, flags, "", "", "", mboximportbundle.GetStringFromName("noWaring"), checkObj);
IETprefs.setBoolPref("extensions.importexporttoolsng.confirm.before_mbox_import", !checkObj.value);
if (button === 0)
importThis = true;
else if (button === 2)
importThis = false;
else
break;
} else {
importThis = true;
}
if (importThis && afile.isFile())
await trytocopy(afile, mboxname, msgFolder);
}
}
}
if (buildMSF || gNeedCompact) {
// I have no idea why so many setTimeout are in here, but each spins out
// of the main thread and it is hard to keep track of the actual execution
// flow. Let us return to sequential coding.
let timeout = keepstructure ? 2000 : 1000;
await new Promise(resolve => setTimeout(resolve, timeout));
await buildMSGfile();
}
}
async function exportfolder(subfolder, keepstructure, locale, zip) {
//console.log("Start: ExportFolders (mbox)");
var folders = GetSelectedMsgFolders();
/*
console.log(" Subfolders:", subfolder);
console.log(" Structured: ", keepstructure);
console.log(" Local: ", locale);
console.log(" Zip: ", zip);
console.log(folders);
*/
for (var i = 0; i < folders.length; i++) {
var isVirtualFolder = folders[i] ? folders[i].flags & 0x0020 : false;
if ((i > 0 && folders[i].server.type !== lastType) || (folders.length > 1 && isVirtualFolder)) {
alert(mboximportbundle.GetStringFromName("noFolderExport"));
return;
}
var lastType = folders[i].server.type;
}
if (locale && (lastType === "imap" || lastType === "nntp")) {
var go = IETremoteWarning();
if (!go)
return;
}
var destdirNSIFILE = getPredefinedFolder(0);
if (!destdirNSIFILE) {
destdirNSIFILE = IETgetPickerModeFolder();
if (!destdirNSIFILE)
return;
}
if (zip) {
if (!String.prototype.trim)
alert(mboximportbundle.GetStringFromName("needTB3"));
else
IETexportZip(destdirNSIFILE, folders);
return;
}
if (locale) {
//console.log("Using exportSingleLocaleFolder");
for (let i = 0; i < folders.length; i++)
await exportSingleLocaleFolder(folders[i], subfolder, keepstructure, destdirNSIFILE);
} else if (folders.length === 1 && isVirtualFolder) {
exportVirtualFolder(msgFolder); //msgFolder?
} else {
exportRemoteFolders(destdirNSIFILE);
}
}
function IETexportZip(destdirNSIFILE, folders) {
for (var i = 0; i < folders.length; i++) {
var zipFile = destdirNSIFILE.clone();
var file = msgFolder2LocalFile(folders[i]);
if (file.exists()) {
var path = file.leafName;
// see https://bugzilla.mozilla.org/show_bug.cgi?id=445065
// and http://ant.apache.org/manual/Tasks/zip.html#encoding
path = path.replace(/[^a-zA-Z0-9\-]/g, "_");
var zipName = folders[i].name;
zipFile.append(zipName + ".zip");
var zipWriter = Components.Constructor("@mozilla.org/zipwriter;1", "nsIZipWriter");
var zipW = new zipWriter();
zipW.open(zipFile, 0x04 | 0x08 | 0x20);
if (file.isDirectory())
IETaddFolderContentsToZip(zipW, file, "");
else
zipW.addEntryFile(path, Ci.nsIZipWriter.COMPRESSION_DEFAULT, file, false);
zipW.close();
}
}
}
function IETaddFolderContentsToZip(zipW, folder, root) {
var entries = folder.directoryEntries;
while (entries.hasMoreElements()) {
var entry = entries.getNext();
entry.QueryInterface(Ci.nsIFile);
zipW.addEntryFile(root + entry.leafName, Ci.nsIZipWriter.COMPRESSION_DEFAULT, entry, false);
if (entry.isDirectory())
IETaddFolderContentsToZip(zipW, entry, root + entry.leafName + "/");
}
}
function exportRemoteFolders(destdirNSIFILE) {
let IETglobalMsgFolders = GetSelectedMsgFolders();
if (IETglobalMsgFolders[0].isServer)
return;
// cleidigh ?
IETglobalMsgFoldersExported = 0;
exportIMAPfolder(IETglobalMsgFolders[0], destdirNSIFILE);
}
// The subfolder argument is true if we have to export also the subfolders
async function exportSingleLocaleFolder(msgFolder, subfolder, keepstructure, destdirNSIFILE) {
var filex = msgFolder2LocalFile(msgFolder);
// thefoldername=the folder name displayed in TB (for ex. "Modelli")
var thefoldername = IETcleanName(msgFolder.name);
var newname;
//console.log("Start: exportSingleLocaleFolder");
//console.log(" SrcPath: ", filex.path);
//console.log(" Folder: ", thefoldername);
//console.log("")
// Check if we're exporting a simple mail folder, a folder with its subfolders or all the folders of the account
if (msgFolder.isServer) {
console.log("Exporting server");
console.log(msgFolder.filePath.path);
console.log(msgFolder.prettyName);
let destPath = destdirNSIFILE.path;
await exportAccount(msgFolder.prettyName, msgFolder.filePath.path, destPath);
IETwritestatus(mboximportbundle.GetStringFromName("exportOK"));
} else if (subfolder && !keepstructure) {
// export the folder with the subfolders
// first we copy the folder, finding a good name from its displayed name
newname = findGoodFolderName(thefoldername, destdirNSIFILE, false);
if (filex.exists())
filex.copyTo(destdirNSIFILE, newname);
// then we export the subfolders
exportSubFolders(msgFolder, destdirNSIFILE, keepstructure);
IETwritestatus(mboximportbundle.GetStringFromName("exportOK"));
} else if (subfolder && msgFolder.hasSubFolders && keepstructure) {
//console.log("Exporting with subfolders");
newname = findGoodFolderName(thefoldername, destdirNSIFILE, true);
console.log(newname);
if (filex.exists()) {
console.log("Copy ", newname);
filex.copyTo(destdirNSIFILE, newname);
} else {
// This fixes #320
// imap profile folders do not have empty
// mbox files. We create one if we encounter
// an msf file, but no mbox file.
// This must have changed...
var topdestdirNSI = destdirNSIFILE.clone();
topdestdirNSI.append(newname);
topdestdirNSI.create(0, 0644);
//console.log("Created: ", topdestdirNSI.leafName);
}
var sbd = filex.parent;
sbd.append(filex.leafName + ".sbd");
if (sbd) {
sbd.copyTo(destdirNSIFILE, newname + ".sbd");
//console.log("Copied: ", sbd.path);
var destdirNsFile = destdirNSIFILE.clone();
destdirNsFile.append(newname + ".sbd");
var listMSF = MBOXIMPORTscandir.find(destdirNsFile);
for (let i = 0; i < listMSF.length; ++i) {
if (listMSF[i].leafName.substring(listMSF[i].leafName.lastIndexOf(".")) === ".msf") {
try {
listMSF[i].remove(false);
let fname = listMSF[i].path.split(".msf")[0];
var nsifile = new FileUtils.File(fname);
if (!nsifile.exists()) {
nsifile.create(0, 0644);
}
} catch (e) {
console.log(e);
}
}
}
}
IETwritestatus(mboximportbundle.GetStringFromName("exportOK"));
} else {
// export just the folder
newname = findGoodFolderName(thefoldername, destdirNSIFILE, false);
if (filex.exists())
filex.copyTo(destdirNSIFILE, newname);
IETwritestatus(mboximportbundle.GetStringFromName("exportOK"));
}
}
// Rewrite / fix account level export - use IOUtils #296
async function exportAccount(accountName, accountFolderPath, destPath) {
console.log("Start: exportAccount");
console.log(" SrcPath: ", accountFolderPath);
console.log(" srcFolder: ", accountName);
console.log(" destPath: ", destPath);