cut / frontend /src /App.tsx
Surf Studio
重写:SQLite + 独立循环 + 实时 Telegram + 一码一推 + 新页面
5936c9d
Raw History Blame Contribute Delete
15 kB
import { useEffect, useState, type ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { ExternalLink, Gift, Loader2, RefreshCw, Search, Send, Settings, X as XIcon } from 'lucide-react'
import { request } from './lib/api'
import { formatCount, timeAgo } from './lib/format'
import type { FeedResponse, StatusResponse, UsableCode } from './lib/types'
import PostCard from './components/PostCard'
import { CopyButton, countdown, useTick } from './components/CodeBadge'
import SettingsPanel from './components/SettingsPanel'
type View = 'gifts' | 'links' | 'talk' | 'all'
type Source = '' | 'x' | 'telegram' | 'manual'
const VIEWS: { id: View; label: string }[] = [
{ id: 'gifts', label: '赠链' },
{ id: 'links', label: '赠链 + 盲盒链接' },
{ id: 'talk', label: '讨论' },
{ id: 'all', label: '全部' },
]
const SOURCES: { id: Source; label: string }[] = [
{ id: '', label: '全部来源' },
{ id: 'x', label: 'X' },
{ id: 'telegram', label: 'Telegram' },
{ id: 'manual', label: '手动' },
]
function useDebounced<T>(value: T, ms = 300) {
const [v, setV] = useState(value)
useEffect(() => {
const t = setTimeout(() => setV(value), ms)
return () => clearTimeout(t)
}, [value, ms])
return v
}
export default function App() {
const qc = useQueryClient()
const [view, setView] = useState<View>('gifts')
const [source, setSource] = useState<Source>('')
const [q, setQ] = useState('')
const query = useDebounced(q.trim())
const [showSettings, setShowSettings] = useState(false)
const [scanning, setScanning] = useState(false)
const [notice, setNotice] = useState<{ text: string; error?: boolean } | null>(null)
const feed = useQuery<FeedResponse>({
queryKey: ['feed', view, source, query],
queryFn: () => {
const params = new URLSearchParams({ view, limit: '200' })
if (source) params.set('source', source)
if (query) params.set('q', query)
return request<FeedResponse>(`feed?${params}`)
},
refetchInterval: 15000,
placeholderData: (prev) => prev,
})
const status = useQuery<StatusResponse>({
queryKey: ['status'],
queryFn: () => request<StatusResponse>('status'),
refetchInterval: 15000,
})
async function scan() {
setScanning(true)
setNotice(null)
try {
const r = await request<{ newPosts?: number; newCodes?: number; seconds?: number; pushed?: unknown[] }>('scan', { body: {} })
const parts = [`抓取完成(${r.seconds ?? 0} 秒)`]
parts.push(r.newPosts ? `新增 ${r.newPosts} 条帖子` : '没有新帖子')
if (r.newCodes) parts.push(`${r.newCodes} 个新赠链`)
if (r.pushed?.length) parts.push(`推送了 ${r.pushed.length} 个`)
setNotice({ text: parts.join(',') })
} catch (err) {
setNotice({ text: err instanceof Error ? err.message : '抓取失败', error: true })
} finally {
setScanning(false)
qc.invalidateQueries({ queryKey: ['feed'] })
qc.invalidateQueries({ queryKey: ['status'] })
}
}
const data = feed.data
const posts = data?.posts ?? []
const usable = data?.usable ?? []
return (
<div className="min-h-screen bg-background text-foreground">
<header className="sticky top-0 z-20 border-b border-[var(--border-strong)] bg-background/85 backdrop-blur">
<div className="mx-auto flex max-w-3xl items-center justify-between gap-3 px-4 py-3">
<div className="min-w-0">
<h1 className="flex items-center gap-2 text-base font-black sm:text-lg">
<Gift className="h-5 w-5 text-brand-100" />
Surf 盲盒赠链雷达
</h1>
<SourceStrip status={status.data} />
</div>
<div className="flex shrink-0 items-center gap-2">
<button
type="button"
onClick={() => setShowSettings(true)}
className="rounded-full border border-[var(--border-strong)] p-2 text-fg-subtle hover:bg-[var(--bg-subtle-hover)]"
title="设置"
>
<Settings className="h-4 w-4" />
</button>
<button
type="button"
onClick={scan}
disabled={scanning}
className="flex items-center gap-1.5 rounded-full bg-brand-100 px-4 py-2 text-sm font-semibold text-white hover:opacity-90 disabled:opacity-50"
>
{scanning ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
{scanning ? '抓取中' : '抓取最新'}
</button>
</div>
</div>
</header>
<main className="mx-auto max-w-3xl px-4 pb-20 pt-5">
{notice && (
<p
className={`mb-4 rounded-lg px-3 py-2 text-xs ${
notice.error ? 'bg-red-500/10 text-red-400' : 'bg-brand-10 text-brand-100'
}`}
>
{notice.text}
</p>
)}
<Alerts status={status.data} onOpenSettings={() => setShowSettings(true)} />
<UsableBoard codes={usable} loading={feed.isLoading} />
<section className="mt-4 grid grid-cols-2 gap-2.5 sm:grid-cols-4">
<Stat label="24 小时新赠链" value={formatCount(data?.stats.codes_24h)} />
<Stat label="累计赠链" value={formatCount(data?.stats.codes)} />
<Stat label="已推送" value={formatCount(data?.stats.pushed)} />
<Stat
label="最近一个新赠链"
value={data?.stats.last_code_at ? timeAgo(data.stats.last_code_at * 1000) : '—'}
/>
</section>
<section className="mt-6 space-y-3">
<div className="flex flex-wrap gap-1.5">
{VIEWS.map((v) => (
<Chip key={v.id} active={view === v.id} onClick={() => setView(v.id)}>
{v.label}
</Chip>
))}
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap gap-1.5">
{SOURCES.map((s) => (
<Chip key={s.id} small active={source === s.id} onClick={() => setSource(s.id)}>
{s.label}
</Chip>
))}
</div>
<label className="relative ml-auto flex min-w-[180px] flex-1 items-center sm:flex-none">
<Search className="pointer-events-none absolute left-2.5 h-3.5 w-3.5 text-fg-muted" />
<input
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="搜索内容 / 作者 / 赠链码"
className="w-full rounded-full border border-[var(--border-strong)] bg-transparent py-1.5 pl-8 pr-7 text-xs outline-none focus:border-brand-60 sm:w-56"
/>
{q && (
<button type="button" onClick={() => setQ('')} className="absolute right-2 text-fg-muted">
<XIcon className="h-3.5 w-3.5" />
</button>
)}
</label>
</div>
</section>
<section className="mt-4 space-y-3">
{feed.isLoading && (
<div className="flex items-center justify-center gap-2 py-16 text-sm text-fg-muted">
<Loader2 className="h-4 w-4 animate-spin" /> 加载中…
</div>
)}
{feed.isError && (
<p className="rounded-lg bg-red-500/10 px-3 py-2 text-xs text-red-400">
读取失败:{(feed.error as Error)?.message}
</p>
)}
{!feed.isLoading && posts.length === 0 && !feed.isError && (
<p className="py-16 text-center text-sm text-fg-muted">这里还没有内容</p>
)}
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
{posts.length >= 200 && <p className="py-4 text-center text-xs text-fg-muted">只显示最近 200 条,可以用搜索找更早的</p>}
</section>
</main>
{showSettings && (
<div className="fixed inset-0 z-40 flex justify-end bg-black/50" onClick={() => setShowSettings(false)}>
<div
className="h-full w-full max-w-lg overflow-y-auto border-l border-[var(--border-strong)] bg-background p-4"
onClick={(e) => e.stopPropagation()}
>
<div className="mb-4 flex items-center justify-between">
<h2 className="text-base font-bold">设置</h2>
<button type="button" onClick={() => setShowSettings(false)} className="rounded-md p-1.5 hover:bg-[var(--bg-subtle-hover)]">
<XIcon className="h-4 w-4" />
</button>
</div>
<SettingsPanel status={status.data} />
</div>
</div>
)}
</div>
)
}
/* ------------------------------------------------------------- pieces -- */
function Chip({ active, small, onClick, children }: { active: boolean; small?: boolean; onClick: () => void; children: ReactNode }) {
return (
<button
type="button"
onClick={onClick}
className={`rounded-full border ${small ? 'px-2.5 py-1 text-[11px]' : 'px-3 py-1.5 text-xs'} font-medium transition ${
active
? 'border-brand-60 bg-brand-10 text-brand-100'
: 'border-[var(--border-strong)] text-fg-subtle hover:bg-[var(--bg-subtle-hover)]'
}`}
>
{children}
</button>
)
}
function Stat({ label, value }: { label: string; value: string }) {
return (
<div className="rounded-[12px] border border-[var(--border-strong)] bg-[var(--bg-subtle)] px-3 py-2.5">
<p className="text-[11px] text-fg-muted">{label}</p>
<p className="mt-0.5 text-lg font-black">{value}</p>
</div>
)
}
function Pill({ tone, children }: { tone: 'ok' | 'warn' | 'bad' | 'off'; children: ReactNode }) {
const dot = { ok: 'bg-emerald-400', warn: 'bg-amber-400', bad: 'bg-red-400', off: 'bg-zinc-500' }[tone]
return (
<span className="inline-flex items-center gap-1.5">
<span className={`h-1.5 w-1.5 rounded-full ${dot}`} />
{children}
</span>
)
}
function SourceStrip({ status }: { status?: StatusResponse }) {
if (!status) return <p className="mt-0.5 text-[11px] text-fg-muted">连接中…</p>
const x = status.x
const t = status.telegram
const xTone = !x.connected ? 'off' : x.expired ? 'bad' : x.pausedUntil ? 'warn' : 'ok'
const xText = !x.connected ? 'X 未登录' : x.expired ? 'X 登录失效' : x.pausedUntil ? 'X 限流中' : 'X 实时搜索'
const tTone = t.phase === 'live' ? 'ok' : t.phase === 'needs-login' || t.phase === 'error' ? 'bad' : t.phase === 'off' ? 'off' : 'warn'
const tText =
t.phase === 'live' ? 'Telegram 实时' : t.phase === 'needs-login' ? 'Telegram 需登录' : t.phase === 'off' ? 'Telegram 未开启' : 'Telegram 连接中'
return (
<p className="mt-0.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-fg-muted">
<Pill tone={xTone}>{xText}</Pill>
<Pill tone={tTone}>{tText}</Pill>
<Pill tone={status.push.configured ? (status.push.lastError ? 'warn' : 'ok') : 'off'}>
{status.push.configured ? '企业微信推送' : '未设置推送'}
</Pill>
</p>
)
}
/** Problems the user should act on, shown in plain words. */
function Alerts({ status, onOpenSettings }: { status?: StatusResponse; onOpenSettings: () => void }) {
if (!status) return null
const items: string[] = []
if (!status.x.connected) items.push('X 还没登录,现在只能读少数账号的主页,大部分赠链会漏掉。')
else if (status.x.expired) items.push('X 登录已失效,请重新粘贴 Cookie。')
if (status.telegram.phase === 'needs-login') items.push(`Telegram 需要重新登录${status.telegram.error ? `(${status.telegram.error})` : ''}。`)
if (!status.push.configured) items.push('还没设置企业微信推送地址。')
else if (status.push.lastError) items.push(`推送失败:${status.push.lastError}`)
if (status.backup.blockSave) items.push('读取备份失败,为了不覆盖旧数据,本次运行暂停了备份。')
if (!items.length) return null
return (
<div className="mb-4 rounded-[12px] border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-xs leading-5 text-amber-300">
{items.map((t, i) => (
<p key={i}>• {t}</p>
))}
<button type="button" onClick={onOpenSettings} className="mt-1 font-semibold underline">
去设置
</button>
</div>
)
}
function UsableBoard({ codes, loading }: { codes: UsableCode[]; loading: boolean }) {
const now = useTick(1000)
const sorted = codes
if (loading) return null
return (
<section className="rounded-[14px] border border-brand-30 bg-[var(--bg-subtle)] p-4">
<div className="flex items-baseline justify-between gap-2">
<h2 className="flex items-center gap-1.5 text-sm font-bold text-brand-100">
<Gift className="h-4 w-4" />
现在还能领({codes.length})
</h2>
<span className="text-[11px] text-fg-muted">每 90 秒复查一次名额</span>
</div>
{sorted.length === 0 ? (
<p className="mt-2 text-xs leading-5 text-fg-muted">暂时没有还有名额的赠链。出现新的会自动推送到企业微信,也会显示在这里。</p>
) : (
<div className="mt-3 space-y-2">
{sorted.map((c) => {
const link = `https://asksurf.ai/mystery-box/g/${c.code}`
return (
<div key={c.code} className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg bg-background/60 px-3 py-2">
<a href={link} target="_blank" rel="noreferrer" className="font-mono text-sm font-bold text-brand-100 hover:underline">
{c.code}
</a>
<span className="text-xs font-semibold">剩 {c.seats} 份</span>
{c.expires_at ? <span className="text-xs text-fg-muted">{countdown(c.expires_at, now)}后到期</span> : null}
{c.tier && <span className="text-xs text-fg-muted">{c.tier}</span>}
<span className="min-w-0 flex-1 truncate text-[11px] text-fg-muted">
{c.source === 'telegram' && <Send className="mr-1 inline h-3 w-3" />}
{c.author_name || c.author || ''}
{c.first_seen ? ` · ${timeAgo(c.first_seen * 1000)}发现` : ''}
</span>
<span className="flex items-center gap-1">
<CopyButton text={link} label="复制" />
{c.url && (
<a href={c.url} target="_blank" rel="noreferrer" className="text-fg-muted hover:text-fg-base" title="原帖">
<ExternalLink className="h-3.5 w-3.5" />
</a>
)}
</span>
</div>
)
})}
</div>
)}
</section>
)
}