-
Notifications
You must be signed in to change notification settings - Fork 0
/
GSoCFinalSubmission.patch
6523 lines (6405 loc) · 249 KB
/
GSoCFinalSubmission.patch
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
# This is the patch containing all my changes for the import wizard during
# the Google Summer of Code 2012 coding period. There are many changes to files
# in here that I omitted from this repository (many Makefile changes, etc.)
diff --git a/chat/Makefile.in b/chat/Makefile.in
--- a/chat/Makefile.in
+++ b/chat/Makefile.in
@@ -21,16 +21,17 @@ ifdef MOZ_DEBUG
PROTOCOLS += jsTest
endif
PREF_JS_EXPORTS = $(srcdir)/chat-prefs.js
PARALLEL_DIRS = \
components/public \
components/src \
+ content \
+ importers \
+ locales \
modules \
- content \
+ $(foreach proto,$(PROTOCOLS),protocols/$(proto)) \
themes \
- locales \
- $(foreach proto,$(PROTOCOLS),protocols/$(proto)) \
$(NULL)
include $(topsrcdir)/config/rules.mk
diff --git a/chat/components/public/Makefile.in b/chat/components/public/Makefile.in
--- a/chat/components/public/Makefile.in
+++ b/chat/components/public/Makefile.in
@@ -13,16 +13,17 @@ MODULE = chat
XPIDLSRCS = \
imIAccount.idl \
imIAccountsService.idl \
imICommandsService.idl \
imIContactsService.idl \
imIConversationsService.idl \
imICoreService.idl \
+ imIImportersService.idl \
imILogger.idl \
imIStatusInfo.idl \
imITagsService.idl \
imIUserStatusInfo.idl \
prplIConversation.idl \
prplIMessage.idl \
prplIPref.idl \
prplIProtocol.idl \
diff --git a/chat/components/public/imIImportersService.idl b/chat/components/public/imIImportersService.idl
new file mode 100644
--- /dev/null
+++ b/chat/components/public/imIImportersService.idl
@@ -0,0 +1,89 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+#include "nsISimpleEnumerator.idl"
+#include "nsIObserver.idl"
+#include "imIAccount.idl"
+
+[scriptable, uuid(c6363da8-04a9-4347-972a-8940ded9cde0)]
+interface imIExistingAccount: nsISupports {
+ readonly attribute AUTF8String name;
+ readonly attribute AUTF8String protocolId;
+ readonly attribute AUTF8String importerId;
+
+ // This time is used to approximate which account is more relevant if a
+ // conflict occurs. A value of 0 indicates this is unknown.
+ attribute PRTime dateModified;
+
+ attribute boolean autoLogin;
+ attribute AUTF8String password;
+ attribute AUTF8String alias;
+
+ // returns an enumerator of prplIPref containing default values set different
+ // than the protocol defaults.
+ nsISimpleEnumerator getOptions();
+
+ // Set the protocol specific options
+ void setBool(in string aName, in boolean aVal);
+ void setInt(in string aName, in long aVal);
+ void setString(in string aName, in AUTF8String aVal);
+};
+
+[scriptable, uuid(59fd4143-c8ab-4e55-b139-98b57e10bcee)]
+interface imIImporter: nsISupports {
+ readonly attribute AUTF8String name;
+ readonly attribute AUTF8String id;
+
+ // Searches for accounts configured by the client software.
+ // When found, the imIImportersService is notified.
+ //
+ // Supported notifications:
+ // importer-found-account
+ // aSubject points to the imImportedAccount found.
+ // importer-search-finished
+ void findAccounts(in nsIObserver aObserver);
+
+ // Handles the task of importing data for an account found from findAccounts.
+ // This method should update its status after completing a task by notifying
+ // 'import-status-updated' with any needed status information in aData.
+ //
+ // Supported notifications:
+ // import-status-updated
+ // aSubject is the aAccount which owns the data.
+ // aData is the preference string with updated status.
+ void importData(in imIAccount aAccount, in string aPreference,
+ in nsIObserver aObserver);
+};
+
+[scriptable, uuid(d1f32c53-2272-4852-9564-4ab00f92b4dd)]
+interface imIImportersService: nsISupports {
+ // Sets the service to observe idle notifications if pending importable data
+ // remains.
+ void initImporters();
+
+ // Closes any observation of idle notifications.
+ void unInitImporters();
+
+ // Returns an instance of an imIImporter based on ID.
+ imIImporter getImporterById(in AUTF8String aImporterId);
+
+ // Each importer checks for available accounts.
+ // The observer (UI) will be notified of new accounts discovered.
+ //
+ // Supported notifications:
+ // existing-account-found
+ // aSubject points to the imImportedAccount found.
+ // account-search-finished
+ void findAccounts(in nsIObserver aObserver);
+
+ // When an account is created, it must be queued for importing data. This
+ // creates the preference indicating an awaiting import.
+ void queueAccount(in string aAccountId, in string aImporterId);
+
+ // observe should only be called by the imIImporter implementations to report
+ // changes.
+ void observe(in nsISupports aObject, in string aTopic,
+ [optional] in wstring aData);
+};
diff --git a/chat/components/public/imILogger.idl b/chat/components/public/imILogger.idl
--- a/chat/components/public/imILogger.idl
+++ b/chat/components/public/imILogger.idl
@@ -37,19 +37,23 @@ interface imILogConversation: nsISupport
interface imILog: nsISupports {
readonly attribute AUTF8String path;
readonly attribute PRTime time;
readonly attribute AUTF8String format;
// Will return null if the log format isn't json.
imILogConversation getConversation();
};
-[scriptable, uuid(ab38c01c-2245-4279-9437-1d6bcc69d556)]
+[scriptable, uuid(f038b621-6419-475d-9621-e86ba055f777)]
interface imILogger: nsISupports {
imILog getLogFromFile(in nsIFile aFile);
nsIFile getLogFileForOngoingConversation(in prplIConversation aConversation);
nsISimpleEnumerator getLogsForAccountBuddy(in imIAccountBuddy aAccountBuddy);
nsISimpleEnumerator getLogsForBuddy(in imIBuddy aBuddy);
nsISimpleEnumerator getLogsForContact(in imIContact aContact);
nsISimpleEnumerator getLogsForConversation(in prplIConversation aConversation);
nsISimpleEnumerator getSystemLogsForAccount(in imIAccount aAccount);
nsISimpleEnumerator getSimilarLogs(in imILog aLog);
+
+ // Adds a conversation manually, optionally dated in the past.
+ void logConversation(in prplIConversation aConversation,
+ [optional] in PRTime aDate);
};
diff --git a/chat/components/src/Makefile.in b/chat/components/src/Makefile.in
--- a/chat/components/src/Makefile.in
+++ b/chat/components/src/Makefile.in
@@ -10,13 +10,14 @@ VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
EXTRA_COMPONENTS = \
imAccounts.js imAccounts.manifest \
imCommands.js imCommands.manifest \
imContacts.js imContacts.manifest \
imConversations.js imConversations.manifest \
imCore.js imCore.manifest \
+ imImporters.js imImporters.manifest \
logger.js logger.manifest \
smileProtocolHandler.js smileProtocolHandler.manifest \
$(NULL)
include $(topsrcdir)/config/rules.mk
diff --git a/chat/components/src/imCore.js b/chat/components/src/imCore.js
--- a/chat/components/src/imCore.js
+++ b/chat/components/src/imCore.js
@@ -261,16 +261,17 @@ CoreService.prototype = {
Services.obs.notifyObservers(aSubject, aTopic, aData);
}
});
let accounts = Services.accounts;
accounts.initAccounts();
Services.contacts.initContacts();
Services.conversations.initConversations();
+ Services.importers.initImporters();
Services.obs.notifyObservers(this, "prpl-init", null);
if (accounts.autoLoginStatus == Ci.imIAccountsService.AUTOLOGIN_ENABLED)
accounts.processAutoLogin();
},
observe: function(aObject, aTopic, aData) {
if (aTopic == kQuitApplicationGranted)
this.quit();
@@ -281,16 +282,17 @@ CoreService.prototype = {
Services.obs.removeObserver(this, kQuitApplicationGranted);
Services.obs.notifyObservers(this, "prpl-quit", null);
Services.conversations.unInitConversations();
Services.accounts.unInitAccounts();
Services.contacts.unInitContacts();
Services.cmd.unInitCommands();
+ Services.importers.unInitImporters();
this.globalUserStatus.unInit();
delete this.globalUserStatus;
delete this._protos;
delete this._initialized;
},
getProtocols: function() {
diff --git a/chat/components/src/imImporters.js b/chat/components/src/imImporters.js
new file mode 100644
--- /dev/null
+++ b/chat/components/src/imImporters.js
@@ -0,0 +1,226 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource:///modules/imXPCOMUtils.jsm");
+Cu.import("resource:///modules/imServices.jsm");
+
+XPCOMUtils.defineLazyServiceGetter(this, "categoryManager",
+ "@mozilla.org/categorymanager;1",
+ "nsICategoryManager");
+
+const kImporterPluginCategory = "im-import-plugin";
+const kImportIdleSeconds = 60;
+
+function ImportersService() { }
+ImportersService.prototype = {
+ // Called when the core initializes. If data importing has not been completed,
+ // it will be scheduled in the idleService.
+ initImporters: function() {
+ let enabled = Services.prefs.getBoolPref("messenger.importWizard.enabled");
+ if (this._pendingImport() && enabled)
+ this._monitorIdleness();
+ },
+
+ unInitImporters: function() {
+ if (this._monitoringIdleness) {
+ this._idleService.removeIdleObserver(this, kImportIdleSeconds);
+ this._monitoringIdleness = false;
+ this._idleService = null;
+ }
+ },
+
+ _idle: false,
+ _monitoringIdleness: false,
+ _monitorIdleness: function() {
+ if (this._monitoringIdleness)
+ return;
+ this._idleService = Cc["@mozilla.org/widget/idleservice;1"]
+ .getService(Ci.nsIIdleService);
+ this._idleService.addIdleObserver(this, kImportIdleSeconds);
+ this._monitoringIdleness = true;
+ },
+
+ // Determines whether there is data awaiting import.
+ _pendingImport: function() {
+ let accounts = Services.prefs.getCharPref("messenger.accounts").split(",");
+ for each (let accountId in accounts) {
+ let prefName = "messenger.account." + accountId + ".import";
+ if (Services.prefs.prefHasUserValue(prefName))
+ return true;
+ }
+ return false;
+ },
+
+ findAccounts: function(aObserver) {
+ this._findAccObserver = aObserver;
+
+ // Locate the registered importers and create instances.
+ this._importers = [];
+ let importers = this.getImporters();
+ while (importers.hasMoreElements())
+ this._importers.push(importers.getNext().QueryInterface(Ci.imIImporter));
+
+ // If there are no importers registered, the observer still needs a signal.
+ if (!this._importers.length) {
+ this._findAccObserver.observe(this, "account-search-finished", null);
+ return;
+ }
+
+ // Call the account search method on each importer. The use of executeSoon
+ // is to prevent race conditions when calling observe() on the UI from the
+ // importers.
+ for each (let importer in this._importers) {
+ try {
+ let findAccounts = importer.findAccounts;
+ executeSoon(function() {
+ try {
+ findAccounts(this);
+ } catch(e) {
+ Cu.reportError("Error in importer findAccounts(): " + e.message);
+ this.observe(importer, "account-search-finished", null);
+ }
+ }.bind(this));
+ }
+ catch (e) {
+ Cu.reportError("Error calling findAccounts(): " + e.message);
+ }
+ }
+ },
+
+ queueAccount: function(aAccountId, aImporterId) {
+ let prefName = "messenger.account." + aAccountId + ".import";
+ if (Services.prefs.prefHasUserValue(prefName)) {
+ // Throw an error if the pref exists; maybe there is further action to
+ // take here? The UI should not allow the user to add the same account
+ // twice.
+ let error = "Account " + aAccountId + " has an existing importer " +
+ "preference: " + Services.prefs.getCharPref(prefName);
+ Cu.reportError(error);
+ return;
+ }
+
+ // Write the initial import preference.
+ let pref = JSON.stringify({account: aAccountId, importer: aImporterId});
+ Services.prefs.setCharPref(prefName, pref);
+ },
+
+ observe: function(aSubject, aTopic, aData) {
+ if (aTopic === "existing-account-found") {
+ this._findAccObserver.observe(aSubject, "existing-account-found", null);
+ }
+ else if (aTopic === "account-search-finished") {
+ let importerIndex = this._importers.indexOf(aSubject);
+ if (importerIndex !== -1)
+ this._importers.splice(importerIndex, 1);
+ if (!this._importers.length)
+ this._findAccObserver.observe(this, "account-search-finished", null);
+ }
+ else if (aTopic === "import-status-updated") {
+ let [account, pref] = [aSubject, aData];
+ let prefName = "messenger.account." + account.id + ".import";
+
+ // The import is finished for this account.
+ if (!pref) {
+ Services.prefs.clearUserPref(prefName);
+ return;
+ }
+ Services.prefs.setCharPref(prefName, pref);
+
+ // The user has returned from idle, yet importing remains. The
+ // next task will be postponed until idle occurs again.
+ if (!this._idle)
+ return;
+
+ let importer = this.getImporterById(JSON.parse(pref).importer);
+ let importData = importer.importData;
+ executeSoon(function() {
+ try {
+ importData(account, pref, this);
+ } catch(e) {
+ Cu.reportError("Error in importer importData(): " + e.message);
+ }
+ }.bind(this));
+ }
+ else if (aTopic === "idle") {
+ this._idle = true;
+
+ // If we have received this notification and there is no pending import,
+ // the idle observation can be removed; it would be added again if new
+ // accounts were selected for import.
+ if (!this._pendingImport()) {
+ this.unInitImporters();
+ return;
+ }
+
+ let accts = Services.prefs.getCharPref("messenger.accounts").split(",");
+ for each (let accountId in accts) {
+ // Check accounts for the pref indicating awaiting importable data.
+ let prefName = "messenger.account." + accountId + ".import";
+ if (!Services.prefs.prefHasUserValue(prefName))
+ continue;
+
+ let dataObj = Services.prefs.getCharPref(prefName);
+ dataObj = JSON.parse(dataObj);
+
+ // Distribute initial call to import the data. The service observer
+ // will make future calls as necessary.
+ let account = Services.accounts.getAccountById(accountId);
+ let importer = this.getImporterById(dataObj.importer);
+ let importData = importer.importData;
+ executeSoon(function() {
+ try {
+ importData(account, JSON.stringify(dataObj), this);
+ } catch(e) {
+ Cu.reportError("Error in importer importData(): " + e.message);
+ }
+ }.bind(this));
+ }
+ }
+ else if (aTopic === "back")
+ this._idle = false;
+ },
+
+ getImporters: function() {
+ let importers = [];
+ let entries = categoryManager.enumerateCategory(kImporterPluginCategory);
+ while (entries.hasMoreElements()) {
+ let id = entries.getNext().QueryInterface(Ci.nsISupportsCString).data;
+ let importer = this.getImporterById(id);
+ if (importer)
+ importers.push(importer);
+ }
+ return new nsSimpleEnumerator(importers);
+ },
+
+ getImporterById: function(aImporterId) {
+ let cid;
+ try {
+ cid = categoryManager.getCategoryEntry(kImporterPluginCategory, aImporterId);
+ } catch (e) {
+ return null; // no importer registered for this id.
+ }
+
+ let importer = null;
+ try {
+ importer = Cc[cid].createInstance(Ci.imIImporter);
+ } catch (e) {
+ // This is a real error, the importer is registered and failed to init.
+ let error = "failed to create an instance of " + cid + ": " + e;
+ Cu.reportError(error);
+ }
+ if (!importer)
+ return null;
+
+ return importer;
+ },
+
+ QueryInterface: XPCOMUtils.generateQI([Ci.imIImportersService]),
+ classDescription: "Importers",
+ classID: Components.ID("{d1f32c53-2272-4852-9564-4ab00f92b4dd}"),
+ contractID: "@mozilla.org/chat/importers-service;1"
+};
+
+const NSGetFactory = XPCOMUtils.generateNSGetFactory([ImportersService]);
diff --git a/chat/components/src/imImporters.manifest b/chat/components/src/imImporters.manifest
new file mode 100644
--- /dev/null
+++ b/chat/components/src/imImporters.manifest
@@ -0,0 +1,2 @@
+component {d1f32c53-2272-4852-9564-4ab00f92b4dd} imImporters.js
+contract @mozilla.org/chat/importers-service;1 {d1f32c53-2272-4852-9564-4ab00f92b4dd}
diff --git a/chat/components/src/logger.js b/chat/components/src/logger.js
--- a/chat/components/src/logger.js
+++ b/chat/components/src/logger.js
@@ -22,34 +22,52 @@ const ConverterInputStream = CC("@mozill
"nsIConverterInputStream",
"init");
const LocalFile = CC("@mozilla.org/file/local;1",
"nsILocalFile",
"initWithPath");
const kLineBreak = "@mozilla.org/windows-registry-key;1" in Cc ? "\r\n" : "\n";
+function encodeName(aName){
+ // Reserved device names by Windows.
+ let reservedNames = ["CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3",
+ "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3",
+ "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"];
+ if (reservedNames.indexOf(aName.toUpperCase()) != -1)
+ return "%" + aName;
+ // "." and " " mustn’t be at the end of a file or folder name, appending "_".
+ if (/[\. _]/.test(aName.slice(-1)))
+ aName += "_";
+ // Reserved characters are replaced by %[hex value]. encodeURIComponent() is
+ // not sufficient, nevertheless decodeURIComponent() can be used to decode.
+ function encodeReservedChars(match) "%" + match.charCodeAt(0).toString(16);
+ return aName.replace(/[<>:"\/\\|?*&%]/g, encodeReservedChars);
+}
+
function getLogFolderForAccount(aAccount, aCreate)
{
let file = logDir.clone();
function createIfNotExists(aFile) {
if (aCreate && !aFile.exists())
aFile.create(Ci.nsIFile.DIRECTORY_TYPE, 0777);
}
createIfNotExists(file);
file.append(aAccount.protocol.normalizedName);
createIfNotExists(file);
- file.append(aAccount.normalizedName);
+ file.append(encodeName(aAccount.normalizedName));
createIfNotExists(file);
return file;
}
-function getNewLogFileName(aFormat)
+function getNewLogFileName(aFormat, aDate)
{
let date = new Date();
+ if (aDate)
+ date = aDate;
let dateTime = date.toLocaleFormat("%Y-%m-%d.%H%M%S");
let offset = date.getTimezoneOffset();
if (offset < 0) {
dateTime += "+";
offset *= -1;
}
else
dateTime += "-";
@@ -57,64 +75,81 @@ function getNewLogFileName(aFormat)
offset = (offset - minutes) / 60;
function twoDigits(aNumber)
aNumber == 0 ? "00" : aNumber < 10 ? "0" + aNumber : aNumber;
if (!aFormat)
aFormat = "txt";
return dateTime + twoDigits(offset) + twoDigits(minutes) + "." + aFormat;
}
+// Performs the disk writing of the log files
+function LogWriter(aFile) {
+ let outputStream = Cc["@mozilla.org/network/file-output-stream;1"].
+ createInstance(Ci.nsIFileOutputStream);
+ const PR_WRITE_ONLY = 0x02;
+ const PR_CREATE_FILE = 0x08;
+ const PR_APPEND = 0x10;
+ outputStream.init(aFile, PR_WRITE_ONLY | PR_CREATE_FILE | PR_APPEND, 0666, 0);
+ // just to be really sure everything is in UTF8
+ let converter = Cc["@mozilla.org/intl/converter-output-stream;1"].
+ createInstance(Ci.nsIConverterOutputStream);
+ converter.init(outputStream, "UTF-8", 0, 0);
+ this._output = converter;
+}
+LogWriter.prototype = {
+ writeMessage: function(aString) {
+ this._output.writeString(aString);
+ },
+ close: function() {
+ if (this._output) {
+ this._output.close();
+ this._output = null;
+ }
+ }
+};
+
/* Conversation logs stuff */
-function ConversationLog(aConversation)
+function ConversationLog(aConversation, aDate)
{
this._conv = aConversation;
+ this._date = aDate;
}
ConversationLog.prototype = {
_log: null,
file: null,
format: "txt",
_init: function cl_init() {
let file = getLogFolderForAccount(this._conv.account, true);
let name = this._conv.normalizedName;
if (this._conv.isChat && this._conv.account.protocol.id != "prpl-twitter")
name += ".chat";
- file.append(name);
+ file.append(encodeName(name));
if (!file.exists())
file.create(Ci.nsIFile.DIRECTORY_TYPE, 0777);
if (Services.prefs.getCharPref("purple.logging.format") == "json")
this.format = "json";
- file.append(getNewLogFileName(this.format));
+ file.append(getNewLogFileName(this.format, this._date));
this.file = file;
- let os = Cc["@mozilla.org/network/file-output-stream;1"].
- createInstance(Ci.nsIFileOutputStream);
- const PR_WRITE_ONLY = 0x02;
- const PR_CREATE_FILE = 0x08;
- const PR_APPEND = 0x10;
- os.init(file, PR_WRITE_ONLY | PR_CREATE_FILE | PR_APPEND, 0666, 0);
- // just to be really sure everything is in UTF8
- let converter = Cc["@mozilla.org/intl/converter-output-stream;1"].
- createInstance(Ci.nsIConverterOutputStream);
- converter.init(os, "UTF-8", 0, 0);
- this._log = converter;
- this._log.writeString(this._getHeader());
+ this._log = new LogWriter(file);
+ this._log.writeMessage(this._getHeader());
},
_getHeader: function cl_getHeader()
{
let account = this._conv.account;
if (this.format == "json") {
- return JSON.stringify({date: new Date(),
+ return JSON.stringify({date: (this._date ? this._date : new Date()),
name: this._conv.name,
title: this._conv.title,
account: account.normalizedName,
protocol: account.protocol.normalizedName,
isChat: this._conv.isChat
}) + "\n";
}
return "Conversation with " + this._conv.name +
- " at " + (new Date).toLocaleString() +
+ " at " + (this._date ? this._date : new Date()).toLocaleString() +
" on " + account.name +
" (" + account.protocol.normalizedName + ")" + kLineBreak;
},
_serialize: function cl_serialize(aString) {
// TODO cleanup once bug 102699 is fixed
let doc = getHiddenHTMLWindow().document;
let div = doc.createElementNS("http://www.w3.org/1999/xhtml", "div");
div.innerHTML = aString.replace(/\r?\n/g, "<br/>").replace(/<br>/gi, "<br/>");
@@ -147,17 +182,17 @@ ConversationLog.prototype = {
flags: ["outgoing", "incoming", "system", "autoResponse",
"containsNick", "error", "delayed",
"noFormat", "containsImages", "notification",
"noLinkification"].filter(function(f) aMessage[f])
};
let alias = aMessage.alias;
if (alias && alias != msg.who)
msg.alias = alias;
- this._log.writeString(JSON.stringify(msg) + "\n");
+ this._log.writeMessage(JSON.stringify(msg) + "\n");
return;
}
let date = new Date(aMessage.time * 1000);
let line = "(" + date.toLocaleTimeString() + ") ";
let msg = this._serialize(aMessage.originalMessage);
if (aMessage.system)
line += msg;
@@ -167,17 +202,18 @@ ConversationLog.prototype = {
line += sender + " <AUTO-REPLY>: " + msg;
else {
if (/^\/me /.test(msg))
line += "***" + sender + " " + msg.replace(/^\/me /, "");
else
line += sender + ": " + msg;
}
}
- this._log.writeString(line + kLineBreak);
+ //this._log.writeString(line + kLineBreak);
+ this._log.writeMessage(line + kLineBreak);
},
close: function cl_close() {
if (this._log) {
this._log.close();
this._log = null;
this.file = null;
}
@@ -213,47 +249,38 @@ function closeLogForConversation(aConver
gConversationLogs[id].close();
delete gConversationLogs[id];
}
/* System logs stuff */
function SystemLog(aAccount)
{
this._init(aAccount);
- this._log.writeString("System log for account " + aAccount.name +
+ this._log.writeMessage("System log for account " + aAccount.name +
" (" + aAccount.protocol.normalizedName +
") connected at " +
(new Date()).toLocaleFormat("%c") + kLineBreak);
}
SystemLog.prototype = {
_log: null,
_init: function sl_init(aAccount) {
let file = getLogFolderForAccount(aAccount, true);
file.append(".system");
if (!file.exists())
file.create(Ci.nsIFile.DIRECTORY_TYPE, 0777);
file.append(getNewLogFileName());
- let os = Cc["@mozilla.org/network/file-output-stream;1"].
- createInstance(Ci.nsIFileOutputStream);
- const PR_WRITE_ONLY = 0x02;
- const PR_CREATE_FILE = 0x08;
- const PR_APPEND = 0x10;
- os.init(file, PR_WRITE_ONLY | PR_CREATE_FILE | PR_APPEND, 0666, 0);
- // just to be really sure everything is in UTF8
- let converter = Cc["@mozilla.org/intl/converter-output-stream;1"].
- createInstance(Ci.nsIConverterOutputStream);
- converter.init(os, "UTF-8", 0, 0);
- this._log = converter;
+ this._log = new LogWriter(file);
},
logEvent: function sl_logEvent(aString) {
if (!this._log)
this._init();
let date = (new Date()).toLocaleFormat("%x %X");
- this._log.writeString("---- " + aString + " @ " + date + " ----" + kLineBreak);
+ let message = "---- " + aString + " @ " + date + " ----" + kLineBreak;
+ this._log.writeMessage(message);
},
close: function sl_close() {
if (this._log) {
this._log.close();
this._log = null;
}
}
@@ -386,42 +413,42 @@ LogEnumerator.prototype = {
new Log(this._entries[0].getNext().QueryInterface(Ci.nsIFile)),
QueryInterface: XPCOMUtils.generateQI([Ci.nsISimpleEnumerator])
};
function Logger() { }
Logger.prototype = {
_enumerateLogs: function logger__enumerateLogs(aAccount, aNormalizedName) {
let file = getLogFolderForAccount(aAccount);
- file.append(aNormalizedName);
+ file.append(encodeName(aNormalizedName));
if (!file.exists())
return EmptyEnumerator;
return new LogEnumerator([file.directoryEntries]);
},
getLogFromFile: function logger_getLogFromFile(aFile) new Log(aFile),
getLogFileForOngoingConversation: function logger_getLogFileForOngoingConversation(aConversation)
getLogForConversation(aConversation).file,
getLogsForContact: function logger_getLogsForContact(aContact) {
let entries = [];
aContact.getBuddies().forEach(function (aBuddy) {
aBuddy.getAccountBuddies().forEach(function (aAccountBuddy) {
let file = getLogFolderForAccount(aAccountBuddy.account);
- file.append(aAccountBuddy.normalizedName);
+ file.append(encodeName(aAccountBuddy.normalizedName));
if (file.exists())
entries.push(file.directoryEntries);
});
});
return new LogEnumerator(entries);
},
getLogsForBuddy: function logger_getLogsForBuddy(aBuddy) {
let entries = [];
aBuddy.getAccountBuddies().forEach(function (aAccountBuddy) {
let file = getLogFolderForAccount(aAccountBuddy.account);
- file.append(aAccountBuddy.normalizedName);
+ file.append(encodeName(aAccountBuddy.normalizedName));
if (file.exists())
entries.push(file.directoryEntries);
});
return new LogEnumerator(entries);
},
getLogsForAccountBuddy: function logger_getLogsForAccountBuddy(aAccountBuddy)
this._enumerateLogs(aAccountBuddy.account, aAccountBuddy.normalizedName),
getLogsForConversation: function logger_getLogsForConversation(aConversation) {
@@ -431,16 +458,31 @@ Logger.prototype = {
name += ".chat";
return this._enumerateLogs(aConversation.account, name);
},
getSystemLogsForAccount: function logger_getSystemLogsForAccount(aAccount)
this._enumerateLogs(aAccount, ".system"),
getSimilarLogs: function(aLog)
new LogEnumerator([new LocalFile(aLog.path).parent.directoryEntries]),
+ // Adds a conversation not notifying the global observer service.
+ logConversation: function(aConversation, aDate) {
+ aConversation.QueryInterface(Ci.prplIConversation);
+ let id = aConversation.id;
+ if (!(id in gConversationLogs)) {
+ if (aDate)
+ aDate = new Date(aDate);
+ let prefName =
+ "purple.logging.log_" + (aConversation.isChat ? "chats" : "ims");
+ if (Services.prefs.getBoolPref(prefName))
+ gConversationLogs[id] = new ConversationLog(aConversation, aDate);
+ }
+ aConversation.addObserver(this);
+ },
+
observe: function logger_observe(aSubject, aTopic, aData) {
switch (aTopic) {
case "profile-after-change":
Services.obs.addObserver(this, "final-ui-startup", false);
break;
case "final-ui-startup":
Services.obs.removeObserver(this, "final-ui-startup");
["new-text", "conversation-closed", "conversation-left-chat",
diff --git a/chat/importers/Makefile.in b/chat/importers/Makefile.in
new file mode 100644
--- /dev/null
+++ b/chat/importers/Makefile.in
@@ -0,0 +1,37 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DEPTH = ../..
+topsrcdir = @top_srcdir@
+srcdir = @srcdir@
+VPATH = @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+EXTRA_COMPONENTS = \
+ pidgin.js pidgin.manifest \
+ xchat.js xchat.manifest \
+ $(NULL)
+
+ifeq ($(OS_ARCH),WINNT)
+EXTRA_COMPONENTS += \
+ aim.js aim.manifest \
+ googletalk.js googletalk.manifest \
+ mIRC.js mIRC.manifest \
+ wlm.js wlm.manifest \
+ $(NULL)
+endif
+
+ifeq ($(OS_ARCH),Darwin)
+EXTRA_COMPONENTS += \
+ colloquy.js colloquy.manifest \
+ $(NULL)
+endif
+
+ifdef ENABLE_TESTS
+relativesrcdir = chat/importers/
+XPCSHELL_TESTS = test
+endif
+
+include $(topsrcdir)/config/rules.mk
diff --git a/chat/importers/aim.js b/chat/importers/aim.js
new file mode 100644
--- /dev/null
+++ b/chat/importers/aim.js
@@ -0,0 +1,240 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource:///modules/imXPCOMUtils.jsm");
+Cu.import("resource:///modules/jsImporterHelper.jsm");
+Cu.import("resource:///modules/imServices.jsm");
+Cu.import("resource://gre/modules/NetUtil.jsm");
+Cu.import("resource:///modules/blowfish.jsm");
+
+/* The importer below contains methods to retrieve configured
+ * AIM 6.x accounts.
+ *
+ * Homepage: http://www.aim.com/
+ * Resources:
+ * A summary of the AIM Blowfish key generation.
+ * http://insecurety.net/?p=112
+ *
+ * Currently supports:
+ * - A findAccounts() implementation which can locate AIM usernames and
+ * passwords from the Windows registry.
+ */
+function aim6Importer() { }
+aim6Importer.prototype = {
+ __proto__: GenericImporterPrototype,
+ get name() "AIM 6.x",
+ get id() "importer-aim6x",
+
+ findAccounts: function(aObserver) {
+ this._observer = aObserver;
+
+ // AIM 6.x stores user account information in the Windows registry:
+ // HKU\Software\America Online\AIM6\Passwords
+ const ACCESS_READ = Ci.nsIWindowsRegKey.ACCESS_READ;
+ let swKey = Cc["@mozilla.org/windows-registry-key;1"]
+ .createInstance(Ci.nsIWindowsRegKey);
+ swKey.open(swKey.ROOT_KEY_CURRENT_USER, "Software", ACCESS_READ);
+ if (!swKey.hasChild("America Online")) {
+ this._endAccountSearch();
+ return;
+ }
+ let aolKey = swKey.openChild("America Online", ACCESS_READ);
+ if (!aolKey.hasChild("AIM6")) {
+ this._endAccountSearch();
+ return;
+ }
+ let aimKey = aolKey.openChild("AIM6", ACCESS_READ);
+ if (!aimKey.hasChild("Passwords")) {
+ this._endAccountSearch();
+ return;
+ }
+ let passwordsKey = aimKey.openChild("Passwords", ACCESS_READ);
+
+ // Within the Passwords key, each value represents an account. The name of
+ // each value is an AIM username, and the string value is the user's
+ // encrypted password base64 encoded.
+ for (let i = 0; i < passwordsKey.valueCount; ++i) {
+ let username = passwordsKey.getValueName(i);
+ let foundAccount = new ExistingAccount(username, "prpl-aim", this.id);
+
+ // Decode and decrypt the user's password.
+ let encodedPass = passwordsKey.readStringValue(username);
+ let decodedPass = atob(encodedPass);
+ foundAccount.password = this.decryptPassword(decodedPass);
+
+ this._returnAccount(foundAccount);
+ }
+
+ // Close the handles on the Windows registry.
+ passwordsKey.close();
+ aimKey.close();
+ aolKey.close();
+ swKey.close();
+ this._endAccountSearch();
+ },
+
+ QueryInterface: XPCOMUtils.generateQI([Ci.imIImporter]),
+ classID: Components.ID("{2aa7b114-6937-4eab-bb5e-f4ff874a2a77}")
+};
+aim6Importer.prototype.decryptPassword = decryptPassword;
+
+/* The importer below contains methods to retrieve configured
+ * AIM 7.x accounts.
+ *
+ * Homepage: http://www.aim.com/
+ *
+ * Currently supports:
+ * - A findAccounts() implementation reading the username and password of a
+ * saved AIM 7.x account.
+ */
+function aim7Importer() { }
+aim7Importer.prototype = {
+ __proto__: GenericImporterPrototype,
+ get name() "AIM 7.x",
+ get id() "importer-aim7x",
+
+ findAccounts: function(aObserver) {
+ this._observer = aObserver;
+
+ let aimxfile = this._getAIMXFile();
+ if (!aimxfile.exists()) {
+ this._endAccountSearch();
+ return;
+ }
+
+ // Asynchronously read the aimx.bin file into a stream and run it through a
+ // parsing function.
+ NetUtil.asyncFetch(aimxfile, this._parseAIMXFile.bind(this));
+ },
+
+ _parseAIMXFile: function(stream, status) {
+ if (!Components.isSuccessCode(status)) {
+ this._endAccountSearch();
+ return;
+ }
+
+ // A StreamListener implementation is needed to receive the asynchronously
+ // decompressed string.
+ let myListener = new StreamListener();
+
+ // The aimx.bin file is compressed with DEFLATE. The asynchronous method
+ // of nsIStreamConverter must be used as the synchronous is not implemented.
+ let converter = Cc["@mozilla.org/streamconv;1?from=deflate&to=uncompressed"]
+ .createInstance(Ci.nsIStreamConverter);
+ converter.asyncConvertData("deflate", "uncompressed", myListener, null);
+ converter.onStartRequest(null, null);
+ converter.onDataAvailable(null, null, stream, 0, stream.available());
+ converter.onStopRequest(null, null, 201);
+
+ // The result of the uncompression is a string containing an AIM username
+ // and Base64 encoded password separated by '-'.
+ let decompressed = myListener.data;
+ let userData = decompressed.split("-");
+
+ // Catch any invalid data
+ if (userData.length !== 2 || !userData[0] || !userData[1]) {
+ this._endAccountSearch();
+ return;
+ }
+
+ let [username, encodedPass] = userData;
+ let foundAccount= new ExistingAccount(username, "prpl-aim", this.id);
+
+ // Base64 decode the password string and Blowfish decrypt the blocks.
+ let encodedPass = encodedPass.slice(0, encodedPass.length - 3);
+ let decodedPass = atob(encodedPass);
+ foundAccount.password = this.decryptPassword(decodedPass);
+
+ this._returnAccount(foundAccount);
+ this._endAccountSearch();
+ },
+
+ // AIM 7.x stores the saved login information in an "aimx.bin" file found in
+ // the user's AppData/Local directory. This file has been gzip compressed, but
+ // without the full gzip heading. Once uncompressed, this file contains a
+ // username and base64 encoded encrypted password. The encryption is the same
+ // that AIM 6.x uses.
+ _getAIMXFile: function() {
+ let aimxFile = Services.dirsvc.get("LocalAppData", Ci.nsIFile);