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 (
{title}
{hint && {hint}
}
{children}
)
}
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 (
)
}
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
}
function Msg({ text, error }: { text: string | null; error?: boolean }) {
if (!text) return null
return
{text}
}
/** Run an action with busy + message state. */
function useAction() {
const [busy, setBusy] = useState(null)
const [msg, setMsg] = useState<{ text: string; error?: boolean; at: string } | null>(null)
async function run(name: string, fn: () => Promise) {
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) ? : null)
return { busy, run, msgFor }
}
/* --------------------------------------------------------------- panel -- */
export default function SettingsPanel({ status }: { status?: StatusResponse }) {
const qc = useQueryClient()
const settings = useQuery({
queryKey: ['settings'],
queryFn: () => request('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
if (settings.isLoading || !settings.data)
return (
{settings.error ? settings.error.message : '读取设置…'}
)
const s = settings.data
return (
)
}
function KeyGate({ onDone }: { onDone: () => void }) {
const [key, setKey] = useState(getAdminKey())
const { busy, run, msgFor } = useAction()
return (
)
}
/* -------------------------------------------------------------- add box -- */
function AddBox({ onDone }: { onDone: () => void }) {
const qc = useQueryClient()
const [input, setInput] = useState('')
const { busy, run, msgFor } = useAction()
return (
)
}
/* -------------------------------------------------------------------- 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 (
登录后才能实时搜索全站的赠链。在电脑浏览器登录 x.com → 按 F12 → Application / 存储 → Cookies → x.com,把
auth_token和ct0
两项复制进来(格式:auth_token=…; ct0=…)。
>
}
>
{label}
)
}
/* ------------------------------------------------------------- Telegram -- */
const TG_PHASE: Record = {
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(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 (
{label}
{live && t.me?.name && · {t.me.name}}
{t.error && {t.error}
}
{showLogin && (
)}
{t.loggedIn && (
run('tg-re', async () => {
await request('tg/reconnect', { body: {} })
onDone()
return '已重新连接'
})
}
>
重新连接
run('tg-out', async () => {
if (!confirm('确定退出 Telegram 登录?')) return
await request('tg/logout', { body: {} })
onDone()
return '已退出'
})
}
>
退出登录
{msgFor('tg-re', 'tg-out')}
)}
重点群 / 频道({t.chats.length})
{t.chats.map((chat) => (
))}
{t.chats.length === 0 &&
还没有添加
}
{live && (
setLink(e.target.value)}
placeholder="群/频道链接,例如 https://t.me/xxx 或 @xxx"
/>
run('tg-link', async () => {
await request('tg/chats', { body: { link } })
setLink('')
onDone()
return '已添加'
})
}
>
添加
run('tg-dialogs', async () => {
setDialogs(await request('tg/dialogs'))
})
}
>
从我加入的群里选
{msgFor('tg-link', 'tg-dialogs')}
{dialogs && (
{dialogs.map((d) => (
{d.title || d.username || d.id}
{d.type === 'channel' ? '频道' : '群'}
{d.members ? ` · ${d.members} 人` : ''}
{d.tracked ? (
已添加
) : (
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()
})
}
>
添加
)}
))}
)}
)}
)
}
function ChatRow({ chat, onDone }: { chat: TgChat; onDone: () => void }) {
const { busy, run, msgFor } = useAction()
return (
{chat.title || chat.username || chat.id}
{chat.auto ? 自动发现 : null}
{chat.username ? `@${chat.username} · ` : ''}
{chat.hits ? `已找到 ${chat.hits} 条赠链 · ` : ''}
{chat.full ? '收录所有提到 Surf 的消息' : '只收录赠链和盲盒相关消息'}
run('full', async () => {
await request(`tg/chats/${encodeURIComponent(chat.id)}/full`, { body: { full: !chat.full } })
onDone()
})
}
>
{chat.full ? '只看赠链' : '看全部 Surf'}
{msgFor('full', 'rm')}
)
}
/* ------------------------------------------------------------------ push -- */
function PushSection({ s, onDone }: { s: SettingsResponse; onDone: () => void }) {
const [hook, setHook] = useState('')
const { busy, run, msgFor } = useAction()
const p = s.push
return (
{p.configured ? p.webhook : '未设置'}
{p.configured && (
本次运行已推送 {p.pushed} 条{p.lastPush ? `,最近一次 ${timeAgo(p.lastPush * 1000)}` : ''}
)}
{p.lastError && 最近一次失败:{p.lastError}
}
setHook(e.target.value)}
placeholder="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…"
/>
run('hook', async () => {
await request('notify', { body: { webhook: hook } })
setHook('')
onDone()
return '已保存'
})
}
>
保存
{p.configured && (
run('test', async () => {
await request('notify/test', { body: {} })
return '测试消息已发出,去企业微信群里看看'
})
}
>
发一条测试消息
)}
{msgFor('hook', 'test')}
)
}
/* ------------------------------------------------------------- admin key -- */
function KeySection({ locked, onDone }: { locked: boolean; onDone: () => void }) {
const [key, setKey] = useState('')
const { busy, run, msgFor } = useAction()
return (
)
}
/* ------------------------------------------------------------------- log -- */
function LogSection({ status }: { status?: StatusResponse }) {
const lines = [...(status?.log || [])].reverse().slice(0, 60)
return (
{lines.map((line, i) => (
{new Date(line.at * 1000).toLocaleTimeString('zh-CN', { hour12: false })} {line.message}
))}
{lines.length === 0 &&
暂无记录
}
)
}