Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/bandwagon/components/bandwagon-service.js
blob: 3e22c3b1b90217cab07023db0d8f6b20d2f9474f (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is bandwagon.
 *
 * The Initial Developer of the Original Code is
 * Mozilla Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): David McNamara
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

const nsISupports = Components.interfaces.nsISupports;
const CLASS_ID = Components.ID("5c896f09-126c-466d-b28a-4e8b87a29916");
const CLASS_NAME = "";
const CONTRACT_ID = "@addons.mozilla.org/bandwagonservice;1";

const Cc = Components.classes;
const Ci = Components.interfaces;

const WindowMediator = Cc["@mozilla.org/appshell/window-mediator;1"];
const Timer = Cc["@mozilla.org/timer;1"];
const ExtensionsManager = Cc["@mozilla.org/extensions/manager;1"];
const Storage = Cc["@mozilla.org/storage/service;1"];
const DirectoryService = Cc["@mozilla.org/file/directory_service;1"];
const ObserverService = Cc["@mozilla.org/observer-service;1"];
const CookieManager = Cc["@mozilla.org/cookiemanager;1"];

const nsIWindowMediator = Ci.nsIWindowMediator;
const nsITimer = Ci.nsITimer;
const nsIExtensionManager = Ci.nsIExtensionManager;
const mozIStorageService = Ci.mozIStorageService;
const nsIProperties = Ci.nsIProperties;
const nsIFile = Ci.nsIFile;
const nsIObserverService = Ci.nsIObserverService;
const nsICookieManager = Ci.nsICookieManager;

var Bandwagon;
var bandwagonService;

var gEmGUID;
var gUninstallObserverInited = false;

/* Restore settings added or changed by the extension:
 *  - extension preferences
 *  - logins stored in the Login Manager?
 */
function cleanupSettings()
{
  // Cleanup preferences
  var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                        .getService(Components.interfaces.nsIPrefBranch);
  try {
    prefs.deleteBranch("extensions.bandwagon");
  }
  catch(e) {}
}

function BandwagonService()
{
    this.wrappedJSObject = this;
    gEmGUID = "sharing@addons.mozilla.org";
}

BandwagonService.prototype = {

    collections: {},

    _initialized: false,
    _service: null,
    _collectionUpdateObservers: [],
    _collectionListChangeObservers: [],
    _authenticationStatusChangeObservers: [],
    _storageConnection: null,
    _collectionFactory: null, 
    _collectionUpdateTimer: null,
    _bwObserver: null,
    _serviceDocument: null,

    init: function()
    {
        if (this._initialized)
            return;

        // get access to Bandwagon.* singletons

        var browserWindow = WindowMediator.getService(nsIWindowMediator).getMostRecentWindow("navigator:browser");

        if (!browserWindow || !browserWindow.Bandwagon)
        {
            debug("Bandwagon: could not get access to Bandwagon singletons from last window");
            return;
        }

        Bandwagon = browserWindow.Bandwagon;
        bandwagonService = this;

        Bandwagon.Logger.info("Initializing Bandwagon");

        this._initAMOHost();

        // init rpc service

        this._service = new Bandwagon.RPC.Service();
        this._service.registerLogger(Bandwagon.Logger);
        this._service.registerObserver(this._getCollectionObserver);
        this._service.registerObserver(this._getServiceDocumentObserver);

        this.registerCollectionUpdateObserver(this._collectionUpdateObserver);
        // init sqlite storage (also creating tables in sqlite if needed). create factory objects.

        this._initStorage();

        // first run stuff

        if (Bandwagon.Preferences.getPreference("firstrun") == true)
        {
            Bandwagon.Preferences.setPreference("firstrun", false);
            this.firstrun();
        }

        // storage initialized, tables created - open the collections and service document
        
        this._initCollections();

        // start the update timer

        this._initUpdateTimer();

        // observe when the app shuts down so we can uninit

        ObserverService.getService(nsIObserverService).addObserver(this._bwObserver, "quit-application", false);

        // kick off the auto-publish functionality

        this.autopublishExtensions();

        this._initialized = true;

        Bandwagon.Logger.info("Bandwagon has been initialized");
    },

    /** 
     * Update "constants" to reflect amo_host in preferences
     */
    _initAMOHost: function()
    {
        var amoHost = Bandwagon.Preferences.getPreference("amo_host");

        Bandwagon.RPC.Constants.BANDWAGON_RPC_SERVICE_DOCUMENT = Bandwagon.RPC.Constants.BANDWAGON_RPC_SERVICE_DOCUMENT.replace("%%AMO_HOST%%", amoHost);
        Bandwagon.LOGINPANE_DO_NEW_ACCOUNT = Bandwagon.LOGINPANE_DO_NEW_ACCOUNT.replace("%%AMO_HOST%%", amoHost);
        Bandwagon.COLLECTIONSPANE_DO_SUBSCRIBE_URL = Bandwagon.COLLECTIONSPANE_DO_SUBSCRIBE_URL.replace("%%AMO_HOST%%", amoHost);
        Bandwagon.COLLECTIONSPANE_DO_NEW_COLLECTION_URL = Bandwagon.COLLECTIONSPANE_DO_NEW_COLLECTION_URL.replace("%%AMO_HOST%%", amoHost);
        Bandwagon.FIRSTRUN_LANDING_PAGE = Bandwagon.FIRSTRUN_LANDING_PAGE.replace("%%AMO_HOST%%", amoHost);
        Bandwagon.AMO_AUTH_COOKIE_HOST = Bandwagon.AMO_AUTH_COOKIE_HOST.replace("%%AMO_HOST%%", amoHost);
    },

    _initCollections: function()
    {
        var storageCollections = this._collectionFactory.openCollections();

        for (var id in storageCollections)
        {
            this.collections[id] = storageCollections[id];
            this.collections[id].setAllNotified();

            if (this.collections[id].isLocalAutoPublisher())
            {
                this.collections[id].autoPublishExtensions = Bandwagon.Preferences.getPreference("local.autopublisher.publish.extensions");
                this.collections[id].autoPublishThemes = Bandwagon.Preferences.getPreference("local.autopublisher.publish.themes");
                this.collections[id].autoPublishDicts = Bandwagon.Preferences.getPreference("local.autopublisher.publish.dictionaries");
                this.collections[id].autoPublishLangPacks = Bandwagon.Preferences.getPreference("local.autopublisher.publish.language.packs");
                this.collections[id].autoPublishDisabled = !Bandwagon.Preferences.getPreference("local.autopublisher.only.publish.enabled");
            }

            Bandwagon.Logger.debug("opened collection from storage: " + id);
        }

        this._serviceDocument = this._collectionFactory.openServiceDocument();
        this._service._serviceDocument = this._serviceDocument;

        if (!this._serviceDocument)
        {
            // no service document in storage, we never had it or we've lost it - go fetch it
            this.updateCollectionsList();
        }
    },

    _initUpdateTimer: function()
    {
        this._bwObserver = 
        {
            observe: function(aSubject, aTopic, aData)
            {
                if (aTopic == "timer-callback")
                {
                    bandwagonService.checkAllForUpdates();
                }
                else if (aTopic == "quit-application")
                {
                    bandwagonService.uninit();
                }
            }
        };

        this._collectionUpdateTimer = Timer.createInstance(nsITimer);
        this._collectionUpdateTimer.init(
            this._bwObserver,
            (Bandwagon.Preferences.getPreference("debug")?120*1000:Bandwagon.COLLECTION_UPDATE_TIMER_DELAY*1000),
            nsITimer.TYPE_REPEATING_SLACK
            );
    },

    uninit: function()
    {
        this._collectionUpdateTimer = null;
        this.commitAll();
        this._service = null;
        this._collectionFactory = null;
        Bandwagon = null;
        bandwagonService = null;
    },

    getLocalAutoPublisher: function()
    {
        for (var id in bandwagonService.collections)
        {
            if (bandwagonService.collections[id].isLocalAutoPublisher())
            {
                return bandwagonService.collections[id];
            }
        }

        return null;
    },

    autopublishExtensions: function(callback)
    {
        Bandwagon.Logger.debug("in autopublishExtensions()");

        var localAutoPublisher = bandwagonService.getLocalAutoPublisher();

        if (localAutoPublisher == null)
        {
            Bandwagon.Preferences.setPreferenceList("autopublished.extensions", []);
            return;
        }

        var internalCallback = function(event)
        {
            if (!event.isError())
            {
                bandwagonService._notifyCollectionUpdateObservers(localAutoPublisher);
            }

            if (callback)
            {
                callback(event);
            }
        }

        var installedExtensions = Bandwagon.Util.getInstalledExtensions();
        var autopublishedExtensions = Bandwagon.Preferences.getPreferenceList("autopublished.extensions");
        var willAutopublishExtensions = [];

        for (var i=0; i<installedExtensions.length; i++)
        {
            //Bandwagon.Logger.debug("checking addon '" + installedExtensions[i].id + "' against user auto pub prefs (type=" +  installedExtensions[i].type + ")");

            // check if user wants to publish this extension (enabled, type)
            
            if ((
                Bandwagon.Util.getExtensionProperty(installedExtensions[i].id, "isDisabled") == "true"
                ||
                Bandwagon.Util.getExtensionProperty(installedExtensions[i].id, "appDisabled") == "true"
                ||
                Bandwagon.Util.getExtensionProperty(installedExtensions[i].id, "userDisabled") == "true"
                )
                && !localAutoPublisher.autoPublishDisabled)
            {
                //Bandwagon.Logger.debug("addon '" + installedExtensions[i].id + "' is disabled, so won't publish");
                continue;
            }

            if (installedExtensions[i].type & installedExtensions[i].TYPE_EXTENSION 
                && !localAutoPublisher.autoPublishExtensions)
            {
                //Bandwagon.Logger.debug("addon '" + installedExtensions[i].id + "' is an extension, so won't publish");
                continue;
            }

            if (installedExtensions[i].type & installedExtensions[i].TYPE_THEME 
                && !localAutoPublisher.autoPublishThemes)
            {
                //Bandwagon.Logger.debug("addon '" + installedExtensions[i].id + "' is a theme, so won't publish");
                continue;
            }

            if (installedExtensions[i].type & installedExtensions[i].TYPE_LOCALE 
                && !localAutoPublisher.autoPublishLangPacks)
            {
                //Bandwagon.Logger.debug("addon '" + installedExtensions[i].id + "' is a locale, so won't publish");
                continue;
            }

            /** TODO
            if (installedExtensions[i].type & installedExtensions[i].TYPE_DICT 
                && !localAutoPublisher.autoPublishDicts)
            {
                Bandwagon.Logger.debug("addon '" + installedExtensions[i].id + "' is a dict, so won't publish");
                continue;
            }
            */

            // check if we have already published this extension
            
            var hasPublished = false;

            for (var j=0; j<autopublishedExtensions.length; j++)
            {
                if (installedExtensions[i].id == autopublishedExtensions[j])
                {
                    hasPublished = true;
                    break;
                }
            }

            if (hasPublished == false)
            {
                //Bandwagon.Logger.debug("addon '" + installedExtensions[i].id + "' added to auto-publish queue");
                willAutopublishExtensions.push(installedExtensions[i]);
            }
            else
            {
                //Bandwagon.Logger.debug("addon '" + installedExtensions[i].id + "' has already been published");
            }
        }

        if (willAutopublishExtensions.length > 0)
        {
            for (var i=0; i<willAutopublishExtensions.length; i++)
            {
                //Bandwagon.Logger.debug("Will autopublish extension '" + willAutopublishExtensions[i].id + "' to collection '" + localAutoPublisher.resourceURL + "'");

                var extension =
                {
                    guid: willAutopublishExtensions[i].id,
                    name: willAutopublishExtensions[i].name
                }

                bandwagonService.publishToCollection(extension, localAutoPublisher, "", internalCallback);

                // add to autopublish
                autopublishedExtensions.push(willAutopublishExtensions[i].id);
            }

            Bandwagon.Preferences.setPreferenceList("autopublished.extensions", autopublishedExtensions);
        }
    },

    _getCollectionObserver: function(event)
    {
        Bandwagon.Logger.info("in _getCollectionObserver()");

        if (event.getType() == Bandwagon.RPC.Constants.BANDWAGON_RPC_EVENT_TYPE_BANDWAGON_RPC_GET_COLLECTION_COMPLETE)
        {
            var collection = event.collection;

            if (event.isError())
            {
                Bandwagon.Logger.error("RPC error: '" + event.getError().getMessage() + "'");
    
                if (event.getError().getCode() == Bandwagon.RPC.Constants.BANDWAGON_RPC_SERVICE_ERROR_UNAUTHORIZED)
                {
                    bandwagonService.deauthenticate();
                }

                // otherwise ignore for now
            }
            else
            {
                if (collection != null && collection.resourceURL != null)
                {
                    Bandwagon.Logger.info("Finished getting updates for collection '" + collection.resourceURL + "'");
                    bandwagonService.collections[collection.resourceURL] = collection;
                }
            }

            // we want to notify the observers even if there's been an error

            bandwagonService._notifyCollectionUpdateObservers(collection);
        }
    },

    _getServiceDocumentObserver: function(event)
    {
        Bandwagon.Logger.info("in _getServiceDocumentObserver()");

        if (event.getType() == Bandwagon.RPC.Constants.BANDWAGON_RPC_EVENT_TYPE_BANDWAGON_RPC_GET_SERVICE_DOCUMENT_COMPLETE)
        {
            if (event.isError())
            {
                Bandwagon.Logger.error("Could not update collections list: " + event.getError().toString());

                if (event.getError().getCode() == Bandwagon.RPC.Constants.BANDWAGON_RPC_SERVICE_ERROR_UNAUTHORIZED)
                {
                    bandwagonService.deauthenticate();
                }
            }
            else
            {
                bandwagonService._serviceDocument = event.serviceDocument;
                bandwagonService._service._serviceDocument = bandwagonService._serviceDocument;

                var collections = bandwagonService._serviceDocument.collections;

                Bandwagon.Logger.debug("Updating collections list: saw " + collections.length + " collections");

                for (var id in bandwagonService.collections)
                {
                    var isStaleCollection = true;

                    for (var jd in collections)
                    {
                        if (bandwagonService.collections[id].equals(collections[jd]))
                        {
                            isStaleCollection = false;
                            break;
                        }
                    }

                    if (isStaleCollection)
                    {
                        Bandwagon.Logger.debug("Updating collections list: removing stale collection: " + bandwagonService.collections[id].toString());

                        bandwagonService.unlinkCollection(bandwagonService.collections[id]);
                    }
                }

                for (var id in collections)
                {
                    var collection = collections[id];

                    if (bandwagonService.collections[collection.resourceURL])
                    {
                        // we have already added this collection
                    }
                    else
                    {
                        // this is a new collection
                        Bandwagon.Logger.debug("Updating collections list: adding new collection: " + collection.toString());

                        bandwagonService.collections[collection.resourceURL] = collection;
                    }
                }

                bandwagonService.forceCheckAllForUpdates();
                
                bandwagonService._notifyListChangeObservers();

                if (Bandwagon.COMMIT_NOW)
                    bandwagonService.commitAll();
            }
        }
    },

    _notifyCollectionUpdateObservers: function(collection)
    {
        Bandwagon.Logger.debug("Notifying collection update observers");

        for (var i=0; i<bandwagonService._collectionUpdateObservers.length; i++)
        {
            if (bandwagonService._collectionUpdateObservers[i])
            {
                bandwagonService._collectionUpdateObservers[i](collection);
            }
        }
    },

    registerCollectionUpdateObserver: function(observer)
    {
        Bandwagon.Logger.debug("Registering collection update observer");
        this._collectionUpdateObservers.push(observer);
    },

    unregisterCollectionUpdateObserver: function(observer)
    {
        Bandwagon.Logger.debug("Unregistering collection update observer");

        for (var i=0; i<this._collectionUpdateObservers.length; i++)
        {
            if (this._collectionUpdateObservers[i] == observer)
            {
                delete this._collectionUpdateObservers[i];
            }
        }
    },

    _notifyAuthenticationStatusChangeObservers: function()
    {
        Bandwagon.Logger.debug("Notifying authentication status change observers");

        for (var i=0; i<bandwagonService._authenticationStatusChangeObservers.length; i++)
        {
            if (bandwagonService._authenticationStatusChangeObservers[i])
            {
                bandwagonService._authenticationStatusChangeObservers[i]();
            }
        }
    },

    registerAuthenticationStatusChangeObserver: function(observer)
    {
        Bandwagon.Logger.debug("Registering authentication status change observer");
        this._authenticationStatusChangeObservers.push(observer);
    },

    unregisterAuthenticationStatusChangeObserver: function(observer)
    {
        Bandwagon.Logger.debug("Unregistering authentication status change observer");

        for (var i=0; i<this._authenticationStatusChangeObservers.length; i++)
        {
            if (this._authenticationStatusChangeObservers[i] == observer)
            {
                delete this._authenticationStatusChangeObservers[i];
            }
        }
    },

    _notifyListChangeObservers: function()
    {
        Bandwagon.Logger.debug("Notifying collection list change observers");

        for (var i=0; i<bandwagonService._collectionListChangeObservers.length; i++)
        {
            if (bandwagonService._collectionListChangeObservers[i])
            {
                bandwagonService._collectionListChangeObservers[i]();
            }
        }
    },

    registerCollectionListChangeObserver: function(observer)
    {
        Bandwagon.Logger.debug("Registering collection list change observer");
        this._collectionListChangeObservers.push(observer);
    },

    unregisterCollectionListChangeObserver: function(observer)
    {
        Bandwagon.Logger.debug("Unregistering collection list change observer");

        for (var i=0; i<this._collectionListChangeObservers.length; i++)
        {
            if (this._collectionListChangeObservers[i] == observer)
            {
                delete this._collectionListChangeObservers[i];
            }
        }
    },

    authenticate: function(login, password, callback)
    {
        Bandwagon.Logger.debug("in authenticate()");

        var service = this;

        Bandwagon.Preferences.setPreference(Bandwagon.PREF_AUTH_TOKEN, "");
        Bandwagon.Preferences.setPreference("login", "");

        // The following is a workaround to allow auth-token based
        // authentication to work when an AMO cookie is also present. Full
        // description in bug 496612.
        // XXX. Comment out when bug 496612 is addressed.
        //this.deleteAMOCookie();

        var internalCallback = function(event)
        {
            if (!event.isError())
            {
                Bandwagon.Preferences.setPreference("login", login);

                service._notifyAuthenticationStatusChangeObservers();
            }

            if (callback)
                callback(event);
        }

        this._service.authenticate(login, password, internalCallback);
    },

    deauthenticate: function(callback)
    {
        Bandwagon.Preferences.setPreference(Bandwagon.PREF_AUTH_TOKEN, "");
        Bandwagon.Preferences.setPreference("login", "");

        this._notifyAuthenticationStatusChangeObservers();

        if (callback)
            callback();
    },

    updateCollectionsList: function(callback)
    {
        Bandwagon.Logger.debug("Updating collections list...");

        this.updateServiceDocument(callback);
    },

    updateServiceDocument: function(callback)
    {
        if (!this.isAuthenticated())
            return;

        this._service.getServiceDocument(callback);
    },

    checkForUpdates: function(collection)
    {
        if (!this.isAuthenticated())
            return;

        this._service.getCollection(collection);

        var now = new Date();

        collection.dateLastCheck = now;
    },

    checkAllForUpdates: function()
    {
        Bandwagon.Logger.debug("in checkAllForUpdates()");

        var now = new Date();

        for (var id in this.collections)
        {
            var collection = this.collections[id];

            if (collection.updateInterval == -1)
            {
                // use global setting
                
                var dateLastCheck = new Date(Bandwagon.Preferences.getPreference("updateall.datelastcheck")*1000);
                var dateNextCheck = new Date(dateLastCheck.getTime() + Bandwagon.Util.intervalUnitsToMilliseconds(
                    Bandwagon.Preferences.getPreference("global.update.interval"),
                    Bandwagon.Preferences.getPreference("global.update.units")
                    ));

                if (dateNextCheck.getTime() > now.getTime())
                {
                    return;
                }
                else
                {
                    this.checkForUpdates(collection);
                }
            }
            else
            {
                // use per-collection setting
                
                var dateLastCheck = null;
                var dateNextCheck = null;

                if (collection.dateLastCheck != null)
                {
                    dateLastCheck = collection.dateLastCheck;
                    dateNextCheck = new Date(dateLastCheck.getTime() + collection.updateInterval*1000);
                }
                else
                {
                    dateLastCheck = null;
                    dateNextCheck = now;
                }

                if (dateLastCheck == null || dateNextCheck.getTime() <= now.getTime())
                {
                    this.checkForUpdates(collection);
                }
            }
        }

        Bandwagon.Preferences.setPreference("updateall.datelastcheck", now.getTime()/1000);
    },

    forceCheckForUpdates: function(collection)
    {
        if (!this.isAuthenticated())
            return;

        this._service.getCollection(collection);
        collection.dateLastCheck = new Date();
    },

    forceCheckAllForUpdates: function()
    {
        Bandwagon.Logger.debug("in forceCheckAllForUpdates()");

        for (var id in this.collections)
        {
            var collection = this.collections[id];
            this.forceCheckForUpdates(collection);
        }
    },

    forceCheckAllForUpdatesAndUpdateCollectionsList: function(callback)
    {
        // All updates to the collections list are forced, i.e. they are always
        // caused by *some* user interaction, never in the background.
        // Updating the collections list also forces the collections to be updated.
        
        this.updateCollectionsList(callback);
    },

    firstrun: function()
    {
        Bandwagon.Logger.info("This is bandwagon's firstrun. Welcome!");

        // the last check date is now

        var now = new Date();
        Bandwagon.Preferences.setPreference("updateall.datelastcheck", now.getTime()/1000);

        // open the firstrun landing page

        Bandwagon.Controller.BrowserOverlay.openFirstRunLandingPage();
    },

    _addDefaultCollection: function(url, name)
    {
        var collection = this._collectionFactory.newCollection();
        collection.resourceURL = url;
        collection.name = name;
        collection.showNotifications = 0;

        this.collections[collection.resourceURL] = collection;

        if (Bandwagon.COMMIT_NOW)
            this.commit(collection);

        this.forceCheckForUpdates(collection);
        this.subscribe(collection);
    },

    uninstall: function()
    {
        // TODO
    },

    commit: function(collection)
    {
        if (!bandwagonService._collectionFactory)
            return;

        Bandwagon.Logger.debug("In commit() with collection: " + collection.resourceURL);

        bandwagonService._collectionFactory.commitCollection(collection);
    },

    commitAll: function()
    {
        Bandwagon.Logger.debug("In commitAll()");

        for (var id in bandwagonService.collections)
        {
            var collection = bandwagonService.collections[id];

            this.commit(collection);
        }

        if (bandwagonService._serviceDocument)
            bandwagonService._collectionFactory.commitServiceDocument(bandwagonService._serviceDocument);
    },

    removeAddonFromCollection: function(guid, collection, callback)
    {
        Bandwagon.Logger.debug("In removeAddonFromCollection()");

        if (!this.isAuthenticated())
            return;

        this._service.removeAddonFromCollection(guid, collection, callback);
    },

    newCollection: function(collection, callback)
    {
        Bandwagon.Logger.debug("In newCollection()");

        if (!this.isAuthenticated())
            return;

        var internalCallback = function(event)
        {
            if (!event.isError())
            {
                var collection = event.collection;

                bandwagonService.collections[collection.resourceURL] = collection;
                //bandwagonService._notifyCollectionUpdateObservers(collection);
                bandwagonService._notifyListChangeObservers();
            }

            if (callback)
            {
                callback(event);
            }
        }

        this._service.newCollection(collection, internalCallback);
    },

    unlinkCollection: function(collection)
    {
        this._collectionFactory.deleteCollection(collection);

        for (var id in bandwagonService.collections)
        {
            if (collection.equals(bandwagonService.collections[id]))
            {
                delete bandwagonService.collections[id];

                bandwagonService._notifyListChangeObservers();

                break;
            }
        }
    },

    deleteCollection: function(collection, callback)
    {
        if (!this.isAuthenticated())
            return;

        this._service.deleteCollection(collection, callback);
    },

    subscribeToCollection: function(collection, callback)
    {
        if (!this.isAuthenticated())
            return;

        var internalCallback = function(event)
        {
            if (!event.isError())
            {
                collection.subscribed = true;
                bandwagonService._notifyListChangeObservers();
            }

            if (callback)
            {
                callback(event);
            }
        }

        this._service.subscribeToCollection(collection, internalCallback);
    },

    unsubscribeFromCollection: function(collection, callback)
    {
        if (!this.isAuthenticated())
            return;

        var internalCallback = function(event)
        {
            if (!event.isError())
            {
                bandwagonService.unlinkCollection(collection);
            }

            if (callback)
            {
                callback(event);
            }
        }

        this._service.unsubscribeFromCollection(collection, internalCallback);
    },

    updateCollectionDetails: function(collection, callback)
    {
        if (!this.isAuthenticated())
            return;

        this._service.updateCollectionDetails(collection, callback);
    },

    /** This function is called when a 3rd party extension is uninstalled by
     * the user.  If this extension is part of a local auto publisher, we
     * remove it from that autopublisher.
     */
    processOtherExtensionUninstall: function(guid, callback)
    {
        Bandwagon.Logger.debug("In processOtherExtensionUninstall() with guid = " + guid);

        var localAutoPublisher = bandwagonService.getLocalAutoPublisher();

        if (!localAutoPublisher)
            return;

        var internalCallback = function(event)
        {
            if (!event.isError())
            {
                // update list of autopublished extensions to remove this one
                var autopublishedExtensions = Bandwagon.Preferences.getPreferenceList("autopublished.extensions");

                for (var j=0; j<autopublishedExtensions.length; j++)
                {
                    if (autopublishedExtensions[j] == guid)
                    {
                        delete autopublishedExtensions[j];
                        break;
                    }
                }

                Bandwagon.Preferences.setPreferenceList("autopublished.extensions", autopublishedExtensions);

                bandwagonService.forceCheckForUpdates(localAutoPublisher);

                if (callback)
                    callback(event);
            }
        }

        for (var id in localAutoPublisher.addons)
        {
            if (localAutoPublisher.addons[id].guid == guid)
            {
                Bandwagon.Logger.debug("Found this extension in local auto publisher: '" + localAutoPublisher.addons[id].guid + "' vs '" + guid + "', will remove.");

                this.removeAddonFromCollection(guid, localAutoPublisher, internalCallback);

                break;
            }
        }
    },

    getAddonsPerPage: function(collection)
    {
        // returns this collection's custom items per page, or else the global value

        var addonsPerPage;
        
        if (collection.addonsPerPage != -1)
        {
            addonsPerPage = collection.addonsPerPage;
        }
        else
        {
            addonsPerPage = Bandwagon.Preferences.getPreference("global.addonsperpage");
        }

        if (addonsPerPage < 1)
        {
            addonsPerPage = 1;
        }

        return addonsPerPage;
    },

    getPreviouslySharedEmailAddresses: function()
    {
        return Bandwagon.Preferences.getPreferenceList("publish.shared.emails");
    },

    clearPreviouslySharedEmailAddresses: function()
    {
        Bandwagon.Preferences.setPreferenceList("publish.shared.emails", []);
    },

    addPreviouslySharedEmailAddress: function(emailAddress)
    {
        emailAddress = emailAddress.replace(/^\s+/, "");
        emailAddress = emailAddress.replace(/\s+$/, "");
        emailAddress = emailAddress.replace(/^,/, "");
        emailAddress = emailAddress.replace(/,$/, "");

        var previouslySharedEmailAddresses = this.getPreviouslySharedEmailAddresses();

        for (var i=0; i<previouslySharedEmailAddresses.length; i++)
        {
            if (previouslySharedEmailAddresses[i] == emailAddress)
            {
                return;
            }
        }

        previouslySharedEmailAddresses.push(emailAddress);

        Bandwagon.Preferences.setPreferenceList("publish.shared.emails", previouslySharedEmailAddresses);
    },

    addPreviouslySharedEmailAddresses: function(commaSeparatedEmailAddresses)
    {
        var bits = commaSeparatedEmailAddresses.split(",");

        for (var i=0; i<bits.length; i++)
        {
            if (bits[i].match(/.*@.*/))
            {
                this.addPreviouslySharedEmailAddress(bits[i]);
            }
        }
    },

    publishToCollection: function(extension, collection, personalNote, callback)
    {
        if (!this.isAuthenticated())
            return;

        this._service.publishToCollection(extension, collection, personalNote, callback);
    },

    shareToEmail: function(extension, emailAddress, personalNote, callback)
    {
        if (!this.isAuthenticated())
            return;

        // trim any commas from a multi-email string

        emailAddress = emailAddress.replace(/^,/, "");
        emailAddress = emailAddress.replace(/,$/, "");

        this._service.shareToEmail(extension, emailAddress, personalNote, callback);
    },

    /**
     * Performs a 'soft' check for authenication. I.e. do we have a token from a previous auth. This method doesn't
     * check if that token is still valid on the server.
     */
    isAuthenticated: function()
    {
        return (Bandwagon.Preferences.getPreference(Bandwagon.PREF_AUTH_TOKEN) != "");
    },

    deleteAMOCookie: function()
    {
        var cm = CookieManager.getService(nsICookieManager);

        var iterator = cm.enumerator;

        while (iterator.hasMoreElements())
        {
            var cookie = iterator.getNext();

            if (cookie instanceof Ci.nsICookie)
            {
                if (cookie.host == Bandwagon.AMO_AUTH_COOKIE_HOST && cookie.name == Bandwagon.AMO_AUTH_COOKIE_NAME)
                {
                    // KILL!
                    cm.remove(cookie.host, cookie.name, cookie.path, false);
                }
            }
        }
    },

    _collectionUpdateObserver: function(collection)
    {
        // called when a collection is updated

        // if there are new items, notify the user if notifications are enabled for this user and it's not a preview of a collection

        Bandwagon.Logger.debug("in _collectionUpdateObserver() with collection '" + collection + "', unnotified collection items = " + collection.getUnnotifiedAddons().length)

        var showNotificationsForThisCollection;

        if (collection.showNotifications == -1)
        {
            showNotificationsForThisCollection = Bandwagon.Preferences.getPreference("global.notify.enabled");
        }
        else
        {
            showNotificationsForThisCollection = collection.showNotifications;
        }

        if (showNotificationsForThisCollection && collection.getUnnotifiedAddons().length > 0)
        {
            var browserWindow = WindowMediator.getService(nsIWindowMediator).getMostRecentWindow("navigator:browser");

            if (browserWindow)
            {
                browserWindow.Bandwagon.Controller.BrowserOverlay.showNewAddonsAlert(collection);
            }
            else
            {
                Bandwagon.Logger.error("Can't find a browser window to notify the user");
            }

            collection.setAllNotified();
        }

        // commit the collection

        if (Bandwagon.COMMIT_NOW)
            bandwagonService.commit(collection);
    },

    _initStorage: function()
    {
        var storageService = Storage.getService(mozIStorageService);

        var file = DirectoryService.getService(nsIProperties).get("ProfD", nsIFile);
        file.append(Bandwagon.EMID);

        if (!file.exists() || !file.isDirectory())
        {
            file.create(nsIFile.DIRECTORY_TYPE, 0777);
        }

        file.append(Bandwagon.SQLITE_FILENAME);

        try
        {
            this._storageConnection = storageService.openUnsharedDatabase(file);
        }
        catch (e)
        {
            Bandwagon.Logger.error("Error opening Storage connection: " + e);
            return;
        }

        this._collectionFactory = new Bandwagon.Factory.CollectionFactory(this._storageConnection);

        this._initStorageTables();
    },

    _initStorageTables: function()
    {
        if (!this._storageConnection)
            return;

        // create tables (if they're not already created)

        this._storageConnection.beginTransaction();

        try
        {
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS serviceDocument "
                + "(emailResourceURL TEXT NOT NULL, "
                + "collectionListResourceURL TEXT NOT NULL)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS collections "
                + "(id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "url TEXT NOT NULL UNIQUE, "
                + "name TEXT NOT NULL, "
                + "description TEXT, "
                + "dateAdded INTEGER NOT NULL, "
                + "dateLastCheck INTEGER, "
                + "updateInterval INTEGER NOT NULL, "
                + "showNotifications INTEGER NOT NULL, "
                + "autoPublish INTEGER NOT NULL, "
                + "active INTEGER NOT NULL DEFAULT 1, "
                + "addonsPerPage INTEGER NOT NULL, "
                + "creator TEXT, "
                + "listed INTEGER NOT NULL DEFAULT 1, "
                + "writable INTEGER NOT NULL DEFAULT 0, "
                + "subscribed INTEGER NOT NULL DEFAULT 1, "
                + "lastModified INTEGER, "
                + "addonsResourceURL TEXT, "
                + "type TEXT)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS collectionsLinks "
                + "(id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "collection INTEGER NOT NULL, "
                + "name TEXT NOT NULL, "
                + "href TEXT NOT NULL)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS collectionsAddons "
                + "(id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "collection INTEGER NOT NULL, "
                + "addon INTEGER NOT NULL, "
                + "read INTEGER NOT NULL DEFAULT 0)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS addons "
                + "(id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "guid TEXT NOT NULL UNIQUE, "
                + "name TEXT NOT NULL, "
                + "type INTEGER NOT NULL, "
                + "version TEXT NOT NULL, "
                + "status INTEGER NOT NULL, "
                + "summary TEXT, "
                + "description TEXT, "
                + "icon TEXT, "
                + "eula TEXT, "
                + "thumbnail TEXT, "
                + "learnmore TEXT NOT NULL, "
                + "author TEXT, "
                + "category TEXT, "
                + "dateAdded INTEGER NOT NULL)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS addonCompatibleApplications "
                + "(addon INTEGER NOT NULL, "
                + "name TEXT NOT NULL, "
                + "applicationId INTEGER NOT NULL, "
                + "minVersion TEXT NOT NULL, "
                + "maxVersion TEXT NOT NULL, "
                + "guid TEXT NOT NULL)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS addonCompatibleOS "
                + "(addon INTEGER NOT NULL, "
                + "name TEXT NOT NULL)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS addonInstalls "
                + "(addon INTEGER NOT NULL, "
                + "url TEXT NOT NULL, "
                + "hash TEXT NOT NULL, "
                + "os TEXT NOT NULL)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS addonComments "
                + "(addon INTEGER NOT NULL, "
                + "comment TEXT NOT NULL, "
                + "author TEXT NOT NULL)"
                );
            this._storageConnection.executeSimpleSQL(
                "CREATE TABLE IF NOT EXISTS addonAuthors "
                + "(addon INTEGER NOT NULL, "
                + "author TEXT NOT NULL)"
                );
        }
        catch (e)
        {
            Bandwagon.Logger.error("Error creating sqlite table: " + e);
            this._storageConnection.rollbackTransaction();
            return;
        }

        this._storageConnection.commitTransaction();
    },

    startUninstallObserver : function ()
    {
        if (gUninstallObserverInited) return;

        var extService = Components.classes["@mozilla.org/extensions/manager;1"]
            .getService(Components.interfaces.nsIExtensionManager);

        if (extService && ("uninstallItem" in extService))
        {
            var observerService = Components.classes["@mozilla.org/observer-service;1"]
                .getService(Components.interfaces.nsIObserverService);
            observerService.addObserver(this.addonsAction, "em-action-requested", false);
            gUninstallObserverInited = true;
        }
        else
        {
            try
            {
                extService.datasource.AddObserver(this.addonsObserver);
                gUninstallObserverInited = true;
            }
            catch (e) { }
        }
    },

    addonsObserver:
    {
        onAssert: function (ds, subject, predicate, target)
        {
            if ((predicate.Value == "http://www.mozilla.org/2004/em-rdf#toBeUninstalled")
                    &&
                    (target instanceof Components.interfaces.nsIRDFLiteral)
                    &&
                    (target.Value == "true"))
            {
                if (subject.Value == "urn:mozilla:extension:" + gEmGUID)
                {
                    // This is case where bandwagon is being uninstalled - clean up

                    cleanupSettings();
                }
                else
                {
                    // This is case where some other extension is being uninstalled

                    var val = subject.Value;
                    val = val.replace(/urn:mozilla:extension:/, "");

                    bandwagonService.processOtherExtensionUninstall(val);
                }
            }
        },

        onUnassert: function (ds, subject, predicate, target) {},
        onChange: function (ds, subject, predicate, oldtarget, newtarget) {},
        onMove: function (ds, oldsubject, newsubject, predicate, target) {},
        onBeginUpdateBatch: function() {},
        onEndUpdateBatch: function() {}
    },

    addonsAction:
    {
        observe: function (subject, topic, data)
        {
            if ((data == "item-uninstalled") &&
                (subject instanceof Components.interfaces.nsIUpdateItem))
            {
                if (subject.id == gEmGUID)
                {
                    // This is case where bandwagon is being uninstalled - clean up

                    cleanupSettings();
                }
                else
                {
                    // This is case where some other extension is being uninstalled

                    bandwagonService.processOtherExtensionUninstall(subject.id);
                }
            }
        }
    },

    // for nsISupports
    QueryInterface: function(aIID)
    {
        // add any other interfaces you support here
        if (!aIID.equals(nsISupports))
            throw Components.results.NS_ERROR_NO_INTERFACE;
                
        return this;
    }
}

var BandwagonServiceFactory = {
    singleton: null,
    createInstance: function (aOuter, aIID)
    {
        if (aOuter != null)
            throw Components.results.NS_ERROR_NO_AGGREGATION;

        if (this.singleton == null)
            this.singleton = new BandwagonService();

        return this.singleton.QueryInterface(aIID);
    }
};

var BandwagonServiceModule = {
    registerSelf: function(aCompMgr, aFileSpec, aLocation, aType)
    {
        aCompMgr = aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        aCompMgr.registerFactoryLocation(CLASS_ID, CLASS_NAME, CONTRACT_ID, aFileSpec, aLocation, aType);
    },

    unregisterSelf: function(aCompMgr, aLocation, aType)
    {
        aCompMgr = aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        aCompMgr.unregisterFactoryLocation(CLASS_ID, aLocation);        
    },

    getClassObject: function(aCompMgr, aCID, aIID)
    {
        if (!aIID.equals(Components.interfaces.nsIFactory))
            throw Components.results.NS_ERROR_NOT_IMPLEMENTED;

        if (aCID.equals(CLASS_ID))
            return BandwagonServiceFactory;

        throw Components.results.NS_ERROR_NO_INTERFACE;
    },

    canUnload: function(aCompMgr) { return true; }
};

//module initialization
function NSGetModule(aCompMgr, aFileSpec) { return BandwagonServiceModule; }