Skip to content

Instantly share code, notes, and snippets.

@wont-stream
Last active April 23, 2024 03:26
Show Gist options
  • Save wont-stream/6734cfc7eeb3bcae221f1d9b2e023951 to your computer and use it in GitHub Desktop.
Save wont-stream/6734cfc7eeb3bcae221f1d9b2e023951 to your computer and use it in GitHub Desktop.
cloudflare worker for analytics
export default {
async fetch(request, env, ctx) {
const { cf, headers, url } = request;
const { continent, country, city, regionCode } = cf;
const path = new URL(url).pathname;
if (!path.startsWith("/_/"))
return new Response(
await (await fetch("https://http.cat/418")).arrayBuffer(),
{
status: 418,
headers: {
"content-type": "image/jpeg",
},
},
);
const ref = await getRef(path.replace("/_/", ""));
const hook = await fetch("WEBHOOK", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
content: null,
embeds: [
{
title: `${city}, ${regionCode}, ${country} ${continent} :flag_${country.toLowerCase()}:`,
color: null,
fields: [
{
name: "User Agent",
value: headers.get("user-agent"),
},
{
name: "Referer",
value: ref,
},
],
timestamp: new Date(),
},
],
username: `${headers.get("CF-Connecting-IP")}`,
avatar_url: `https://api.dicebear.com/8.x/rings/png?seed=${headers.get("CF-Connecting-IP")}`,
attachments: [],
flags: 4096,
}),
});
return new Response(JSON.stringify(hook.json()), {
headers: {
"Access-Control-Allow-Origin": "https://wont.stream",
},
});
},
};
const getRef = async (referer) => {
const database = await (
await fetch(
"https://cdn.jsdelivr.net/gh/wont-stream/snowplow-referer-minified@main/referers-latest.min.json",
)
).json();
const refHost = (() => {
try {
return new URL(referer).host;
} catch (e) {
return "Unknown";
}
})();
for (let cat of Object.keys(database)) {
for (let comp of Object.keys(database[cat])) {
if (database[cat][comp].domains.includes(refHost)) {
return comp;
}
}
}
return refHost;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment