sendou.ink/app/routines/syncLiveStreams.ts
Kalle a004cf33b7
Store Twitch live streams in SQLite3 (#2738)
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 16:51:44 +02:00

42 lines
1.2 KiB
TypeScript

import * as LiveStreamRepository from "~/features/live-streams/LiveStreamRepository.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import { getStreams } from "~/modules/twitch";
import { hasTwitchEnvVars } from "~/modules/twitch/utils";
import { Routine } from "./routine.server";
export const SyncLiveStreamsRoutine = new Routine({
name: "SyncLiveStreams",
func: syncLiveStreams,
});
async function syncLiveStreams() {
if (!hasTwitchEnvVars()) return;
const streams = await getStreams();
if (streams.length === 0) {
await LiveStreamRepository.replaceAll([]);
return;
}
const streamTwitchNames = streams.map((s) => s.twitchUserName);
const matchingUsers =
await UserRepository.findIdsByTwitchUsernames(streamTwitchNames);
const twitchToUserId = new Map<string, number>();
for (const user of matchingUsers) {
if (user.twitch) {
twitchToUserId.set(user.twitch, user.id);
}
}
const liveStreams = streams.map((stream) => ({
userId: twitchToUserId.get(stream.twitchUserName) ?? null,
viewerCount: stream.viewerCount,
thumbnailUrl: stream.thumbnailUrl,
twitch: stream.twitchUserName,
}));
await LiveStreamRepository.replaceAll(liveStreams);
}