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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135/** * Turns a normalized WatchEvent into Popfeed records. * * This module is source-agnostic on purpose. Adding a new source means writing * an adapter that produces WatchEvents; nothing here changes. */
import { withSession } from './session.js';import { addEpisodes, createRecord, findItem, forgetItem, itemUri, movieRecord, rememberItem,} from './records.js';import { movieIdFromImdb, movieMetadata, resolveSeries, seasonEpisodes, seriesMetadata,} from './tmdb.js';import { compact } from './util.js';import { skipped } from './watch-event.js';
const dedupeKey = (event) => `seen:${event.source}:${event.sourceId}`;
async function movieIdentifiers(env, ids) { const imdbId = ids.imdbId || undefined; let tmdbId = ids.tmdbId || undefined; if (!tmdbId && imdbId) tmdbId = (await movieIdFromImdb(env, imdbId)) ?? undefined; return compact({ tmdbId, imdbId });}
async function scrobbleMovie(env, event) { if (!env.POPFEED_MOVIE_LIST_URI) throw new Error('POPFEED_MOVIE_LIST_URI is not set');
const identifiers = await movieIdentifiers(env, event.ids); if (!identifiers.tmdbId && !identifiers.imdbId) { return skipped(`no tmdb or imdb id for "${event.title}"`); }
// Enrichment is best-effort. Without it the app still hydrates from tmdbId. const metadata = identifiers.tmdbId ? (await movieMetadata(env, identifiers.tmdbId)) ?? {} : {}; const record = movieRecord({ identifiers, title: event.title, metadata, env, now: event.watchedAt, });
// A watched list holds a film once. A rewatch must not add a second entry. const result = await withSession(env, async (session) => { const existing = await findItem(env, session, 'movie', identifiers); if (existing) return { status: 'already-logged', uri: itemUri(session, existing.rkey) }; const created = await createRecord(session, record); return { status: 'created', uri: created.uri }; });
if (result.status === 'created') { await rememberItem(env, 'movie', identifiers, result.uri.split('/').pop()); } return { ...result, kind: 'movie', title: record.title };}
/** Retry a read-modify-write that lost a race with a concurrent update. */async function retryOnSwap(env, seriesTmdbId, run, attempts = 3) { for (let attempt = 1; ; attempt++) { try { return await run(); } catch (err) { if (err.code !== 'InvalidSwap' || attempt >= attempts) throw err; await forgetItem(env, 'tv_show', { tmdbId: seriesTmdbId }); } }}
/** Attach each episode's own TMDb id. One batched lookup covers every season. */async function withEpisodeIds(env, seriesTmdbId, episodes) { const seasons = [...new Set(episodes.map((e) => e.season))]; const bySeason = await seasonEpisodes(env, seriesTmdbId, seasons); return episodes.map((e) => ({ ...e, tmdbId: bySeason.get(e.season)?.[e.episode] }));}
async function scrobbleSeries(env, event) { if (!env.POPFEED_TV_LIST_URI) throw new Error('POPFEED_TV_LIST_URI is not set'); if (!event.episodes?.length) return skipped(`no episodes for "${event.seriesName}"`);
const seriesTmdbId = await resolveSeries(env, event); if (!seriesTmdbId) return skipped(`could not resolve "${event.seriesName}" on TMDb`);
const [metadata, episodes] = await Promise.all([ seriesMetadata(env, seriesTmdbId).then((m) => m ?? {}), withEpisodeIds(env, seriesTmdbId, event.episodes), ]);
const ctx = { seriesTmdbId, episodes, title: event.seriesName, metadata, now: event.watchedAt }; const result = await retryOnSwap(env, seriesTmdbId, () => withSession(env, (session) => addEpisodes(env, session, ctx)) );
return { status: result.action, kind: 'series', uri: result.uri, series: event.seriesName, added: result.added, episodes: result.episodes, };}
/** * Record one watch event. Safe to call repeatedly with the same event: the * dedupe key short-circuits before any TMDb request is made. */export async function scrobble(env, event) { const key = dedupeKey(event); if (await env.BRIDGE.get(key)) return skipped(`duplicate: ${event.title}`);
const result = event.kind === 'movie' ? await scrobbleMovie(env, event) : await scrobbleSeries(env, event);
if (result.status !== 'skipped') { await env.BRIDGE.put(key, '1', { expirationTtl: Math.max(60, Number(env.DEDUPE_TTL_SECONDS) || 21600), }); const at = typeof event.progress === 'number' ? ` at ${event.progress.toFixed(0)}%` : ''; console.log(`${result.status} ${result.kind} "${event.title}"${at} -> ${result.uri}`); } return result;}