cut / frontend /src /components /SettingsPanel.tsx
Surf Studio
重写:SQLite + 独立循环 + 实时 Telegram + 一码一推 + 新页面
5936c9d
Raw History Blame Contribute Delete
22.9 kB
import { useState, type ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Loader2, Lock, Plus, Trash2 } from 'lucide-react'
import { ApiError, getAdminKey, request, setAdminKey } from '@/lib/api'
import { timeAgo } from '@/lib/format'
import type { SettingsResponse, StatusResponse, TgChat, TgDialog } from '@/lib/types'
/* ------------------------------------------------------------- helpers -- */
function Section({ title, hint, children }: { title: string; hint?: ReactNode; children: ReactNode }) {
return (
<section className="rounded-[14px] border border-[var(--border-strong)] bg-[var(--bg-subtle)] p-4">
<h3 className="text-sm font-bold">{title}</h3>
{hint && <div className="mt-1 text-xs leading-5 text-fg-muted">{hint}</div>}
<div className="mt-3 space-y-3">{children}</div>
</section>
)
}
function Btn({
children,
onClick,
busy,
kind = 'primary',
disabled,
}: {
children: ReactNode
onClick: () => void
busy?: boolean
kind?: 'primary' | 'ghost' | 'danger'
disabled?: boolean
}) {
const style =
kind === 'primary'
? 'bg-brand-100 text-white hover:opacity-90'
: kind === 'danger'
? 'border border-red-500/40 text-red-400 hover:bg-red-500/10'
: 'border border-[var(--border-strong)] text-fg-base hover:bg-[var(--bg-subtle-hover)]'
return (
<button
type="button"
onClick={onClick}
disabled={busy || disabled}
className={`inline-flex items-center justify-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition disabled:opacity-50 ${style}`}
>
{busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
{children}
</button>
)
}
const inputCls =
'w-full rounded-lg border border-[var(--border-strong)] bg-background px-3 py-2 text-sm outline-none focus:border-brand-60'
function Dot({ tone }: { tone: 'ok' | 'warn' | 'bad' | 'off' }) {
const color = { ok: 'bg-emerald-400', warn: 'bg-amber-400', bad: 'bg-red-400', off: 'bg-zinc-500' }[tone]
return <span className={`inline-block h-2 w-2 shrink-0 rounded-full ${color}`} />
}
function Msg({ text, error }: { text: string | null; error?: boolean }) {
if (!text) return null
return <p className={`text-xs leading-5 ${error ? 'text-red-400' : 'text-emerald-400'}`}>{text}</p>
}
/** Run an action with busy + message state. */
function useAction() {
const [busy, setBusy] = useState<string | null>(null)
const [msg, setMsg] = useState<{ text: string; error?: boolean; at: string } | null>(null)
async function run(name: string, fn: () => Promise<string | void>) {
setBusy(name)
setMsg(null)
try {
const text = await fn()
if (text) setMsg({ text, at: name })
} catch (err) {
setMsg({ text: err instanceof Error ? err.message : String(err), error: true, at: name })
} finally {
setBusy(null)
}
}
const msgFor = (...names: string[]) => (msg && names.includes(msg.at) ? <Msg text={msg.text} error={msg.error} /> : null)
return { busy, run, msgFor }
}
/* --------------------------------------------------------------- panel -- */
export default function SettingsPanel({ status }: { status?: StatusResponse }) {
const qc = useQueryClient()
const settings = useQuery<SettingsResponse, ApiError>({
queryKey: ['settings'],
queryFn: () => request<SettingsResponse>('settings'),
refetchInterval: 15000,
retry: (count, err) => !(err instanceof ApiError && err.needsKey) && count < 2,
})
const refresh = () => {
qc.invalidateQueries({ queryKey: ['settings'] })
qc.invalidateQueries({ queryKey: ['status'] })
}
if (settings.error?.needsKey) return <KeyGate onDone={refresh} />
if (settings.isLoading || !settings.data)
return (
<div className="flex items-center gap-2 p-6 text-sm text-fg-muted">
<Loader2 className="h-4 w-4 animate-spin" />
{settings.error ? settings.error.message : '读取设置…'}
</div>
)
const s = settings.data
return (
<div className="space-y-4">
<AddBox onDone={refresh} />
<XSection s={s} onDone={refresh} />
<TelegramSection s={s} onDone={refresh} />
<PushSection s={s} onDone={refresh} />
<KeySection locked={s.locked} onDone={refresh} />
<LogSection status={status} />
</div>
)
}
function KeyGate({ onDone }: { onDone: () => void }) {
const [key, setKey] = useState(getAdminKey())
const { busy, run, msgFor } = useAction()
return (
<Section title="输入管理密码" hint="设置页面需要管理密码,输入一次后这台设备会记住。">
<div className="flex gap-2">
<input className={inputCls} type="password" value={key} onChange={(e) => setKey(e.target.value)} placeholder="管理密码" />
<Btn
busy={busy === 'key'}
onClick={() =>
run('key', async () => {
setAdminKey(key.trim())
await request('auth/check', { body: {} })
onDone()
})
}
>
<Lock className="h-3.5 w-3.5" />
确认
</Btn>
</div>
{msgFor('key')}
</Section>
)
}
/* -------------------------------------------------------------- add box -- */
function AddBox({ onDone }: { onDone: () => void }) {
const qc = useQueryClient()
const [input, setInput] = useState('')
const { busy, run, msgFor } = useAction()
return (
<Section title="手动添加" hint="粘贴推文链接、赠链链接或赠链码(可多个,用空格隔开),会立刻检查名额,有名额就推送。">
<div className="flex gap-2">
<input
className={inputCls}
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="https://x.com/…/status/… 或 赠链码"
/>
<Btn
busy={busy === 'add'}
disabled={!input.trim()}
onClick={() =>
run('add', async () => {
const r = await request<{ message?: string; codes?: { code: string; usable: boolean; seats: number | null; status: string | null }[]; pushed?: unknown[] }>('add', {
body: { input },
})
setInput('')
qc.invalidateQueries({ queryKey: ['feed'] })
onDone()
if (r.message) return r.message
const list = (r.codes || [])
.map((c) => `${c.code}:${c.usable ? `有名额(${c.seats} 份)` : c.status === 'INVALID' ? '无效' : '已不可用'}`)
.join(';')
return `已添加 ${list}${r.pushed?.length ? ',已推送' : ''}`
})
}
>
<Plus className="h-3.5 w-3.5" />
添加
</Btn>
</div>
{msgFor('add')}
</Section>
)
}
/* -------------------------------------------------------------------- X -- */
function XSection({ s, onDone }: { s: SettingsResponse; onDone: () => void }) {
const [cookies, setCookies] = useState('')
const { busy, run, msgFor } = useAction()
const x = s.x
const tone = !x.connected ? 'off' : x.expired ? 'bad' : x.pausedUntil ? 'warn' : 'ok'
const label = !x.connected
? '未登录:只能读少数账号主页,很多赠链会漏掉'
: x.expired
? `登录已失效:${x.error || '请重新粘贴 Cookie'}`
: x.pausedUntil
? `X 限流中,${timeAgo(x.pausedUntil * 1000).replace('前', '后')}自动恢复`
: `已登录${x.username ? ` @${x.username}` : ''},每分钟搜索一次`
return (
<Section
title="X(推特)"
hint={
<>
登录后才能实时搜索全站的赠链。在电脑浏览器登录 x.com → 按 F12 → Application / 存储 → Cookies → x.com,把
<code className="mx-1 rounded bg-background px-1">auth_token</code>和<code className="mx-1 rounded bg-background px-1">ct0</code>
两项复制进来(格式:auth_token=…; ct0=…)。
</>
}
>
<div className="flex items-center gap-2 text-sm">
<Dot tone={tone} />
<span>{label}</span>
</div>
<textarea
className={`${inputCls} h-20 font-mono text-xs`}
value={cookies}
onChange={(e) => setCookies(e.target.value)}
placeholder="auth_token=xxxx; ct0=xxxx"
/>
<div className="flex gap-2">
<Btn
busy={busy === 'x'}
disabled={!cookies.trim()}
onClick={() =>
run('x', async () => {
await request('x/connect', { body: { cookies } })
setCookies('')
onDone()
return 'X 登录成功,已经开始搜索'
})
}
>
{x.connected ? '更新登录' : '登录 X'}
</Btn>
{x.connected && (
<Btn
kind="ghost"
busy={busy === 'x-off'}
onClick={() =>
run('x-off', async () => {
await request('x', { method: 'DELETE' })
onDone()
return '已退出 X'
})
}
>
退出
</Btn>
)}
</div>
{msgFor('x', 'x-off')}
</Section>
)
}
/* ------------------------------------------------------------- Telegram -- */
const TG_PHASE: Record<string, [string, 'ok' | 'warn' | 'bad' | 'off']> = {
live: ['已连接,实时接收消息', 'ok'],
connecting: ['正在连接…', 'warn'],
waiting: ['刚启动,稍等一下再连接(避免和旧实例冲突)', 'warn'],
'needs-login': ['需要登录', 'bad'],
flood: ['Telegram 限流中,稍后自动恢复', 'warn'],
error: ['连接出错,会自动重试', 'bad'],
off: ['未开启', 'off'],
}
function TelegramSection({ s, onDone }: { s: SettingsResponse; onDone: () => void }) {
const t = s.telegram
const [phone, setPhone] = useState('')
const [code, setCode] = useState('')
const [password, setPassword] = useState('')
const [link, setLink] = useState('')
const [dialogs, setDialogs] = useState<TgDialog[] | null>(null)
const { busy, run, msgFor } = useAction()
const [label, tone] = TG_PHASE[t.phase] || [t.phase, 'warn']
const live = t.phase === 'live'
const showLogin = !live || t.pendingCode
return (
<Section
title="Telegram"
hint="用你的 Telegram 账号读取群和频道里的消息。登录后,你加入的所有群里一出现赠链都会被收录;下面列表里的群还会补读离线期间的历史消息。"
>
<div className="flex flex-wrap items-center gap-2 text-sm">
<Dot tone={tone} />
<span>{label}</span>
{live && t.me?.name && <span className="text-fg-muted">· {t.me.name}</span>}
</div>
{t.error && <p className="text-xs text-red-400">{t.error}</p>}
{showLogin && (
<div className="space-y-2 rounded-lg border border-[var(--border-strong)] p-3">
{!t.pendingCode ? (
<div className="flex gap-2">
<input className={inputCls} value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="手机号,例如 +8613800138000" />
<Btn
busy={busy === 'tg-start'}
disabled={!phone.trim()}
onClick={() =>
run('tg-start', async () => {
await request('tg/login/start', { body: { phone } })
onDone()
return '验证码已发到你的 Telegram,请在下面填写'
})
}
>
发送验证码
</Btn>
</div>
) : (
<>
<input className={inputCls} value={code} onChange={(e) => setCode(e.target.value)} placeholder="Telegram 收到的验证码" />
{t.needsPassword && (
<input
className={inputCls}
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="两步验证密码"
/>
)}
<Btn
busy={busy === 'tg-code'}
disabled={!code.trim()}
onClick={() =>
run('tg-code', async () => {
const r = await request<{ ok: boolean; needPassword?: boolean }>('tg/login/code', { body: { code, password } })
onDone()
if (r.needPassword) return '这个账号开了两步验证,请再填写密码'
setCode('')
setPassword('')
return '登录成功'
})
}
>
登录
</Btn>
</>
)}
{msgFor('tg-start', 'tg-code')}
</div>
)}
{t.loggedIn && (
<div className="flex flex-wrap gap-2">
<Btn
kind="ghost"
busy={busy === 'tg-re'}
onClick={() =>
run('tg-re', async () => {
await request('tg/reconnect', { body: {} })
onDone()
return '已重新连接'
})
}
>
重新连接
</Btn>
<Btn
kind="danger"
busy={busy === 'tg-out'}
onClick={() =>
run('tg-out', async () => {
if (!confirm('确定退出 Telegram 登录?')) return
await request('tg/logout', { body: {} })
onDone()
return '已退出'
})
}
>
退出登录
</Btn>
{msgFor('tg-re', 'tg-out')}
</div>
)}
<div>
<p className="mb-2 text-xs font-semibold text-fg-subtle">重点群 / 频道({t.chats.length})</p>
<div className="space-y-1.5">
{t.chats.map((chat) => (
<ChatRow key={chat.id} chat={chat} onDone={onDone} />
))}
{t.chats.length === 0 && <p className="text-xs text-fg-muted">还没有添加</p>}
</div>
</div>
{live && (
<div className="space-y-2">
<div className="flex gap-2">
<input
className={inputCls}
value={link}
onChange={(e) => setLink(e.target.value)}
placeholder="群/频道链接,例如 https://t.me/xxx 或 @xxx"
/>
<Btn
busy={busy === 'tg-link'}
disabled={!link.trim()}
onClick={() =>
run('tg-link', async () => {
await request('tg/chats', { body: { link } })
setLink('')
onDone()
return '已添加'
})
}
>
添加
</Btn>
</div>
<Btn
kind="ghost"
busy={busy === 'tg-dialogs'}
onClick={() =>
run('tg-dialogs', async () => {
setDialogs(await request<TgDialog[]>('tg/dialogs'))
})
}
>
从我加入的群里选
</Btn>
{msgFor('tg-link', 'tg-dialogs')}
{dialogs && (
<div className="max-h-72 space-y-1 overflow-y-auto rounded-lg border border-[var(--border-strong)] p-2">
{dialogs.map((d) => (
<div key={d.id} className="flex items-center justify-between gap-2 px-1 py-1 text-xs">
<span className="min-w-0 truncate">
{d.title || d.username || d.id}
<span className="ml-1 text-fg-muted">
{d.type === 'channel' ? '频道' : '群'}
{d.members ? ` · ${d.members} 人` : ''}
</span>
</span>
{d.tracked ? (
<span className="shrink-0 text-fg-muted">已添加</span>
) : (
<Btn
kind="ghost"
onClick={() =>
run('tg-dialogs', async () => {
await request('tg/chats', { body: { items: [d] } })
setDialogs((list) => list?.map((x) => (x.id === d.id ? { ...x, tracked: true } : x)) || null)
onDone()
})
}
>
添加
</Btn>
)}
</div>
))}
</div>
)}
</div>
)}
</Section>
)
}
function ChatRow({ chat, onDone }: { chat: TgChat; onDone: () => void }) {
const { busy, run, msgFor } = useAction()
return (
<div className="rounded-lg bg-background/50 px-3 py-2">
<div className="flex items-center justify-between gap-2">
<div className="min-w-0">
<p className="truncate text-sm">
{chat.title || chat.username || chat.id}
{chat.auto ? <span className="ml-1.5 text-[11px] text-fg-muted">自动发现</span> : null}
</p>
<p className="text-[11px] text-fg-muted">
{chat.username ? `@${chat.username} · ` : ''}
{chat.hits ? `已找到 ${chat.hits} 条赠链 · ` : ''}
{chat.full ? '收录所有提到 Surf 的消息' : '只收录赠链和盲盒相关消息'}
</p>
</div>
<div className="flex shrink-0 items-center gap-1">
<Btn
kind="ghost"
busy={busy === 'full'}
onClick={() =>
run('full', async () => {
await request(`tg/chats/${encodeURIComponent(chat.id)}/full`, { body: { full: !chat.full } })
onDone()
})
}
>
{chat.full ? '只看赠链' : '看全部 Surf'}
</Btn>
<button
type="button"
title="移除"
disabled={busy === 'rm'}
onClick={() =>
run('rm', async () => {
await request(`tg/chats/${encodeURIComponent(chat.id)}`, { method: 'DELETE' })
onDone()
})
}
className="rounded-md p-1.5 text-fg-muted hover:bg-red-500/10 hover:text-red-400"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
{msgFor('full', 'rm')}
</div>
)
}
/* ------------------------------------------------------------------ push -- */
function PushSection({ s, onDone }: { s: SettingsResponse; onDone: () => void }) {
const [hook, setHook] = useState('')
const { busy, run, msgFor } = useAction()
const p = s.push
return (
<Section
title="企业微信推送"
hint="发现还有名额的赠链时,推送到企业微信群机器人。每个赠链只推送一次。"
>
<div className="flex items-center gap-2 text-sm">
<Dot tone={p.configured ? (p.lastError ? 'warn' : 'ok') : 'off'} />
<span className="min-w-0 truncate">{p.configured ? p.webhook : '未设置'}</span>
</div>
{p.configured && (
<p className="text-xs text-fg-muted">
本次运行已推送 {p.pushed} 条{p.lastPush ? `,最近一次 ${timeAgo(p.lastPush * 1000)}` : ''}
</p>
)}
{p.lastError && <p className="text-xs text-red-400">最近一次失败:{p.lastError}</p>}
<div className="flex gap-2">
<input
className={inputCls}
value={hook}
onChange={(e) => setHook(e.target.value)}
placeholder="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…"
/>
<Btn
busy={busy === 'hook'}
disabled={!hook.trim()}
onClick={() =>
run('hook', async () => {
await request('notify', { body: { webhook: hook } })
setHook('')
onDone()
return '已保存'
})
}
>
保存
</Btn>
</div>
{p.configured && (
<Btn
kind="ghost"
busy={busy === 'test'}
onClick={() =>
run('test', async () => {
await request('notify/test', { body: {} })
return '测试消息已发出,去企业微信群里看看'
})
}
>
发一条测试消息
</Btn>
)}
{msgFor('hook', 'test')}
</Section>
)
}
/* ------------------------------------------------------------- admin key -- */
function KeySection({ locked, onDone }: { locked: boolean; onDone: () => void }) {
const [key, setKey] = useState('')
const { busy, run, msgFor } = useAction()
return (
<Section
title="管理密码"
hint={
locked
? '已设置:别人打开网页只能看,不能改设置、登录或退出账号。'
: '还没设置:任何打开这个网页的人都能改设置。建议设置一个。'
}
>
<div className="flex gap-2">
<input
className={inputCls}
type="password"
value={key}
onChange={(e) => setKey(e.target.value)}
placeholder={locked ? '新密码(留空则取消密码)' : '设置密码(至少 6 位)'}
/>
<Btn
busy={busy === 'setkey'}
onClick={() =>
run('setkey', async () => {
await request('auth/key', { body: { key } })
setAdminKey(key.trim())
setKey('')
onDone()
return key.trim() ? '已设置,这台设备会记住密码' : '已取消密码'
})
}
>
保存
</Btn>
</div>
{msgFor('setkey')}
</Section>
)
}
/* ------------------------------------------------------------------- log -- */
function LogSection({ status }: { status?: StatusResponse }) {
const lines = [...(status?.log || [])].reverse().slice(0, 60)
return (
<Section title="运行记录" hint="最近的抓取、推送和出错情况(最新的在最上面)。">
<div className="max-h-80 space-y-1 overflow-y-auto font-mono text-[11px] leading-5">
{lines.map((line, i) => (
<div key={i} className={line.level === 'error' ? 'text-red-400' : line.level === 'warn' ? 'text-amber-400' : 'text-fg-subtle'}>
<span className="text-fg-muted">{new Date(line.at * 1000).toLocaleTimeString('zh-CN', { hour12: false })}</span> {line.message}
</div>
))}
{lines.length === 0 && <p className="text-fg-muted">暂无记录</p>}
</div>
</Section>
)
}