-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.ts
189 lines (166 loc) · 5.19 KB
/
background.ts
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
/// <reference types="chrome"/>
console.log("background.ts is loaded");
// NB: must match what the Bloom Gallery component expects
type DownloadMetadata = {
urlOfPage: string;
url: string;
filename: string;
when: Date;
};
const downloads: DownloadMetadata[] = [];
async function postDownloadsToBloom() {
if (downloads.length === 0) return;
try {
console.log(
"Attempting post of downloads to Bloom:",
JSON.stringify(downloads, null, 2)
);
const response = await fetch(
"http://localhost:5000/image-gallery/takeDownloads",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(downloads),
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
console.log("Successfully posted to Bloom.");
// Clear the array after successful POST
downloads.length = 0;
} catch (error) {
console.error("Error posting to Bloom:", error);
}
}
// Periodic try to deliver
setInterval(postDownloadsToBloom, 1000);
function updateIcon(tabId: number, shouldEnable: boolean) {
const iconPath =
downloads.length > 0
? "icon-when-queued.png"
: shouldEnable
? "icon.png"
: "icon-disabled.png";
chrome.action.setIcon({
path: iconPath,
tabId: tabId,
});
if (shouldEnable) {
chrome.action.enable(tabId);
}
}
// chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// console.log(`onUpdated ${tabId}`, changeInfo, tab);
// if (tab.url) {
// const url = new URL(tab.url);
// const shouldEnable = hostPatterns.some((pattern) => {
// const regexp = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
// return regexp.test(url.href);
// });
// updateIcon(tabId, shouldEnable);
// }
// });
// chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// console.log("onMessage", request);
// if (request.type === "checkSupport") {
// try {
// const url = new URL(request.url);
// const isSupported = hostPatterns.some((pattern) => {
// const regexp = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
// return regexp.test(url.href);
// });
// console.log(`URL ${url} supported: ${isSupported}`);
// sendResponse({ isSupported });
// } catch (e) {
// console.error("Error checking URL support:", e);
// sendResponse({ isSupported: false });
// }
// } else if (request.type === "getQueueStatus") {
// sendResponse({ queuedCount: downloads.length });
// }
// return true;
// });
function isImage(url: string): boolean {
const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"];
const lowerUrl = url.toLowerCase();
return imageExtensions.some((ext) => lowerUrl.endsWith(ext));
}
// Add download completion listener before the runtime.onMessage listener
chrome.downloads.onDeterminingFilename.addListener(
async (downloadItem, suggest) => {
if (
!(
isImage(downloadItem.url) ||
(downloadItem.filename && isImage(downloadItem.filename))
)
)
return;
//suggest();
console.log(
`onDeterminingFilename: ${JSON.stringify(downloadItem, null, 2)}`
);
// Get the current tab's URL
const tabs = await chrome.tabs.query({
active: true,
currentWindow: true,
});
const currentPage = tabs[0]?.url || "";
downloads.push({
urlOfPage: currentPage,
url: downloadItem.url,
filename: downloadItem.filename,
when: new Date(),
});
console.log(`Queued download:`, downloads[downloads.length - 1]);
// Update icons in all tabs when queue changes
chrome.tabs.query({}, (tabs) => {
tabs.forEach((tab) => {
if (tab.id) updateIcon(tab.id, true);
});
});
}
);
/*
In this experiment, I was preventing the download and jsut recording
chrome.downloads.onCreated.addListener(async (downloadItem) => {
console.log(`onCreated`);
chrome.downloads.cancel(downloadItem.id);
console.log(`Intercepted download: ${downloadItem.url}`);
// Get the current active tab's URL
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const currentPage = tabs[0]?.url;
for (const adapter of adapters) {
if (adapter.canHandleDownload(downloadItem.url)) {
const metadata = await adapter.getMetadata(currentPage, downloadItem.url);
if (metadata) {
// Store the metadata in our array
queuedDownloads.push(metadata);
// Update icons in all tabs when queue changes
chrome.tabs.query({}, (tabs) => {
tabs.forEach((tab) => {
if (tab.id) updateIcon(tab.id, true);
});
});
postDownloadsToBloom();
} else {
chrome.notifications.create({
type: "basic",
iconUrl: "icon.png",
title: "Bloom Downloader",
message: "Could not get the metadata for that image.",
});
}
}
break;
}
});
*/
// Listen for messages from the popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "GET_QUEUE_SIZE") {
sendResponse({ number: downloads.length });
}
});