-
Notifications
You must be signed in to change notification settings - Fork 54
/
NewTabUtils.jsm
2216 lines (1977 loc) · 65.7 KB
/
NewTabUtils.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
var EXPORTED_SYMBOLS = ["NewTabUtils"];
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
// Android tests don't import these properly, so guard against that
let didSuccessfulImport = false;
#if 0
let shortURL = {};
let searchShortcuts = {};
try {
ChromeUtils.import("resource://activity-stream/lib/ShortURL.jsm", shortURL);
ChromeUtils.import("resource://activity-stream/lib/SearchShortcuts.jsm", searchShortcuts);
didSuccessfulImport = true;
} catch (e) {
// The test failed to import these files
}
#endif
ChromeUtils.defineModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
ChromeUtils.defineModuleGetter(this, "PageThumbs",
"resource://gre/modules/PageThumbs.jsm");
ChromeUtils.defineModuleGetter(this, "BinarySearch",
"resource://gre/modules/BinarySearch.jsm");
#if 0
ChromeUtils.defineModuleGetter(this, "pktApi",
"chrome://pocket/content/pktApi.jsm");
ChromeUtils.defineModuleGetter(this, "Pocket",
"chrome://pocket/content/Pocket.jsm");
#endif
XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function() {
return Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
});
XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function() {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "utf8";
return converter;
});
// Boolean preferences that control newtab content
const PREF_NEWTAB_ENABLED = "browser.newtabpage.enabled";
// The maximum number of results PlacesProvider retrieves from history.
const HISTORY_RESULTS_LIMIT = 100;
// The maximum number of links Links.getLinks will return.
const LINKS_GET_LINKS_LIMIT = 100;
// The gather telemetry topic.
const TOPIC_GATHER_TELEMETRY = "gather-telemetry";
// Some default frecency threshold for Activity Stream requests
const ACTIVITY_STREAM_DEFAULT_FRECENCY = 150;
// Some default query limit for Activity Stream requests
const ACTIVITY_STREAM_DEFAULT_LIMIT = 12;
// Some default seconds ago for Activity Stream recent requests
const ACTIVITY_STREAM_DEFAULT_RECENT = 5 * 24 * 60 * 60;
const POCKET_UPDATE_TIME = 24 * 60 * 60 * 1000; // 1 day
const POCKET_INACTIVE_TIME = 7 * 24 * 60 * 60 * 1000; // 1 week
const PREF_POCKET_LATEST_SINCE = "extensions.pocket.settings.latestSince";
/**
* Calculate the MD5 hash for a string.
* @param aValue
* The string to convert.
* @return The base64 representation of the MD5 hash.
*/
function toHash(aValue) {
let value = gUnicodeConverter.convertToByteArray(aValue);
gCryptoHash.init(gCryptoHash.MD5);
gCryptoHash.update(value, value.length);
return gCryptoHash.finish(true);
}
/**
* Singleton that provides storage functionality.
*/
XPCOMUtils.defineLazyGetter(this, "Storage", function() {
return new LinksStorage();
});
function LinksStorage() {
// Handle migration of data across versions.
try {
if (this._storedVersion < this._version) {
// This is either an upgrade, or version information is missing.
if (this._storedVersion < 1) {
// Version 1 moved data from DOM Storage to prefs. Since migrating from
// version 0 is no more supported, we just reportError a dataloss later.
throw new Error("Unsupported newTab storage version");
}
// Add further migration steps here.
} else {
// This is a downgrade. Since we cannot predict future, upgrades should
// be backwards compatible. We will set the version to the old value
// regardless, so, on next upgrade, the migration steps will run again.
// For this reason, they should also be able to run multiple times, even
// on top of an already up-to-date storage.
}
} catch (ex) {
// Something went wrong in the update process, we can't recover from here,
// so just clear the storage and start from scratch (dataloss!).
Cu.reportError(
"Unable to migrate the newTab storage to the current version. " +
"Restarting from scratch.\n" + ex);
this.clear();
}
// Set the version to the current one.
this._storedVersion = this._version;
}
LinksStorage.prototype = {
get _version() {
return 1;
},
get _prefs() {
return Object.freeze({
pinnedLinks: "browser.newtabpage.pinned",
blockedLinks: "browser.newtabpage.blocked",
});
},
get _storedVersion() {
if (this.__storedVersion === undefined) {
// When the pref is not set, the storage version is unknown, so either:
// - it's a new profile
// - it's a profile where versioning information got lost
// In this case we still run through all of the valid migrations,
// starting from 1, as if it was a downgrade. As previously stated the
// migrations should already support running on an updated store.
this.__storedVersion =
Services.prefs.getIntPref("browser.newtabpage.storageVersion", 1);
}
return this.__storedVersion;
},
set _storedVersion(aValue) {
Services.prefs.setIntPref("browser.newtabpage.storageVersion", aValue);
this.__storedVersion = aValue;
return aValue;
},
/**
* Gets the value for a given key from the storage.
* @param aKey The storage key (a string).
* @param aDefault A default value if the key doesn't exist.
* @return The value for the given key.
*/
get: function Storage_get(aKey, aDefault) {
let value;
try {
let prefValue = Services.prefs.getStringPref(this._prefs[aKey]);
value = JSON.parse(prefValue);
} catch (e) {}
return value || aDefault;
},
/**
* Sets the storage value for a given key.
* @param aKey The storage key (a string).
* @param aValue The value to set.
*/
set: function Storage_set(aKey, aValue) {
// Page titles may contain unicode, thus use complex values.
Services.prefs.setStringPref(this._prefs[aKey], JSON.stringify(aValue));
},
/**
* Removes the storage value for a given key.
* @param aKey The storage key (a string).
*/
remove: function Storage_remove(aKey) {
Services.prefs.clearUserPref(this._prefs[aKey]);
},
/**
* Clears the storage and removes all values.
*/
clear: function Storage_clear() {
for (let key in this._prefs) {
this.remove(key);
}
},
};
/**
* Singleton that serves as a registry for all open 'New Tab Page's.
*/
var AllPages = {
/**
* The array containing all active pages.
*/
_pages: [],
/**
* Cached value that tells whether the New Tab Page feature is enabled.
*/
_enabled: null,
/**
* Adds a page to the internal list of pages.
* @param aPage The page to register.
*/
register: function AllPages_register(aPage) {
this._pages.push(aPage);
this._addObserver();
},
/**
* Removes a page from the internal list of pages.
* @param aPage The page to unregister.
*/
unregister: function AllPages_unregister(aPage) {
let index = this._pages.indexOf(aPage);
if (index > -1)
this._pages.splice(index, 1);
},
/**
* Returns whether the 'New Tab Page' is enabled.
*/
get enabled() {
if (this._enabled === null)
this._enabled = Services.prefs.getBoolPref(PREF_NEWTAB_ENABLED);
return this._enabled;
},
/**
* Enables or disables the 'New Tab Page' feature.
*/
set enabled(aEnabled) {
if (this.enabled != aEnabled)
Services.prefs.setBoolPref(PREF_NEWTAB_ENABLED, !!aEnabled);
},
/**
* Returns the number of registered New Tab Pages (i.e. the number of open
* about:newtab instances).
*/
get length() {
return this._pages.length;
},
/**
* Updates all currently active pages but the given one.
* @param aExceptPage The page to exclude from updating.
* @param aReason The reason for updating all pages.
*/
update(aExceptPage, aReason = "") {
for (let page of this._pages.slice()) {
if (aExceptPage != page) {
page.update(aReason);
}
}
},
/**
* Implements the nsIObserver interface to get notified when the preference
* value changes or when a new copy of a page thumbnail is available.
*/
observe: function AllPages_observe(aSubject, aTopic, aData) {
if (aTopic == "nsPref:changed") {
// Clear the cached value.
switch (aData) {
case PREF_NEWTAB_ENABLED:
this._enabled = null;
break;
}
}
// and all notifications get forwarded to each page.
this._pages.forEach(function(aPage) {
aPage.observe(aSubject, aTopic, aData);
}, this);
},
/**
* Adds a preference and new thumbnail observer and turns itself into a
* no-op after the first invokation.
*/
_addObserver: function AllPages_addObserver() {
Services.prefs.addObserver(PREF_NEWTAB_ENABLED, this, true);
Services.obs.addObserver(this, "page-thumbnail:create", true);
this._addObserver = function() {};
},
QueryInterface: ChromeUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference]),
};
/**
* Singleton that keeps track of all pinned links and their positions in the
* grid.
*/
var PinnedLinks = {
/**
* The cached list of pinned links.
*/
_links: null,
/**
* The array of pinned links.
*/
get links() {
if (!this._links)
this._links = Storage.get("pinnedLinks", []);
return this._links;
},
/**
* Pins a link at the given position.
* @param aLink The link to pin.
* @param aIndex The grid index to pin the cell at.
* @return true if link changes, false otherwise
*/
pin: function PinnedLinks_pin(aLink, aIndex) {
// Clear the link's old position, if any.
this.unpin(aLink);
// change pinned link into a history link
let changed = this._makeHistoryLink(aLink);
this.links[aIndex] = aLink;
this.save();
return changed;
},
/**
* Unpins a given link.
* @param aLink The link to unpin.
*/
unpin: function PinnedLinks_unpin(aLink) {
let index = this._indexOfLink(aLink);
if (index == -1)
return;
let links = this.links;
links[index] = null;
// trim trailing nulls
let i = links.length - 1;
while (i >= 0 && links[i] == null)
i--;
links.splice(i + 1);
this.save();
},
/**
* Saves the current list of pinned links.
*/
save: function PinnedLinks_save() {
Storage.set("pinnedLinks", this.links);
},
/**
* Checks whether a given link is pinned.
* @params aLink The link to check.
* @return whether The link is pinned.
*/
isPinned: function PinnedLinks_isPinned(aLink) {
return this._indexOfLink(aLink) != -1;
},
/**
* Resets the links cache.
*/
resetCache: function PinnedLinks_resetCache() {
this._links = null;
},
/**
* Finds the index of a given link in the list of pinned links.
* @param aLink The link to find an index for.
* @return The link's index.
*/
_indexOfLink: function PinnedLinks_indexOfLink(aLink) {
for (let i = 0; i < this.links.length; i++) {
let link = this.links[i];
if (link && link.url == aLink.url)
return i;
}
// The given link is unpinned.
return -1;
},
/**
* Transforms link into a "history" link
* @param aLink The link to change
* @return true if link changes, false otherwise
*/
_makeHistoryLink: function PinnedLinks_makeHistoryLink(aLink) {
if (!aLink.type || aLink.type == "history") {
return false;
}
aLink.type = "history";
return true;
},
/**
* Replaces existing link with another link.
* @param aUrl The url of existing link
* @param aLink The replacement link
*/
replace: function PinnedLinks_replace(aUrl, aLink) {
let index = this._indexOfLink({url: aUrl});
if (index == -1) {
return;
}
this.links[index] = aLink;
this.save();
},
};
/**
* Singleton that keeps track of all blocked links in the grid.
*/
var BlockedLinks = {
/**
* A list of objects that are observing blocked link changes.
*/
_observers: [],
/**
* The cached list of blocked links.
*/
_links: null,
/**
* Registers an object that will be notified when the blocked links change.
*/
addObserver(aObserver) {
this._observers.push(aObserver);
},
/**
* Remove the observers.
*/
removeObservers() {
this._observers = [];
},
/**
* The list of blocked links.
*/
get links() {
if (!this._links)
this._links = Storage.get("blockedLinks", {});
return this._links;
},
/**
* Blocks a given link. Adjusts siteMap accordingly, and notifies listeners.
* @param aLink The link to block.
*/
block: function BlockedLinks_block(aLink) {
this._callObservers("onLinkBlocked", aLink);
this.links[toHash(aLink.url)] = 1;
this.save();
// Make sure we unpin blocked links.
PinnedLinks.unpin(aLink);
},
/**
* Unblocks a given link. Adjusts siteMap accordingly, and notifies listeners.
* @param aLink The link to unblock.
*/
unblock: function BlockedLinks_unblock(aLink) {
if (this.isBlocked(aLink)) {
delete this.links[toHash(aLink.url)];
this.save();
this._callObservers("onLinkUnblocked", aLink);
}
},
/**
* Saves the current list of blocked links.
*/
save: function BlockedLinks_save() {
Storage.set("blockedLinks", this.links);
},
/**
* Returns whether a given link is blocked.
* @param aLink The link to check.
*/
isBlocked: function BlockedLinks_isBlocked(aLink) {
return (toHash(aLink.url) in this.links);
},
/**
* Checks whether the list of blocked links is empty.
* @return Whether the list is empty.
*/
isEmpty: function BlockedLinks_isEmpty() {
return Object.keys(this.links).length == 0;
},
/**
* Resets the links cache.
*/
resetCache: function BlockedLinks_resetCache() {
this._links = null;
},
_callObservers(methodName, ...args) {
for (let obs of this._observers) {
if (typeof(obs[methodName]) == "function") {
try {
obs[methodName](...args);
} catch (err) {
Cu.reportError(err);
}
}
}
},
};
/**
* Singleton that serves as the default link provider for the grid. It queries
* the history to retrieve the most frequently visited sites.
*/
var PlacesProvider = {
/**
* A count of how many batch updates are under way (batches may be nested, so
* we keep a counter instead of a simple bool).
**/
_batchProcessingDepth: 0,
/**
* A flag that tracks whether onFrecencyChanged was notified while a batch
* operation was in progress, to tell us whether to take special action after
* the batch operation completes.
**/
_batchCalledFrecencyChanged: false,
/**
* Set this to change the maximum number of links the provider will provide.
*/
maxNumLinks: HISTORY_RESULTS_LIMIT,
/**
* Must be called before the provider is used.
*/
init: function PlacesProvider_init() {
PlacesUtils.history.addObserver(this, true);
this._placesObserver =
new PlacesWeakCallbackWrapper(this.handlePlacesEvents.bind(this));
PlacesObservers.addListener(["page-visited"], this._placesObserver);
},
/**
* Gets the current set of links delivered by this provider.
* @param aCallback The function that the array of links is passed to.
*/
getLinks: function PlacesProvider_getLinks(aCallback) {
let options = PlacesUtils.history.getNewQueryOptions();
options.maxResults = this.maxNumLinks;
// Sort by frecency, descending.
options.sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_FRECENCY_DESCENDING;
let links = [];
let callback = {
handleResult(aResultSet) {
let row;
while ((row = aResultSet.getNextRow())) {
let url = row.getResultByIndex(1);
if (LinkChecker.checkLoadURI(url)) {
let title = row.getResultByIndex(2);
let frecency = row.getResultByIndex(12);
let lastVisitDate = row.getResultByIndex(5);
links.push({
url,
title,
frecency,
lastVisitDate,
type: "history",
});
}
}
},
handleError(aError) {
// Should we somehow handle this error?
aCallback([]);
},
handleCompletion(aReason) {
// The Places query breaks ties in frecency by place ID descending, but
// that's different from how Links.compareLinks breaks ties, because
// compareLinks doesn't have access to place IDs. It's very important
// that the initial list of links is sorted in the same order imposed by
// compareLinks, because Links uses compareLinks to perform binary
// searches on the list. So, ensure the list is so ordered.
let i = 1;
let outOfOrder = [];
while (i < links.length) {
if (Links.compareLinks(links[i - 1], links[i]) > 0)
outOfOrder.push(links.splice(i, 1)[0]);
else
i++;
}
for (let link of outOfOrder) {
i = BinarySearch.insertionIndexOf(Links.compareLinks, links, link);
links.splice(i, 0, link);
}
aCallback(links);
},
};
// Execute the query.
let query = PlacesUtils.history.getNewQuery();
PlacesUtils.history.asyncExecuteLegacyQuery(query, options, callback);
},
/**
* Registers an object that will be notified when the provider's links change.
* @param aObserver An object with the following optional properties:
* * onLinkChanged: A function that's called when a single link
* changes. It's passed the provider and the link object. Only the
* link's `url` property is guaranteed to be present. If its `title`
* property is present, then its title has changed, and the
* property's value is the new title. If any sort properties are
* present, then its position within the provider's list of links may
* have changed, and the properties' values are the new sort-related
* values. Note that this link may not necessarily have been present
* in the lists returned from any previous calls to getLinks.
* * onManyLinksChanged: A function that's called when many links
* change at once. It's passed the provider. You should call
* getLinks to get the provider's new list of links.
*/
addObserver: function PlacesProvider_addObserver(aObserver) {
this._observers.push(aObserver);
},
_observers: [],
/**
* Called by the history service.
*/
onBeginUpdateBatch() {
this._batchProcessingDepth += 1;
},
onEndUpdateBatch() {
this._batchProcessingDepth -= 1;
if (this._batchProcessingDepth == 0 && this._batchCalledFrecencyChanged) {
this.onManyFrecenciesChanged();
this._batchCalledFrecencyChanged = false;
}
},
handlePlacesEvents(aEvents) {
if (!this._batchProcessingDepth) {
for (let event of aEvents) {
if (event.visitCount == 1 && event.lastKnownTitle) {
this.onTitleChanged(event.url, event.lastKnownTitle, event.pageGuid);
}
}
}
},
onDeleteURI: function PlacesProvider_onDeleteURI(aURI, aGUID, aReason) {
// let observers remove sensetive data associated with deleted visit
this._callObservers("onDeleteURI", {
url: aURI.spec,
});
},
onClearHistory() {
this._callObservers("onClearHistory");
},
/**
* Called by the history service.
*/
onFrecencyChanged: function PlacesProvider_onFrecencyChanged(aURI, aNewFrecency, aGUID, aHidden, aLastVisitDate) {
// If something is doing a batch update of history entries we don't want
// to do lots of work for each record. So we just track the fact we need
// to call onManyFrecenciesChanged() once the batch is complete.
if (this._batchProcessingDepth > 0) {
this._batchCalledFrecencyChanged = true;
return;
}
// The implementation of the query in getLinks excludes hidden and
// unvisited pages, so it's important to exclude them here, too.
if (!aHidden && aLastVisitDate) {
this._callObservers("onLinkChanged", {
url: aURI.spec,
frecency: aNewFrecency,
lastVisitDate: aLastVisitDate,
type: "history",
});
}
},
/**
* Called by the history service.
*/
onManyFrecenciesChanged: function PlacesProvider_onManyFrecenciesChanged() {
this._callObservers("onManyLinksChanged");
},
/**
* Called by the history service.
*/
onTitleChanged: function PlacesProvider_onTitleChanged(aURI, aNewTitle, aGUID) {
if (aURI instanceof Ci.nsIURI) {
aURI = aURI.spec;
}
this._callObservers("onLinkChanged", {
url: aURI,
title: aNewTitle,
});
},
_callObservers: function PlacesProvider__callObservers(aMethodName, aArg) {
for (let obs of this._observers) {
if (obs[aMethodName]) {
try {
obs[aMethodName](this, aArg);
} catch (err) {
Cu.reportError(err);
}
}
}
},
QueryInterface: ChromeUtils.generateQI([Ci.nsINavHistoryObserver,
Ci.nsISupportsWeakReference]),
};
/**
* Queries history to retrieve the most frecent sites. Emits events when the
* history changes.
*/
var ActivityStreamProvider = {
/**
* Shared adjustment for selecting potentially blocked links.
*/
_adjustLimitForBlocked({ignoreBlocked, numItems}) {
// Just use the usual number if blocked links won't be filtered out
if (ignoreBlocked) {
return numItems;
}
// Additionally select the number of blocked links in case they're removed
return Object.keys(BlockedLinks.links).length + numItems;
},
/**
* Shared sub-SELECT to get the guid of a bookmark of the current url while
* avoiding LEFT JOINs on moz_bookmarks. This avoids gettings tags. The guid
* could be one of multiple possible guids. Assumes `moz_places h` is in FROM.
*/
_commonBookmarkGuidSelect: `(
SELECT guid
FROM moz_bookmarks b
WHERE fk = h.id
AND type = :bookmarkType
AND (
SELECT id
FROM moz_bookmarks p
WHERE p.id = b.parent
AND p.parent <> :tagsFolderId
) NOTNULL
) AS bookmarkGuid`,
/**
* Shared WHERE expression filtering out undesired pages, e.g., hidden,
* unvisited, and non-http/s urls. Assumes moz_places is in FROM / JOIN.
*
* NB: SUBSTR(url) is used even without an index instead of url_hash because
* most desired pages will match http/s, so it will only run on the ~10s of
* rows matched. If url_hash were to be used, it should probably *not* be used
* by the query optimizer as we primarily want it optimized for the other
* conditions, e.g., most frecent first.
*/
_commonPlacesWhere: `
AND hidden = 0
AND last_visit_date > 0
AND (SUBSTR(url, 1, 6) == "https:"
OR SUBSTR(url, 1, 5) == "http:")
`,
/**
* Shared parameters for getting correct bookmarks and LIMITed queries.
*/
_getCommonParams(aOptions, aParams = {}) {
return Object.assign({
bookmarkType: PlacesUtils.bookmarks.TYPE_BOOKMARK,
limit: this._adjustLimitForBlocked(aOptions),
tagsFolderId: PlacesUtils.tagsFolderId,
}, aParams);
},
/**
* Shared columns for Highlights related queries.
*/
_highlightsColumns: ["bookmarkGuid", "description", "guid",
"preview_image_url", "title", "url"],
/**
* Shared post-processing of Highlights links.
*/
_processHighlights(aLinks, aOptions, aType) {
// Filter out blocked if necessary
if (!aOptions.ignoreBlocked) {
aLinks = aLinks.filter(link =>
!BlockedLinks.isBlocked(link.pocket_id ? {url: link.open_url} : link));
}
// Limit the results to the requested number and set a type corresponding to
// which query selected it
return aLinks.slice(0, aOptions.numItems).map(item => Object.assign(item, {
type: aType,
}));
},
/**
* From an Array of links, if favicons are present, convert to data URIs
*
* @param {Array} aLinks
* an array containing objects with favicon data and mimeTypes
*
* @returns {Array} an array of links with favicons as data uri
*/
_faviconBytesToDataURI(aLinks) {
return aLinks.map(link => {
if (link.favicon) {
let encodedData = btoa(String.fromCharCode.apply(null, link.favicon));
link.favicon = `data:${link.mimeType};base64,${encodedData}`;
}
delete link.mimeType;
return link;
});
},
/**
* Get favicon data (and metadata) for a uri.
*
* @param aUri {nsIURI} Page to check for favicon data
* @returns A promise of an object (possibly null) containing the data
*/
_getIconData(aUri) {
// Use 0 to get the biggest width available
const preferredWidth = 0;
return new Promise(resolve => PlacesUtils.favicons.getFaviconDataForPage(
aUri,
// Package up the icon data in an object if we have it; otherwise null
(iconUri, faviconLength, favicon, mimeType, faviconSize) =>
resolve(iconUri ? {favicon, faviconLength, faviconRef: iconUri.ref, faviconSize, mimeType} : null),
preferredWidth));
},
/**
* Computes favicon data for each url in a set of links
*
* @param {Array} links
* an array containing objects without favicon data or mimeTypes yet
*
* @returns {Promise} Returns a promise with the array of links with the largest
* favicon available (as a byte array), mimeType, byte array
* length, and favicon size (width)
*/
_addFavicons(aLinks) {
// Each link in the array needs a favicon for it's page - so we fire off a
// promise for each link to compute the favicon data and attach it back to
// the original link object. We must wait until all favicons for the array
// of links are computed before returning
return Promise.all(aLinks.map(link => new Promise(async resolve => {
// Never add favicon data for pocket items
if (link.type === "pocket") {
resolve(link);
return;
}
let iconData;
try {
let linkUri = Services.io.newURI(link.url);
iconData = await this._getIconData(linkUri);
// Switch the scheme to try again with the other
if (!iconData) {
linkUri = linkUri.mutate()
.setScheme(linkUri.scheme === "https" ? "http" : "https")
.finalize();
iconData = await this._getIconData(linkUri);
}
} catch (e) {
// We just won't put icon data on the link
}
// Add the icon data to the link if we have any
resolve(Object.assign(link, iconData || {}));
})));
},
/**
* Helper function which makes the call to the Pocket API to fetch the user's
* saved Pocket items.
*/
fetchSavedPocketItems(requestData) {
return Promise.reject(null);
#if 0
const latestSince = (Services.prefs.getStringPref(PREF_POCKET_LATEST_SINCE, 0) * 1000);
// Do not fetch Pocket items for users that have been inactive for too long, or are not logged in
if (!pktApi.isUserLoggedIn() || (Date.now() - latestSince > POCKET_INACTIVE_TIME)) {
return Promise.resolve(null);
}
return new Promise((resolve, reject) => {
pktApi.retrieve(requestData, {
success(data) {
resolve(data);
},
error(error) {
reject(error);
},
});
});
#endif
},
/**
* Get the most recently Pocket-ed items from a user's Pocket list. See:
* https://getpocket.com/developer/docs/v3/retrieve for details
*
* @param {Object} aOptions
* {int} numItems: The max number of pocket items to fetch
*/
async getRecentlyPocketed(aOptions) {
const pocketSecondsAgo = Math.floor(Date.now() / 1000) - ACTIVITY_STREAM_DEFAULT_RECENT;
const requestData = {
detailType: "complete",
count: aOptions.numItems,
since: pocketSecondsAgo,
};
let data;
try {
data = await this.fetchSavedPocketItems(requestData);
if (!data) {
return [];
}
} catch (e) {
Cu.reportError(e);
return [];
}
/* Extract relevant parts needed to show this card as a highlight:
* url, preview image, title, description, and the unique item_id
* necessary for Pocket to identify the item
*/
let items = Object.values(data.list)
// status "0" means not archived or deleted
.filter(item => item.status === "0")
.map(item => ({
date_added: item.time_added * 1000,
description: item.excerpt,
preview_image_url: item.image && item.image.src,
title: item.resolved_title,
url: item.resolved_url,
pocket_id: item.item_id,
open_url: item.open_url,
}));
// Append the query param to let Pocket know this item came from highlights
for (let item of items) {
let url = new URL(item.open_url);
url.searchParams.append("src", "fx_new_tab");
item.open_url = url.href;
}
return this._processHighlights(items, aOptions, "pocket");
},
/**
* Get most-recently-created visited bookmarks for Activity Stream.