/** Community chat: persistent outbox, explicit retries, HTTP + WebSocket. */ import { useCallback, useEffect, useRef, useState } from 'react' import Taro, { useDidHide, useDidShow } from '@tarojs/taro' import { createSocialRequestId, getSocialGuestId, socialApi, type SocialChatAttachment, type SocialChatMessage, type SocialChatReplyTo, } from '@/services/socialApi' import { connectChatRealtime } from '@/services/socialRealtime' import { maxChatSeq, mergeChatMessages } from '@/services/socialChatState' import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal' import { getCachedRemoteConfig } from '@/services/remoteConfig' import { isSocialFeatureEnabled, resolveSocialOps } from '@/utils/socialOps' export type ChatLinkStatus = 'connecting' | 'live' | 'polling' | 'offline' export function useSocialChat(channelId: string) { const guest = getSocialGuestId() const outboxKey = `outbox_${guest}_${channelId}` const draftKey = `chat_draft_${channelId}` const [messages, setMessages] = useState([]) const [draft, setDraft] = useState(() => readSocialLocal(draftKey, '')) const [nick, setNick] = useState(() => { try { return String(Taro.getStorageSync('nick') || '游民') } catch { return '游民' } }) const [status, setStatus] = useState('connecting') const [sending, setSending] = useState(false) const [typingPeers, setTypingPeers] = useState([]) const [online, setOnline] = useState(0) const lock = useRef(false) const active = useRef(channelId) const mounted = useRef(false) const initializedKey = useRef('') const visible = useRef(true) const typingBeat = useRef(0) const typingClear = useRef | null>(null) const refreshRef = useRef<() => Promise>(async () => {}) active.current = channelId useDidHide(() => { visible.current = false }) useDidShow(() => { visible.current = true; void refreshRef.current() }) useEffect(() => { const timer = setTimeout(() => writeSocialLocal(draftKey, draft), 250) return () => clearTimeout(timer) }, [draft, draftKey]) useEffect(() => { if (!mounted.current || initializedKey.current !== outboxKey) return const pending = messages.filter((m) => m.mine && m.delivery !== 'sent').slice(-50) .map((m) => ({ ...m, delivery: 'local' as const })) writeSocialLocal(outboxKey, pending) }, [messages, outboxKey]) useEffect(() => { mounted.current = true let cancelled = false let stopWs: (() => void) | undefined let refreshing = false let realtime = false let failures = 0 let nextRefresh = 0 let lastSeq = 0 const refresh = async (mode: 'full' | 'since' = 'since') => { if (cancelled || refreshing || !visible.current) return refreshing = true try { const since = mode === 'since' && lastSeq > 0 ? lastSeq : undefined const response = await socialApi.listMessages(channelId, { limit: since ? 200 : 100, since, }) if (cancelled) return if (!Array.isArray(response.items)) throw new Error('消息格式异常') setMessages((current) => { const next = mergeChatMessages(current, response.items, guest) lastSeq = Math.max(lastSeq, maxChatSeq(next), Number(response.seq || 0)) return next }) if (lastSeq > 0) { void socialApi.postNote(channelId, 'read', lastSeq).catch(() => undefined) } failures = 0 nextRefresh = 0 setStatus(realtime ? 'live' : 'polling') } catch { failures++ nextRefresh = Date.now() + Math.min(60000, 8000 * 2 ** Math.min(failures, 3)) if (!cancelled) setStatus(realtime ? 'live' : 'offline') } finally { refreshing = false } } refreshRef.current = refresh const local = readSocialLocal(outboxKey, []) initializedKey.current = outboxKey setMessages(Array.isArray(local) ? local.filter((m) => m.channelId === channelId && m.guestId === guest).map((m) => ({ ...m, delivery: 'local' as const })) : []) setDraft(readSocialLocal(draftKey, '')) setSending(false) lock.current = false setStatus('connecting') const beatPresence = () => { void socialApi.presence(channelId, nick).then((info) => { if (!cancelled) setOnline(Number(info.online || 0)) }).catch(() => undefined) } void refresh('full') beatPresence() const timer = setInterval(() => { if (Date.now() >= nextRefresh) void refresh('since') }, 12000) const presenceTimer = setInterval(beatPresence, 20000) const realtimeOn = isSocialFeatureEnabled( resolveSocialOps(getCachedRemoteConfig()), 'chatRealtime', ) if (realtimeOn) { void connectChatRealtime( channelId, (item) => { if (cancelled) return setMessages((current) => { const next = mergeChatMessages(current, [item], guest) lastSeq = Math.max(lastSeq, maxChatSeq(next)) return next }) if (item.seq) { void socialApi.postNote(channelId, 'recv', item.seq).catch(() => undefined) } }, (connected) => { realtime = connected if (!cancelled) setStatus(connected ? 'live' : 'polling') }, (note) => { if (cancelled || note.guestId === guest) return if (note.what !== 'kp') return setTypingPeers((prev) => (prev.includes(note.guestId) ? prev : [...prev, note.guestId])) if (typingClear.current) clearTimeout(typingClear.current) typingClear.current = setTimeout(() => { setTypingPeers((prev) => prev.filter((id) => id !== note.guestId)) }, 2800) }, ).then((connection) => { if (cancelled) connection?.disconnect() else stopWs = connection?.disconnect }).catch(() => { if (!cancelled) setStatus('polling') }) } else if (!cancelled) { setStatus('polling') } return () => { cancelled = true mounted.current = false clearInterval(timer) clearInterval(presenceTimer) if (typingClear.current) clearTimeout(typingClear.current) stopWs?.() } }, [channelId, guest, nick, outboxKey, draftKey]) const mergeOne = useCallback((saved: SocialChatMessage) => { setMessages((current) => mergeChatMessages(current, [{ ...saved, guestId: saved.guestId || guest }], guest)) }, [guest]) const deliver = useCallback(async (item: SocialChatMessage) => { if (lock.current) return false lock.current = true setSending(true) setMessages((current) => current.map((m) => m.id === item.id ? { ...m, delivery: 'pending' as const } : m)) try { const saved = await socialApi.sendMessage(channelId, item.author, item.text, item.clientId, { replyTo: item.replyTo, attachments: item.attachments, mentions: item.mentions, }) if (!saved?.id) throw new Error('发送结果异常') const pending = readSocialLocal(outboxKey, []) if (Array.isArray(pending)) writeSocialLocal(outboxKey, pending.filter((message) => message.id !== item.id && (!item.clientId || message.clientId !== item.clientId))) if (!mounted.current || active.current !== channelId) return true setMessages((current) => { const next = mergeChatMessages(current.filter((m) => m.id !== item.id), [{ ...saved, guestId: guest, clientId: item.clientId }], guest) return next }) return true } catch { if (!mounted.current || active.current !== channelId) return false setMessages((current) => current.map((m) => m.id === item.id ? { ...m, delivery: 'local' as const } : m)) setStatus('offline') void Taro.showToast({ title: '消息已保留,点击重试发送', icon: 'none' }) return false } finally { if (active.current === channelId) { lock.current = false if (mounted.current) setSending(false) } } }, [channelId, guest, outboxKey]) const send = useCallback(async (opts?: { replyTo?: SocialChatReplyTo | null attachments?: SocialChatAttachment[] mentions?: string[] }) => { const text = draft.trim() const atts = opts?.attachments || [] if ((!text && !atts.length) || text.length > 2000 || lock.current) return false const clientId = createSocialRequestId() const mentions = opts?.mentions || Array.from(text.matchAll(/@([\w\u4e00-\u9fff-]{1,24})/g)).map((m) => m[1]) const item: SocialChatMessage = { id: `local_${clientId}`, clientId, channelId, author: nick.trim().slice(0, 24) || '游民', text, at: new Date().toISOString(), guestId: guest, mine: true, delivery: 'pending', replyTo: opts?.replyTo || undefined, attachments: atts.length ? atts : undefined, mentions: mentions.length ? mentions : undefined, } const existing = readSocialLocal(outboxKey, []) if (!writeSocialLocal(outboxKey, [...(Array.isArray(existing) ? existing : []), { ...item, delivery: 'local' }].slice(-50))) { void Taro.showToast({ title: '本地保存失败,请保留输入后重试', icon: 'none' }) return false } setMessages((current) => [...current, item].slice(-300)) setDraft('') writeSocialLocal(draftKey, '') try { Taro.setStorageSync('nick', item.author) } catch { /* optional */ } return deliver(item) }, [channelId, draft, draftKey, deliver, guest, nick, outboxKey]) const retryLocal = useCallback(async (id: string) => { const item = messages.find((m) => m.id === id && m.delivery === 'local') if (item) await deliver(item) }, [deliver, messages]) const editMessage = useCallback(async (msgId: string, text: string) => { try { mergeOne(await socialApi.editMessage(channelId, msgId, text)) return true } catch { void Taro.showToast({ title: '编辑失败', icon: 'none' }) return false } }, [channelId, mergeOne]) const recallMessage = useCallback(async (msgId: string) => { try { mergeOne(await socialApi.recallMessage(channelId, msgId)) return true } catch { void Taro.showToast({ title: '撤回失败', icon: 'none' }) return false } }, [channelId, mergeOne]) const reactMessage = useCallback(async (msgId: string, emoji: string) => { try { mergeOne(await socialApi.reactMessage(channelId, msgId, emoji)) return true } catch { return false } }, [channelId, mergeOne]) const pinMessage = useCallback(async (msgId: string, pinned = true) => { try { mergeOne(await socialApi.pinMessage(channelId, msgId, pinned)) return true } catch { return false } }, [channelId, mergeOne]) const upload = useCallback( (filePath: string, kind?: string, name?: string) => socialApi.upload(channelId, filePath, kind, name), [channelId], ) const reportMessage = useCallback(async (msgId: string, reason = '') => { try { await socialApi.reportMessage(channelId, msgId, reason) void Taro.showToast({ title: '已提交举报', icon: 'none' }) return true } catch { void Taro.showToast({ title: '举报失败', icon: 'none' }) return false } }, [channelId]) const notifyTyping = useCallback(() => { const now = Date.now() if (now - typingBeat.current < 1800) return typingBeat.current = now void socialApi.postNote(channelId, 'kp', 0).catch(() => undefined) }, [channelId]) return { messages, draft, setDraft, nick, setNick, status, sending, send, retryLocal, editMessage, recallMessage, reactMessage, pinMessage, reportMessage, upload, online, typingPeers, notifyTyping, refresh: () => refreshRef.current(), } }