summaryrefslogtreecommitdiffstats
path: root/background.js
blob: 0f6a3a9af81154df965c87b55db86eee3fca0a6d (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
import { setIcon } from "./util.js";

let urls = new Set();
let lastUrlsUpdateTime = 0;
let updating = false;

function updateUrls() {
  return browser.storage.local
    .get(["apiUrl", "authToken"])
    .then(async ({ apiUrl, authToken }) => {
      if (!apiUrl) {
        console.warn("API URL not configured.");
        setIcon(tabId, "default");
        return;
      }

      await fetch(`${apiUrl}/entry`, {
        headers: {
          Authorization: authToken ? `Bearer ${authToken}` : undefined,
        },
      })
        .then((response) => response.json())
        .then((data) => {
          urls = new Set(data.data);
          lastUrlsUpdateTime = Date.now();
        })
        .catch((error) => {
          console.error(error);
        });
    });
}

async function handleTabUpdate(tabId, url) {
  setIcon(tabId, "wait");

  if (updating) {
    return;
  }

  if (Date.now() - lastUrlsUpdateTime > 10 * 60 * 1000) {
    updating = true;
    await updateUrls();
    updating = false;
  }

  if (urls.has(url)) {
    setIcon(tabId, "saved");
  } else {
    setIcon(tabId, "ready");
  }
}

browser.tabs.onActivated.addListener(async (activeInfo) => {
  const tab = await browser.tabs.get(activeInfo.tabId);
  if (tab.url && tab.url.startsWith("http")) {
    handleTabUpdate(tab.id, tab.url);
  }
});

browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (
    changeInfo.status === "loading" &&
    tab.active &&
    tab.url?.startsWith("http")
  ) {
    setIcon(tabId, "wait");
  }

  if (
    changeInfo.status === "complete" &&
    tab.active &&
    tab.url?.startsWith("http")
  ) {
    handleTabUpdate(tabId, tab.url);
  }
});

browser.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action === "addSavedUrl") {
    urls.add(request.data.url);
  } else if (request.action === "removeSavedUrl") {
    urls.delete(request.data.url);
  }
});