-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
224 lines (199 loc) · 7.6 KB
/
Copy pathbackground.js
File metadata and controls
224 lines (199 loc) · 7.6 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// background.js
// Periodically checks tracked Amazon products and fires a notification the moment
// one flips back to free shipping. Runs as a non-persistent event page: all
// listeners are registered synchronously at top level, and all state lives in
// storage.local so nothing is lost when the page unloads between alarms.
const STORE = { products: "products", settings: "settings" };
const ALARM = "freeship-check";
const CHECK_GAP_MS = 1600; // polite spacing between per-product requests
const TAB_RENDER_MS = 2600; // extra settle time for Amazon's delivery block JS
// ---- storage helpers -------------------------------------------------------
async function getProducts() {
const data = await browser.storage.local.get(STORE.products);
return Array.isArray(data.products) ? data.products : [];
}
async function saveProducts(products) {
await browser.storage.local.set({ [STORE.products]: products });
}
async function getSettings() {
const data = await browser.storage.local.get(STORE.settings);
return Object.assign(
{ intervalMinutes: 30, webhookUrl: "", freeRegex: "", chargeRegex: "", unavailableRegex: "" },
data.settings || {}
);
}
function detectOpts(settings) {
const o = {};
if (settings.freeRegex) o.freeRegex = settings.freeRegex;
if (settings.chargeRegex) o.chargeRegex = settings.chargeRegex;
if (settings.unavailableRegex) o.unavailableRegex = settings.unavailableRegex;
return o;
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ---- page fetching ---------------------------------------------------------
// Primary path: invisible, cheap, uses the signed-in Amazon session (so the
// Israel delivery address is reflected in the returned HTML).
async function fetchViaHttp(url) {
const res = await fetch(url, {
credentials: "include",
headers: { "Accept-Language": "en-US,en;q=0.9" }
});
return await res.text();
}
// Fallback path: render the page in a background tab and read the live DOM.
// Slower and briefly shows a tab, but survives bot checks and async rendering.
async function fetchViaTab(url) {
const tab = await browser.tabs.create({ url, active: false });
try {
await waitForComplete(tab.id, 20000);
await sleep(TAB_RENDER_MS);
const results = await browser.tabs.executeScript(tab.id, {
code: "document.documentElement.outerHTML"
});
return results && results[0];
} finally {
browser.tabs.remove(tab.id).catch(() => {});
}
}
function waitForComplete(tabId, timeoutMs) {
return new Promise((resolve) => {
const deadline = Date.now() + timeoutMs;
(function poll() {
browser.tabs
.get(tabId)
.then((t) => {
if (t.status === "complete" || Date.now() > deadline) resolve();
else setTimeout(poll, 300);
})
.catch(() => resolve());
})();
});
}
// Check one product, preferring the cheap path and falling back when the result
// is missing or ambiguous.
async function checkProduct(url, opts) {
let result;
try {
result = FreeShipDetect.detect(await fetchViaHttp(url), opts);
} catch (e) {
result = { ok: false, reason: "neterr" };
}
if (!result.ok || result.status === "unknown") {
try {
const html = await fetchViaTab(url);
const viaTab = FreeShipDetect.detect(html, opts);
if (viaTab.ok) result = viaTab;
} catch (e) {
/* keep the http result */
}
}
return result;
}
// ---- the check loop --------------------------------------------------------
let running = false;
async function checkAll() {
if (running) return;
running = true;
try {
const settings = await getSettings();
const opts = detectOpts(settings);
let products = await getProducts();
for (let i = 0; i < products.length; i++) {
const result = await checkProduct(products[i].url, opts);
products = await getProducts(); // re-read in case the popup edited the list
const p = products.find((x) => x.asin === products[i].asin) || products[i];
applyResult(p, result, settings);
await saveProducts(products);
if (i < products.length - 1) await sleep(CHECK_GAP_MS);
}
} finally {
running = false;
}
}
async function checkOne(asin) {
const settings = await getSettings();
const products = await getProducts();
const p = products.find((x) => x.asin === asin);
if (!p) return;
const result = await checkProduct(p.url, settings ? detectOpts(settings) : {});
applyResult(p, result, settings);
await saveProducts(products);
}
// Fold a detection result into a product record and decide about notifying.
// "Returns to free" semantics: we notify only when a KNOWN non-free item turns
// free — the first successful read just establishes a baseline.
function applyResult(p, result, settings) {
p.lastChecked = Date.now();
if (!result.ok) {
p.error = result.reason || "error";
return;
}
p.error = null;
p.status = result.status;
p.snippet = result.snippet || p.snippet;
if (result.title && !p.title) p.title = result.title;
if (result.price) p.price = result.price;
if (result.image) p.image = result.image;
const hadBaseline = typeof p.lastFree === "boolean";
const wasFree = p.lastFree === true;
if (result.freeShip) {
if (hadBaseline && !wasFree && !p.notifiedFree) {
notifyFree(p, settings);
p.notifiedFree = true;
}
} else {
p.notifiedFree = false; // armed again for the next return-to-free
}
p.lastFree = result.freeShip;
}
// ---- notifications ---------------------------------------------------------
function notifyFree(p, settings) {
const id = "fsopen::" + p.asin + "::" + p.lastChecked;
browser.notifications.create(id, {
type: "basic",
iconUrl: browser.runtime.getURL("icons/icon.svg"),
title: "Free shipping is back",
message: (p.title || p.asin) + (p.price ? " · " + p.price : "") + "\nShips free to Israel again."
});
if (settings && settings.webhookUrl) sendWebhook(p, settings.webhookUrl);
}
async function sendWebhook(p, webhookUrl) {
// Body/headers are shaped for ntfy.sh (which can forward to email), but any
// endpoint that accepts a POST works.
try {
await fetch(webhookUrl, {
method: "POST",
headers: { "Content-Type": "text/plain", Title: "Free shipping is back", Tags: "package,tada" },
body: (p.title || p.asin) + " ships free to Israel again\n" + (p.price ? p.price + "\n" : "") + p.url
});
} catch (e) {
/* best effort */
}
}
browser.notifications.onClicked.addListener(async (id) => {
if (!id.startsWith("fsopen::")) return;
const asin = id.split("::")[1];
const products = await getProducts();
const p = products.find((x) => x.asin === asin);
browser.tabs.create({ url: p ? p.url : FreeShipDetect.canonicalUrl(asin) });
browser.notifications.clear(id);
});
// ---- messages from the popup ----------------------------------------------
browser.runtime.onMessage.addListener((msg) => {
if (msg && msg.type === "checkAll") return checkAll().then(() => ({ ok: true }));
if (msg && msg.type === "checkOne") return checkOne(msg.asin).then(() => ({ ok: true }));
if (msg && msg.type === "reschedule") return schedule().then(() => ({ ok: true }));
return false;
});
// ---- scheduling ------------------------------------------------------------
async function schedule() {
const settings = await getSettings();
const mins = Math.max(5, Number(settings.intervalMinutes) || 30);
await browser.alarms.clear(ALARM);
browser.alarms.create(ALARM, { periodInMinutes: mins, delayInMinutes: 1 });
}
browser.alarms.onAlarm.addListener((a) => {
if (a.name === ALARM) checkAll();
});
browser.runtime.onInstalled.addListener(schedule);
browser.runtime.onStartup.addListener(schedule);