Spaces:
Sleeping
Sleeping
File size: 22,874 Bytes
5936c9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 | 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>
)
}
|