TippyTopProvider.jsm 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
  5. XPCOMUtils.defineLazyGlobalGetters(this, ["fetch", "URL"]);
  6. const TIPPYTOP_JSON_PATH = "resource://activity-stream/data/content/tippytop/top_sites.json";
  7. const TIPPYTOP_URL_PREFIX = "resource://activity-stream/data/content/tippytop/images/";
  8. function getDomain(url) {
  9. let domain;
  10. try {
  11. domain = new URL(url).hostname;
  12. } catch (ex) {}
  13. if (domain && domain.startsWith("www.")) {
  14. domain = domain.slice(4);
  15. }
  16. return domain;
  17. }
  18. this.TippyTopProvider = class TippyTopProvider {
  19. constructor() {
  20. this._sitesByDomain = new Map();
  21. this.initialized = false;
  22. }
  23. async init() {
  24. // Load the Tippy Top sites from the json manifest.
  25. try {
  26. for (const site of await (await fetch(TIPPYTOP_JSON_PATH, {credentials: "omit"})).json()) {
  27. // The tippy top manifest can have a url property (string) or a
  28. // urls property (array of strings)
  29. for (const url of site.url ? [site.url] : site.urls || []) {
  30. this._sitesByDomain.set(getDomain(url), site);
  31. }
  32. }
  33. this.initialized = true;
  34. } catch (error) {
  35. Cu.reportError("Failed to load tippy top manifest.");
  36. }
  37. }
  38. processSite(site) {
  39. const tippyTop = this._sitesByDomain.get(getDomain(site.url));
  40. if (tippyTop) {
  41. site.tippyTopIcon = TIPPYTOP_URL_PREFIX + tippyTop.image_url;
  42. site.backgroundColor = tippyTop.background_color;
  43. }
  44. return site;
  45. }
  46. };
  47. const EXPORTED_SYMBOLS = ["TippyTopProvider", "getDomain"];