web/website/scripts/set-unimatrix-clan-emblem.mjs

17 lines
2.1 KiB
JavaScript

import {fileURLToPath} from 'node:url';import {resolve} from 'node:path';import {readFile} from 'node:fs/promises';
import {openDatabase} from '../node/mysql.mjs';import {createClanEmblems} from '../control-panel/clan-emblems.mjs';
const OWNER='f3ffda37-01e4-41ea-b89d-fbeda82e453e',CLAN='89fe4fdc-27b6-4197-a16b-b094c44aed5a';
export async function installOwnerClanEmblem(db,{apply=false}={}){
const owner=await db.prepare("SELECT id,username FROM site_accounts WHERE id=? AND username='unimatrix999' AND password_hash NOT LIKE '!%'").bind(OWNER).first();
const clan=await db.prepare("SELECT id FROM site_clans WHERE id=? AND owner_id=? AND name='Unimatrix-Artreides' AND active=1").bind(CLAN,OWNER).first();if(!owner||!clan)throw Error('Pinned clan owner and identity must match.');
const image=await readFile(new URL('../web/assets/clans/unimatrix-artreides-blue-v1.webp',import.meta.url));
const existing=await db.prepare('SELECT image_blob,version FROM site_clan_emblems WHERE clan_id=?').bind(CLAN).first();
if(existing?.image_blob&&Buffer.from(existing.image_blob).equals(image))return {applied:apply,changed:false};
if(existing?.image_blob)throw Error('An emblem already exists; keep the owner upload instead of overwriting it.');
if(!apply)return {applied:false,clan:'Unimatrix-Artreides',version:Number(existing?.version||0)};
const handler=createClanEmblems(db,{authenticate:async()=>owner,normalize:async bytes=>Buffer.from(bytes)});
// This exact asset was already decoded and bounded during the build workflow.
const response=await handler(new Request('https://cp.dunerealms.com/api/clan-emblems/'+CLAN,{method:'POST',headers:{Origin:'https://cp.dunerealms.com','Content-Type':'image/webp','If-Match':'"'+Number(existing?.version||0)+'"'},body:image}));
const result=await response.json();if(!response.ok)throw Error(result.message);return {applied:true,...result};
}
if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){const db=await openDatabase(process.env);try{console.log(JSON.stringify(await installOwnerClanEmblem(db,{apply:process.argv.includes('--apply')})));}finally{await db.close();}}