Feat: Include user geolocation in ntfy notifications

This commit is contained in:
2026-02-17 15:58:54 -08:00
parent 3763e4fa84
commit 249e7bb99a

View File

@@ -42,12 +42,14 @@ export default {
const id = env.MY_DURABLE_OBJECT.idFromName(uid); const id = env.MY_DURABLE_OBJECT.idFromName(uid);
const stub = env.MY_DURABLE_OBJECT.get(id); const stub = env.MY_DURABLE_OBJECT.get(id);
const { city, region, country } = req.cf || {}; const cf = req.cf || {};
const loc = [city, region, country].filter(Boolean).join(', ') || 'Unknown'; const locParts = [cf.city, cf.region, cf.country].filter(Boolean);
const proxied = new Request(req.url, req); const location = locParts.length ? locParts.join(', ') : 'Unknown';
proxied.headers.set('X-Client-Geo', loc);
const resp = await stub.fetch(proxied); const doReq = new Request(req.url, req);
doReq.headers.set('X-Client-Location', location);
const resp = await stub.fetch(doReq);
return isWs ? resp : withCORS(resp); return isWs ? resp : withCORS(resp);
} }
@@ -98,10 +100,9 @@ export class MyDurableObject {
notify(msg, pri = 3, tags = []) { notify(msg, pri = 3, tags = []) {
if (!this.env.NTFY_URL) return; if (!this.env.NTFY_URL) return;
const headers = { Title: 'Sune ORP', Priority: `${pri}`, Tags: tags.join(',') }; const headers = { Title: 'Sune ORP', Priority: `${pri}`, Tags: tags.join(',') };
const body = `[${this.location}] ${msg}`;
this.state.waitUntil(fetch(this.env.NTFY_URL, { this.state.waitUntil(fetch(this.env.NTFY_URL, {
method: 'POST', method: 'POST',
body, body: `${msg}\n📍 ${this.location}`,
headers, headers,
}).catch(e => console.error('ntfy failed:', e))); }).catch(e => console.error('ntfy failed:', e)));
} }
@@ -190,11 +191,11 @@ export class MyDurableObject {
} }
async fetch(req) { async fetch(req) {
const geo = req.headers.get('X-Client-Geo');
if (geo && geo !== 'Unknown') this.location = geo;
if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: CORS_HEADERS }); if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: CORS_HEADERS });
const incomingLocation = req.headers.get('X-Client-Location');
if (incomingLocation) this.location = incomingLocation;
if (req.headers.get('Upgrade') === 'websocket') { if (req.headers.get('Upgrade') === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()); const [client, server] = Object.values(new WebSocketPair());
server.accept(); server.accept();