Add sunrise Threads automation and improve capture and character interactions
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
||||
import { resolve, join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { chromium } from 'playwright';
|
||||
import { THREADS } from '../../src/constants/threads.ts';
|
||||
import { kstClock, kstFields } from '../../src/ui/time.ts';
|
||||
import { dailySchedule, publishCarousel, threadsRequest } from './publisher.ts';
|
||||
import { loadThreadsConfig } from './config.ts';
|
||||
import type {} from '../../src/ui/threadsCapture.ts';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const dryRun = args.includes('--dry-run');
|
||||
const config = loadThreadsConfig(undefined, dryRun);
|
||||
const stateDir = resolve(config.stateDir);
|
||||
const imageDir = resolve(config.imageDir);
|
||||
const siteUrl = new URL(config.siteUrl);
|
||||
const publicUrl = new URL(config.imageBaseUrl);
|
||||
|
||||
async function readJson(path: string) {
|
||||
try { return JSON.parse(await readFile(path, 'utf8')); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
|
||||
}
|
||||
|
||||
async function saveJson(path: string, data: unknown) {
|
||||
const temporary = `${path}.${randomUUID()}.tmp`;
|
||||
await writeFile(temporary, JSON.stringify(data, null, 2), { mode: 0o600 });
|
||||
await rename(temporary, path);
|
||||
}
|
||||
|
||||
async function accessToken() {
|
||||
const path = join(stateDir, 'token.json');
|
||||
let saved = await readJson(path);
|
||||
if (!saved) {
|
||||
const token = config.accessToken.trim();
|
||||
if (!token) throw new Error('Set accessToken in .env.threads.json to a long-lived Threads token');
|
||||
saved = { token, refreshedAt: Date.now() };
|
||||
await saveJson(path, saved);
|
||||
}
|
||||
if (Date.now() - saved.refreshedAt >= THREADS.tokenRefreshMs) {
|
||||
const refreshed = await threadsRequest(saved.token, '/refresh_access_token', { grant_type: 'th_refresh_token' });
|
||||
if (!refreshed.access_token) throw new Error('Token refresh returned no access token');
|
||||
saved = { token: refreshed.access_token, refreshedAt: Date.now() };
|
||||
await saveJson(path, saved);
|
||||
}
|
||||
return saved.token as string;
|
||||
}
|
||||
|
||||
async function waitUntil(date: Date) {
|
||||
while (+date > Date.now()) await delay(Math.min(+date - Date.now(), 60_000));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (args.some(arg => !['--dry-run', '--now'].includes(arg)) || (args.includes('--now') && !dryRun)) {
|
||||
throw new Error('Usage: run.ts [--dry-run [--now]]. --now is capture-only.');
|
||||
}
|
||||
const schedule = dailySchedule(new Date());
|
||||
const recordPath = join(stateDir, `${schedule.date}.json`);
|
||||
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
||||
if (!dryRun && await readJson(recordPath)) {
|
||||
console.log(`${schedule.date}: publication already recorded; inspect the record if status is publishing`);
|
||||
return;
|
||||
}
|
||||
const immediate = dryRun && args.includes('--now');
|
||||
const capturePath = join(stateDir, `${schedule.date}.capture.json`);
|
||||
const savedCapture = dryRun ? null : await readJson(capturePath);
|
||||
if (!savedCapture && !immediate && Date.now() > +schedule.sunrise + THREADS.maxLatenessMs) {
|
||||
console.log(`${schedule.date}: sunrise has passed; skipping late capture`);
|
||||
return;
|
||||
}
|
||||
const captured = savedCapture ?? await captureSunrise(schedule, immediate);
|
||||
const { images, capturedAt } = captured;
|
||||
if (!Array.isArray(images) || images.length !== THREADS.angles.length) {
|
||||
throw new Error('Saved capture is not a two-angle capture; archive the old capture record before running again');
|
||||
}
|
||||
const sunrise = new Date(captured.sunrise);
|
||||
if (dryRun) { console.log('Dry run: no Threads API calls or publication records'); return; }
|
||||
if (!savedCapture) await saveJson(capturePath, captured);
|
||||
// Authentication/network outages must not lose the time-sensitive capture.
|
||||
const token = await accessToken();
|
||||
for (const { imageUrl, imagePath } of images) {
|
||||
if (new URL(imageUrl).protocol !== 'https:') throw new Error('Public image URL must use HTTPS');
|
||||
const check = await fetch(imageUrl, { signal: AbortSignal.timeout(THREADS.requestTimeoutMs) });
|
||||
const remoteImage = Buffer.from(await check.arrayBuffer());
|
||||
if (!check.ok || !remoteImage.equals(await readFile(imagePath))) throw new Error('Public image URL does not serve the captured image');
|
||||
}
|
||||
const text = `🌅 오늘의 관악산 일출\n${schedule.date} · ${kstClock(sunrise)} KST\n관악산 정상의 일출 시각을 담은 3D 시뮬레이션입니다.\n${siteUrl.origin}`;
|
||||
const record = { date: schedule.date, sunrise: sunrise.toISOString(), capturedAt, images, status: 'publishing' };
|
||||
const postId = await publishCarousel(token, images.map((image: { imageUrl: string }) => image.imageUrl), text, async containerId => {
|
||||
// Atomic claim survives restarts and blocks concurrent/ambiguous publication retries.
|
||||
await writeFile(recordPath, JSON.stringify({ ...record, containerId }, null, 2), { flag: 'wx', mode: 0o600 });
|
||||
});
|
||||
const pending = await readJson(recordPath);
|
||||
await saveJson(recordPath, { ...pending, status: 'published', postId });
|
||||
console.log(`Threads published: ${postId}`);
|
||||
}
|
||||
|
||||
async function captureSunrise(schedule: ReturnType<typeof dailySchedule>, immediate: boolean) {
|
||||
console.log(`Sunrise estimate: ${schedule.sunrise.toISOString()} (${kstClock(schedule.sunrise)} KST)`);
|
||||
if (!immediate) await waitUntil(schedule.prepareAt);
|
||||
await mkdir(imageDir, { recursive: true });
|
||||
const browser = await chromium.launch({ headless: true, chromiumSandbox: true,
|
||||
args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] });
|
||||
const images: { name: string; imagePath: string; imageUrl: string }[] = [];
|
||||
let sunrise: Date;
|
||||
let capturedAt: string;
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: THREADS.viewport, deviceScaleFactor: 1, timezoneId: 'Asia/Seoul' });
|
||||
const url = new URL(siteUrl);
|
||||
url.searchParams.set('mode', 'solo'); url.searchParams.set('site', 'gwanaksan');
|
||||
url.searchParams.set('capture', 'threads');
|
||||
await page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: 120_000 });
|
||||
await page.waitForFunction(() => Boolean(window.sunriseThreads), undefined, { timeout: 180_000 });
|
||||
await page.waitForFunction(() => !document.getElementById('lobby') || document.getElementById('lobby')!.hidden);
|
||||
sunrise = new Date(await page.evaluate(() => window.sunriseThreads!.sunrise()));
|
||||
if (!Number.isFinite(+sunrise) || kstFields(sunrise).date !== schedule.date) throw new Error('Unexpected page sunrise date');
|
||||
console.log(`Page sunrise: ${sunrise.toISOString()} (${kstClock(sunrise)} KST)`);
|
||||
if (!immediate) {
|
||||
if (Date.now() > +sunrise + THREADS.maxLatenessMs) throw new Error('Page loaded after capture deadline');
|
||||
await waitUntil(sunrise);
|
||||
}
|
||||
const capture = await page.evaluate(() => window.sunriseThreads!.capture());
|
||||
capturedAt = capture.capturedAt;
|
||||
if (!immediate && Math.abs(Date.parse(capturedAt) - +sunrise) > THREADS.maxLatenessMs) throw new Error('Capture missed sunrise deadline');
|
||||
if (capture.images?.length !== THREADS.angles.length) throw new Error('Deploy the two-angle capture frontend first');
|
||||
for (const [index, shot] of capture.images.entries()) {
|
||||
if (shot.name !== THREADS.angles[index].name) throw new Error('Unexpected capture angle order');
|
||||
const filename = `${schedule.date}-${randomUUID()}-${shot.name}.jpg`;
|
||||
const imagePath = join(imageDir, filename);
|
||||
const imageUrl = new URL(filename, publicUrl.href.replace(/\/?$/, '/')).href;
|
||||
const image = Buffer.from(shot.image.split(',')[1], 'base64');
|
||||
if (image.length < 1000) throw new Error('Capture is empty');
|
||||
await writeFile(imagePath, image);
|
||||
images.push({ name: shot.name, imagePath, imageUrl });
|
||||
console.log(`Saved ${shot.name} capture: ${imagePath}`);
|
||||
}
|
||||
} finally { await browser.close(); }
|
||||
return { images, capturedAt, sunrise: sunrise.toISOString() };
|
||||
}
|
||||
|
||||
void main().catch(error => {
|
||||
// Avoid logging fetch error causes/URLs that may contain credentials.
|
||||
console.error(error instanceof Error ? error.message : 'Threads job failed');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in New Issue
Block a user