Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/bandwagon/components/bandwagon-service.js
blob: 8c484cd6218e9419045b30a85b5c1c327c7145fc (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
/* ***** 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;

function BandwagonService()
{
    this.wrappedJSObject = this;
}

BandwagonService.prototype = {

    collections: {},

    _initialized: false,
    _service: null,
    _collectionUpdateObservers: [],
    _collectionListChangeObservers: [],
    _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");

        // 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

        var storageCollections = this._collectionFactory.openCollections();

        for (var id in storageCollections)
        {
            this.collections[id] = storageCollections[id];
            this.collections[id].setAllNotified();
            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();
        }

        // start the update timer

        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")?30*1000:Bandwagon.COLLECTION_UPDATE_TIMER_DELAY*1000),
            nsITimer.TYPE_REPEATING_SLACK
            );

        // 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");
    },

    uninit: function()
    {
        this._collectionUpdateTimer = null;
        this.commitAll();
    },

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

        return null;
    },

    _autopublishExtensions: function()
    {
        var localAutoPublisher = bandwagonService.getLocalAutoPublisher();

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

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

        for (var i=0; i<installedExtensions.length; i++)
        {
            var hasPublished = false;

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

            if (hasPublished == false)
            {
                willAutopublishExtensions.push(installedExtensions[i]);
            }
        }

        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, "", null);

                // 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() + "'");
                // 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());
            }
            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];
            }
        }
    },

    _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];
            }
        }
    },

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

        this.updateServiceDocument();
    },

    updateServiceDocument: function()
    {
        if (!this.isAMOAuthenticated())
        {
            Bandwagon.Logger.debug("Not authenticated in AMO");
            return;
        }
        
        this._service.getServiceDocument();
    },

    checkForUpdates: function(collection)
    {
        this._service.getCollection(collection);
        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)
    {
        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()
    {
        // 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();
    },

    /** OBSOLETE
    subscribe: function(collection)
    {
        collection.preview = false;
        collection.setAllNotified();

        this._service.subscribeCollection(collection);
    },
    */

    /** OBSOLETE
    unsubscribe: function(collection)
    {
        this._service.unsubscribeCollection(collection);
    },
    */

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

        // set up and save default collections

        // FIXME temporarily disabling this
        //this._addDefaultCollection(Bandwagon.DEFAULT_COLLECTION1_URL, Bandwagon.DEFAULT_COLLECTION1_NAME);
        //this._addDefaultCollection("http://www.33eels.com/clients/briks/bandwagon/testcollection.xml", "test collection");
        
        /** OBSOLETE
        // check for cookie to see if we have to add a collection like that
        var addCollectionCookieValue = Bandwagon.Util.getCookie(Bandwagon.MAGIC_ADD_COLLECTION_COOKIE_HOST, Bandwagon.MAGIC_ADD_COLLECTION_COOKIE_NAME);
        if (addCollectionCookieValue)
        {
            Bandwagon.Logger.info("Found magic 'add collection' cookie. Adding the collection '" + addCollectionCookieValue + "'.");
            this.addPreviewCollection(addCollectionCookieValue);

            // TODO we don't have to because we're in firstrun, but should we delete cookie to be neat?
        }
        */

        // 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);
    },

    /** OBSOLETE
    addPreviewCollection: function(url)
    {
        var collection = this._collectionFactory.newCollection();
        collection.resourceURL = url;
        collection.preview = true;
        this.collections[collection.resourceURL] = collection;

        this.forceCheckForUpdates(collection);

        bandwagonService._notifyListChangeObservers();

        return collection;
    },
    */

    uninstall: function()
    {
        // TODO
    },

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

        /** OBSOLETE
        if (collection.preview)
            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)
    {
        Bandwagon.Logger.debug("In removeAddonFromCollection()");

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

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

        /*
        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);
        */

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

    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)
    {
        this._service.deleteCollection(collection, callback);
    },

    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+$/, "");

        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++)
        {
            this.addPreviouslySharedEmailAddress(bits[i]);
        }
    },

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

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

    isAMOAuthenticated: 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)
                    return true;
            }
        }

        return 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.openDatabase(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)

        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);
        }
    },

    // 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; }