Add player profile pages with transaction history and social share cards

This commit is contained in:
Meghdad committed 2026-10-27 02:46:37 +03:30
1 parent e6e5d9cb13
commit acffaa9e76
45 files changed
+30767 -7

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
'use client';
import {useEffect,useState,useMemo} from 'react';
import {Shield,ArrowUpRight,ArrowDownLeft,Search,ChevronLeft,Trophy,Flame,Coins,History,Lock,Upload,AlertTriangle,RefreshCw,Share2} from 'lucide-react';
import {playerPath} from '../../lib/player.mjs';
import {withShareTimestamp} from '../../lib/share-link.mjs';
import {summarize,parseLog,identity,minimum} from '../../lib/ledger.mjs';
import migration from '../migration/ledger.json';
const seed=migration.rows;
type Row={id:string;date:string;player:string;reason:string;amount:number};
const num=(n:number)=>n.toLocaleString('fa-IR');
const digits=(s:string)=>s.replace(/[0-9]/g,n=>'۰۱۲۳۴۵۶۷۸۹'[Number(n)]);
function status(n:number){return n<0?'بدهکار':n<minimum?'نیازمند شارژ':'آمادهٔ نبرد';}
export default function Dashboard({adminMode=false}:{adminMode?:boolean}){
const [rows,setRows]=useState<Row[]>(seed as Row[]),[loading,setLoading]=useState(true),[error,setError]=useState(''),[query,setQuery]=useState(''),[tab,setTab]=useState('all'),[log,setLog]=useState(''),[message,setMessage]=useState(''),[saving,setSaving]=useState(false),[admin,setAdmin]=useState(false),[view,setView]=useState('leaderboard'),[shareUrl,setShareUrl]=useState(''),[shareNotice,setShareNotice]=useState(''),[sharing,setSharing]=useState(false);
async function refresh(){setLoading(true);setError('');try{const r=await fetch('/ledger.json',{cache:'no-store'});const d=await r.json() as {error?:string;rows:Row[];admin:boolean;shareUrl:string};if(!r.ok)throw Error(d.error);setRows(d.rows);setAdmin(d.admin);setShareUrl(d.shareUrl);}catch(e){setError(e instanceof Error?e.message:'ارتباط برقرار نشد.');}finally{setLoading(false);}}
useEffect(()=>{refresh();},[]);
const players=useMemo(()=>summarize(rows),[rows]);const low=players.filter(p=>p.balance<minimum);const total=players.reduce((s,p)=>s+p.balance,0);const deposits=rows.reduce((s,r)=>s+Math.max(r.amount,0),0);const withdrawals=rows.reduce((s,r)=>s+Math.max(-r.amount,0),0);
const filtered=players.filter(p=>p.name.toLowerCase().includes(query.toLowerCase())&&(tab!=='low'||p.balance<minimum));
const preview=useMemo(()=>{if(!log.trim())return null;try{const parsed=parseLog(log);const ids=new Set(rows.map(identity));let fresh=0;for(const r of parsed){const id=identity(r);if(!ids.has(id)){fresh++;ids.add(id);}}return {total:parsed.length,fresh,duplicates:parsed.length-fresh,error:''};}catch(e){return {error:(e as Error).message,total:0,fresh:0,duplicates:0};}},[log,rows]);
async function shareLatest(){
setSharing(true);setShareNotice('');
const url=withShareTimestamp(new URL('/',shareUrl).href,Math.floor(Date.now()/1000));
try {
try{if(!navigator.clipboard)throw Error('Clipboard unavailable');await navigator.clipboard.writeText(url);setShareNotice('لینک آخرین وضعیت کپی شد؛ در دیسکورد پیست کن.');}
catch{setShareNotice(url);}
}finally{setSharing(false);}
}
async function importLog(){setSaving(true);setMessage('');try{const r=await fetch('/api/import',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({log})});const d=await r.json() as {error?:string;added:number;duplicates:number;rows:Row[];revision:number;previewPending:boolean};if(!r.ok)throw Error(d.error);setMessage(`${num(d.added)} تراکنش جدید ثبت شد؛ ${num(d.duplicates)} رکورد تکراری کنار گذاشته شد.`);setLog('');await refresh();}catch(e){setMessage((e as Error).message);}finally{setSaving(false);}}
return <div className="shell"><aside className="sidebar"><a className="brand" href="/"><span className="brandmark"><img src="/siphoned-energy.svg" width="44" height="44" alt=""/></span><span dir="ltr">سایفوند انرژی<small>خزانه گیلد</small></span></a><div className="guild"><span className="guild-icon"><img src="/siphoned-energy.svg" width="31" height="31" alt=""/></span><div>خزانهٔ گیلد<small>آلبیون آنلاین</small></div><span className="live-dot"/></div><div className="nav-label">میدان گیلد</div><button className={view==='leaderboard'?'nav active':'nav'} onClick={()=>setView('leaderboard')}><Trophy size={19}/> لیدربورد <ChevronLeft size={16}/></button><button className={view==='history'?'nav active':'nav'} onClick={()=>setView('history')}><History size={19}/> تاریخچهٔ خزانه</button><button className="nav" onClick={()=>{setTab('low');setView('leaderboard');}}><Flame size={19}/> نیازمند اقدام <span className="nav-count">{num(low.length)}</span></button><div className="sidebar-bottom"><div className="pledge"><Shield size={22}/><p>قدرت گیلد، از سهم هر عضو شروع می‌شود.</p><small>هر سایفوند انرژی، یک قدم تا پیروزی</small></div><span className="version">خزانه گیلد / نسخه ۱</span></div></aside>
<main><header className="topbar"><div className="breadcrumb">گیلد <ChevronLeft size={13}/><strong>خزانهٔ سایفوند انرژی</strong></div><div className="topbar-actions"><button className="share-button" disabled={!shareUrl||loading||!!error||sharing} onClick={shareLatest}><Share2 size={15}/>{sharing?'در حال اشتراک…':'اشتراک‌گذاری'}</button><span className="public-label"><span className="live-dot"/> نمای عمومی</span></div></header><div className="content"><section className="hero"><div><div className="eyebrow"><span/> قدرت گیلد، از خزانه شروع می‌شود</div><h1>خزانه پُر. <em>گیلد قدرتمند.</em></h1><p>سهمت را ببین، جایگاهت را بشناس و برای نبرد بعدی آماده باش.</p><div className="hero-tags"><span><Shield size={14}/> شفاف برای همهٔ اعضا</span><span><RefreshCw size={14}/> به‌روزرسانی با لاگ بازی</span></div></div><div className="artifact" aria-hidden="true"><div className="orbit orbit-one"/><div className="orbit orbit-two"/><img className="energy-vial" src="/siphoned-energy.svg" width="174" height="174" alt=""/><span className="artifact-label">سایفوند انرژی</span><i className="spark s1"/><i className="spark s2"/><i className="spark s3"/></div></section>
{error&&<div className="notice error"><AlertTriangle size={18}/>{error} داده‌های اولیه نمایش داده می‌شوند.<button onClick={refresh}>تلاش مجدد</button></div>}
<section className="stats"><div className="stat"><div className="stat-top">بالانس خزانه <Coins size={19}/></div><strong className="energy" dir="ltr">{num(total)}<small>سایفوند انرژی</small></strong><span>خالص واریز و برداشت اعضا</span></div><div className="stat"><div className="stat-top">کل واریزها <ArrowDownLeft size={19}/></div><strong dir="ltr">{num(deposits)}<small className="green">واریز</small></strong><span>سهم اعضا در قدرت گیلد</span></div><div className="stat"><div className="stat-top">کل برداشت‌ها <ArrowUpRight size={19}/></div><strong dir="ltr">{num(withdrawals)}<small>برداشت</small></strong><span>{num(rows.length)} تراکنش ثبت‌شده</span></div><div className="stat"><div className="stat-top">اعضای نیازمند اقدام <Flame size={19}/></div><strong className="orange" dir="ltr">{num(low.length)}<small>از {num(players.length)} عضو</small></strong><span>بالانس کمتر از {num(minimum)} سایفوند انرژی</span></div></section>
{adminMode&&<section className="admin-panel"><div className="section-title"><div><div className="eyebrow">خزانه را به‌روز نگه دار</div><h2>ورود لاگ خزانه</h2></div><Lock size={23}/></div><p>خروجی بازی را همراه عنوان ستون‌ها اینجا پیست کن. پیش‌نمایش را بررسی و سپس ثبت کن.</p><textarea aria-label="لاگ تراکنش‌ها" dir="ltr" placeholder={'"Date"\t"Player"\t"Reason"\t"Amount"'} value={log} onChange={e=>setLog(e.target.value)}/>{preview&&<div className={preview.error?'notice error':'notice'}>{preview.error||`${num(preview.total)} ردیف · ${num(preview.fresh)} جدید · ${num(preview.duplicates)} تکراری`}</div>}<button className="primary" disabled={!preview||!!preview.error||saving||loading||!!error} onClick={importLog}><Upload size={17}/>{saving?'در حال ثبت…':'ادغام و ثبت تراکنش‌ها'}</button>{message&&<p role="status">{message}</p>}<small>تشخیص تکرار: زمان، نام بازیکن، نوع و مقدار. لاگ ناقص یا نامعتبر به‌طور کامل رد می‌شود.</small></section>}
<section className="action-banner"><div className="action-icon"><Flame size={23}/></div><div><strong>برای نبرد بعدی، آماده‌ای؟</strong><p>حداقل {num(minimum)} سایفوند انرژی نگه دار. حساب منفی یعنی وقت جبران سهم خزانه است.</p></div><button onClick={()=>{setTab('low');setView('leaderboard');document.getElementById('leaderboard')?.scrollIntoView({behavior:'smooth'});}}>بررسی حساب‌های کم‌موجودی <ChevronLeft size={17}/></button></section>
<div className="lower-grid"><section className="leaderboard panel" id="leaderboard"><div className="section-title"><div><div className="eyebrow">سهم هر عضو ارزشمند است</div><h2>{view==='history'?'تاریخچهٔ خزانه':'لیدربورد اعضا'} <span>{num(players.length)} عضو</span></h2></div><Trophy className="energy" size={22}/></div><div className="mobile-views"><button className={view==='leaderboard'?'selected':''} onClick={()=>setView('leaderboard')}>لیدربورد</button><button className={view==='history'?'selected':''} onClick={()=>setView('history')}>تاریخچه</button></div><div className="filters"><div className="tabs"><button className={tab==='all'?'selected':''} onClick={()=>setTab('all')}>همهٔ اعضا</button><button className={tab==='low'?'selected':''} onClick={()=>setTab('low')}>نیازمند اقدام <span>{num(low.length)}</span></button></div><label className="search"><Search size={16}/><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="نام بازیکن…" aria-label="جست‌وجوی بازیکن"/></label></div><div className="table-wrap"><table><thead><tr><th>{view==='history'?'زمان':'رتبه'}</th><th>بازیکن</th><th>{view==='history'?'نوع':'بالانس'}</th><th>{view==='history'?'مقدار':'وضعیت'}</th><th/></tr></thead><tbody>{view==='history'?rows.filter(r=>r.player.toLowerCase().includes(query.toLowerCase())&&(tab!=='low'||low.some(p=>p.name.toLowerCase()===r.player.toLowerCase()))).map(r=><tr key={identity(r)}><td className="date" dir="ltr">{digits(r.date)}</td><td><a className="player-name" dir="ltr" href={playerPath(r.player)}>{r.player}</a></td><td>{r.reason==='Deposit'?'واریز':'برداشت'}</td><td className={r.amount>0?'green':'red'} dir="ltr">{r.amount>0?'+':''}{num(r.amount)}</td><td/></tr>):filtered.map(p=>{const rank=players.indexOf(p)+1;return <tr key={p.name} className={p.balance<0?'debt-row':''}><td><span className={'rank r'+rank}>{rank<4?<Trophy size={15}/>:num(rank)}</span></td><td><a className="player-cell" href={playerPath(p.name)}><span className={'avatar a'+(rank%5)}>{p.name.slice(0,2).toUpperCase()}</span><span className="player-name" dir="ltr">{p.name}{rank===1&&<small>بزرگ‌ترین حامی خزانه</small>}</span></a></td><td><strong className={p.balance<0?'red':p.balance<minimum?'orange':''} dir="ltr">{num(p.balance)}</strong><small className="unit">سایفوند انرژی</small></td><td><span className={'badge '+(p.balance<0?'bad':p.balance<minimum?'warn':'good')}><i/>{status(p.balance)}</span></td><td><a className="row-open" href={playerPath(p.name)} aria-label={'مشاهده حساب '+p.name}><ChevronLeft size={17}/></a></td></tr>;})}</tbody></table>{(view==='leaderboard'&&!filtered.length)&&<div className="empty">بازیکنی با این مشخصات پیدا نشد.</div>}</div><div className="table-footer">رتبه‌بندی بر اساس بالانس خالص <span>واریز − برداشت = بالانس</span></div></section>
<aside className="right-column"><section className="spotlight panel"><div className="eyebrow">بزرگ‌ترین حامی خزانه</div><div className="champion-medal"><Trophy size={35}/></div><span className="champion-sub">حامی شمارهٔ یک خزانه</span><h3 dir="ltr">{players[0]?.name||'—'}</h3><strong className="champion-balance" dir="ltr">{num(players[0]?.balance||0)} <small>سایفوند انرژی</small></strong><p>سهم بیشتر، گیلد قدرتمندتر.<br/>جایگاه بعدی می‌تواند مال تو باشد.</p><a className="champion-link" href={players[0]?playerPath(players[0].name):'/'}>مشاهدهٔ حساب <ChevronLeft size={15}/></a></section><section className="health panel"><h3><Shield size={18}/> وضعیت آمادگی گیلد</h3><div className="health-number"><strong>{num(Math.round((players.length-low.length)/Math.max(players.length,1)*100))}<small>%</small></strong><span>اعضا آماده‌اند</span></div><div className="progress"><i style={{width:`${(players.length-low.length)/Math.max(players.length,1)*100}%`}}/></div><div className="legend"><span><i className="green-dot"/>آماده <b>{num(players.length-low.length)}</b></span><span><i className="orange-dot"/>نیازمند شارژ <b>{num(low.filter(p=>p.balance>=0).length)}</b></span><span><i className="red-dot"/>بدهکار <b>{num(low.filter(p=>p.balance<0).length)}</b></span></div></section></aside></div>
<footer><span><span className="live-dot"/> {loading?'در حال دریافت…':`آخرین تراکنش: ${digits(rows[0]?.date||'—')}`}</span><button onClick={refresh} disabled={loading}><RefreshCw size={13}/> تازه‌سازی</button><p>بالانس بر اساس لاگ‌های ثبت‌شده است؛ موجودی پیش از اولین لاگ لحاظ نشده است.</p><span dir="ltr">برای گیلد ساخته شده، با سهم تو قدرتمند می‌شود</span></footer></div></main>
{shareNotice&&<div className="share-feedback" role="status" dir="auto">{shareNotice}</div>}
</div>;
}
+15
View File
@@ -0,0 +1,15 @@
let cache;
const decode=s=>Uint8Array.from(atob(s.replace(/-/g,'+').replace(/_/g,'/').padEnd(Math.ceil(s.length/4)*4,'=')),c=>c.charCodeAt(0));
export async function administrator(request,env){
if(!env.ACCESS_TEAM_DOMAIN||!env.ACCESS_AUD)return false;
const team=env.ACCESS_TEAM_DOMAIN.replace(/^https:\/\//,'').replace(/\/$/,'');
if(!/^[a-z0-9-]+\.cloudflareaccess\.com$/.test(team))return false;
const token=request.headers.get('Cf-Access-Jwt-Assertion')||request.headers.get('cookie')?.match(/(?:^|;\s*)CF_Authorization=([^;]+)/)?.[1];
if(!token)return false;
try{const [h,p,s,...extra]=token.split('.');if(extra.length||!s)return false;const head=JSON.parse(new TextDecoder().decode(decode(h)));const claims=JSON.parse(new TextDecoder().decode(decode(p)));const now=Math.floor(Date.now()/1000);
if(head.alg!=='RS256'||typeof head.kid!=='string'||claims.iss!==`https://${team}`||!Array.isArray(claims.aud)||!claims.aud.includes(env.ACCESS_AUD)||!Number.isFinite(claims.exp)||claims.exp<=now||claims.nbf>now||String(claims.email).toLowerCase()!=='meghdad.social@gmail.com')return false;
if(!cache||cache.team!==team||cache.expires<Date.now()){const response=await fetch(`https://${team}/cdn-cgi/access/certs`);if(!response.ok)return false;cache={team,expires:Date.now()+300000,keys:(await response.json()).keys};}
const jwk=cache.keys.find(k=>k.kid===head.kid);if(!jwk)return false;const key=await crypto.subtle.importKey('jwk',jwk,{name:'RSASSA-PKCS1-v1_5',hash:'SHA-256'},false,['verify']);
return await crypto.subtle.verify('RSASSA-PKCS1-v1_5',key,decode(s),new TextEncoder().encode(h+'.'+p));
}catch{return false;}
}
+14
View File
@@ -0,0 +1,14 @@
import React from 'react';
import {createRoot} from 'react-dom/client';
import Dashboard from './Dashboard';
import PlayerPage from '../../components/player-page';
import {playerFromPath} from '../../lib/player.mjs';
import migration from '../migration/ledger.json';
const name=playerFromPath(window.location.pathname);
function PlayerAccount(){
const [rows,setRows]=React.useState(migration.rows);
const [error,setError]=React.useState(false);
React.useEffect(()=>{fetch('/ledger.json',{cache:'no-store'}).then(r=>{if(!r.ok)throw Error();return r.json() as Promise<{rows:typeof migration.rows}>;}).then(d=>setRows(d.rows)).catch(()=>setError(true));},[]);
return <>{error&&<div className="notice error" role="status">دریافت آخرین نسخه ممکن نشد؛ اطلاعات نسخهٔ همراه سایت نمایش داده می‌شود. <button onClick={()=>window.location.reload()}>تلاش مجدد</button></div>}<PlayerPage rows={rows} name={name!} origin="https://siphoned.oneup.megh.dad"/></>;
}
createRoot(document.getElementById('root')!).render(name?<PlayerAccount/>:<Dashboard/>);
+1
View File
@@ -0,0 +1 @@
{"revision":"094ea70c029d199f","profiles":[{"name":"ESc4a","balance":522,"deposits":2786,"withdrawals":2264,"count":76,"last":"2026-10-26 20:51:39","rank":1,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-16 16:43:55","path":"/@esc4a","imagePath":"/player-images/6573633461.png"},{"name":"AliSorena","balance":250,"deposits":440,"withdrawals":190,"count":24,"last":"2026-10-26 03:02:56","rank":2,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-10-20 09:22:16","path":"/@alisorena","imagePath":"/player-images/616c69736f72656e61.png"},{"name":"MMFerii","balance":233,"deposits":563,"withdrawals":330,"count":41,"last":"2026-10-26 21:47:58","rank":3,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-10-03 14:25:34","path":"/@mmferii","imagePath":"/player-images/6d6d6665726969.png"},{"name":"Khalafkar","balance":198,"deposits":438,"withdrawals":240,"count":27,"last":"2026-10-26 21:52:24","rank":4,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-16 20:59:57","path":"/@khalafkar","imagePath":"/player-images/6b68616c61666b6172.png"},{"name":"Meghdad","balance":144,"deposits":594,"withdrawals":450,"count":47,"last":"2026-10-26 20:51:15","rank":5,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-16 13:22:26","path":"/@meghdad","imagePath":"/player-images/6d656768646164.png"},{"name":"Fishduli","balance":138,"deposits":138,"withdrawals":0,"count":1,"last":"2026-10-15 13:17:12","rank":6,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-10-15 13:17:12","path":"/@fishduli","imagePath":"/player-images/6669736864756c69.png"},{"name":"guosthunter","balance":128,"deposits":280,"withdrawals":152,"count":25,"last":"2026-10-26 21:52:30","rank":7,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-20 22:00:04","path":"/@guosthunter","imagePath":"/player-images/67756f737468756e746572.png"},{"name":"SaMFOrT","balance":121,"deposits":171,"withdrawals":50,"count":11,"last":"2026-10-16 18:11:05","rank":8,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-10-07 13:05:15","path":"/@samfort","imagePath":"/player-images/73616d666f7274.png"},{"name":"babysamurai","balance":82,"deposits":82,"withdrawals":0,"count":1,"last":"2026-10-09 04:37:39","rank":9,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-10-09 04:37:39","path":"/@babysamurai","imagePath":"/player-images/6261627973616d75726169.png"},{"name":"GODpori","balance":76,"deposits":461,"withdrawals":385,"count":50,"last":"2026-10-26 18:41:13","rank":10,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-14 21:25:41","path":"/@godpori","imagePath":"/player-images/676f64706f7269.png"},{"name":"Alinaghi","balance":75,"deposits":335,"withdrawals":260,"count":57,"last":"2026-10-13 13:46:44","rank":11,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-15 17:59:45","path":"/@alinaghi","imagePath":"/player-images/616c696e61676869.png"},{"name":"mtrix","balance":60,"deposits":120,"withdrawals":60,"count":9,"last":"2026-10-20 19:51:12","rank":12,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-15 21:30:29","path":"/@mtrix","imagePath":"/player-images/6d74726978.png"},{"name":"GTRraven","balance":15,"deposits":35,"withdrawals":20,"count":5,"last":"2026-10-20 21:03:33","rank":13,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-16 17:53:54","path":"/@gtrraven","imagePath":"/player-images/677472726176656e.png"},{"name":"ADragon","balance":10,"deposits":10,"withdrawals":0,"count":1,"last":"2026-10-03 01:05:20","rank":14,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-10-03 01:05:20","path":"/@adragon","imagePath":"/player-images/61647261676f6e.png"},{"name":"LibraJoker","balance":10,"deposits":10,"withdrawals":0,"count":2,"last":"2026-10-20 16:23:15","rank":15,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-10-20 16:22:51","path":"/@librajoker","imagePath":"/player-images/6c696272616a6f6b6572.png"},{"name":"OxV","balance":10,"deposits":10,"withdrawals":0,"count":1,"last":"2026-09-20 22:00:12","rank":16,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-09-20 22:00:12","path":"/@oxv","imagePath":"/player-images/6f7876.png"},{"name":"RezGhoulSG","balance":10,"deposits":10,"withdrawals":0,"count":1,"last":"2026-10-18 22:44:56","rank":17,"members":39,"topUp":0,"status":"آمادهٔ نبرد","first":"2026-10-18 22:44:56","path":"/@rezghoulsg","imagePath":"/player-images/72657a67686f756c7367.png"},{"name":"Shmeet01","balance":7,"deposits":7,"withdrawals":0,"count":1,"last":"2026-09-29 22:43:09","rank":18,"members":39,"topUp":3,"status":"نیازمند شارژ","first":"2026-09-29 22:43:09","path":"/@shmeet01","imagePath":"/player-images/73686d6565743031.png"},{"name":"chessmanm","balance":6,"deposits":6,"withdrawals":0,"count":1,"last":"2026-09-16 11:34:41","rank":1Line truncated
+21
View File
@@ -0,0 +1,21 @@
import {summarize} from '../../lib/ledger.mjs';
const number=(n:number)=>n.toLocaleString('fa-IR');
export async function updatePreview(rows:any[],revision:number){
await document.fonts.load('400 24px Vazirmatn');await document.fonts.load('700 32px Vazirmatn');
const c=document.createElement('canvas');c.width=1600;c.height=1200;const ctx=c.getContext('2d')!;
const players=summarize(rows),low=players.filter(p=>p.balance<10).sort((a,b)=>a.balance-b.balance),balance=players.reduce((s,p)=>s+p.balance,0);
const rect=(x:number,y:number,w:number,h:number,color:string,stroke?:string)=>{ctx.fillStyle=color;ctx.beginPath();ctx.roundRect(x,y,w,h,14);ctx.fill();if(stroke){ctx.strokeStyle=stroke;ctx.lineWidth=1;ctx.stroke();}};
const text=(s:string,x:number,y:number,size=22,color='#e8f2fa',bold=false,rtl=true)=>{ctx.font=`${bold?700:400} ${size}px Vazirmatn`;ctx.fillStyle=color;ctx.textAlign=rtl?'right':'left';ctx.direction=rtl?'rtl':'ltr';ctx.fillText(s,x,y);};
rect(0,0,1600,1200,'#080f18');text('خزانه سایفوند انرژی',1540,91,34,'#e8f2fa',true);text('آخرین وضعیت خزانه',278,88,22,'#91bba8');text('سهم هر عضو، قدرت تمام گیلد',1540,164,45,'#e8f2fa',true);text(`${number(players.length)} عضو · ${number(rows.length)} تراکنش · ${number(players.length-low.length)} عضو آماده نبرد`,1540,200,22,'#94999f');
const stats=[['نیازمند اقدام',low.length,'#e19b58',`${number(players.filter(p=>p.balance<0).length)} حساب بدهکار`],['کل برداشت',rows.reduce((s,r)=>s+Math.max(0,-r.amount),0),'#da9494','سایفوند انرژی مصرف شده'],['کل واریز',rows.reduce((s,r)=>s+Math.max(0,r.amount),0),'#91bba8','مجموع سهم اعضای گیلد'],['بالانس خزانه',balance,balance<0?'#e47878':'#56d3ff','سایفوند انرژی · خالص واریز و برداشت']];
stats.forEach((s,i)=>{const x=48+i*381;rect(x,224,363,155,'#101c29','#253a4d');text(String(s[0]),x+339,258,21,'#94999f');text(number(Number(s[1])),x+339,315,48,String(s[2]),true);text(String(s[3]),x+339,355,16,'#94999f');});
rect(48,402,740,435,'#28221c','#5a4431');rect(812,402,740,435,'#102b3e','#275772');text('حساب‌های نیازمند اقدام',761,451,27,'#e19b58',true);text('حداقل مطلوب: ۱۰',210,445,18,'#94999f');text('لیدربورد · بالاترین بالانس‌ها',1525,451,27,'#56d3ff',true);
text('واریز لازم',165,488,17,'#ad9580');text('بالانس',300,488,17,'#ad9580');text('بازیکن',761,488,17,'#ad9580');text('بالانس',953,488,17,'#94bcd4');text('بازیکن',1460,488,17,'#94bcd4');text('رتبه',1525,488,17,'#94bcd4');
low.slice(0,8).forEach((p,i)=>{const y=526+i*35;text(number(10-p.balance),76,y,22,'#e0bb85',false,false);text(number(p.balance),207,y,22,p.balance<0?'#e47878':'#e19b58',false,false);text(p.name.slice(0,21),761,y,22);});
players.slice(0,8).forEach((p,i)=>{const y=526+i*35;text(number(p.balance),840,y,22,p.balance<0?'#e47878':'#56d3ff',true,false);text(p.name.slice(0,21),1460,y,22);text(number(i+1),1525,y,22,'#56d3ff');});
text(low.length>8?`${number(low.length-8)} حساب دیگر · برای جزئیات وارد سایت شو`:'برای رسیدن به حداقل، مبلغ واریز لازم را جبران کن',761,811,16,'#ad9580');text('رتبه‌بندی بر اساس خالص واریز و برداشت است',1525,811,16,'#94bcd4');
rect(48,861,1504,232,'#101c29','#294358');text('آخرین تراکنش‌ها',1525,905,25,'#e8f2fa',true);rows.slice(0,4).forEach((r,i)=>{const y=949+i*35;text((r.amount>0?'+':'')+number(r.amount),76,y,21,r.amount>0?'#91bba8':'#e47878',false,false);text(r.amount>0?'واریز':'برداشت',530,y,21,r.amount>0?'#91bba8':'#e47878');text(r.player.slice(0,27),895,y,21);text(r.date.replace(/[0-9]/g,(d:string)=>'۰۱۲۳۴۵۶۷۸۹'[Number(d)]),1525,y,18,'#94999f');});
text('بالانس بر اساس لاگ‌های واردشده است · آلبیون آنلاین',48,1140,17,'#94999f',false,false);text('آخرین تراکنش: '+rows[0]?.date,1540,1140,17,'#94999f');
const blob=await new Promise<Blob>((resolve,reject)=>c.toBlob(b=>b?resolve(b):reject(Error('تولید تصویر ممکن نشد.')),'image/png'));
const response=await fetch('/api/preview',{method:'POST',headers:{'Content-Type':'image/png','X-Ledger-Revision':String(revision)},body:blob});if(!response.ok)throw Error('تصویر ذخیره نشد. برای تازه‌سازی آن دوباره ثبت کن.');
}
+10
View File
@@ -0,0 +1,10 @@
import { ImageResponse } from '@vercel/og';
import {createElement} from 'react';
import fs from 'node:fs/promises';
import {ShareCard,cardWidth,cardHeight} from '../../lib/share-card';
import {socialFonts} from '../../lib/social-fonts';
import {ledgerSnapshot} from '../../lib/share';
const rows=JSON.parse(await fs.readFile(process.argv[2],'utf8')).rows;
const data=await ledgerSnapshot(rows);
const response=new ImageResponse(createElement(ShareCard,{data}),{width:cardWidth,height:cardHeight,fonts:[...socialFonts]});
await fs.writeFile(process.argv[3],Buffer.from(await response.arrayBuffer()));
+14
View File
@@ -0,0 +1,14 @@
import {ImageResponse} from '@vercel/og';
import {createElement} from 'react';
import fs from 'node:fs/promises';
import {summarize} from '../../lib/ledger.mjs';
import {playerSnapshot} from '../../lib/player.mjs';
import {PlayerCard,playerCardWidth,playerCardHeight} from '../../lib/player-card';
import {socialFonts} from '../../lib/social-fonts';
const rows=JSON.parse(await fs.readFile(process.argv[2],'utf8')).rows;
for(const player of summarize(rows)) {
const data=playerSnapshot(rows,player.name)!;
const response=new ImageResponse(createElement(PlayerCard,{data}),{width:playerCardWidth,height:playerCardHeight,fonts:[...socialFonts]});
await fs.writeFile(process.argv[3]+data.imagePath,Buffer.from(await response.arrayBuffer()));
}
console.log(`Generated ${summarize(rows).length} player share images.`);
+23
View File
@@ -0,0 +1,23 @@
import metadata from './metadata.json';
import {playerFromPath, playerPath} from '../../lib/player.mjs';
const origin='https://siphoned.oneup.megh.dad';
const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const worker={async fetch(request,env){
const url=new URL(request.url),name=playerFromPath(url.pathname);
if(url.pathname!=='/'&&!name&&!url.pathname.startsWith('/@'))return env.ASSETS.fetch(request);
const n=v=>Number(v).toLocaleString('fa-IR'),m=metadata;
const profile=name?m.profiles.find(p=>p.name.toLowerCase()===name.toLowerCase()):null;
if(url.pathname!=='/'&&!profile)return new Response('<!doctype html><html lang="fa" dir="rtl"><meta charset="utf-8"><meta name="robots" content="noindex"><title>بازیکن پیدا نشد</title><h1>بازیکن پیدا نشد</h1><p>هنوز تراکنشی برای این نام ثبت نشده است.</p><a href="/">بازگشت به خزانه</a></html>',{status:404,headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}});
const title=profile?`${profile.name} | ${profile.status} · خزانه سایفوند انرژی`:`سایفوند انرژی | ${n(m.balance)} در خزانه`;
const description=profile?`بالانس ${n(profile.balance)} سایفوند انرژی · رتبه ${n(profile.rank)} از ${n(profile.members)} · ${n(profile.count)} تراکنش · واریز لازم تا آمادگی: ${n(profile.topUp)}`:`${n(m.members)} عضو، ${n(m.count)} تراکنش، ${n(m.low)} حساب نیازمند شارژ. آخرین تراکنش: ${m.latest.replace(/[0-9]/g,d=>'۰۱۲۳۴۵۶۷۸۹'[Number(d)])}`;
const stamp=/^\d{1,12}$/.test(url.searchParams.get('t')||'')?url.searchParams.get('t'):null;
const canonical=origin+(profile?playerPath(profile.name):'/');
const page=canonical+(stamp?'?t='+stamp:'');
const image=origin+(profile?profile.imagePath:'/share-image.png')+'?v=player-v1-'+m.revision+(stamp?'&t='+stamp:'');
const alt=profile?`وضعیت و آخرین تراکنش‌های ${profile.name}`:'وضعیت خزانه و اعضای گیلد';
const template=await env.ASSETS.fetch(new Request(new URL('/shell.html',request.url)));
const html=(await template.text()).replace('__SOCIAL_META__',`<title>${esc(title)}</title><meta name="description" content="${esc(description)}"><link rel="canonical" href="${esc(canonical)}"><meta property="og:type" content="website"><meta property="og:locale" content="fa_IR"><meta property="og:site_name" content="خزانه سایفوند انرژی"><meta property="og:title" content="${esc(title)}"><meta property="og:description" content="${esc(description)}"><meta property="og:url" content="${esc(page)}"><meta property="og:image" content="${esc(image)}"><meta property="og:image:alt" content="${esc(alt)}"><meta property="og:image:width" content="1600"><meta property="og:image:height" content="${profile?900:1200}"><meta property="og:image:type" content="image/png"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="${esc(title)}"><meta name="twitter:description" content="${esc(description)}"><meta name="twitter:image" content="${esc(image)}"><meta name="twitter:image:alt" content="${esc(alt)}">`);
return new Response(html,{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff','Referrer-Policy':'same-origin'}});
}};
export default worker;
+28
View File
@@ -0,0 +1,28 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
import fs from 'node:fs/promises';
const result=await build({entryPoints:[new URL('./worker.mjs',import.meta.url).pathname],bundle:true,write:false,format:'esm',platform:'browser'});
const {default:worker}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].text).toString('base64'));
const metadata=JSON.parse(await fs.readFile(new URL('./metadata.json',import.meta.url),'utf8'));
const env={ASSETS:{fetch:async r=>new Response(new URL(r.url).pathname==='/shell.html'?'<head>__SOCIAL_META__</head>':'asset')}};
test('player metadata has canonical URL, player image, status and matching share timestamp',async()=>{
const p=metadata.profiles[0];
const response=await worker.fetch(new Request('https://test.local/@'+p.name.toUpperCase()+'?t=12345'),env);
assert.equal(response.status,200);const html=await response.text();
assert.ok(html.includes(p.status));assert.ok(html.includes(p.imagePath));
assert.ok(html.includes(`rel="canonical" href="https://siphoned.oneup.megh.dad${p.path}"`));
assert.ok(html.includes(`${p.path}?t=12345`));assert.ok(html.includes('&amp;t=12345'));
assert.ok(html.includes('content="900"'));assert.ok(html.includes('summary_large_image'));
assert.equal(response.headers.get('Cache-Control'),'no-store');
});
test('unknown and malformed profiles return real 404, never the guild preview',async()=>{
for(const path of ['/@unknown-player','/@%ZZ','/@','/@a/b']){
const r=await worker.fetch(new Request('https://test.local'+path),env);assert.equal(r.status,404);assert.ok(!(await r.text()).includes('og:image'));
}
});
test('root preview and static assets still work, invalid timestamps are discarded',async()=>{
const r=await worker.fetch(new Request('https://test.local/?t=%22%3E%3Cscript%3E'),env);const html=await r.text();
assert.equal(r.status,200);assert.ok(html.includes('/share-image.png'));assert.ok(html.includes('content="1200"'));assert.ok(!html.includes('<script>'));
assert.equal(await (await worker.fetch(new Request('https://test.local/app.js'),env)).text(),'asset');
});