Something went wrong. Try again.
Records what you watch to Popfeed, via ATProto, using a Cloudflare Worker. Currently supports Jellyfin and Stremio.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178/** Small shared helpers. */
/** Drop keys that are undefined, null, empty string, or empty array. */export function compact(obj) { return Object.fromEntries( Object.entries(obj).filter( ([, v]) => v !== undefined && v !== null && v !== '' && !(Array.isArray(v) && v.length === 0) ) );}
/** Jellyfin sends numbers as strings, and empty string for "absent". */export function toInt(value) { if (value === null || value === undefined || value === '') return null; // Only plain decimal integers. Number() alone would accept "0x10" as 16 and // "1e3" as 1000, neither of which is a season or an episode number. const text = String(value).trim(); return /^-?\d+$/.test(text) ? Number(text) : null;}
/** Handlebars may render a boolean as true or as the string "True". */export function isTrue(value) { return value === true || value === 1 || /^(true|1)$/i.test(String(value));}
/** * Validate an external id before it reaches a URL path, a KV key, or a * permanent ATProto record. A media server hands over whatever its metadata * provider happened to store, which is not always an id. */const ID_PATTERNS = { tmdb: /^\d{1,12}$/, imdb: /^tt\d{6,12}$/, tvdb: /^\d{1,12}$/,};
export function externalId(kind, value) { const id = String(value ?? '').trim(); return ID_PATTERNS[kind].test(id) ? id : undefined;}
/** * Handlebars escapes for HTML, not for JSON, so a title arrives entity-encoded: * "Rock & Roll" becomes "Rock & Roll" and "Don't Look Up" becomes * "Don't Look Up". Decode it before it reaches a record. * * The named set is exactly what Handlebars escapes, so it is complete rather * than a guess. Numeric forms are handled too, because ' is how it writes * an apostrophe. A single pass is deliberate: "&lt;" must decode to "<", * not to "<". */const NAMED_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'",};
export function decodeEntities(value) { if (typeof value !== 'string' || !value.includes('&')) return value; return value.replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (whole, code) => { if (code[0] !== '#') return NAMED_ENTITIES[code.toLowerCase()] ?? whole; const point = code[1] === 'x' || code[1] === 'X' ? parseInt(code.slice(2), 16) : Number(code.slice(1)); if (!Number.isInteger(point) || point < 0 || point > 0x10ffff) return whole; return String.fromCodePoint(point); });}
/** * A cached lookup that found nothing. Stored under its own sentinel because KV * cannot tell a missing key from a key holding null, and "TMDb does not know * this id" is a real answer worth remembering. */const NOT_FOUND = '\u0000not-found';
const store = (env, key, value, ttl) => env.BRIDGE.put(key, JSON.stringify(value ?? NOT_FOUND), { expirationTtl: ttl });
/** * Read-through KV cache. A failed load is logged and never cached, because a * failure is not an answer. A load that returns null is cached, because it is. */export async function cached(env, key, ttl, load) { const hit = await env.BRIDGE.get(key, 'json'); if (hit === NOT_FOUND) return null; if (hit !== null) return hit;
try { const value = await load(); await store(env, key, value, ttl); return value ?? null; } catch (err) { console.error(`lookup failed for ${key}:`, err.message); return null; }}
/** * Read-through KV cache for a set of related ids, where one loader call can * answer several misses at once. * * Hits are served per id, so the cache stays fine-grained; only the misses are * handed to `loadMany`, which returns a Map of the ones it found. Each answer, * including "not found", is written back under its own key. */export async function cachedAll(env, ids, keyFor, ttl, loadMany) { const found = new Map(); const missing = [];
for (const id of ids) { const hit = await env.BRIDGE.get(keyFor(id), 'json'); if (hit === NOT_FOUND) found.set(id, null); else if (hit !== null) found.set(id, hit); else missing.push(id); } if (!missing.length) return found;
let loaded = new Map(); try { loaded = await loadMany(missing); } catch (err) { console.error(`batch lookup failed for ${missing.length} key(s):`, err.message); for (const id of missing) found.set(id, null); return found; }
for (const id of missing) { const value = loaded.get(id) ?? null; await store(env, keyFor(id), value, ttl); found.set(id, value); } return found;}
/** * Compare two secrets without leaking their contents through timing. * Network jitter makes a remote timing attack impractical either way, but this * costs nothing and the source is public. */export function secretsMatch(a, b) { if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); return diff === 0;}
/** Both authenticated routes share one bearer secret. */export function authorized(request, env) { const header = request.headers.get('authorization') ?? ''; return Boolean(env.WEBHOOK_SECRET) && secretsMatch(header, `Bearer ${env.WEBHOOK_SECRET}`);}
/** * The `exp` claim of a JWT, in epoch seconds, or null if it cannot be read. * Used to bound how long a token may sit in KV. JWT payloads are unpadded * base64url, and atob rejects both, so the padding is restored first. */export function jwtExpiry(token) { const payload = String(token ?? '').split('.')[1]; if (!payload) return null; const base64 = payload.replace(/-/g, '+').replace(/_/g, '/'); try { const { exp } = JSON.parse(atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4))); return Number.isFinite(exp) ? exp : null; } catch { return null; }}
/** Split a list into runs of at most `size`. */export function chunk(list, size) { const out = []; for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size)); return out;}