mirror of
https://github.com/Dasemu/Phenocheck.git
synced 2026-11-26 15:26:17 +00:00
142 lines
4.4 KiB
JavaScript
142 lines
4.4 KiB
JavaScript
// Background service worker – fetches "Account based in" country via X.com GraphQL.
|
||
// Persistent cache + throttled queue to avoid X rate limits.
|
||
|
||
const BEARER = 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA';
|
||
const ABOUT_QUERY_ID = 'TzOG2twZEfhr9KmClvVVqA';
|
||
|
||
const MIN_INTERVAL = 400; // ms between consecutive requests
|
||
const RATE_LIMIT_COOLDOWN = 60000; // ms to back off after a 429
|
||
const STORAGE_KEY = 'phenocheck_country_cache';
|
||
|
||
const memCache = new Map(); // handleLower -> country(string) | null
|
||
const queue = []; // { handle, resolve }
|
||
let processing = false;
|
||
let rateLimitedUntil = 0;
|
||
let storageLoaded = false;
|
||
|
||
// ── Persistent cache ────────────────────────────────────────────────
|
||
|
||
async function loadCache() {
|
||
if (storageLoaded) return;
|
||
try {
|
||
const data = await chrome.storage.local.get(STORAGE_KEY);
|
||
const obj = data[STORAGE_KEY];
|
||
if (obj && typeof obj === 'object') {
|
||
for (const [k, v] of Object.entries(obj)) memCache.set(k, v);
|
||
}
|
||
} catch {}
|
||
storageLoaded = true;
|
||
}
|
||
|
||
let saveTimer = null;
|
||
function scheduleSave() {
|
||
if (saveTimer) return;
|
||
saveTimer = setTimeout(async () => {
|
||
saveTimer = null;
|
||
try {
|
||
await chrome.storage.local.set({ [STORAGE_KEY]: Object.fromEntries(memCache) });
|
||
} catch {}
|
||
}, 1500);
|
||
}
|
||
|
||
// ── Messaging ───────────────────────────────────────────────────────
|
||
|
||
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||
if (message.type === 'FETCH_BASED_IN') {
|
||
handleRequest(message.handle).then(sendResponse).catch(() => sendResponse({ status: 'unavailable' }));
|
||
return true; // async
|
||
}
|
||
});
|
||
|
||
async function handleRequest(handle) {
|
||
await loadCache();
|
||
const key = handle.toLowerCase();
|
||
if (memCache.has(key)) {
|
||
return { status: 'ok', country: memCache.get(key) };
|
||
}
|
||
return new Promise((resolve) => {
|
||
queue.push({ handle, key, resolve });
|
||
processQueue();
|
||
});
|
||
}
|
||
|
||
// ── Throttled queue ─────────────────────────────────────────────────
|
||
|
||
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|
||
|
||
async function processQueue() {
|
||
if (processing) return;
|
||
processing = true;
|
||
while (queue.length) {
|
||
const job = queue.shift();
|
||
|
||
// Already resolved by a concurrent request?
|
||
if (memCache.has(job.key)) {
|
||
job.resolve({ status: 'ok', country: memCache.get(job.key) });
|
||
continue;
|
||
}
|
||
// Backing off due to rate limit → respond unavailable, don't cache
|
||
if (Date.now() < rateLimitedUntil) {
|
||
job.resolve({ status: 'unavailable' });
|
||
continue;
|
||
}
|
||
|
||
const result = await doFetch(job.handle, job.key);
|
||
job.resolve(result);
|
||
|
||
if (result.status === 'ok') await sleep(MIN_INTERVAL);
|
||
}
|
||
processing = false;
|
||
}
|
||
|
||
async function getCsrf() {
|
||
try {
|
||
const cookie = await chrome.cookies.get({ url: 'https://x.com', name: 'ct0' });
|
||
return cookie ? cookie.value : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function doFetch(handle, key) {
|
||
const ct0 = await getCsrf();
|
||
if (!ct0) return { status: 'unavailable' };
|
||
|
||
const url =
|
||
'https://x.com/i/api/graphql/' + ABOUT_QUERY_ID + '/AboutAccountQuery?variables=' +
|
||
encodeURIComponent(JSON.stringify({ screenName: handle }));
|
||
|
||
try {
|
||
const res = await fetch(url, {
|
||
headers: {
|
||
'authorization': BEARER,
|
||
'x-csrf-token': ct0,
|
||
'x-twitter-active-user': 'yes',
|
||
'x-twitter-auth-type': 'OAuth2Session',
|
||
'x-twitter-client-language': 'en',
|
||
'content-type': 'application/json',
|
||
},
|
||
credentials: 'include',
|
||
});
|
||
|
||
if (res.status === 429) {
|
||
rateLimitedUntil = Date.now() + RATE_LIMIT_COOLDOWN;
|
||
return { status: 'unavailable' };
|
||
}
|
||
if (!res.ok) {
|
||
return { status: 'unavailable' };
|
||
}
|
||
|
||
const data = await res.json();
|
||
const country =
|
||
data?.data?.user_result_by_screen_name?.result?.about_profile?.account_based_in ?? null;
|
||
|
||
// Cache successful lookups (including genuine "no country" as null)
|
||
memCache.set(key, country);
|
||
scheduleSave();
|
||
return { status: 'ok', country };
|
||
} catch {
|
||
return { status: 'unavailable' };
|
||
}
|
||
}
|