-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackground.js
67 lines (60 loc) · 1.76 KB
/
background.js
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
const blacklistedHostName = [
"localhost",
"127.0.0.1",
"facebook.com",
]
const blacklistedProtocol = [
]
function isValidUrl(url) {
try {
url = new URL(url)
return !blacklistedHostName.includes(url.hostname)
&& ! blacklistedProtocol.includes(url.protocol)
} catch(e) {
console.error("Invalid url: ", url)
console.error(e)
return false;
}
}
async function getLastModified(url) {
try {
let res = await fetch(url, {method: 'head'})
return new Date(res.headers.get("Last-Modified"))
} catch(e) {
console.error("Couldn't fetch last updated time of", url, e)
return new Date();
}
}
function archive_org(url) {
return fetch(`https://web.archive.org/save/${url}`, {method: 'head'})
}
async function archiveAndUpdate(url) {
console.info("Archiving ", url)
let lastModified = await getLastModified(url);
let lastArchived = await browser.storage.local.get(url);;
console.info("Last archived on ", lastArchived[url])
console.info("Last modified on ", new Date(lastModified))
if(lastArchived && new Date(lastArchived[url]).getTime() >= lastModified ) {
console.info("Already up to date.")
return;
}
console.log("Archiving.")
try {
let res = await archive_org(url)
if(res.ok && res.status === 200) {
let object = {}
object[url] = lastModified
await browser.storage.local.set(object)
}
} catch(e) {
console.error(e)
}
}
browser.bookmarks.onCreated.addListener(onBookmarked)
async function onBookmarked(id, bookmark) {
let {title, url, dateAdded } = bookmark;
if(!url || !isValidUrl(url)){
return;
}
return await archiveAndUpdate(url)
}