19 lines
9.5 KiB
JavaScript
19 lines
9.5 KiB
JavaScript
import {createHash} from 'node:crypto';import {spawn} from 'node:child_process';import {automatedMailTemplate} from './automated-mail-templates.mjs';import {ensureStaffMailbox} from './internal-mail-staff.mjs';
|
||
export const politicalDeliveryId=(event,user)=>{const b=createHash('sha256').update('political:'+event+':'+user).digest().subarray(0,16);b[6]=(b[6]&15)|80;b[8]=(b[8]&63)|128;const h=b.toString('hex');return `${h.slice(0,8)}-${h.slice(8,12)}-${h.slice(12,16)}-${h.slice(16,20)}-${h.slice(20)}`;};
|
||
export function nativeApplicationTicket(payload){return new Promise((resolve,reject)=>{const child=spawn('/usr/bin/php',['/home/dunerealms/apps/integrations/osticket/political-application-ticket.php'],{stdio:['pipe','pipe','ignore']});let out='',done=false;const fail=()=>{if(done)return;done=true;clearTimeout(timer);child.kill();reject(Error('Application receipt pending'));};const timer=setTimeout(fail,60000);child.on('error',fail);child.stdin.on('error',fail);child.stdout.on('data',v=>{out+=v;if(out.length>32768)fail();});child.on('close',code=>{if(done)return;try{const v=JSON.parse(out);if(code||!v.ok)throw Error();done=true;clearTimeout(timer);resolve(v);}catch{fail();}});child.stdin.end(JSON.stringify(payload));});}
|
||
export function candidateVoteNotice({publicId,kind,top3=[]}){return {subject:'Vote received · '+publicId,message:'A vote has been recorded for your '+(kind==='imperial'?'Imperial':'faction')+' candidature. Voter identities are private.\n\nCurrent top three at notification time:\n'+(top3.length?top3.slice(0,3).map((c,i)=>(i+1)+'. '+c.username+' · '+Number(c.votes)+' votes').join('\n'):'Standings are not available yet.')+'\n\nThese are provisional standings, not a final result.'};}
|
||
export async function initializePoliticalNotifications(db){for(const sql of ["CREATE TABLE IF NOT EXISTS site_political_event_receipts(event_id CHAR(36) NOT NULL,event_type VARCHAR(16) NOT NULL,processed_at BIGINT NOT NULL,PRIMARY KEY(event_id,event_type))","CREATE TABLE IF NOT EXISTS site_political_mail_queue(id CHAR(36) PRIMARY KEY,user_id CHAR(36) NOT NULL,subject VARCHAR(200) NOT NULL,body TEXT NOT NULL,page VARCHAR(40) NOT NULL,state VARCHAR(16) NOT NULL,attempts INT NOT NULL DEFAULT 0,next_attempt BIGINT NOT NULL,created_at BIGINT NOT NULL)","CREATE TABLE IF NOT EXISTS site_political_ticket_links(application_id CHAR(36) PRIMARY KEY,ticket_id INT NOT NULL,ticket_number VARCHAR(32) NOT NULL)"])await db.prepare(sql).run();await db.prepare('DELETE FROM site_political_mail_queue WHERE created_at<?').bind(Date.now()-30*86400000).run();}
|
||
export async function runPoliticalNotifications(db,{broker,eligible,createTicket=nativeApplicationTicket,now=Date.now}={}){
|
||
await initializePoliticalNotifications(db);const since=now()-30*86400000;
|
||
const enqueue=async(event,user,subject,body,page='applications')=>{if(!user)return;await db.prepare('INSERT INTO site_political_mail_queue(id,user_id,subject,body,page,state,next_attempt,created_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET id=excluded.id').bind(politicalDeliveryId(event,user),user,subject.slice(0,200),body.slice(0,12000),page,'pending',now(),now()).run();};
|
||
const done=async(id,type)=>db.prepare('INSERT INTO site_political_event_receipts(event_id,event_type,processed_at) VALUES(?,?,?) ON CONFLICT(event_id,event_type) DO UPDATE SET event_id=excluded.event_id').bind(id,type,now()).run();
|
||
const apps=await db.prepare("SELECT e.id AS event_id,a.*,u.username FROM political_application_events e JOIN political_applications a ON a.id=e.application_id JOIN site_accounts u ON u.id=a.user_id LEFT JOIN site_political_event_receipts x ON x.event_id=e.id AND x.event_type='application' WHERE e.event='submitted' AND e.created_at>=? AND x.event_id IS NULL ORDER BY e.created_at,e.id LIMIT 20").bind(since).all();
|
||
for(const a of apps.results){const ticket=await createTicket({applicationId:a.id,userId:a.user_id,username:a.username,publicId:a.public_id,kind:a.kind,faction:a.faction,electionDate:new Date(Number(a.election_start)).toISOString(),motivation:a.motivation});await db.prepare('INSERT INTO site_political_ticket_links(application_id,ticket_id,ticket_number) VALUES(?,?,?) ON CONFLICT(application_id) DO UPDATE SET application_id=excluded.application_id').bind(a.id,ticket.ticketId,ticket.ticketNumber).run();await enqueue(a.event_id,a.user_id,'Application registered · '+a.public_id,'Your candidature has been registered.\n\nApplication: '+a.public_id+'\nRegistration receipt: '+ticket.ticketNumber+'\n\nThe linked Support ticket is automatically closed as a receipt. This does not approve, reject or withdraw your candidature. Follow the election in Realm & Politics.');await done(a.event_id,'application');}
|
||
const ballots=await db.prepare("SELECT e.id,e.actor_id,b.id AS ballot_id,b.round_id,b.kind,b.election_start FROM political_ballot_events e JOIN political_ballots b ON b.id=e.ballot_id LEFT JOIN site_political_event_receipts x ON x.event_id=e.id AND x.event_type='ballot' WHERE e.created_at>=? AND x.event_id IS NULL ORDER BY e.created_at,e.id LIMIT 30").bind(since).all();
|
||
for(const b of ballots.results){await enqueue(b.id,b.actor_id,'Your vote was received','Your definitive vote was recorded. Your voting choices and identity will not be included in candidate notifications.',b.kind==='imperial'?'imperial-elections':'house-elections');const candidates=await db.prepare('SELECT a.user_id,a.public_id FROM political_ballot_allocations v JOIN political_applications a ON a.id=v.application_id WHERE v.ballot_id=?').bind(b.ballot_id).all();const top=await db.prepare('SELECT u.username,COALESCE(SUM(v.votes),0) AS votes FROM political_round_candidates c JOIN political_applications a ON a.id=c.application_id JOIN site_accounts u ON u.id=a.user_id LEFT JOIN political_ballots b ON b.round_id=c.round_id LEFT JOIN political_ballot_allocations v ON v.ballot_id=b.id AND v.application_id=a.id WHERE c.round_id=? GROUP BY a.id,u.username ORDER BY votes DESC,u.username LIMIT 3').bind(b.round_id).all();for(const c of candidates.results){const notice=candidateVoteNotice({publicId:c.public_id,kind:b.kind,top3:top.results});await enqueue(b.id+':candidate',c.user_id,notice.subject,notice.message,b.kind==='imperial'?'imperial-elections':'house-elections');}await done(b.id,'ballot');}
|
||
const rounds=await db.prepare("SELECT e.id AS event_id,e.event,r.* FROM political_round_events e JOIN political_election_rounds r ON r.id=e.round_id LEFT JOIN site_political_event_receipts x ON x.event_id=e.id AND x.event_type='round' WHERE e.created_at>=? AND x.event_id IS NULL ORDER BY e.created_at,e.id LIMIT 20").bind(since).all();
|
||
for(const r of rounds.results){const members=await db.prepare('SELECT DISTINCT a.user_id FROM political_round_candidates c JOIN political_applications a ON a.id=c.application_id WHERE c.round_id=? UNION SELECT DISTINCT user_id FROM political_voters WHERE round_id=?').bind(r.id,r.id).all();for(const member of members.results)await enqueue(r.event_id,member.user_id,r.event==='opened'?'Election round opened':'Election round closed','Election: '+(r.kind==='imperial'?'Imperial':r.faction)+'\nRound: '+(Number(r.round_number)+1)+'\nOpens: '+new Date(Number(r.opens_at)).toISOString()+'\nCloses: '+new Date(Number(r.closes_at)).toISOString()+'\n\n'+(r.event==='opened'?'Voting is available during this round’s official window.':'This round has closed. Review the official register for its result or deciding round. No role grant is implied by this notification.'),r.kind==='imperial'?'imperial-elections':'house-elections');await done(r.event_id,'round');}
|
||
const offices=await db.prepare("SELECT e.id AS event_id,t.* FROM political_office_events e JOIN political_office_terms t ON t.id=e.term_id LEFT JOIN site_political_event_receipts x ON x.event_id=e.id AND x.event_type='office' WHERE e.created_at>=? AND x.event_id IS NULL ORDER BY e.created_at,e.id LIMIT 20").bind(since).all();for(const t of offices.results){await enqueue(t.event_id,t.user_id,'Election result recorded','Your election result has been recorded in the official term ledger.\nOffice: '+t.office+'\nTerm expires: '+new Date(Number(t.expires_at)).toISOString()+'\n\nThis message records the election result; it does not claim that an in-game rank or seal was granted.',t.kind==='imperial'?'imperial-elections':'house-elections');await done(t.event_id,'office');}
|
||
const pending=await db.prepare("SELECT * FROM site_political_mail_queue WHERE state='pending' AND next_attempt<=? ORDER BY created_at LIMIT 10").bind(now()).all();if(!pending.results.length)return;const sender=await ensureStaffMailbox(broker);
|
||
for(const row of pending.results){try{const user=await db.prepare('SELECT id,username,role FROM site_accounts WHERE id=?').bind(row.user_id).first();if(!user||!await eligible(db,user)){await db.prepare("UPDATE site_political_mail_queue SET state='cancelled' WHERE id=?").bind(row.id).run();continue;}const mailbox=await broker({action:'internal_ensure',userId:user.id,eligible:true}),mail=automatedMailTemplate('political-event',{recipientName:user.username,subject:row.subject,message:row.body,url:'https://cp.dunerealms.com/#'+row.page});const sent=await broker({action:'internal_send',userId:sender.userId,requestId:row.id,to:[mailbox.address],cc:[],bcc:[],senderName:'DuneRealms Election Register',...mail,subject:row.subject});if(!sent.accepted)throw Error();await db.prepare("UPDATE site_political_mail_queue SET state='sent',attempts=attempts+1 WHERE id=?").bind(row.id).run();}catch{await db.prepare('UPDATE site_political_mail_queue SET attempts=attempts+1,next_attempt=? WHERE id=?').bind(now()+Math.min(3600000,60000*2**Math.min(row.attempts,6)),row.id).run();}}
|
||
}
|

Staff