Add QQ avatar proxy and render avatars

Add a /avatar/:uin proxy endpoint that fetches QQ avatars (fetchQqAvatar) and caches them server-side (30d TTL) with browser-cache headers (30d max-age, immutable). Validate UINs and handle upstream failures (502 if no cache), and log failures. Update ConfigPage and OverviewPage to render avatar <img> from /avatar/:uin (referrerPolicy=no-referrer) and adjust styles (overflow-hidden, object-cover) to replace initial-letter placeholders with actual avatars.
This commit is contained in:
手瓜一十雪 committed 2026-05-02 20:11:11 +08:00
1 parent e059a12cc4
commit ac1ddee54e
3 files changed
+70 -4

No files matched your search

+48
View File
@@ -22,6 +22,10 @@ const loginAttempts = new Map<string, { count: number; resetAt: number }>();
const LOGIN_MAX_ATTEMPTS = 5;
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; // 15 minutes
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
function purgeExpiredTokens() {
const now = Date.now();
@@ -34,6 +38,23 @@ function getClientIp(req: Request): string {
return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1';
}
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
headers: {
'User-Agent': 'SnowLuma WebUI',
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
},
});
if (!response.ok) {
throw new Error(`avatar upstream responded with ${response.status}`);
}
const contentType = response.headers.get('content-type') || 'image/jpeg';
const body = new Uint8Array(await response.arrayBuffer());
return { body, contentType };
}
export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hookManager?: HookManager) {
const app = new Hono();
@@ -98,6 +119,33 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
}
});
app.get('/avatar/:uin', async (c) => {
const uin = c.req.param('uin');
if (!/^\d{5,12}$/.test(uin)) {
return c.text('invalid uin', 400);
}
const now = Date.now();
let cached = avatarCache.get(uin);
if (!cached || cached.expiresAt <= now) {
try {
const avatar = await fetchQqAvatar(uin);
cached = { ...avatar, expiresAt: now + AVATAR_CACHE_TTL_MS };
avatarCache.set(uin, cached);
} catch (err) {
log.warn('failed to proxy avatar for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
if (!cached) return c.text('avatar unavailable', 502);
}
}
return new Response(cached.body, {
headers: {
'Content-Type': cached.contentType,
'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
},
});
});
// API Routes
app.get('/api/status', (c) => {
return c.json({ status: 'running' });
+11 -2
View File
@@ -16,6 +16,10 @@ interface ConfigPageProps {
onConfigChange: (config: OneBotConfig) => void;
}
function qqAvatarUrl(uin: string): string {
return `/avatar/${encodeURIComponent(uin)}`;
}
export function ConfigPage({
qqList, selectedUin, config, saveStatus,
onSelectAccount, onSave, onConfigChange,
@@ -63,7 +67,7 @@ export function ConfigPage({
}}
>
<div
className="size-7 rounded-md flex items-center justify-center text-white text-[11px] font-bold shrink-0"
className="size-7 rounded-md flex items-center justify-center text-white text-[11px] font-bold shrink-0 overflow-hidden"
style={{
background: isActive
? 'linear-gradient(135deg, var(--accent), #818cf8)'
@@ -71,7 +75,12 @@ export function ConfigPage({
color: isActive ? '#fff' : 'var(--text-secondary)',
}}
>
{q.nickname[0]?.toUpperCase() || '?'}
<img
src={qqAvatarUrl(q.uin)}
alt={q.nickname || q.uin}
className="size-full object-cover"
referrerPolicy="no-referrer"
/>
</div>
<div className="min-w-0 flex-1">
<div
+11 -2
View File
@@ -32,6 +32,10 @@ function processStatusColor(status: HookProcessInfo['status']): string {
return 'var(--text-secondary)';
}
function qqAvatarUrl(uin: string): string {
return `/avatar/${encodeURIComponent(uin)}`;
}
export function OverviewPage({
qqList,
status,
@@ -250,13 +254,18 @@ export function OverviewPage({
}}
>
<div
className="size-10 rounded-lg flex items-center justify-center text-white text-sm font-bold shrink-0"
className="size-10 rounded-lg flex items-center justify-center text-white text-sm font-bold shrink-0 overflow-hidden"
style={{
background: 'linear-gradient(135deg, var(--accent), #818cf8)',
boxShadow: '0 0 12px var(--accent-glow)',
}}
>
{q.nickname[0]?.toUpperCase() || '?'}
<img
src={qqAvatarUrl(q.uin)}
alt={q.nickname || q.uin}
className="size-full object-cover"
referrerPolicy="no-referrer"
/>
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold truncate" style={{ color: 'var(--text-primary)' }}>