import React, { useEffect, useMemo, useState } from 'react' import { Radio, Plus, RefreshCw, History, Trash2, Search, Star, StarOff, Eye, Heart, BarChart3, Lightbulb, List, Bookmark, Compass, Gauge, UserCircle2, X, ExternalLink, Play, Square, EyeOff, RotateCw, ChevronDown, ChevronUp, Image as ImageIcon, } from 'lucide-react' import { del, get, post, qs } from '../api' import { copyText, cx, fmtAgo, fmtDate, fmtNum, go, useAsync, useDebounced } from '../lib' import { VaultGate, VaultTools } from './Vault' import { Empty, ErrorNote, Field, Loading, Modal, Pager, Segmented, Spinner, Tabs, Tag, useConfirm, useToast } from '../ui' type Channel = { channel: string; title: string; description?: string; avatar?: string; added_at?: string; last_synced_at?: string backfill_status?: string; backfilling?: boolean; annotated?: number; posts?: number; oldest_at?: string; newest_at?: string } const SPECIAL = ['~saved', '~discover', '~clean'] export default function Sources(props: { channel: string; tab: string }) { return } function SourcesInner({ channel, tab }: { channel: string; tab: string }) { const chs = useAsync(() => get<{ items: Channel[] }>('/api/channels'), []) const acct = useAsync(() => get('/api/tgauth/status'), []) const [filter, setFilter] = useState('') const [addOpen, setAddOpen] = useState(false) const [acctOpen, setAcctOpen] = useState(false) const list = chs.data?.items || [] const anyBackfill = list.some(c => c.backfilling) useEffect(() => { if (!anyBackfill) return const t = setInterval(() => chs.reload(), 8000) return () => clearInterval(t) }, [anyBackfill]) const shown = list.filter(c => !filter || c.channel.toLowerCase().includes(filter.toLowerCase()) || (c.title || '').includes(filter)) const current = list.find(c => c.channel === channel) const totalPosts = list.reduce((a, c) => a + (c.posts || 0), 0) let main: React.ReactNode if (channel === '~saved') main = else if (channel === '~discover') main = chs.reload()} connected={!!acct.data?.connected} onAccount={() => setAcctOpen(true)} /> else if (channel === '~clean') main = else if (channel && current) main = chs.reload()} /> else if (channel && chs.data) main =
它可能已被移除。
else if (!chs.data) main = chs.error ?
: else main = setAddOpen(true)} onAccount={() => setAcctOpen(true)} /> return (
{main}
setAddOpen(false)} onAdded={ch => { chs.reload(); go(`sources/${ch}`) }} onAccount={() => { setAddOpen(false); setAcctOpen(true) }} /> { setAcctOpen(false); acct.reload() }} status={acct.data} reload={acct.reload} />
) } function Avatar({ c, size = 30 }: { c: { avatar?: string; title?: string; channel: string }; size?: number }) { const [bad, setBad] = useState(false) if (c.avatar && !bad) return setBad(true)} loading="lazy" /> return {(c.title || c.channel).slice(0, 1)} } function Overview({ list, totalPosts, acct, onAdd, onAccount }: { list: Channel[]; totalPosts: number; acct: any; onAdd: () => void; onAccount: () => void }) { const recent = [...list].sort((a, b) => String(b.last_synced_at).localeCompare(String(a.last_synced_at))).slice(0, 8) const annotated = list.filter(c => (c.annotated || 0) > 0) return (
素材采集

从 Telegram 频道收集真实故事

添加频道后会自动抓取全部历史帖子并定期更新。打过分的频道可以在「灵感」里按质量挑选。

{list.length}个频道
{fmtNum(totalPosts)}条帖子
{annotated.length}个频道已标注灵感
{acct?.error &&
账号状态:{acct.error}
}
{annotated.length > 0 &&

可以挑灵感的频道

{annotated.map(c => )}
}

最近更新

{recent.map(c => )}
) } function ChCard({ c, to }: { c: Channel; to: string }) { return ( ) } /* ================= 频道 ================= */ type CTab = 'inspo' | 'posts' | 'stats' function ChannelView({ ch, tab, onChanged }: { ch: Channel; tab: string; onChanged: () => void }) { const toast = useToast() const confirm = useConfirm() const hasInspo = (ch.annotated || 0) > 0 const t = (['inspo', 'posts', 'stats'].includes(tab) ? tab : hasInspo ? 'inspo' : 'posts') as CTab const [busy, setBusy] = useState('') const [bump, setBump] = useState(0) const [descOpen, setDescOpen] = useState(false) const sync = async () => { setBusy('sync') try { const r = await post('/api/posts/sync', { channel: ch.channel, pages: 5 }); toast(r.note || `已更新,新增 ${r.added ?? r.fetched ?? 0} 条`, 'ok'); onChanged(); setBump(b => b + 1) } catch (e: any) { toast(e.message, 'err') } finally { setBusy('') } } const backfill = async () => { setBusy('bf') try { const r = await post(`/api/channels/${ch.channel}/backfill`, {}); toast(r.started ? '已开始在后台收集全部历史帖子' : '历史已收集完,或正在收集中'); onChanged() } catch (e: any) { toast(e.message, 'err') } finally { setBusy('') } } const remove = async () => { const ok = await confirm({ title: `移除频道 @${ch.channel}?`, body: '会删除这个频道已抓取的全部帖子和收藏,无法恢复。素材库里已经清洗好的素材不受影响。', ok: '永久移除', danger: true, typeToConfirm: ch.channel }) if (!ok) return setBusy('del') try { await del(`/api/channels/${ch.channel}`); toast('频道已移除'); onChanged(); go('sources') } catch (e: any) { toast(e.message, 'err') } finally { setBusy('') } } return (

{ch.title || ch.channel}

@{ch.channel} {' · '}{fmtNum(ch.posts || 0)} 条帖子 · {fmtAgo(ch.last_synced_at)}更新 {' · '}{ch.backfilling ? 正在收集历史… : ch.backfill_status === 'done' ? '历史已收全' : '历史未收全'}
{ch.description &&
setDescOpen(o => !o)}>{ch.description}
}
{ch.backfill_status !== 'done' && !ch.backfilling && }
value={t} onChange={v => go(`sources/${ch.channel}/${v}`)} className="room-tabs" items={[ { id: 'inspo', label: <>灵感, count: ch.annotated || undefined }, { id: 'posts', label: <>全部帖子, count: ch.posts || undefined }, { id: 'stats', label: <>统计 }, ]} /> {t === 'posts' && } {t === 'inspo' && (hasInspo ? : } title="这个频道还没有灵感标注">标注完成后,这里会按素材价值给帖子打分、归类,方便挑选。现在可以先在「全部帖子」里浏览。)} {t === 'stats' && }
) } const SORT_POSTS = [{ id: 'latest', label: '最新' }, { id: 'views', label: '最多浏览' }, { id: 'reactions', label: '最多互动' }, { id: 'long', label: '最长' }] function PostsTab({ ch, bump }: { ch: string; bump: number }) { const [cat, setCat] = useState('') const [q, setQ] = useState('') const [sort, setSort] = useState('latest') const [hidePromo, setHidePromo] = useState(true) const [items, setItems] = useState([]) const [total, setTotal] = useState(0) const [loading, setLoading] = useState(true) const [err, setErr] = useState('') const dq = useDebounced(q, 400) const stats = useAsync(() => get(`/api/posts/stats${qs({ channel: ch })}`), [ch, bump]) const load = async (offset: number) => { setLoading(true); setErr('') try { const r = await get(`/api/posts${qs({ channel: ch, category: cat, q: dq, sort, hidePromo: hidePromo ? 1 : '', limit: 30, offset })}`) setItems(prev => offset ? [...prev, ...r.items] : r.items); setTotal(r.total) } catch (e: any) { setErr(e.message) } finally { setLoading(false) } } useEffect(() => { load(0) }, [ch, cat, dq, sort, hidePromo, bump]) const cats: any[] = stats.data?.categories || [] return (
{cats.map(c => )}
{err && load(0)} />}
共 {fmtNum(total)} 条
{items.map(p => )}
{loading ? : items.length < total && } {!loading && !items.length && !err && }
) } function PostCard({ p, ch, children, head }: { p: any; ch: string; children?: React.ReactNode; head?: React.ReactNode }) { const [open, setOpen] = useState(false) const toast = useToast() const long = (p.text || '').length > 260 return (
{head} {p.category && {p.category}} {fmtDate(p.posted_at)} {fmtNum(p.views)} {p.reaction_total ? {fmtNum(p.reaction_total)} : null} {p.char_count} 字 {p.photos?.length ? {p.photos.length} : null}
{p.text}
{long && } {p.reactions?.length ?
{p.reactions.slice(0, 6).map((r: any, i: number) => {r.emoji} {r.count})}
: null} {children}
) } /* ---------- 灵感 ---------- */ const PRESETS: Record }> = { best: { label: '精选', d: '完整故事 · 4 分以上 · 同类只留最佳', p: { kinds: '故事', minScore: 4, minChars: '', dedupe: '' } }, wide: { label: '宽松', d: '故事和片段 · 3 分以上 · 100 字以上', p: { kinds: '故事,片段', minScore: 3, minChars: 100, dedupe: '' } }, all: { label: '全部', d: '60 字以上 · 不去重', p: { kinds: '', minScore: '', minChars: 60, dedupe: '0' } }, } const KINDS = ['故事', '片段', '倾诉', '求助'] function InspoTab({ ch }: { ch: string }) { const [preset, setPreset] = useState('best') const [kinds, setKinds] = useState(['故事']) const [minScore, setMinScore] = useState(4) const [minChars, setMinChars] = useState('') const [dedupe, setDedupe] = useState(true) const [motif, setMotif] = useState('') const [tag, setTag] = useState('') const [q, setQ] = useState('') const [saved, setSaved] = useState(false) const [sort, setSort] = useState('score') const [page, setPage] = useState(1) const [group, setGroup] = useState('') const dq = useDebounced(q, 400) const applyPreset = (id: string) => { const p = PRESETS[id].p setPreset(id); setKinds(p.kinds ? String(p.kinds).split(',') : []); setMinScore(p.minScore || ''); setMinChars(p.minChars || ''); setDedupe(p.dedupe !== '0') } const params = { channel: ch, kinds: kinds.join(','), minScore, minChars, dedupe: dedupe ? '' : '0', motif, tag, q: dq, saved: saved ? 1 : '' } const key = JSON.stringify(params) useEffect(() => setPage(1), [key, sort]) const size = 20 const funnel = useAsync(() => get(`/api/inspo/funnel${qs(params)}`), [key]) const list = useAsync(() => get(`/api/inspo${qs({ ...params, sort, limit: size, offset: (page - 1) * size })}`), [key, sort, page]) const f = funnel.data const toggleKind = (k: string) => { setPreset(''); setKinds(ks => ks.includes(k) ? ks.filter(x => x !== k) : [...ks, k]) } const updateItem = (post_id: number, patch: any) => list.setData((d: any) => d ? { ...d, items: d.items.map((x: any) => x.post_id === post_id ? { ...x, ...patch } : x) } : d) return (
{Object.entries(PRESETS).map(([id, p]) => ( ))}
类型{KINDS.map(k => )}
素材分 {['', 1, 2, 3, 4, 5].map(s => )} {f?.scoreDist?.length > 0 && {f.scoreDist.map((x: any) => y.n))) * 100)}%` }} />)}}
字数 {['', 60, 100, 300, 800].map(n => )}
{f?.motifs?.length > 0 &&
母题 {motif && } {f.motifs.filter((m: any) => m.motif !== motif).slice(0, 24).map((m: any) => )}
} {f?.tags?.length > 0 &&
元素 {tag && } {f.tags.filter((t: any) => t.tag !== tag).slice(0, 20).map((t: any) => )}
}
{f?.steps && (
{f.steps.map((s: any, i: number) =>
{fmtNum(s.n)}{s.label}
)}
)}
{list.error ? : !list.data ? : list.data.items.length === 0 ? 放宽筛选条件试试。 : <>
{list.data.items.map((p: any) => setGroup(p.plot_group)} onUpdate={patch => updateItem(p.post_id, patch)} />)}
} setGroup('')} />
) } function InspoCard({ p, ch, onGroup, onUpdate }: { p: any; ch: string; onGroup?: () => void; onUpdate: (patch: any) => void }) { const toast = useToast() const [noteOpen, setNoteOpen] = useState(false) const [note, setNote] = useState(p.saved_note || p.note || '') const [busy, setBusy] = useState(false) const save = async (withNote?: string) => { setBusy(true) try { await post('/api/inspo/saves', { channel: p.channel || ch, post_id: p.post_id, note: withNote ?? (note || null) }); onUpdate({ saved: true, saved_note: withNote ?? note }); toast('已收藏', 'ok'); setNoteOpen(false) } catch (e: any) { toast(e.message, 'err') } finally { setBusy(false) } } const unsave = async () => { setBusy(true) try { await del(`/api/inspo/saves/${p.post_id}${qs({ channel: p.channel || ch })}`); onUpdate({ saved: false, saved_note: null }); toast('已取消收藏') } catch (e: any) { toast(e.message, 'err') } finally { setBusy(false) } } return ( {p.score != null && {p.score}} {p.kind && {p.kind}} {p.motif && {p.motif}} }> {p.logline &&
{p.logline}
} {p.detail &&
「{p.detail}」
}
{p.tags?.map((t: string) => #{t})} {p.group_size > 1 && onGroup && } {p.saved ? <> : }
{p.saved && p.saved_note && !noteOpen &&
笔记:{p.saved_note}
} {noteOpen && (
setNote(e.target.value)} placeholder="为什么收藏它?可以怎么用?" autoFocus onKeyDown={e => { if (e.key === 'Enter') save(note) }} />
)}
) } function GroupModal({ ch, gkey, onClose }: { ch: string; gkey: string; onClose: () => void }) { const [items, setItems] = useState(null) useEffect(() => { if (!gkey) return; setItems(null); get(`/api/inspo/group${qs({ channel: ch, key: gkey })}`).then(r => setItems(r.items), () => setItems([])) }, [ch, gkey]) return ( {!items ? :
{items.map(p => {p.score} : null}>{p.logline &&
{p.logline}
}
)}
}
) } /* ---------- 统计 ---------- */ function StatsTab({ ch }: { ch: string }) { const s = useAsync(() => get(`/api/posts/stats${qs({ channel: ch })}`), [ch]) if (s.error) return if (!s.data) return const d = s.data, sum = d.summary || {} const cats: any[] = d.categories || [] const maxCat = Math.max(1, ...cats.map(c => c.n)) const daily: any[] = (d.daily || []).slice(-120) const maxDay = Math.max(1, ...daily.map(x => x.n)) return (
{fmtNum(sum.total)}条帖子
{fmtNum(sum.avg_views)}平均浏览
{fmtNum(sum.avg_chars)}平均字数
{fmtNum(sum.total_reactions)}总互动

时间跨度:{fmtDate(sum.oldest_at, false)} — {fmtDate(sum.newest_at, false)}

话题分布

{cats.map(c =>
{c.category}{c.n}均浏览 {fmtNum(c.avg_views)}
)}
{daily.length > 0 &&

发帖节奏 最近 {daily.length} 个有帖的日子

{daily.map(x => )}
} {d.emojis?.length > 0 &&

读者反应

{d.emojis.map((e: any) => {e.emoji}{fmtNum(e.n)})}
}
) } /* ================= 收藏 ================= */ function SavedView() { const s = useAsync(() => get('/api/inspo/saves?channel=*'), []) const items: any[] = s.data?.items || [] return (
收藏的灵感

随手存下的好故事

{s.error ? : !s.data ? : items.length === 0 ? } title="还没有收藏">在频道的「灵感」里点「收藏」,就会出现在这里。 : (
{items.map(p => s.setData((d: any) => ({ ...d, items: patch.saved === false ? d.items.filter((x: any) => !(x.channel === p.channel && x.post_id === p.post_id)) : d.items.map((x: any) => x.channel === p.channel && x.post_id === p.post_id ? { ...x, note: patch.saved_note } : x) }))} />)}
)}
) } /* ================= 发现 ================= */ function DiscoverView({ onAdded, connected, onAccount }: { onAdded: () => void; connected: boolean; onAccount: () => void }) { const toast = useToast() const confirm = useConfirm() const d = useAsync(() => get('/api/discover'), []) const [kw, setKw] = useState('') const [show, setShow] = useState<'good' | 'all' | 'ignored'>('good') const [busy, setBusy] = useState('') const [open, setOpen] = useState('') const running = !!d.data?.running useEffect(() => { if (d.data && !kw) setKw((d.data.keywords || []).join('、')) }, [d.data]) useEffect(() => { if (!running) return const t = setInterval(() => d.reload(), 4000) return () => clearInterval(t) }, [running]) const act = async (name: string, fn: () => Promise, msg?: string) => { setBusy(name) try { await fn(); if (msg) toast(msg, 'ok'); await d.reload() } catch (e: any) { toast(e.message, 'err') } finally { setBusy('') } } const items: any[] = d.data?.items || [] const filtered = items.filter(x => show === 'ignored' ? x.ignored : !x.ignored && (show === 'all' || x.suitable)).sort((a, b) => (b.score || 0) - (a.score || 0)) return (
发现新频道

用关键词找更多故事频道

输入几个关键词,系统会搜索相关频道,读取最新内容,判断是否适合当素材来源。

{!connected &&
需要先连接 Telegram 账号才能搜索。
}
setKw(e.target.value)} placeholder="树洞、情感、真实经历" />
{running ? : } {items.length > 0 && !running && } {d.data?.phase && {running && } {d.data.phase}}
{d.error ? : !d.data ? : <> !x.ignored && x.suitable).length}` }, { id: 'all', label: `全部 ${items.filter(x => !x.ignored).length}` }, { id: 'ignored', label: `已忽略 ${items.filter(x => x.ignored).length}` }, ]} />
{filtered.map(x => (
{x.score ?? '—'}
{x.title || x.username}@{x.username}
{x.verdict && {x.verdict}} {x.adult && 含成人内容} {x.ad && 广告多} {x.status !== 'checked' && {x.status === 'pending' ? '待检查' : x.status}}
{x.stats &&
最近 {x.stats.n} 条 · 中位 {x.stats.median} 字 · 长文 {Math.round((x.stats.long || 0) * 100)}% · 故事 {Math.round((x.stats.story || 0) * 100)}% · 推广 {Math.round((x.stats.promo || 0) * 100)}%{x.last_post_at ? ` · 最近发帖 ${fmtAgo(x.last_post_at)}` : ''}{x.keywords?.length ? ` · 来自「${x.keywords.join('、')}」` : ''}
} {x.samples?.length > 0 && <> {open === x.username &&
{x.samples.map((s: any, i: number) =>
{String(s.text || '').slice(0, 400)}
)}
} }
))} {!filtered.length && }
}
) } /* ================= 清洗进度 ================= */ function CleanView() { const p = useAsync(() => get('/api/clean/progress'), []) const [page, setPage] = useState(0) const [showMat, setShowMat] = useState(false) const m = useAsync(() => showMat ? get(`/api/clean/materials${qs({ page: page || '0' })}`) : Promise.resolve(null), [page, showMat]) if (p.error) return
if (!p.data) return const s = p.data.stats || {} const batches: any[] = [...(p.data.batches || [])].reverse() return (
清洗进度

原帖 → 可用素材

逐批读取原帖,去掉不适合的内容,必要时改写。更新于 {fmtDate(p.data.updated_at)}。

{s.percent ?? 0}%
{fmtNum(s.read)}已读 / {fmtNum(s.total)}
{fmtNum(s.kept)}原样保留
{fmtNum(s.rewritten)}改写后保留
{fmtNum(s.dropped)}丢弃
{fmtNum(s.materials)}条素材 · {fmtNum(s.chars_out)} 字
{showMat && (m.loading && !m.data ? : m.error ? : m.data &&
{m.data.items.map((x: any) => {x.verdict === 'keep' ? '保留' : '改写'}}>{x.note &&
{x.note}
}
)}
setPage(pg - 1)} />
)}

最近处理的批次

{batches.slice(0, 40).map(b => (
第 {b.no} 批 {(b.channels || []).join('、')} 保留 {b.kept} · 改写 {b.rewritten} · 丢弃 {b.dropped} {fmtAgo(b.finished_at)}
))}
) } /* ================= 添加频道 ================= */ function AddChannel({ open, onClose, onAdded, onAccount }: { open: boolean; onClose: () => void; onAdded: (ch: string) => void; onAccount: () => void }) { const toast = useToast() const [v, setV] = useState('') const [backfill, setBackfill] = useState(true) const [busy, setBusy] = useState(false) const [err, setErr] = useState<{ msg: string; needAccount?: boolean } | null>(null) useEffect(() => { if (open) { setV(''); setErr(null) } }, [open]) const submit = async (e: React.FormEvent) => { e.preventDefault() if (!v.trim()) return setBusy(true); setErr(null) try { const r = await post('/api/channels', { channel: v.trim(), backfill }); toast(`已添加 @${r.channel}`, 'ok'); onClose(); onAdded(r.channel) } catch (e: any) { setErr({ msg: e.message, needAccount: e.data?.needAccount }) } finally { setBusy(false) } } return (
setV(e.target.value)} autoFocus placeholder="@频道用户名" /> {err &&
{err.msg}{err.needAccount && }
}
) } /* ================= Telegram 账号 ================= */ function AccountModal({ open, onClose, status, reload }: { open: boolean; onClose: () => void; status: any; reload: () => void }) { const toast = useToast() const confirm = useConfirm() const [step, setStep] = useState<'idle' | 'start' | 'code' | 'password'>('idle') const [f, setF] = useState({ apiId: '', apiHash: '', phone: '', code: '', password: '' }) const [hint, setHint] = useState('') const [busy, setBusy] = useState(false) useEffect(() => { if (open) { setStep(status?.step === 'code' ? 'code' : status?.step === 'password' ? 'password' : 'idle'); setHint(status?.hint || '') } }, [open]) const set = (k: string, v: string) => setF(s => ({ ...s, [k]: v })) const call = async (url: string, body: any) => { setBusy(true) try { const r = await post(url, body) if (r.done) { toast('Telegram 账号已连接', 'ok'); setStep('idle'); reload() } else if (r.step === 'code') { setStep('code'); toast(r.viaApp ? '验证码已发到你的 Telegram App' : '验证码已发送') } else if (r.step === 'password') { setStep('password'); setHint(r.hint || '') } } catch (e: any) { toast(e.message, 'err') } finally { setBusy(false) } } const logout = async () => { if (!(await confirm({ title: '退出 Telegram 账号?', body: '退出后,关闭了网页预览的频道将无法继续抓取。', ok: '退出', danger: true }))) return setBusy(true) try { await post('/api/tgauth/logout'); toast('已退出'); reload() } catch (e: any) { toast(e.message, 'err') } finally { setBusy(false) } } return (
{status?.connected ? <>{status.name}
{status.username ? `@${status.username} · ` : ''}{status.phone}
: <>未连接
大部分公开频道无需登录;关闭网页预览的频道和「发现新频道」需要登录。
}
{status?.connected && }
{status?.error &&
{status.error}
} {step === 'idle' && } {step === 'start' &&
{ e.preventDefault(); call('/api/tgauth/start', { apiId: f.apiId, apiHash: f.apiHash, phone: f.phone }) }}>

到 my.telegram.org 的 API development tools 创建应用,复制 API ID 和 API Hash。

set('apiId', e.target.value)} inputMode="numeric" /> set('phone', e.target.value)} placeholder="+8613800000000" /> set('apiHash', e.target.value)} />
} {step === 'code' &&
{ e.preventDefault(); call('/api/tgauth/code', { code: f.code }) }}> set('code', e.target.value)} autoFocus inputMode="numeric" />
} {step === 'password' &&
{ e.preventDefault(); call('/api/tgauth/password', { password: f.password }) }}> set('password', e.target.value)} autoFocus />
}
) }