summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/lib/TippyTopProvider.jsm
blob: f0e50ad329631faf627f23977b6754fddc3926ca (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
/* 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/. */

const TIPPYTOP_PATH = "chrome://activity-stream/content/data/content/tippytop/";
const TIPPYTOP_JSON_PATH =
  "chrome://activity-stream/content/data/content/tippytop/top_sites.json";

/*
 * Get a domain from a url optionally stripping subdomains.
 */
function getDomain(url, strip = "www.") {
  let domain = "";
  try {
    domain = new URL(url).hostname;
  } catch (ex) {}
  if (strip === "*") {
    try {
      domain = Services.eTLD.getBaseDomainFromHost(domain);
    } catch (ex) {}
  } else if (domain.startsWith(strip)) {
    domain = domain.slice(strip.length);
  }
  return domain;
}

class TippyTopProvider {
  constructor() {
    this._sitesByDomain = new Map();
    this.initialized = false;
  }

  async init() {
    // Load the Tippy Top sites from the json manifest.
    try {
      for (const site of await (
        await fetch(TIPPYTOP_JSON_PATH, {
          credentials: "omit",
        })
      ).json()) {
        for (const domain of site.domains) {
          this._sitesByDomain.set(domain, site);
        }
      }
      this.initialized = true;
    } catch (error) {
      console.error("Failed to load tippy top manifest.");
    }
  }

  processSite(site, strip) {
    const tippyTop = this._sitesByDomain.get(getDomain(site.url, strip));
    if (tippyTop) {
      site.tippyTopIcon = TIPPYTOP_PATH + tippyTop.image_url;
      site.smallFavicon = TIPPYTOP_PATH + tippyTop.favicon_url;
      site.backgroundColor = tippyTop.background_color;
    }
    return site;
  }
}

const EXPORTED_SYMBOLS = ["TippyTopProvider", "getDomain"];