import {execFile} from 'node:child_process'; import {GAZETTE_NAME} from './jarvis-gazette.mjs'; import {existsSync} from 'node:fs'; import {createHash,randomUUID} from 'node:crypto'; export async function initializeForumNews(db){ await db.prepare("CREATE TABLE IF NOT EXISTS forum_news_delivery(post_id CHAR(36) PRIMARY KEY,state VARCHAR(16) NOT NULL,thread_id BIGINT NOT NULL DEFAULT 0,claim_token CHAR(36) NOT NULL DEFAULT '',claimed_at BIGINT NOT NULL DEFAULT 0,last_error VARCHAR(120) NOT NULL DEFAULT '')").run(); await db.prepare("CREATE TABLE IF NOT EXISTS forum_news_revision(post_id CHAR(36) PRIMARY KEY,delivered_hash VARCHAR(64) NOT NULL DEFAULT '')").run(); } const nativeSend=post=>new Promise((resolve,reject)=>{const child=execFile('/usr/bin/php',['/home/dunerealms/apps/integrations/forum-news.php'],{timeout:30000,maxBuffer:262144},(error,stdout)=>{if(error)return reject(error);try{resolve(JSON.parse(stdout));}catch(e){reject(e);}});child.stdin.end(JSON.stringify(post));}); export function forumNewsRevision(row,time){ // Withdrawal payloads deliberately contain no current draft/private/future content. const post=row.status==='published'&&row.published_at!=null&&Number.isFinite(Number(row.published_at))&&Number(row.published_at)<=time ?{id:row.id,status:'published',title:row.title,body:row.body,category:row.category,published_at:Number(row.published_at),author_name:row.author_name||'DuneRealms',publisher:GAZETTE_NAME,format_version:2} :{id:row.id,status:'archived'}; return {...post,revision:createHash('sha256').update(JSON.stringify(post)).digest('hex')}; } const sourceSQL="SELECT d.post_id AS id,d.thread_id,d.state,p.title,p.body,p.category,p.published_at,p.status,COALESCE(a.display_name,a.username,'DuneRealms') author_name,r.delivered_hash FROM forum_news_delivery d LEFT JOIN website_posts p ON p.id=d.post_id LEFT JOIN site_accounts a ON a.id=p.author_id LEFT JOIN forum_news_revision r ON r.post_id=d.post_id"; export async function drainForumNews(db,{send=nativeSend,now=Date.now}={}){ const time=now(); // Native source-marker reconciliation makes an interrupted claim safe to inspect again. await db.prepare("UPDATE forum_news_delivery SET state='queued',claim_token='' WHERE state='sending' AND claimed_at{};await initializeForumNews(db);let stopped=false,busy=false;const tick=async()=>{if(stopped||busy)return;busy=true;try{await drainForumNews(db);}catch{logger.warn('Forum news delivery check failed');}finally{busy=false;}};const timer=setInterval(tick,10000);timer.unref?.();void tick();return()=>{stopped=true;clearInterval(timer);};}