Surf Studio commited on
Commit
440f26b
·
1 Parent(s): 7b0d635

Telegram 群组覆盖:一键扫描账号全部群组/频道批量导入、公开群组关键词搜索、按命中轮换扫描、连接自愈(重新连接)

Browse files
README.md CHANGED
@@ -19,6 +19,9 @@ pinned: false
19
  - 登录 X 后可以**实时搜索关键词**,拿到比网页索引更新的帖子(含搜索结果里的新账号)
20
  - **Telegram**
21
  - 用手机号登录 Telegram 账号(验证码 + 两步验证),可以读取**私有频道 / 私有群**里的赠链消息
 
 
 
22
  - 未登录时以公开模式读取公开频道
23
  - **名额检查**:每 5 分钟复查剩余名额(每个码 4 分钟内不重复查,遇到接口限流自动退避 10 分钟)
24
  - **企业微信推送**:一旦发现有「还有名额」的赠链,立刻推送到群机器人(每个赠链只推一次)
 
19
  - 登录 X 后可以**实时搜索关键词**,拿到比网页索引更新的帖子(含搜索结果里的新账号)
20
  - **Telegram**
21
  - 用手机号登录 Telegram 账号(验证码 + 两步验证),可以读取**私有频道 / 私有群**里的赠链消息
22
+ - 点「扫描我的群组」可一次性列出账号加入的全部群组/频道,勾选批量添加(中文群、私有群都行)
23
+ - 还能按关键词搜索公开群组(Telegram 只索引英文名称,例如 airdrop / crypto)
24
+ - 手动添加的频道每轮都读;批量导入的群组轮流读,其中出过 Surf 内容的群组每轮都读
25
  - 未登录时以公开模式读取公开频道
26
  - **名额检查**:每 5 分钟复查剩余名额(每个码 4 分钟内不重复查,遇到接口限流自动退避 10 分钟)
27
  - **企业微信推送**:一旦发现有「还有名额」的赠链,立刻推送到群机器人(每个赠链只推一次)
frontend/src/components/SourcePanel.tsx CHANGED
@@ -3,14 +3,18 @@ import {
3
  AlertCircle,
4
  Check,
5
  ChevronDown,
 
6
  Loader2,
 
7
  Plus,
8
  RefreshCw,
 
9
  Send,
10
  Unplug,
11
  X,
12
  } from 'lucide-react'
13
  import { api } from '../lib/api'
 
14
 
15
  type XStatus = {
16
  connected: boolean
@@ -21,7 +25,19 @@ type XStatus = {
21
  searchCount?: number
22
  }
23
 
24
- type TelegramChannel = { id: string; ref?: string; username?: string | null; title?: string }
 
 
 
 
 
 
 
 
 
 
 
 
25
  type TelegramStatus = {
26
  loggedIn: boolean
27
  mode?: 'user' | 'public'
@@ -66,6 +82,10 @@ export default function SourcePanel({ onChanged }: { onChanged: () => void }) {
66
  const [notice, setNotice] = useState<string | null>(null)
67
  const [error, setError] = useState<string | null>(null)
68
  const [link, setLink] = useState('')
 
 
 
 
69
  const [adminKey, setAdminKey] = useState('')
70
  const [keyDraft, setKeyDraft] = useState('')
71
  const [needsKey, setNeedsKey] = useState(false)
@@ -216,6 +236,82 @@ export default function SourcePanel({ onChanged }: { onChanged: () => void }) {
216
  if (body) setTelegram((prev) => (prev ? { ...prev, channels: body.channels } : prev))
217
  }
218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  async function startTgLogin() {
220
  if (!phone.trim() || busy) return
221
  const body = await call(
@@ -539,6 +635,32 @@ export default function SourcePanel({ onChanged }: { onChanged: () => void }) {
539
  )}
540
  同步消息
541
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  <button
543
  type="button"
544
  onClick={logoutTelegram}
@@ -549,8 +671,116 @@ export default function SourcePanel({ onChanged }: { onChanged: () => void }) {
549
  退出登录
550
  </button>
551
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
552
  <p className="mt-2 text-[11px] leading-5 text-fg-muted">
553
- 后台每 5 分钟自动读取一次新消息,无需手动同步。
554
  </p>
555
  </>
556
  ) : (
 
3
  AlertCircle,
4
  Check,
5
  ChevronDown,
6
+ ListPlus,
7
  Loader2,
8
+ PlugZap,
9
  Plus,
10
  RefreshCw,
11
+ Search,
12
  Send,
13
  Unplug,
14
  X,
15
  } from 'lucide-react'
16
  import { api } from '../lib/api'
17
+ import { formatCount } from '../lib/format'
18
 
19
  type XStatus = {
20
  connected: boolean
 
25
  searchCount?: number
26
  }
27
 
28
+ type TelegramChannel = { id: string; ref?: string; username?: string | null; title?: string; auto?: boolean }
29
+ type TelegramDialog = {
30
+ id: string
31
+ ref: string
32
+ username: string | null
33
+ title: string
34
+ type: 'group' | 'channel'
35
+ members: number | null
36
+ isPrivate: boolean
37
+ added: boolean
38
+ }
39
+ /** Pre-tick chats that look like crypto / airdrop groups. */
40
+ const LIKELY_CHAT_RE = /空投|撸毛|撸|羊毛|白嫖|加密|币圈|区块链|交易所|钱包|web3|crypto|airdrop|defi|nft|dao|surf|token|福利/i
41
  type TelegramStatus = {
42
  loggedIn: boolean
43
  mode?: 'user' | 'public'
 
82
  const [notice, setNotice] = useState<string | null>(null)
83
  const [error, setError] = useState<string | null>(null)
84
  const [link, setLink] = useState('')
85
+ const [dialogs, setDialogs] = useState<TelegramDialog[] | null>(null)
86
+ const [picked, setPicked] = useState<Record<string, boolean>>({})
87
+ const [dialogQuery, setDialogQuery] = useState('')
88
+ const [dialogSearch, setDialogSearch] = useState('')
89
  const [adminKey, setAdminKey] = useState('')
90
  const [keyDraft, setKeyDraft] = useState('')
91
  const [needsKey, setNeedsKey] = useState(false)
 
236
  if (body) setTelegram((prev) => (prev ? { ...prev, channels: body.channels } : prev))
237
  }
238
 
239
+ async function reconnectTelegram() {
240
+ const body = await call(
241
+ 'tg-reconnect',
242
+ 'telegram/reconnect',
243
+ { method: 'POST' },
244
+ (result) => `Telegram 已重新连接${result.username ? `:@${result.username}` : ''}`
245
+ )
246
+ if (body) {
247
+ const fresh = await call('tg-status-refresh', 'telegram/status', {}, () => '')
248
+ if (fresh) setTelegram(fresh)
249
+ onChanged()
250
+ }
251
+ }
252
+
253
+ async function scanDialogs() {
254
+ const body = await call(
255
+ 'tg-dialogs',
256
+ 'telegram/dialogs',
257
+ {},
258
+ (result) =>
259
+ `找到 ${result.dialogs.length} 个群组/频道,已自动勾选可能是空投/加密相关的`
260
+ )
261
+ if (body) {
262
+ setDialogs(body.dialogs)
263
+ const next: Record<string, boolean> = {}
264
+ for (const item of body.dialogs) {
265
+ next[item.ref] = !item.added && LIKELY_CHAT_RE.test(item.title)
266
+ }
267
+ setPicked(next)
268
+ setDialogQuery('')
269
+ }
270
+ }
271
+
272
+ async function searchPublicGroups() {
273
+ const term = dialogSearch.trim()
274
+ if (!term) {
275
+ setError('请输入关键词,例如 airdrop / crypto / web3')
276
+ return
277
+ }
278
+ const body = await call(
279
+ 'tg-search',
280
+ `telegram/search?q=${encodeURIComponent(term)}`,
281
+ {},
282
+ (result) =>
283
+ result.dialogs.length > 0
284
+ ? `找到 ${result.dialogs.length} 个公开群组/频道`
285
+ : '没找到公开群组,换英文关键词试试(Telegram 搜不到中文群名)'
286
+ )
287
+ if (body) {
288
+ setDialogs(body.dialogs)
289
+ const next: Record<string, boolean> = {}
290
+ for (const item of body.dialogs) next[item.ref] = !item.added
291
+ setPicked(next)
292
+ setDialogQuery('')
293
+ }
294
+ }
295
+
296
+ async function importPicked() {
297
+ const refs = (dialogs || []).filter((item) => picked[item.ref] && !item.added)
298
+ if (refs.length === 0) {
299
+ setError('请先勾选要监控的群组或频道')
300
+ return
301
+ }
302
+ const body = await call(
303
+ 'tg-import',
304
+ 'telegram/channels/import',
305
+ { method: 'POST', body: JSON.stringify({ channels: refs }) },
306
+ (result) => `已添加 ${result.added} 个,现在共监控 ${result.total} 个群组/频道`
307
+ )
308
+ if (body) {
309
+ setTelegram((prev) => (prev ? { ...prev, channels: body.channels } : prev))
310
+ setDialogs(null)
311
+ onChanged()
312
+ }
313
+ }
314
+
315
  async function startTgLogin() {
316
  if (!phone.trim() || busy) return
317
  const body = await call(
 
635
  )}
636
  同步消息
637
  </button>
638
+ <button
639
+ type="button"
640
+ onClick={reconnectTelegram}
641
+ disabled={busy === 'tg-reconnect'}
642
+ className={ghostButton}
643
+ >
644
+ {busy === 'tg-reconnect' ? (
645
+ <Loader2 className="h-4 w-4 animate-spin" />
646
+ ) : (
647
+ <PlugZap className="h-4 w-4" />
648
+ )}
649
+ 重新连接
650
+ </button>
651
+ <button
652
+ type="button"
653
+ onClick={scanDialogs}
654
+ disabled={busy === 'tg-dialogs'}
655
+ className={ghostButton}
656
+ >
657
+ {busy === 'tg-dialogs' ? (
658
+ <Loader2 className="h-4 w-4 animate-spin" />
659
+ ) : (
660
+ <ListPlus className="h-4 w-4" />
661
+ )}
662
+ 扫描我的群组
663
+ </button>
664
  <button
665
  type="button"
666
  onClick={logoutTelegram}
 
671
  退出登录
672
  </button>
673
  </div>
674
+
675
+ {dialogs ? (
676
+ <div className="mt-3 rounded-[10px] border border-[var(--border-strong)] p-2.5">
677
+ <div className="flex flex-wrap items-center gap-2">
678
+ <input
679
+ value={dialogSearch}
680
+ onChange={(event) => setDialogSearch(event.target.value)}
681
+ onKeyDown={(event) => {
682
+ if (event.key === 'Enter') void searchPublicGroups()
683
+ }}
684
+ placeholder="搜索公开群组(英文关键词)"
685
+ className={`${inputClass} max-w-[200px]`}
686
+ />
687
+ <button
688
+ type="button"
689
+ onClick={searchPublicGroups}
690
+ disabled={busy === 'tg-search'}
691
+ className={ghostButton}
692
+ >
693
+ {busy === 'tg-search' ? (
694
+ <Loader2 className="h-4 w-4 animate-spin" />
695
+ ) : (
696
+ <Search className="h-4 w-4" />
697
+ )}
698
+ 搜索
699
+ </button>
700
+ <span className="text-[11px] text-fg-muted">
701
+ 例如 airdrop / crypto / web3(中文群名 Telegram 搜不到)
702
+ </span>
703
+ </div>
704
+ <div className="mt-2 flex flex-wrap items-center gap-2">
705
+ <input
706
+ value={dialogQuery}
707
+ onChange={(event) => setDialogQuery(event.target.value)}
708
+ placeholder="按名称筛选…"
709
+ className={`${inputClass} max-w-[180px]`}
710
+ />
711
+ <span className="text-[11px] text-fg-muted">
712
+ 共 {dialogs.length} 个 · 已勾选{' '}
713
+ {Object.values(picked).filter(Boolean).length} 个
714
+ </span>
715
+ <button
716
+ type="button"
717
+ onClick={() => {
718
+ const next: Record<string, boolean> = {}
719
+ for (const item of dialogs) next[item.ref] = !item.added
720
+ setPicked(next)
721
+ }}
722
+ className="text-[11px] text-[var(--accent)] hover:underline"
723
+ >
724
+ 全选未添加
725
+ </button>
726
+ <button
727
+ type="button"
728
+ onClick={() => setPicked({})}
729
+ className="text-[11px] text-fg-muted hover:underline"
730
+ >
731
+ 清空
732
+ </button>
733
+ </div>
734
+ <ul className="mt-2 max-h-56 space-y-1 overflow-y-auto pr-1">
735
+ {dialogs
736
+ .filter((item) =>
737
+ dialogQuery.trim()
738
+ ? item.title.toLowerCase().includes(dialogQuery.trim().toLowerCase())
739
+ : true
740
+ )
741
+ .map((item) => (
742
+ <li key={item.ref}>
743
+ <label className="flex cursor-pointer items-center gap-2 rounded-[8px] px-2 py-1 text-[11px] hover:bg-[var(--bg-chat)]">
744
+ <input
745
+ type="checkbox"
746
+ checked={Boolean(picked[item.ref])}
747
+ disabled={item.added}
748
+ onChange={(event) =>
749
+ setPicked((prev) => ({ ...prev, [item.ref]: event.target.checked }))
750
+ }
751
+ className="h-3.5 w-3.5 accent-[var(--accent)]"
752
+ />
753
+ <span className="min-w-0 flex-1 truncate text-fg-subtle">
754
+ {item.title}
755
+ </span>
756
+ <span className="shrink-0 text-fg-muted">
757
+ {item.type === 'group' ? '群组' : '频道'}
758
+ {item.members ? ` · ${formatCount(item.members)}` : ''}
759
+ </span>
760
+ {item.added ? (
761
+ <span className="shrink-0 text-[var(--accent)]">已监控</span>
762
+ ) : null}
763
+ </label>
764
+ </li>
765
+ ))}
766
+ </ul>
767
+ <div className="mt-2 flex gap-2">
768
+ <button type="button" onClick={importPicked} disabled={busy === 'tg-import'} className={primaryButton}>
769
+ {busy === 'tg-import' ? (
770
+ <Loader2 className="h-4 w-4 animate-spin" />
771
+ ) : (
772
+ <Plus className="h-4 w-4" />
773
+ )}
774
+ 添加勾选的
775
+ </button>
776
+ <button type="button" onClick={() => setDialogs(null)} className={ghostButton}>
777
+ 取消
778
+ </button>
779
+ </div>
780
+ </div>
781
+ ) : null}
782
  <p className="mt-2 text-[11px] leading-5 text-fg-muted">
783
+ 后台每 5 分钟自动读取一轮消息(你手动加的频道每轮都读,批量导入的群组轮流读,出过 Surf 内容的群组每轮都读)。点「扫描我的群组」可以把你账号里的中文群、其他群一次性加进来。
784
  </p>
785
  </>
786
  ) : (
frontend/tsconfig.tsbuildinfo CHANGED
The diff for this file is too large to render. See raw diff
 
lib/telegram.js CHANGED
@@ -303,6 +303,10 @@ async function sync({ upsert, upsertParams }) {
303
 
304
  module.exports = {
305
  status,
 
 
 
 
306
  addChannel,
307
  removeChannel,
308
  sync,
 
303
 
304
  module.exports = {
305
  status,
306
+ reconnect: (...args) => telegramUser.reconnect(...args),
307
+ listDialogs: (...args) => telegramUser.listDialogs(...args),
308
+ searchPublicChats: (...args) => telegramUser.searchPublicChats(...args),
309
+ importChannels: (...args) => telegramUser.importChannels(...args),
310
  addChannel,
311
  removeChannel,
312
  sync,
lib/telegramUser.js CHANGED
@@ -17,6 +17,8 @@ const DEFAULT_API_ID = 2040
17
  const DEFAULT_API_HASH = 'b18441a1ff607e10a989891a5462e627'
18
 
19
  const KEEP_DAYS = 60
 
 
20
  const MESSAGES_PER_CHANNEL = 50
21
 
22
  const GIFT_LINK_RE = /asksurf\.ai\/mystery-box\/g\/([A-Za-z0-9]+)/i
@@ -99,6 +101,7 @@ function friendlyError(err) {
99
  FLOOD_WAIT: '操作太频繁,请稍后再试',
100
  API_ID_INVALID: 'api_id / api_hash 无效',
101
  AUTH_KEY_UNREGISTERED: '登录已失效,请重新登录',
 
102
  USER_DEACTIVATED_BAN: '这个账号已被 Telegram 限制',
103
  }
104
  const key = Object.keys(map).find((name) => raw.includes(name))
@@ -281,6 +284,135 @@ function chatToChannel(chat, ref) {
281
  }
282
 
283
  /** Add a public channel (@name / link) or a private one (invite link). */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  async function addChannel(input) {
285
  const session = await getSetting('tg_session')
286
  if (!session) throw new Error('请先用手机号登录 Telegram')
@@ -463,8 +595,9 @@ async function sync({ upsert, upsertParams }) {
463
  let throttled = 0
464
 
465
  const c = await client(session)
 
466
  {
467
- for (const channel of list) {
468
  try {
469
  // Older entries only carry a username, newer ones a ref/id — accept all.
470
  const target = channel.ref || channel.id || channel.username
@@ -482,6 +615,7 @@ async function sync({ upsert, upsertParams }) {
482
  if (!isRelevant(row)) continue
483
  if (row.has_link) withLink += 1
484
  stored += 1
 
485
  await dbQuery(upsert, upsertParams(row))
486
  }
487
  // Space the channel reads out so a long list never looks like a burst.
@@ -500,12 +634,28 @@ async function sync({ upsert, upsertParams }) {
500
  }
501
  }
502
 
 
 
 
 
503
  await setSetting('telegram_last_sync', new Date().toISOString())
504
- return { channels: list.length, scanned, stored, withLink, errors, throttled }
 
 
 
 
 
 
 
 
505
  }
506
 
507
  module.exports = {
508
  status,
 
 
 
 
509
  startLogin,
510
  submitCode,
511
  logout,
 
17
  const DEFAULT_API_HASH = 'b18441a1ff607e10a989891a5462e627'
18
 
19
  const KEEP_DAYS = 60
20
+ /** Auto-imported chats are scanned in rotation: this many per run. */
21
+ const AUTO_CHANNELS_PER_RUN = 8
22
  const MESSAGES_PER_CHANNEL = 50
23
 
24
  const GIFT_LINK_RE = /asksurf\.ai\/mystery-box\/g\/([A-Za-z0-9]+)/i
 
101
  FLOOD_WAIT: '操作太频繁,请稍后再试',
102
  API_ID_INVALID: 'api_id / api_hash 无效',
103
  AUTH_KEY_UNREGISTERED: '登录已失效,请重新登录',
104
+ AUTH_KEY_DUPLICATED: 'Telegram 会话被重复登录占用,正在自动重连;若持续失败请重新登录',
105
  USER_DEACTIVATED_BAN: '这个账号已被 Telegram 限制',
106
  }
107
  const key = Object.keys(map).find((name) => raw.includes(name))
 
284
  }
285
 
286
  /** Add a public channel (@name / link) or a private one (invite link). */
287
+ /** Drop the cached connection and log back in with the stored session. */
288
+ async function reconnect() {
289
+ await releaseClient()
290
+ const session = await getSetting('tg_session')
291
+ if (!session) throw new Error('Telegram 尚未登录,请重新登录')
292
+ const c = await client(session)
293
+ const me = await c.getMe()
294
+ return { ok: true, username: me?.username || null, id: String(me?.id || '') }
295
+ }
296
+
297
+ /** Every group / channel the logged-in account belongs to. */
298
+ async function listDialogs({ limit = 300 } = {}) {
299
+ const session = await getSetting('tg_session')
300
+ if (!session) {
301
+ const err = new Error('Telegram 尚未登录')
302
+ err.status = 400
303
+ throw err
304
+ }
305
+ const c = await client(session)
306
+ const dialogs = await c.getDialogs({ limit })
307
+ const out = []
308
+ for (const dialog of dialogs) {
309
+ const entity = dialog.entity
310
+ if (!entity || entity.className === 'User') continue
311
+ const isChannel = entity.className === 'Channel'
312
+ const username = entity.username || null
313
+ out.push({
314
+ id: String(entity.id),
315
+ ref: username || String(entity.id),
316
+ username,
317
+ title: entity.title || dialog.name || username || String(entity.id),
318
+ type: isChannel && !entity.megagroup ? 'channel' : 'group',
319
+ members: Number(entity.participantsCount || 0) || null,
320
+ isPrivate: !username,
321
+ })
322
+ }
323
+ out.sort((a, b) => (b.members || 0) - (a.members || 0))
324
+ return out
325
+ }
326
+
327
+ /** Search public groups/channels by keyword (Telegram only indexes latin titles). */
328
+ async function searchPublicChats(query, { limit = 20 } = {}) {
329
+ const term = String(query || '').trim()
330
+ if (!term) return []
331
+ const session = await getSetting('tg_session')
332
+ if (!session) {
333
+ const err = new Error('Telegram 尚未登录')
334
+ err.status = 400
335
+ throw err
336
+ }
337
+ const c = await client(session)
338
+ const res = await c.invoke(new Api.contacts.Search({ q: term, limit }))
339
+ const out = []
340
+ for (const chat of res.chats || []) {
341
+ if (!chat || chat.className === 'User') continue
342
+ if (!chat.username) continue // without a username the chat cannot be added
343
+ const isChannel = chat.className === 'Channel'
344
+ out.push({
345
+ id: String(chat.id),
346
+ ref: chat.username,
347
+ username: chat.username,
348
+ title: chat.title || chat.username,
349
+ type: isChannel && !chat.megagroup ? 'channel' : 'group',
350
+ members: Number(chat.participantsCount || 0) || null,
351
+ isPrivate: false,
352
+ })
353
+ }
354
+ return out
355
+ }
356
+
357
+ /** Bulk-add the chats picked in the "scan my groups" panel. */
358
+ async function importChannels(items) {
359
+ const list = await getJson('telegram_channels', [])
360
+ const keyOf = (item) => String(item.ref || item.username || item.id || '')
361
+ const existing = new Map()
362
+ for (const item of list) {
363
+ existing.set(keyOf(item), item)
364
+ if (item.id) existing.set(String(item.id), item)
365
+ }
366
+ let added = 0
367
+ let updated = 0
368
+ for (const item of items || []) {
369
+ const ref = String(item.ref || item.username || item.id || '').trim()
370
+ if (!ref) continue
371
+ const found = existing.get(ref) || (item.id ? existing.get(String(item.id)) : null)
372
+ if (found) {
373
+ found.id = String(item.id || found.id || ref)
374
+ found.username = item.username || found.username || null
375
+ found.title = item.title || found.title
376
+ updated += 1
377
+ continue
378
+ }
379
+ const entry = {
380
+ id: String(item.id || ref),
381
+ ref,
382
+ username: item.username || null,
383
+ title: item.title || ref,
384
+ type: item.type || 'channel',
385
+ auto: true,
386
+ hits: 0,
387
+ addedAt: new Date().toISOString(),
388
+ }
389
+ list.push(entry)
390
+ existing.set(ref, entry)
391
+ existing.set(String(entry.id), entry)
392
+ added += 1
393
+ }
394
+ await setSetting('telegram_channels', JSON.stringify(list))
395
+ return { added, updated, total: list.length, channels: list }
396
+ }
397
+
398
+ /**
399
+ * Manual channels are read every round, chats that already produced Surf posts
400
+ * too; the remaining auto-imported ones rotate so a long list stays gentle.
401
+ */
402
+ async function channelsToScan(list) {
403
+ const manual = list.filter((item) => item.auto !== true)
404
+ const hot = list.filter((item) => item.auto === true && Number(item.hits || 0) > 0)
405
+ const auto = list.filter((item) => item.auto === true && Number(item.hits || 0) === 0)
406
+ const chosen = [...manual, ...hot]
407
+ if (auto.length > 0) {
408
+ const cursor = (Number(await getSetting('tg_channel_cursor')) || 0) % auto.length
409
+ const take = Math.min(AUTO_CHANNELS_PER_RUN, auto.length)
410
+ for (let i = 0; i < take; i += 1) chosen.push(auto[(cursor + i) % auto.length])
411
+ await setSetting('tg_channel_cursor', (cursor + take) % auto.length)
412
+ }
413
+ return chosen
414
+ }
415
+
416
  async function addChannel(input) {
417
  const session = await getSetting('tg_session')
418
  if (!session) throw new Error('请先用手机号登录 Telegram')
 
595
  let throttled = 0
596
 
597
  const c = await client(session)
598
+ const chosen = await channelsToScan(list)
599
  {
600
+ for (const channel of chosen) {
601
  try {
602
  // Older entries only carry a username, newer ones a ref/id — accept all.
603
  const target = channel.ref || channel.id || channel.username
 
615
  if (!isRelevant(row)) continue
616
  if (row.has_link) withLink += 1
617
  stored += 1
618
+ channel.hits = Number(channel.hits || 0) + 1
619
  await dbQuery(upsert, upsertParams(row))
620
  }
621
  // Space the channel reads out so a long list never looks like a burst.
 
634
  }
635
  }
636
 
637
+ // Persist per-chat hit counts so the next round knows where the good stuff is.
638
+ const byRef = new Map(chosen.map((item) => [String(item.ref || item.username || item.id || ''), item]))
639
+ const merged = list.map((item) => byRef.get(String(item.ref || item.username || item.id || '')) || item)
640
+ await setSetting('telegram_channels', JSON.stringify(merged))
641
  await setSetting('telegram_last_sync', new Date().toISOString())
642
+ return {
643
+ channels: chosen.length,
644
+ totalChannels: list.length,
645
+ scanned,
646
+ stored,
647
+ withLink,
648
+ errors,
649
+ throttled,
650
+ }
651
  }
652
 
653
  module.exports = {
654
  status,
655
+ reconnect,
656
+ listDialogs,
657
+ searchPublicChats,
658
+ importChannels,
659
  startLogin,
660
  submitCode,
661
  logout,
routes/telegram.js CHANGED
@@ -3,7 +3,7 @@ const telegram = require('../lib/telegram')
3
  const telegramUser = require('../lib/telegramUser')
4
  const notify = require('../lib/notify')
5
  const { requireKey } = require('../lib/auth')
6
- const { setSetting } = require('../lib/settings')
7
  const { UPSERT_SQL, upsertParams, checkInvites } = require('../lib/mystery')
8
 
9
  const router = express.Router()
@@ -65,6 +65,74 @@ router.delete('/channels/:channel', requireKey, async (req, res) => {
65
  }
66
  })
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  router.post('/sync', requireKey, async (_req, res) => {
69
  try {
70
  const result = await telegram.sync({ upsert: UPSERT_SQL, upsertParams })
 
3
  const telegramUser = require('../lib/telegramUser')
4
  const notify = require('../lib/notify')
5
  const { requireKey } = require('../lib/auth')
6
+ const { setSetting, getJson } = require('../lib/settings')
7
  const { UPSERT_SQL, upsertParams, checkInvites } = require('../lib/mystery')
8
 
9
  const router = express.Router()
 
65
  }
66
  })
67
 
68
+ /** Force a fresh Telegram connection (used when the session gets stuck). */
69
+ router.post('/reconnect', requireKey, async (_req, res) => {
70
+ try {
71
+ const result = await telegram.reconnect()
72
+ res.json({ ok: true, ...result })
73
+ } catch (err) {
74
+ res.status(err.status || 500).json({ error: err.message })
75
+ }
76
+ })
77
+
78
+ /** Everything the account is a member of — used by the "scan my groups" panel. */
79
+ router.get('/dialogs', async (_req, res) => {
80
+ try {
81
+ const state = await telegram.status()
82
+ if (!state.loggedIn) {
83
+ return res.status(400).json({ error: '请先用手机号登录 Telegram 账号' })
84
+ }
85
+ const dialogs = await telegram.listDialogs()
86
+ const list = await getJson('telegram_channels', [])
87
+ const added = new Set()
88
+ for (const item of list) {
89
+ added.add(String(item.ref || item.username || item.id || ''))
90
+ if (item.id) added.add(String(item.id))
91
+ }
92
+ res.json({
93
+ ok: true,
94
+ dialogs: dialogs.map((item) => ({
95
+ ...item,
96
+ added: added.has(item.ref) || added.has(String(item.id)),
97
+ })),
98
+ })
99
+ } catch (err) {
100
+ res.status(err.status || 500).json({ error: err.message })
101
+ }
102
+ })
103
+
104
+ /** Search public Telegram groups/channels by keyword. */
105
+ router.get('/search', requireKey, async (req, res) => {
106
+ try {
107
+ const query = String(req.query.q || '').trim()
108
+ if (!query) return res.status(400).json({ error: '请输入搜索关键词' })
109
+ const state = await telegram.status()
110
+ if (!state.loggedIn) return res.status(400).json({ error: '请先用手机号登录 Telegram 账号' })
111
+ const found = await telegram.searchPublicChats(query, { limit: 20 })
112
+ const list = await getJson('telegram_channels', [])
113
+ const added = new Set()
114
+ for (const item of list) {
115
+ added.add(String(item.ref || item.username || item.id || ''))
116
+ if (item.id) added.add(String(item.id))
117
+ }
118
+ res.json({ ok: true, dialogs: found.map((item) => ({ ...item, added: added.has(item.ref) })) })
119
+ } catch (err) {
120
+ res.status(err.status || 500).json({ error: err.message })
121
+ }
122
+ })
123
+
124
+ /** Add the chats the user picked from that panel. */
125
+ router.post('/channels/import', requireKey, async (req, res) => {
126
+ try {
127
+ const items = Array.isArray(req.body?.channels) ? req.body.channels : []
128
+ if (items.length === 0) return res.status(400).json({ error: '没有选择要添加的群组' })
129
+ const result = await telegram.importChannels(items.slice(0, 200))
130
+ res.json({ ok: true, ...result })
131
+ } catch (err) {
132
+ res.status(err.status || 500).json({ error: err.message })
133
+ }
134
+ })
135
+
136
  router.post('/sync', requireKey, async (_req, res) => {
137
  try {
138
  const result = await telegram.sync({ upsert: UPSERT_SQL, upsertParams })