source ⟩ app ⟩ thumbnail-cron.js

import { mkdirSync, renameSync } from "fs";
import path from "path";

import { CronJob } from "cron";
import { firefox } from "playwright-core";

import { rootFolder } from "./helpers.js";

const targetPath = path.join(
	rootFolder,
	"hypertext",
	"public",
	"index",
	"thumbnail.jpg"
);
const firefoxPath = process.env.PLAYWRIGHT_FIREFOX_PATH || "/usr/bin/firefox";

const takeScreenshot = async () => {
	mkdirSync(path.dirname(targetPath), { recursive: true });

	const browser = await firefox.launch({
		executablePath: firefoxPath,
		headless: true
	});

	const page = await browser.newPage({
		viewport: { height: 1080, width: 1920 }
	});

	await page.goto("https://satyrs.eu", { waitUntil: "networkidle" });

	const tmpPath = `${targetPath}.tmp`;
	await page.screenshot({
		fullPage: false,
		path: tmpPath,
		quality: 85,
		type: "jpeg"
	});

	await browser.close();

	// Atomic-ish replacement, so visitors never see a half-written file —Euda }:3
	renameSync(tmpPath, targetPath);
	console.log(`[thumbnail] Refreshed at ${new Date().toISOString()}`);
};

export const refreshThumbnail = async () => {
	try {
		await takeScreenshot();
	} catch (error) {
		console.error("[thumbnail] Failed to refresh:", error);
	}
};

/**
 * Starts the daily thumbnail cron job: screenshots https://satyrs.eu at 1920×1080
 * every day at 12:00 UK time, saving it as hypertext/public/index/thumbnail.jpg.
 * Uses the system-installed Firefox; override with PLAYWRIGHT_FIREFOX_PATH if needed.
 *
 * —Euda Ꮚ^ω^Ꮚ
 */
const startThumbnailCron = () => {
	new CronJob(
		"0 0 12 * * *",
		refreshThumbnail,
		null,
		true,
		"Europe/London"
	);

	console.log(
		"[thumbnail] Scheduled daily refresh at 12:00 Europe/London"
	);
};

export default startThumbnailCron;