-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathStorage.jsm
2201 lines (1818 loc) · 77.7 KB
/
Storage.jsm
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
const EXPORTED_SYMBOLS = ['Storage', 'Query'];
Components.utils.import('resource://digest/common.jsm');
Components.utils.import('resource://digest/StorageUtils.jsm');
Components.utils.import('resource://digest/FeedContainer.jsm');
Components.utils.import('resource://digest/FeedUpdateService.jsm');
Components.utils.import('resource://gre/modules/Services.jsm');
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
IMPORT_COMMON(this);
const PURGE_ENTRIES_INTERVAL = 3600*24; // 1 day
const DELETED_FEEDS_RETENTION_TIME = 3600*24*7; // 1 week
const LIVEMARKS_SYNC_DELAY = 100;
const BACKUP_FILE_EXPIRATION_AGE = 3600*24*14; // 2 weeks
const DATABASE_VERSION = 16;
const DATABASE_CACHE_SIZE = 256; // With the default page size of 32KB, it gives us 8MB of cache memory.
const FEEDS_TABLE_SCHEMA = [
'feedID TEXT UNIQUE',
'feedURL TEXT',
'websiteURL TEXT',
'title TEXT',
'subtitle TEXT',
'favicon TEXT',
'bookmarkID TEXT',
'parent TEXT',
'rowIndex INTEGER',
'isFolder INTEGER',
'hidden INTEGER DEFAULT 0',
'lastUpdated INTEGER DEFAULT 0',
'oldestEntryDate INTEGER',
'entryAgeLimit INTEGER DEFAULT 0',
'maxEntries INTEGER DEFAULT 0',
'updateInterval INTEGER DEFAULT 0',
'dateModified INTEGER DEFAULT 0',
'lastFaviconRefresh INTEGER DEFAULT 0',
'markModifiedEntriesUnread INTEGER DEFAULT 1',
'omitInUnread INTEGER DEFAULT 0'
]
const ENTRIES_TABLE_SCHEMA = [
'id INTEGER PRIMARY KEY AUTOINCREMENT',
'feedID TEXT',
'primaryHash TEXT',
'secondaryHash TEXT',
'providedID TEXT',
'entryURL TEXT',
'date INTEGER',
'read INTEGER DEFAULT 0',
'updated INTEGER DEFAULT 0',
'starred INTEGER DEFAULT 0',
'deleted INTEGER DEFAULT 0',
'bookmarkID INTEGER DEFAULT -1 '
]
const ENTRIES_TEXT_TABLE_SCHEMA = [
'title TEXT ',
'content TEXT ',
'authors TEXT ',
'tags TEXT '
]
const ENTRY_TAGS_TABLE_SCHEMA = [
'tagName TEXT ',
'entryID INTEGER '
]
const REASON_FINISHED = Ci.mozIStorageStatementCallback.REASON_FINISHED;
const REASON_ERROR = Ci.mozIStorageStatementCallback.REASON_ERROR;
XPCOMUtils.defineLazyServiceGetter(this, 'Bookmarks', '@mozilla.org/browser/nav-bookmarks-service;1', 'nsINavBookmarksService');
XPCOMUtils.defineLazyGetter(this, 'Prefs', function() {
return Services.prefs.getBranch('extensions.brief.').QueryInterface(Ci.nsIPrefBranch);
})
XPCOMUtils.defineLazyGetter(this, 'Places', function() {
Components.utils.import('resource://gre/modules/PlacesUtils.jsm');
return PlacesUtils;
})
let Connection = null;
function Statement(aStatement, aDefaultParams) {
StorageStatement.call(this, Connection, aStatement, aDefaultParams);
}
Statement.prototype = StorageStatement.prototype;
// Exported object exposing public properties.
const Storage = Object.freeze({
ENTRY_STATE_NORMAL: 0,
ENTRY_STATE_TRASHED: 1,
ENTRY_STATE_DELETED: 2,
/**
* Returns a feed or a folder with given ID.
*
* @param aFeedID
* @returns Feed object, without entries.
*/
getFeed: function(aFeedID) {
return StorageInternal.getFeed(aFeedID);
},
/**
* Gets all feeds, without entries.
*
* @param aIncludeFolders [optional]
* @param aIncludeInactive [optional]
* @returns array of Feed objects.
*/
getAllFeeds: function(aIncludeFolders, aIncludeInactive) {
return StorageInternal.getAllFeeds(aIncludeFolders, aIncludeInactive);
},
/**
* Gets a list of distinct tags for URLs of entries stored in the database.
*
* @param aCallback
* Receives an array of strings of tag names.
*/
getAllTags: function(aCallback) {
return StorageInternal.getAllTags(aCallback);
},
/**
* Updates feed properties and inserts/updates entries.
*
* @param aFeed
* Feed object containing the current feed's properties.
* @param aEntries
* Array of Entry objects to process.
* @param aCallback
*/
processFeed: function(aFeed, aEntries, aCallback) {
return StorageInternal.processFeed(aFeed, aEntries, aCallback);
},
/**
* Updates feed properties and settings.
*
* @param aFeeds
* Feed object, or array of Feed objects, containing the current properties.
* @param aCallback [optional]
*/
updateFeedProperties: function(aFeeds, aCallback) {
return StorageInternal.updateFeedProperties(aFeeds, aCallback);
},
/**
* Synchronizes database with Live Bookmarks from home folder which ID is
* specified by extensions.brief.homeFolder.
* Feeds that were removed from the home folder remain in the database in the hidden
* state for a certain amount of time in case they are added back.
*/
syncWithLivemarks: function() {
return StorageInternal.syncWithLivemarks();
},
/**
* Registers an object to be notified of changes to feed entries. A strong reference
* is held to this object, so all observers have to be removed using
* Storage.removeObserver().
*
* An observer may implement any of the following functions:
*
* function onEntriesAdded(aEntryList)
*
* Called when new entries are added to the database.
*
* function onEntriesUpdated(aEntryList);
*
* Called when properties of existing entries - such as title, content, authors
* and date - are changed. When entries are updated, they can also be marked as unread.
*
* function onEntriesMarkedRead(aEntryList, aNewState);
*
* Called when the read/unread state of entries changes.
*
* function onEntriesStarred(aEntryList, aNewState);
*
* Called when URLs of entries are bookmarked/unbookmarked.
*
* function onEntriesTagged(aEntryList, aNewState, aTagName);
*
* Called when a tag is added or removed from entries.
*
* function onEntriesDeleted(aEntryList, aNewState);
*
* Called when the deleted state of entries changes.
*/
addObserver: function(aObserver) {
return StorageInternal.addObserver(aObserver);
},
/**
* Unregisters an observer object.
*/
removeObserver: function(aObserver) {
return StorageInternal.removeObserver(aObserver);
}
})
let StorageInternal = {
allItemsCache: null,
activeItemsCache: null,
activeFeedsCache: null,
init: function StorageInternal_init() {
let profileDir = Services.dirsvc.get('ProfD', Ci.nsIFile);
let databaseFile = profileDir.clone();
databaseFile.append('brief.sqlite');
let databaseIsNew = !databaseFile.exists();
Connection = new StorageConnection(databaseFile, false);
let schemaVersion = Connection.schemaVersion;
// Remove the backup file after certain amount of time.
let backupFile = profileDir.clone();
backupFile.append('brief-backup-' + (schemaVersion - 1) + '.sqlite');
if (backupFile.exists() && Date.now() - backupFile.lastModifiedTime > BACKUP_FILE_EXPIRATION_AGE)
backupFile.remove(false);
if (!Connection.connectionReady) {
// The database was corrupted, back it up and create a new one.
Services.storage.backupDatabaseFile(databaseFile, 'brief-backup.sqlite');
Connection.close();
databaseFile.remove(false);
Connection = new StorageConnection(databaseFile, false);
this.setupDatabase();
}
else if (databaseIsNew) {
this.setupDatabase();
}
else if (schemaVersion < DATABASE_VERSION) {
// Remove the old backup file.
if (backupFile.exists())
backupFile.remove(false);
// Backup the database before migration.
let filename = 'brief-backup-' + schemaVersion + '.sqlite';
Services.storage.backupDatabaseFile(databaseFile, filename);
// No support for migration from versions older than 1.2,
// create a new database.
if (schemaVersion < 9) {
Connection.close();
databaseFile.remove(false);
Connection = new StorageConnection(databaseFile, false);
this.setupDatabase();
}
else {
this.upgradeDatabase();
}
}
Connection.executeSQL('PRAGMA cache_size = ' + DATABASE_CACHE_SIZE);
Connection.executeSQL(
'DELETE FROM entries WHERE rowid NOT IN ' +
'(SELECT docid FROM entries_text)');
Connection.executeSQL(
'DELETE FROM entries_text WHERE docid NOT IN ' +
'(SELECT rowid FROM entries)');
Connection.executeSQL(
'INSERT OR IGNORE INTO entries_text(rowid) SELECT seq FROM sqlite_sequence WHERE name=\'entries\';');
this.refreshFeedsCache();
this.homeFolderID = Prefs.getIntPref('homeFolder');
Prefs.addObserver('', this, false);
Services.obs.addObserver(this, 'quit-application', false);
Services.obs.addObserver(this, 'idle-daily', false);
// This has to be on the end, in case getting bookmarks service throws.
Bookmarks.addObserver(BookmarkObserver, false);
},
setupDatabase: function Database_setupDatabase() {
Connection.executeSQL(
'CREATE TABLE IF NOT EXISTS feeds (' + FEEDS_TABLE_SCHEMA.join(',') + ') ',
'CREATE TABLE IF NOT EXISTS entries (' + ENTRIES_TABLE_SCHEMA.join(',') + ') ',
'CREATE TABLE IF NOT EXISTS entry_tags (' + ENTRY_TAGS_TABLE_SCHEMA.join(',') + ') ',
'CREATE VIRTUAL TABLE entries_text USING fts3 (' + ENTRIES_TEXT_TABLE_SCHEMA.join(',') + ')',
'CREATE INDEX IF NOT EXISTS entries_date_index ON entries (date) ',
'CREATE INDEX IF NOT EXISTS entries_feedID_date_index ON entries (feedID, date) ',
// Speed up lookup when checking for updates.
'CREATE INDEX IF NOT EXISTS entries_primaryHash_index ON entries (primaryHash) ',
// Speed up SELECTs in the bookmarks observer.
'CREATE INDEX IF NOT EXISTS entries_bookmarkID_index ON entries (bookmarkID) ',
'CREATE INDEX IF NOT EXISTS entries_entryURL_index ON entries (entryURL) ',
'CREATE INDEX IF NOT EXISTS entry_tagName_index ON entry_tags (tagName)',
'PRAGMA journal_mode=WAL',
'ANALYZE'
)
Connection.schemaVersion = DATABASE_VERSION;
},
upgradeDatabase: function StorageInternal_upgradeDatabase() {
switch (Connection.schemaVersion) {
// To 1.5b2
case 9:
// Remove dead rows from entries_text.
Connection.executeSQL('DELETE FROM entries_text '+
'WHERE rowid IN ( '+
' SELECT entries_text.rowid '+
' FROM entries_text LEFT JOIN entries '+
' ON entries_text.rowid = entries.id '+
' WHERE NOT EXISTS ( '+
' SELECT id '+
' FROM entries '+
' WHERE entries_text.rowid = entries.id '+
' ) '+
') AND rowid <> (SELECT max(rowid) from entries_text) ');
// To 1.5b3
case 10:
Connection.executeSQL('ALTER TABLE feeds ADD COLUMN lastFaviconRefresh INTEGER DEFAULT 0');
// To 1.5
case 11:
Connection.executeSQL('ANALYZE');
// These were for one-time fixes on 1.5 branch.
case 12:
case 13:
// To 1.6.
case 14:
Connection.executeSQL('PRAGMA journal_mode=WAL');
// To 1.7
case 15:
Connection.executeSQL('ALTER TABLE feeds ADD COLUMN omitInUnread INTEGER DEFAULT 0');
}
Connection.schemaVersion = DATABASE_VERSION;
},
// See Storage.
getFeed: function StorageInternal_getFeed(aFeedID) {
let foundFeed = null;
let feeds = this.getAllFeeds(true, true);
for (let i = 0; i < feeds.length; i++) {
if (feeds[i].feedID == aFeedID) {
foundFeed = feeds[i];
break;
}
}
return foundFeed;
},
/**
* See Storage.
*
* It's not worth the trouble to make this function asynchronous like the
* rest of the IO, as in-memory cache is practically always available.
* However, in the rare case when the cache has just been invalidated
* and hasn't been refreshed yet, we must fall back to a synchronous query.
*/
getAllFeeds: function StorageInternal_getAllFeeds(aIncludeFolders, aIncludeInactive) {
if (!this.allItemsCache)
this.refreshFeedsCache(true);
if (aIncludeFolders && aIncludeInactive)
return this.allItemsCache;
else if (aIncludeFolders)
return this.activeItemsCache;
else
return this.activeFeedsCache;
},
refreshFeedsCache: function StorageInternal_refreshFeedsCache(aSynchronous, aNotify, aCallback) {
let resume = StorageInternal_refreshFeedsCache.resume;
this.allItemsCache = null;
this.activeItemsCache = null;
this.activeFeedsCache = null;
let results = aSynchronous ? Stm.getAllFeeds.results
: yield Stm.getAllFeeds.getResultsAsync(resume);
this.allItemsCache = [];
this.activeItemsCache = [];
this.activeFeedsCache = [];
for (let row in results) {
let feed = new Feed();
for (let column in row)
feed[column] = row[column];
this.allItemsCache.push(feed);
if (!feed.hidden) {
this.activeItemsCache.push(feed);
if (!feed.isFolder)
this.activeFeedsCache.push(feed);
}
}
Object.freeze(this.allItemsCache);
Object.freeze(this.activeItemsCache);
Object.freeze(this.activeFeedsCache);
if (aNotify)
Services.obs.notifyObservers(null, 'brief:invalidate-feedlist', '')
if (aCallback)
aCallback();
}.gen(),
// See Storage.
getAllTags: function StorageInternal_getAllTags(aCallback) {
Stm.getAllTags.getResultsAsync(function(results) {
aCallback([row.tagName for each (row in results)]);
})
},
// See Storage.
processFeed: function StorageInternal_processFeed(aFeed, aEntries, aCallback) {
new FeedProcessor(aFeed, aEntries, aCallback);
},
// See Storage.
updateFeedProperties: function StorageInternal_updateFeedProperties(aFeeds, aCallback) {
let feeds = Array.isArray(aFeeds) ? aFeeds : [aFeeds];
for (let feed in feeds) {
let params = {};
for (let paramName in Stm.updateFeedProperties.params)
params[paramName] = feed[paramName];
Stm.updateFeedProperties.paramSets.push(params);
}
Stm.updateFeedProperties.executeAsync(aCallback);
},
// Moves items to Trash based on age and number limits.
expireEntries: function StorageInternal_expireEntries(aFeed) {
let resume = StorageInternal_expireEntries.resume;
// Delete entries exceeding the maximum amount specified by maxStoredEntries pref.
if (Prefs.getBoolPref('database.limitStoredEntries')) {
let query = new Query({
feeds: [aFeed.feedID],
deleted: Storage.ENTRY_STATE_NORMAL,
starred: false,
sortOrder: Query.prototype.SORT_BY_DATE,
offset: Prefs.getIntPref('database.maxStoredEntries')
})
yield query.deleteEntries(Storage.ENTRY_STATE_TRASHED, resume);
}
// Delete old entries in feeds that don't have per-feed setting enabled.
if (Prefs.getBoolPref('database.expireEntries') && !aFeed.entryAgeLimit) {
let expirationAge = Prefs.getIntPref('database.entryExpirationAge');
let query = new Query({
feeds: [aFeed.feedID],
deleted: Storage.ENTRY_STATE_NORMAL,
starred: false,
endDate: Date.now() - expirationAge * 86400000
})
yield query.deleteEntries(Storage.ENTRY_STATE_TRASHED, resume);
}
// Delete old entries based on per-feed limit.
if (aFeed.entryAgeLimit > 0) {
let query = new Query({
feeds: [aFeed.feedID],
deleted: Storage.ENTRY_STATE_NORMAL,
starred: false,
endDate: Date.now() - aFeed.entryAgeLimit * 86400000
})
query.deleteEntries(Storage.ENTRY_STATE_TRASHED);
}
}.gen(),
// Permanently removes deleted items from database.
purgeDeleted: function StorageInternal_purgeDeleted() {
Stm.purgeDeletedEntriesText.params = {
'deletedState': Storage.ENTRY_STATE_DELETED,
'currentDate': Date.now(),
'retentionTime': DELETED_FEEDS_RETENTION_TIME
}
Stm.purgeDeletedEntries.params = {
'deletedState': Storage.ENTRY_STATE_DELETED,
'currentDate': Date.now(),
'retentionTime': DELETED_FEEDS_RETENTION_TIME
}
Stm.purgeDeletedFeeds.params = {
'currentDate': Date.now(),
'retentionTime': DELETED_FEEDS_RETENTION_TIME
}
Connection.executeAsync([Stm.purgeDeletedEntriesText,
Stm.purgeDeletedEntries,
Stm.purgeDeletedFeeds])
// Prefs can only store longs while Date is a long long.
let now = Math.round(Date.now() / 1000);
Prefs.setIntPref('database.lastPurgeTime', now);
},
// nsIObserver
observe: function StorageInternal_observe(aSubject, aTopic, aData) {
switch (aTopic) {
case 'quit-application':
Bookmarks.removeObserver(BookmarkObserver);
Prefs.removeObserver('', this);
Services.obs.removeObserver(this, 'quit-application');
Services.obs.removeObserver(this, 'idle-daily');
BookmarkObserver.syncDelayTimer = null;
break;
case 'idle-daily':
// Integer prefs are longs while Date is a long long.
let now = Math.round(Date.now() / 1000);
let lastPurgeTime = Prefs.getIntPref('database.lastPurgeTime');
if (now - lastPurgeTime > PURGE_ENTRIES_INTERVAL)
this.purgeDeleted();
break;
case 'nsPref:changed':
if (aData == 'homeFolder') {
this.homeFolderID = Prefs.getIntPref('homeFolder');
this.syncWithLivemarks();
}
break;
}
},
// See Storage.
syncWithLivemarks: function StorageInternal_syncWithLivemarks() {
new LivemarksSync();
},
observers: [],
// See Storage.
addObserver: function StorageInternal_addObserver(aObserver) {
this.observers.push(aObserver);
},
// See Storage.
removeObserver: function StorageInternal_removeObserver(aObserver) {
let index = this.observers.indexOf(aObserver);
if (index !== -1)
this.observers.splice(index, 1);
},
/**
* Sets starred status of an entry.
*
* @param aState
* New state. TRUE for starred, FALSE for not starred.
* @param aEntryID
* Subject entry.
* @param aBookmarkID
* ItemId of the corresponding bookmark in Places database.
* @param aDontNotify
* Don't notify observers.
*/
starEntry: function StorageInternal_starEntry(aState, aEntryID, aBookmarkID, aDontNotify) {
let resume = StorageInternal_starEntry.resume;
if (aState) {
Stm.starEntry.params = { 'bookmarkID': aBookmarkID, 'entryID': aEntryID };
yield Stm.starEntry.executeAsync(resume);
}
else {
Stm.unstarEntry.params = { 'id': aEntryID };
yield Stm.unstarEntry.executeAsync(resume);
}
if (!aDontNotify) {
let list = yield new Query(aEntryID).getEntryList(resume);
for (let observer in StorageInternal.observers) {
if (observer.onEntriesStarred)
observer.onEntriesStarred(list, aState);
}
}
}.gen(),
/**
* Adds or removes a tag for an entry.
*
* @param aState
* TRUE to add the tag, FALSE to remove it.
* @param aEntryID
* Subject entry.
* @param aTagName
* Name of the tag.
*/
tagEntry: function StorageInternal_tagEntry(aState, aEntryID, aTagName) {
let resume = StorageInternal_tagEntry.resume;
let params = { 'entryID': aEntryID, 'tagName': aTagName };
if (aState) {
Stm.checkTag.params = params;
let results = yield Stm.checkTag.getResultsAsync(resume);
if (results[0].alreadyTagged)
return;
Stm.tagEntry.params = params;
yield Stm.tagEntry.executeAsync(resume);
}
else {
Stm.untagEntry.params = params;
yield Stm.untagEntry.executeAsync(resume);
}
// Update the serialized list of tags stored in entries_text table.
let newTags = yield Utils.getTagsForEntry(aEntryID, resume);
Stm.setSerializedTagList.params = {
'tags': newTags.join(', '),
'entryID': aEntryID
}
yield Stm.setSerializedTagList.executeAsync(resume);
let list = yield new Query(aEntryID).getEntryList(resume);
for (let observer in StorageInternal.observers) {
if (observer.onEntriesTagged)
observer.onEntriesTagged(list, aState, aTagName);
}
}.gen(),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver])
}
/**
* Evaluates provided entries, inserting any new items and updating existing
* items when newer versions are found. Also updates feed's properties.
*/
function FeedProcessor(aFeed, aEntries, aCallback) {
this.feed = aFeed;
this.callback = aCallback;
let newDateModified = new Date(aFeed.wrappedFeed.updated).getTime();
let prevDateModified = aFeed.dateModified;
if (aEntries.length && (!newDateModified || newDateModified > prevDateModified)) {
this.remainingEntriesCount = aEntries.length;
this.newOldestEntryDate = Date.now();
this.updatedEntries = [];
this.updateEntry = Stm.updateEntry.clone();
this.insertEntry = Stm.insertEntry.clone();
this.updateEntryText = Stm.updateEntryText.clone();
this.insertEntryText = Stm.insertEntryText.clone();
aEntries.forEach(this.processEntry, this);
}
else {
aCallback(0);
}
aFeed.oldestEntryDate = this.newOldestEntryDate || aFeed.oldestEntryDate;
aFeed.lastUpdated = Date.now();
aFeed.dateModified = newDateModified;
StorageInternal.updateFeedProperties(aFeed);
}
FeedProcessor.prototype = {
processEntry: function FeedProcessor_processEntry(aEntry) {
if (aEntry.date && aEntry.date < this.newOldestEntryDate)
this.newOldestEntryDate = aEntry.date;
// This function checks whether a downloaded entry is already in the database or
// it is a new one. To do this we need a way to uniquely identify entries. Many
// feeds don't provide unique identifiers for their entries, so we have to use
// hashes for this purpose. There are two hashes.
// The primary hash is used as a standard unique ID throughout the codebase.
// Ideally, we just compute it from the GUID provided by the feed. Otherwise, we
// use the entry's URL.
// There is a problem, though. Even when a feed does provide its own GUID, it
// seems to randomly get lost (maybe a bug in the parser?). This means that the
// same entry may sometimes be hashed using the GUID and other times using the
// URL. Different hashes lead to the entry being duplicated.
// This is why we need a secondary hash, which is always based on the URL. If the
// GUID is empty (either because it was lost or because it wasn't provided to
// begin with), we look up the entry using the secondary hash.
let providedID = aEntry.wrappedEntry.id;
let primarySet = providedID ? [this.feed.feedID, providedID]
: [this.feed.feedID, aEntry.entryURL];
let secondarySet = [this.feed.feedID, aEntry.entryURL];
// Special case for MediaWiki feeds: include the date in the hash. In
// "Recent changes" feeds, entries for subsequent edits of a page differ
// only in date (not in URL or GUID).
let generator = this.feed.wrappedFeed.generator;
if (generator && generator.agent.match('MediaWiki')) {
primarySet.push(aEntry.date);
secondarySet.push(aEntry.date);
}
let primaryHash = Utils.hashString(primarySet.join(''));
let secondaryHash = Utils.hashString(secondarySet.join(''));
// Look up if the entry is already present in the database.
if (providedID) {
var select = Stm.getEntryByPrimaryHash;
select.params.primaryHash = primaryHash;
}
else {
select = Stm.getEntryBySecondaryHash;
select.params.secondaryHash = secondaryHash;
}
let storedID, storedDate, isEntryRead;
let self = this;
select.executeAsync({
handleResult: function(row) {
storedID = row.id;
storedDate = row.date;
isEntryRead = row.read;
},
handleCompletion: function(aReason) {
if (aReason == REASON_FINISHED) {
if (storedID) {
if (aEntry.date && storedDate < aEntry.date) {
self.addUpdateParams(aEntry, storedID, isEntryRead);
}
}
else {
self.addInsertParams(aEntry, primaryHash, secondaryHash);
}
}
if (!--self.remainingEntriesCount)
self.executeAndNotify();
}
})
},
addUpdateParams: function FeedProcessor_addUpdateParams(aEntry, aStoredEntryID, aIsRead) {
let title = aEntry.title ? aEntry.title.replace(/<[^>]+>/g, '') : ''; // Strip tags
let markUnread = StorageInternal.getFeed(this.feed.feedID).markModifiedEntriesUnread;
this.updateEntry.paramSets.push({
'date': aEntry.date,
'read': markUnread || !aIsRead ? 0 : 1,
'id': aStoredEntryID
})
this.updateEntryText.paramSets.push({
'title': title,
'content': aEntry.content || aEntry.summary,
'authors': aEntry.authors,
'id': aStoredEntryID
})
this.updatedEntries.push(aStoredEntryID);
},
addInsertParams: function FeedProcessor_addInsertParams(aEntry, aPrimaryHash, aSecondaryHash) {
let title = aEntry.title ? aEntry.title.replace(/<[^>]+>/g, '') : ''; // Strip tags
try {
var insertEntryParamSet = {
'feedID': this.feed.feedID,
'primaryHash': aPrimaryHash,
'secondaryHash': aSecondaryHash,
'providedID': aEntry.wrappedEntry.id,
'entryURL': aEntry.entryURL,
'date': aEntry.date || Date.now()
}
var insertEntryTextParamSet = {
'title': title,
'content': aEntry.content || aEntry.summary,
'authors': aEntry.authors
}
}
catch (ex) {
Cu.reportError('Error updating feeds. Failed to bind parameters to insert statement.');
Cu.reportError(ex);
return;
}
this.insertEntry.paramSets.push(insertEntryParamSet);
this.insertEntryText.paramSets.push(insertEntryTextParamSet);
},
executeAndNotify: function FeedProcessor_executeAndNotify() {
let resume = FeedProcessor_executeAndNotify.resume;
let insertedEntries = [];
if (this.insertEntry.paramSets.length) {
if (this.insertEntry.paramSets.length != this.insertEntryText.paramSets.length) {
this.callback(0);
throw new Error('Mismatched parameteres between insertEntry and insertEntryText statements.');
}
Stm.getLastRowids.params.count = this.insertEntry.paramSets.length;
let statements = [this.insertEntry, this.insertEntryText, Stm.getLastRowids];
let reason = yield Connection.executeAsync(statements, {
handleResult: function(row) {
insertedEntries.push(row.id);
},
handleCompletion: resume
})
if (reason === REASON_FINISHED) {
let list = yield new Query(insertedEntries).getEntryList(resume);
for (let observer in StorageInternal.observers) {
if (observer.onEntriesAdded)
observer.onEntriesAdded(list);
}
StorageInternal.expireEntries(this.feed);
}
}
if (this.updateEntry.paramSets.length) {
let statements = [this.updateEntry, this.updateEntryText];
yield Connection.executeAsync(statements, resume);
let list = yield new Query(this.updatedEntries).getEntryList(resume);
for (let observer in StorageInternal.observers) {
if (observer.onEntriesUpdated)
observer.onEntriesUpdated(list);
}
}
this.callback(insertedEntries.length);
}.gen()
}
/**
* A query to the Brief's database. Constraints are AND-ed.
*
* @param aConstraints
* Entry ID, array of entry IDs, or object containing name-value pairs
* of query constraints.
*/
function Query(aConstraints) {
if (!aConstraints)
return;
if (typeof aConstraints == 'number') {
this.entries = [aConstraints];
}
else if (aConstraints.splice) {
this.entries = aConstraints;
}
else {
for (let constraint in aConstraints)
this[constraint] = aConstraints[constraint];
}
}
Query.prototype = {
/**
* Array of IDs of entries to be selected.
*/
entries: undefined,
/**
* Array of IDs of feeds containing the entries to be selected.
*/
feeds: undefined,
/**
* Array of IDs of folders containing the entries to be selected.
*/
folders: undefined,
/**
* Array of tags which selected entries must have.
*/
tags: undefined,
/**
* Read state of entries to be selected.
*/
read: undefined,
/**
* Starred state of entries to be selected.
*/
starred: undefined,
/**
* Deleted state of entries to be selected. See constants in StorageInternal.
*/
deleted: undefined,
/**
* String that must be contained by title, content, authors or tags of the
* selected entries.
*/
searchString: undefined,
/**
* Date range for the selected entries.
*/
startDate: undefined,
endDate: undefined,
/**
* Maximum number of entries to be selected.
*/
limit: undefined,
/**
* Specifies how many result entries to skip at the beggining of the result set.
*/
offset: 0,
/**
* By which column to sort the results.
*/
SORT_BY_DATE: 1,
SORT_BY_TITLE: 2,
SORT_BY_FEED_ROW_INDEX: 3,
sortOrder: undefined,
/**
* Direction in which to sort the results.
*/
SORT_DESCENDING: 0,
SORT_ASCENDING: 1,
sortDirection: 0,
/**
* Include hidden feeds i.e. the ones whose Live Bookmarks are no longer
* to be found in Brief's home folder. This attribute is ignored if
* the list of feeds is explicitly specified by Query.feeds.
*/
includeHiddenFeeds: false,
/**
* Include feeds the user has explicitly marked to be omitted from global unread views.
*/
includeOmittedUnread: true,
/**
* Indicates if there are any entries that match this query.
*
* @param aCallback
*/
hasMatches: function Query_hasMatches(aCallback) {
let sql = 'SELECT EXISTS (SELECT entries.id ' + this._getQueryString(true) + ') AS found';
new Statement(sql).executeAsync({
handleResult: function(row) aCallback(row.found),
handleError: this._onDatabaseError
})
},
/**
* Get a simple list of entries.
* XXX Check performance.
*
* @param aCallback
* Receives an array if IDs.
*/
getEntries: function Query_getEntries(aCallback) {