-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
190 lines (159 loc) · 6.41 KB
/
background.js
File metadata and controls
190 lines (159 loc) · 6.41 KB
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
function normalizeUrl(inputUrl) {
try {
const url = new URL(inputUrl);
// Remove 'www.' from hostname
let hostname = url.hostname.replace(/^www\./, '');
// Remove trailing slashes from pathname
let pathname = url.pathname.replace(/\/+$/, '');
// Reconstruct the normalized URL without protocol
let normalized = `${hostname}${pathname}`;
// Include query and hash if present
if (url.search) normalized += url.search;
if (url.hash) normalized += url.hash;
return normalized;
} catch (e) {
console.error('Invalid URL:', inputUrl);
return null;
}
}
var ENDPOINT_URL = "https://artemis.jamesg.blog";
var CACHE_PREFIX = "";
if (ENDPOINT_URL.includes("localhost")) {
CACHE_PREFIX = "staging-";
}
console.log("Cache prefix:", CACHE_PREFIX);
var date = new Date();
var today = date.toISOString().split("T")[0];
var failed = false;
function getCache() {
console.log("No cache found for today. Fetching links from Artemis.");
return new Promise((resolve, reject) => {
chrome.storage.local.get("api-key", (result) => {
if (chrome.runtime.lastError) {
reject(new Error("Error fetching API key from storage."));
return;
}
const apiKey = result["api-key"];
if (!apiKey) {
reject(new Error("API key not found in storage."));
return;
}
fetch(ENDPOINT_URL + "/link-graph.json", {
method: "GET",
headers: new Headers({
"Authorization": apiKey
}),
})
.then(response => {
if (response.status === 401) {
console.error("Unauthorized: Invalid API key.");
throw new Error("Unauthorized");
}
return response.json();
})
.then(data => {
// delete all other cache
chrome.storage.local.get(null, function(items) {
for (var key in items) {
if (key.startsWith(CACHE_PREFIX) && key !== `${CACHE_PREFIX}link-graph-${today}` && key !== "api-key") {
chrome.storage.local.remove(key);
}
}
});
console.log("Fetched links from Artemis.");
chrome.storage.local.set({ [`${CACHE_PREFIX}link-graph-${today}`]: JSON.stringify(data) }, () => {
resolve(data); // Resolve the Promise with the fetched data
});
})
.catch(err => {
console.error("Failed to fetch links from Artemis.");
console.error(err);
reject(err); // Reject the Promise in case of error
});
});
});
}
console.log("Configuring link graph... for today:", today);
function updateTab (activeInfo, cache) {
var tabId = (typeof activeInfo === "number") ? activeInfo : activeInfo.tabId;
// console.log("Updating tab:", tabId);
chrome.action.setBadgeText({ text: "" });
chrome.action.setIcon({"path": "mascot.png"});
if (!tabId) return;
chrome.tabs.get(tabId, function (tab) {
chrome.action.setBadgeText({ text: "" });
if (!cache) return; // Ensure cache is available
var subscriptions = cache["subscriptions"];
var tabDomain = new URL(tab.url).hostname;
var tabPath = new URL(tab.url).pathname;
tabPath = tabPath.replace(/\/$/, '');
tabPath = tabPath || "/";
var linksForPage = cache["links"]?.[tabDomain]?.[tabPath] || [];
if (linksForPage.length > 0) {
chrome.action.setBadgeText({ text: linksForPage.length.toString() });
chrome.action.setBadgeBackgroundColor({ color: "#" + cache["preferences"]["theme_color"] || "royalblue" });
}
if (subscriptions.includes(tabDomain)) {
chrome.action.setIcon({"path": "link_found.png"});
}
});
}
function setupListeners(cache) {
chrome.tabs.onActivated.addListener((activeInfo) => {
updateTab(activeInfo, cache);
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
updateTab(tabId, cache);
});
chrome.tabs.onCreated.addListener((tab) => {
updateTab(tab.id, cache);
});
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs[0]) updateTab({ tabId: tabs[0].id }, cache);
});
}
chrome.storage.local.get(`${CACHE_PREFIX}link-graph-${today}`, (result) => {
var cache = result[`${CACHE_PREFIX}link-graph-${today}`] ? JSON.parse(result[`${CACHE_PREFIX}link-graph-${today}`]) : null;
getCache().then((data) => {
cache = data;
setupListeners(cache);
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
updateTab({ tabId: tabs[0].id });
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "getLinks") {
if (!cache) {
sendResponse({ failed: true });
return;
}
var url = normalizeUrl(request.url);
var tabDomain = new URL(request.url).hostname;
var tabPath = new URL(request.url).pathname;
// trim / from path
tabPath = tabPath.replace(/\/$/, '');
// if no path, set to /
tabPath = tabPath || "/";
// remove www from domain
tabDomain = tabDomain.replace(/^www\./, '');
sendResponse({
links: cache["links"]?.[tabDomain]?.[tabPath] || [],
failed: failed,
bidirectional_links: cache["bidirectional_links"] || [] ,
subscribedTo: cache["subscribed_to"] || []
});
} else if (request.action === "setApiKey") {
chrome.storage.local.set({ "api-key": request.key });
getCache().then(() => {
sendResponse({ success: true });
});
}
return true;
});
})
.catch(err => {
failed = true;
console.error("Failed to fetch links from Artemis.");
console.error(err);
chrome.action.setBadgeText({ text: "!" });
});
});