Reduce noisy runtime logging in frontend flows.
This keeps chat, notification, and post interactions cleaner in production while preserving error-level visibility.
This commit is contained in:
5
App.tsx
5
App.tsx
@@ -55,7 +55,6 @@ export default function App() {
|
||||
// 初始化后台保活服务
|
||||
const { initBackgroundService } = await import('./src/services/backgroundService');
|
||||
await initBackgroundService();
|
||||
console.log('[App] 后台保活服务已初始化');
|
||||
|
||||
// 监听 App 状态变化
|
||||
const subscription = AppState.addEventListener('change', (nextAppState) => {
|
||||
@@ -72,14 +71,14 @@ export default function App() {
|
||||
notificationResponseListener.current = Notifications.addNotificationResponseReceivedListener(
|
||||
(response) => {
|
||||
const data = response.notification.request.content.data;
|
||||
console.log('[App] 通知被点击:', data);
|
||||
void data;
|
||||
}
|
||||
);
|
||||
|
||||
// 监听通知到达(用于前台显示时额外处理)
|
||||
const notificationReceivedSubscription = Notifications.addNotificationReceivedListener(
|
||||
(notification) => {
|
||||
console.log('[App] 通知已接收:', notification.request.content.title);
|
||||
void notification;
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -70,10 +70,6 @@ class PrefetchService {
|
||||
}
|
||||
this.queue.splice(insertIndex, 0, task);
|
||||
|
||||
if (this.DEBUG) {
|
||||
console.log(`[Prefetch] 添加任务: ${task.key}, 优先级: ${Priority[task.priority]}`);
|
||||
}
|
||||
|
||||
this.processQueue();
|
||||
}
|
||||
|
||||
@@ -106,13 +102,7 @@ class PrefetchService {
|
||||
*/
|
||||
private async executeTask(task: PrefetchTask): Promise<void> {
|
||||
try {
|
||||
if (this.DEBUG) {
|
||||
console.log(`[Prefetch] 执行任务: ${task.key}`);
|
||||
}
|
||||
await task.executor();
|
||||
if (this.DEBUG) {
|
||||
console.log(`[Prefetch] 任务完成: ${task.key}`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.DEBUG) {
|
||||
console.warn(`[Prefetch] 任务失败: ${task.key}`, error);
|
||||
@@ -230,10 +220,6 @@ function prefetchGroupMembers(groupIds: string[]): void {
|
||||
* 预取最关键的数据
|
||||
*/
|
||||
function prefetchOnAppLaunch(): void {
|
||||
if (__DEV__) {
|
||||
console.log('[Prefetch] 开始应用启动预取');
|
||||
}
|
||||
|
||||
// 高优先级:用户信息
|
||||
prefetchUserInfo();
|
||||
|
||||
|
||||
@@ -189,7 +189,6 @@ export const HomeScreen: React.FC = () => {
|
||||
setLoadingMore(true);
|
||||
}
|
||||
|
||||
console.log('[HomeScreen] loadPosts - activeIndex:', activeIndex, 'postType:', postType);
|
||||
const response = await fetchPosts(postType, pageNum);
|
||||
const newPosts = response.list || [];
|
||||
|
||||
@@ -359,7 +358,7 @@ export const HomeScreen: React.FC = () => {
|
||||
|
||||
// 分享帖子
|
||||
const handleShare = (post: Post) => {
|
||||
console.log('Share post:', post.id);
|
||||
void post;
|
||||
};
|
||||
|
||||
// 删除帖子
|
||||
|
||||
@@ -122,7 +122,6 @@ export const PostDetailScreen: React.FC = () => {
|
||||
try {
|
||||
// 从API获取帖子详情
|
||||
const postData = await postService.getPost(postId);
|
||||
console.log('[PostDetailScreen] postData:', JSON.stringify(postData, null, 2));
|
||||
if (postData) {
|
||||
setPost(postData);
|
||||
// 初始化关注状态
|
||||
@@ -141,11 +140,9 @@ export const PostDetailScreen: React.FC = () => {
|
||||
|
||||
// 如果是投票帖子,立即加载投票数据
|
||||
if (postData.is_vote) {
|
||||
console.log('[PostDetailScreen] is_vote is true, loading vote data...');
|
||||
setIsVoteLoading(true);
|
||||
try {
|
||||
const voteData = await voteService.getVoteResult(postId);
|
||||
console.log('[PostDetailScreen] voteData:', JSON.stringify(voteData, null, 2));
|
||||
if (voteData) {
|
||||
setVoteResult(voteData);
|
||||
}
|
||||
@@ -154,8 +151,6 @@ export const PostDetailScreen: React.FC = () => {
|
||||
} finally {
|
||||
setIsVoteLoading(false);
|
||||
}
|
||||
} else {
|
||||
console.log('[PostDetailScreen] is_vote is false or undefined:', postData.is_vote);
|
||||
}
|
||||
} else {
|
||||
// 如果API返回空,尝试从store中获取
|
||||
@@ -357,7 +352,7 @@ export const PostDetailScreen: React.FC = () => {
|
||||
// 分享帖子
|
||||
const handleShare = useCallback(() => {
|
||||
// TODO: 实现分享功能
|
||||
console.log('Share post:', post?.id);
|
||||
void post;
|
||||
}, [post?.id]);
|
||||
|
||||
// 投票处理函数
|
||||
|
||||
@@ -133,7 +133,7 @@ const GroupInfoScreen: React.FC = () => {
|
||||
const announcementsData = await groupService.getAnnouncements(groupId, 1, 10);
|
||||
setAnnouncements(announcementsData.list);
|
||||
} catch (e) {
|
||||
console.log('加载群公告失败:', e);
|
||||
console.error('加载群公告失败:', e);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载群组信息失败:', error);
|
||||
|
||||
@@ -190,7 +190,6 @@ export const MessageListScreen: React.FC = () => {
|
||||
// 【新架构】页面获得焦点时初始化MessageManager
|
||||
useEffect(() => {
|
||||
if (isFocused) {
|
||||
console.log('[MessageListScreen] 页面获得焦点,初始化MessageManager');
|
||||
messageManager.initialize();
|
||||
}
|
||||
}, [isFocused]);
|
||||
|
||||
@@ -312,14 +312,8 @@ export const MessageBubble: React.FC<MessageBubbleProps> = ({
|
||||
memberMap={memberMap}
|
||||
replyMessage={getReplyMessage()}
|
||||
getSenderInfo={getSenderInfo}
|
||||
onAtPress={(userId) => {
|
||||
// TODO: 跳转到用户资料页
|
||||
console.log('At pressed:', userId);
|
||||
}}
|
||||
onReplyPress={(messageId) => {
|
||||
// TODO: 滚动到被回复的消息
|
||||
console.log('Reply pressed:', messageId);
|
||||
}}
|
||||
onAtPress={() => undefined}
|
||||
onReplyPress={() => undefined}
|
||||
onImagePress={(url) => {
|
||||
// 查找点击的图片索引
|
||||
const clickIndex = imageSegments.findIndex(img => img.url === url);
|
||||
@@ -343,9 +337,7 @@ export const MessageBubble: React.FC<MessageBubbleProps> = ({
|
||||
handleLongPress();
|
||||
}
|
||||
}}
|
||||
onLinkPress={(url) => {
|
||||
console.log('Link pressed:', url);
|
||||
}}
|
||||
onLinkPress={() => undefined}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -270,7 +270,6 @@ export const useChatScreen = () => {
|
||||
shouldAutoScrollOnEnterRef.current = true;
|
||||
autoScrollTimersRef.current.forEach(clearTimeout);
|
||||
autoScrollTimersRef.current = [];
|
||||
console.log('[ChatScreen] 会话切换,重置状态');
|
||||
}, [conversationId]);
|
||||
|
||||
// 组件卸载时清理定时器
|
||||
@@ -389,8 +388,6 @@ export const useChatScreen = () => {
|
||||
|
||||
// 【改造】加载更多历史消息
|
||||
const loadMoreHistory = useCallback(async () => {
|
||||
console.log('[ChatScreen] 加载更多历史消息');
|
||||
|
||||
if (!conversationId || !hasMoreHistory || loadingMore) {
|
||||
return;
|
||||
}
|
||||
@@ -730,8 +727,6 @@ export const useChatScreen = () => {
|
||||
try {
|
||||
const segments = buildTextSegments(trimmedText, replyingTo);
|
||||
|
||||
console.log('[ChatScreen] handleSend - replyingTo:', replyingTo?.id, 'segments:', JSON.stringify(segments));
|
||||
|
||||
if (isGroupChat && routeGroupId) {
|
||||
// 群聊消息发送
|
||||
websocketService.sendGroupChatMessage({
|
||||
@@ -1041,7 +1036,6 @@ export const useChatScreen = () => {
|
||||
setFirstSeq(0);
|
||||
setHasMoreHistory(true);
|
||||
await clearConversationMessages(conversationId);
|
||||
console.log('[ChatScreen] 会话消息已清空:', conversationId);
|
||||
// 刷新消息列表
|
||||
await refreshMessages();
|
||||
} catch (error) {
|
||||
|
||||
@@ -91,9 +91,7 @@ export const ProfileScreen: React.FC = () => {
|
||||
const loadUserFavorites = useCallback(async () => {
|
||||
if (currentUser) {
|
||||
try {
|
||||
console.log('[ProfileScreen] load, userUserFavorites calledId:', currentUser.id);
|
||||
const response = await postService.getUserFavorites(currentUser.id);
|
||||
console.log('[ProfileScreen] getUserFavorites response:', response);
|
||||
setFavorites(response.list);
|
||||
} catch (error) {
|
||||
console.error('获取用户收藏失败:', error);
|
||||
|
||||
@@ -96,7 +96,7 @@ export const SettingsScreen: React.FC = () => {
|
||||
);
|
||||
break;
|
||||
default:
|
||||
console.log('Settings item pressed:', key);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -81,9 +81,7 @@ export const UserScreen: React.FC = () => {
|
||||
const loadUserFavorites = useCallback(async () => {
|
||||
if (!userId) return;
|
||||
try {
|
||||
console.log('[UserScreen] getUserFavorites called, userId:', userId);
|
||||
const response = await postService.getUserFavorites(userId);
|
||||
console.log('[UserScreen] getUserFavorites response:', response);
|
||||
setFavorites(response.list);
|
||||
} catch (error) {
|
||||
console.error('获取用户收藏失败:', error);
|
||||
|
||||
@@ -46,12 +46,9 @@ let appStateSubscription: any = null;
|
||||
|
||||
// 定义后台任务
|
||||
TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
|
||||
console.log('[BackgroundService] 后台任务执行中...');
|
||||
|
||||
try {
|
||||
// 检查 WebSocket 连接状态
|
||||
if (!websocketService.isConnected()) {
|
||||
console.log('[BackgroundService] WebSocket 断开,尝试重连');
|
||||
await websocketService.connect();
|
||||
}
|
||||
|
||||
@@ -65,11 +62,8 @@ TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
|
||||
|
||||
// WebSocket 保活任务
|
||||
TaskManager.defineTask(WEBSOCKET_KEEPALIVE_TASK, async () => {
|
||||
console.log('[BackgroundService] WebSocket 保活任务执行...');
|
||||
|
||||
try {
|
||||
if (!websocketService.isConnected()) {
|
||||
console.log('[BackgroundService] WebSocket 断开,尝试重连');
|
||||
await websocketService.connect();
|
||||
}
|
||||
return BackgroundFetch.BackgroundFetchResult.NewData;
|
||||
@@ -178,7 +172,6 @@ async function registerBackgroundTasks(): Promise<void> {
|
||||
stopOnTerminate: false, // App 终止后继续运行
|
||||
startOnBoot: true, // 设备启动后自动运行
|
||||
});
|
||||
console.log('[BackgroundService] 后台任务注册成功');
|
||||
}
|
||||
|
||||
// 注册 WebSocket 保活任务
|
||||
@@ -189,7 +182,6 @@ async function registerBackgroundTasks(): Promise<void> {
|
||||
stopOnTerminate: false,
|
||||
startOnBoot: true,
|
||||
});
|
||||
console.log('[BackgroundService] WebSocket 保活任务注册成功');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 注册后台任务失败:', error);
|
||||
@@ -203,7 +195,6 @@ async function unregisterBackgroundTasks(): Promise<void> {
|
||||
try {
|
||||
await BackgroundFetch.unregisterTaskAsync(BACKGROUND_FETCH_TASK);
|
||||
await BackgroundFetch.unregisterTaskAsync(WEBSOCKET_KEEPALIVE_TASK);
|
||||
console.log('[BackgroundService] 后台任务已取消');
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 取消后台任务失败:', error);
|
||||
}
|
||||
@@ -218,17 +209,12 @@ function setupAppStateListener(): void {
|
||||
}
|
||||
|
||||
appStateSubscription = AppState.addEventListener('change', (nextAppState: AppStateStatus) => {
|
||||
console.log('[BackgroundService] App 状态变化:', nextAppState);
|
||||
|
||||
void nextAppState;
|
||||
if (nextAppState === 'active') {
|
||||
// App 回到前台,确保连接
|
||||
console.log('[BackgroundService] App 回到前台');
|
||||
if (!websocketService.isConnected()) {
|
||||
websocketService.connect();
|
||||
}
|
||||
} else if (nextAppState === 'background') {
|
||||
// App 进入后台,启动保活
|
||||
console.log('[BackgroundService] App 进入后台,启动保活机制');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -238,13 +224,10 @@ function setupAppStateListener(): void {
|
||||
*/
|
||||
export async function initBackgroundService(): Promise<boolean> {
|
||||
if (isInitialized) {
|
||||
console.log('[BackgroundService] 服务已初始化');
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('[BackgroundService] 初始化后台保活服务...');
|
||||
|
||||
// 检查后台任务状态
|
||||
const status = await BackgroundFetch.getStatusAsync();
|
||||
if (status !== BackgroundFetch.BackgroundFetchStatus.Available) {
|
||||
@@ -259,7 +242,6 @@ export async function initBackgroundService(): Promise<boolean> {
|
||||
setupAppStateListener();
|
||||
|
||||
isInitialized = true;
|
||||
console.log('[BackgroundService] 后台保活服务初始化完成');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 初始化失败:', error);
|
||||
@@ -280,7 +262,6 @@ export async function stopBackgroundService(): Promise<void> {
|
||||
}
|
||||
|
||||
isInitialized = false;
|
||||
console.log('[BackgroundService] 后台保活服务已停止');
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 停止服务失败:', error);
|
||||
}
|
||||
|
||||
@@ -35,19 +35,16 @@ export const initDatabase = async (userId?: string): Promise<void> => {
|
||||
|
||||
// 如果存在旧的数据库连接且用户ID变化,需要关闭旧连接
|
||||
if (db && currentDbUserId !== userId) {
|
||||
console.log(`[Database] 切换用户数据库: ${currentDbUserId} -> ${userId}`);
|
||||
await closeDatabase();
|
||||
}
|
||||
|
||||
// 如果已经打开了正确的数据库,直接返回
|
||||
if (db && currentDbUserId === userId) {
|
||||
console.log(`[Database] 数据库已初始化: ${dbName}`);
|
||||
return;
|
||||
}
|
||||
|
||||
db = await SQLite.openDatabaseAsync(dbName);
|
||||
currentDbUserId = userId || null;
|
||||
console.log(`[Database] 打开数据库: ${dbName}`);
|
||||
|
||||
// 创建消息表(包含新字段 seq, status, segments)
|
||||
await db.execAsync(`
|
||||
@@ -153,7 +150,6 @@ export const initDatabase = async (userId?: string): Promise<void> => {
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_conversation_seq ON messages(conversationId, seq);
|
||||
`);
|
||||
|
||||
console.log('数据库初始化成功');
|
||||
} catch (error) {
|
||||
console.error('数据库初始化失败:', error);
|
||||
throw error;
|
||||
@@ -167,7 +163,6 @@ export const closeDatabase = async (): Promise<void> => {
|
||||
if (db) {
|
||||
try {
|
||||
await db.closeAsync();
|
||||
console.log('[Database] 数据库连接已关闭');
|
||||
} catch (error) {
|
||||
console.error('[Database] 关闭数据库失败:', error);
|
||||
}
|
||||
@@ -198,19 +193,16 @@ const migrateDatabase = async (): Promise<void> => {
|
||||
// 添加 seq 列
|
||||
if (!columns.includes('seq')) {
|
||||
await database.execAsync(`ALTER TABLE messages ADD COLUMN seq INTEGER DEFAULT 0`);
|
||||
console.log('数据库迁移:添加 seq 列');
|
||||
}
|
||||
|
||||
// 添加 status 列
|
||||
if (!columns.includes('status')) {
|
||||
await database.execAsync(`ALTER TABLE messages ADD COLUMN status TEXT DEFAULT 'normal'`);
|
||||
console.log('数据库迁移:添加 status 列');
|
||||
}
|
||||
|
||||
// 添加 segments 列(用于存储消息的 segments JSON)
|
||||
if (!columns.includes('segments')) {
|
||||
await database.execAsync(`ALTER TABLE messages ADD COLUMN segments TEXT`);
|
||||
console.log('数据库迁移:添加 segments 列');
|
||||
}
|
||||
|
||||
// 检查 conversations 表是否有 lastSeq 列
|
||||
@@ -221,7 +213,6 @@ const migrateDatabase = async (): Promise<void> => {
|
||||
|
||||
if (!convColumns.includes('lastSeq')) {
|
||||
await database.execAsync(`ALTER TABLE conversations ADD COLUMN lastSeq INTEGER DEFAULT 0`);
|
||||
console.log('数据库迁移:添加 lastSeq 列');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('数据库迁移失败:', error);
|
||||
|
||||
@@ -130,11 +130,8 @@ class PostService {
|
||||
// 点赞帖子
|
||||
async likePost(postId: string): Promise<Post | null> {
|
||||
try {
|
||||
console.log('[postService] likePost called, postId:', postId);
|
||||
const response = await api.post<Post>(`/posts/${postId}/like`);
|
||||
console.log('[postService] likePost response:', response);
|
||||
if (response.code === 0) {
|
||||
console.log('[postService] likePost success, data:', response.data);
|
||||
return response.data;
|
||||
}
|
||||
console.warn('[postService] likePost failed, code:', response.code);
|
||||
@@ -148,11 +145,8 @@ class PostService {
|
||||
// 取消点赞帖子
|
||||
async unlikePost(postId: string): Promise<Post | null> {
|
||||
try {
|
||||
console.log('[postService] unlikePost called, postId:', postId);
|
||||
const response = await api.delete<Post>(`/posts/${postId}/like`);
|
||||
console.log('[postService] unlikePost response:', response);
|
||||
if (response.code === 0) {
|
||||
console.log('[postService] unlikePost success, data:', response.data);
|
||||
return response.data;
|
||||
}
|
||||
console.warn('[postService] unlikePost failed, code:', response.code);
|
||||
@@ -166,11 +160,8 @@ class PostService {
|
||||
// 收藏帖子
|
||||
async favoritePost(postId: string): Promise<Post | null> {
|
||||
try {
|
||||
console.log('[postService] favoritePost called, postId:', postId);
|
||||
const response = await api.post<Post>(`/posts/${postId}/favorite`);
|
||||
console.log('[postService] favoritePost response:', response);
|
||||
if (response.code === 0) {
|
||||
console.log('[postService] favoritePost success, data:', response.data);
|
||||
return response.data;
|
||||
}
|
||||
console.warn('[postService] favoritePost failed, code:', response.code);
|
||||
@@ -184,11 +175,8 @@ class PostService {
|
||||
// 取消收藏帖子
|
||||
async unfavoritePost(postId: string): Promise<Post | null> {
|
||||
try {
|
||||
console.log('[postService] unfavoritePost called, postId:', postId);
|
||||
const response = await api.delete<Post>(`/posts/${postId}/favorite`);
|
||||
console.log('[postService] unfavoritePost response:', response);
|
||||
if (response.code === 0) {
|
||||
console.log('[postService] unfavoritePost success, data:', response.data);
|
||||
return response.data;
|
||||
}
|
||||
console.warn('[postService] unfavoritePost failed, code:', response.code);
|
||||
|
||||
@@ -73,7 +73,6 @@ export const addStickerFromUrl = async (
|
||||
return response.data.sticker;
|
||||
} catch (error: any) {
|
||||
if (error.response?.status === 409) {
|
||||
console.log('表情已存在');
|
||||
return null;
|
||||
}
|
||||
console.error('添加自定义表情失败:', error);
|
||||
|
||||
@@ -68,7 +68,6 @@ class SystemNotificationService {
|
||||
}
|
||||
|
||||
if (finalStatus !== 'granted') {
|
||||
console.log('[SystemNotification] 通知权限未授权');
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -100,7 +99,6 @@ class SystemNotificationService {
|
||||
});
|
||||
|
||||
this.isInitialized = true;
|
||||
console.log('[SystemNotification] 通知服务初始化成功');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('[SystemNotification] 初始化失败:', error);
|
||||
@@ -138,7 +136,6 @@ class SystemNotificationService {
|
||||
trigger: null, // null 表示立即显示
|
||||
});
|
||||
|
||||
console.log('[SystemNotification] 通知已显示:', notificationId);
|
||||
return notificationId;
|
||||
} catch (error) {
|
||||
console.error('[SystemNotification] 显示通知失败:', error);
|
||||
@@ -182,23 +179,20 @@ class SystemNotificationService {
|
||||
}
|
||||
|
||||
async handleWSMessage(message: WSChatMessage | WSNotificationMessage | WSAnnouncementMessage): Promise<void> {
|
||||
console.log('[SystemNotification] handleWSMessage 被调用, 当前AppState:', this.currentAppState);
|
||||
|
||||
// 仅在后台时显示通知,前台时不显示(用户正在使用应用,可以直接看到消息)
|
||||
if (this.currentAppState !== 'active') {
|
||||
// 判断是否是聊天消息(通过 segments 字段)
|
||||
if ('segments' in message) {
|
||||
const chatMsg = message as WSChatMessage;
|
||||
const body = extractTextFromSegments(chatMsg.segments);
|
||||
console.log('[SystemNotification] 后台模式 - 显示聊天通知:', chatMsg.id, body);
|
||||
void chatMsg;
|
||||
void body;
|
||||
await this.showChatNotification(chatMsg);
|
||||
} else {
|
||||
const notifMsg = message as WSNotificationMessage | WSAnnouncementMessage;
|
||||
console.log('[SystemNotification] 后台模式 - 显示系统通知:', notifMsg.id, notifMsg.content);
|
||||
void notifMsg;
|
||||
await this.showWSNotification(notifMsg);
|
||||
}
|
||||
} else {
|
||||
console.log('[SystemNotification] 前台模式 - 不显示通知');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -293,7 +293,6 @@ class WebSocketService {
|
||||
// 连接 WebSocket
|
||||
async connect(): Promise<boolean> {
|
||||
if (this.socket?.readyState === WebSocket.OPEN || this.isConnecting) {
|
||||
console.log('WebSocket 已经在连接中或已连接');
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -317,7 +316,6 @@ class WebSocketService {
|
||||
|
||||
// 设置事件处理器
|
||||
this.socket.onopen = () => {
|
||||
console.log('WebSocket 连接成功');
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
this.startHeartbeat();
|
||||
@@ -336,12 +334,10 @@ class WebSocketService {
|
||||
this.socket.onerror = () => {
|
||||
// 静默处理错误,不打印完整错误对象
|
||||
// WebSocket 错误通常会在 onclose 中处理,这里只标记状态
|
||||
console.log('[WebSocket] 连接出现错误,将在 onclose 中处理重连');
|
||||
this.isConnecting = false;
|
||||
};
|
||||
|
||||
this.socket.onclose = (event) => {
|
||||
console.log('[WebSocket] 连接关闭, code:', event.code, 'reason:', event.reason || '未知');
|
||||
this.isConnecting = false;
|
||||
this.stopHeartbeat();
|
||||
|
||||
@@ -425,7 +421,6 @@ class WebSocketService {
|
||||
},
|
||||
};
|
||||
this.socket.send(JSON.stringify(payload));
|
||||
console.log('[WebSocket] 发送消息 (新格式):', JSON.stringify(payload));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('发送 WebSocket 消息失败:', error);
|
||||
@@ -464,7 +459,6 @@ class WebSocketService {
|
||||
private handleMessage(rawMessage: any): void {
|
||||
// 忽略心跳消息的日志,减少噪音
|
||||
if (rawMessage.type !== 'ping' && rawMessage.type !== 'pong') {
|
||||
console.log('[WebSocket] 收到消息:', JSON.stringify(rawMessage));
|
||||
}
|
||||
|
||||
// 处理心跳消息 - 不需要特殊处理,只需不报错
|
||||
@@ -475,17 +469,14 @@ private handleMessage(rawMessage: any): void {
|
||||
// 统一处理所有消息类型:后端发送格式为 { type, data },需要提取 data 字段
|
||||
let message = rawMessage;
|
||||
if (rawMessage.data) {
|
||||
console.log('[WebSocket] 提取 data 字段, type:', rawMessage.type);
|
||||
message = {
|
||||
type: rawMessage.type,
|
||||
...rawMessage.data, // 将 data 的内容展开到顶层
|
||||
};
|
||||
console.log('[WebSocket] 转换后的消息:', JSON.stringify(message));
|
||||
}
|
||||
|
||||
// 检测新事件格式:通过 detail_type 字段判断
|
||||
if (message.detail_type && (message.type === 'message' || message.type === 'notice' || message.type === 'request' || message.type === 'meta')) {
|
||||
console.log('[WebSocket] 检测到新事件格式, type:', message.type, 'detail_type:', message.detail_type);
|
||||
this.handleNewEventFormat(message);
|
||||
return;
|
||||
}
|
||||
@@ -496,11 +487,8 @@ private handleMessage(rawMessage: any): void {
|
||||
// 如果有 group_id,说明这是后端同时发送的群聊消息旧格式帧,忽略它
|
||||
// 群聊消息会通过另一帧 type:'group_message' 到达,那里有完整的 sender_id
|
||||
if (message.group_id) {
|
||||
console.log('[WebSocket] 忽略群聊消息的 message 格式帧,等待 group_message 帧:', message.id);
|
||||
return;
|
||||
}
|
||||
console.log('[WebSocket] 收到 message 类型消息');
|
||||
console.log('[WebSocket] 原始消息:', JSON.stringify(message));
|
||||
|
||||
// 解析 segments(只支持 segments 字段)
|
||||
let segments = message.segments;
|
||||
@@ -512,7 +500,6 @@ private handleMessage(rawMessage: any): void {
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[WebSocket] segments:', JSON.stringify(segments));
|
||||
|
||||
// 转换为前端 WSChatMessage 格式
|
||||
const chatMessage: WSChatMessage = {
|
||||
@@ -528,7 +515,6 @@ private handleMessage(rawMessage: any): void {
|
||||
// 调用 chat 类型的处理器
|
||||
const handlers = this.messageHandlers.get('chat');
|
||||
if (handlers) {
|
||||
console.log('[WebSocket] 转换 message -> chat, 处理器数量:', handlers.length);
|
||||
handlers.forEach(handler => handler(chatMessage));
|
||||
}
|
||||
|
||||
@@ -538,7 +524,6 @@ private handleMessage(rawMessage: any): void {
|
||||
});
|
||||
|
||||
// 收到聊天消息时也调用系统通知服务
|
||||
console.log('[WebSocket] 收到聊天消息,调用系统通知服务');
|
||||
systemNotificationService.handleWSMessage(chatMessage).catch(err => {
|
||||
console.error('[WebSocket] 聊天消息通知显示失败:', err);
|
||||
});
|
||||
@@ -548,7 +533,6 @@ private handleMessage(rawMessage: any): void {
|
||||
|
||||
// 处理 "read" 已读回执消息 - 转换格式后路由到处理器
|
||||
if (message.type === 'read') {
|
||||
console.log('[WebSocket] 收到 read 类型消息');
|
||||
const readHandlers = this.messageHandlers.get('read');
|
||||
if (readHandlers) {
|
||||
// 转换为前端期望的格式(保持string类型)
|
||||
@@ -559,7 +543,6 @@ private handleMessage(rawMessage: any): void {
|
||||
user_id: message.user_id || message.userId,
|
||||
seq: typeof message.seq === 'string' ? parseInt(message.seq, 10) : message.seq,
|
||||
};
|
||||
console.log('[WebSocket] 转换 read 消息, handlers数量:', readHandlers.length);
|
||||
readHandlers.forEach(handler => handler(readMessage));
|
||||
}
|
||||
return;
|
||||
@@ -573,7 +556,6 @@ private handleMessage(rawMessage: any): void {
|
||||
try {
|
||||
const parsedSegments = JSON.parse(message.segments);
|
||||
processedMessage = { ...message, segments: parsedSegments };
|
||||
console.log('[WebSocket] 解析 group_message segments 成功:', JSON.stringify(parsedSegments));
|
||||
} catch (e) {
|
||||
console.error('[WebSocket] 解析 group_message segments 失败:', e);
|
||||
}
|
||||
@@ -581,26 +563,21 @@ private handleMessage(rawMessage: any): void {
|
||||
|
||||
const handlers = this.messageHandlers.get(message.type);
|
||||
if (handlers) {
|
||||
console.log('[WebSocket] 找到处理器,数量:', handlers.length, '类型:', message.type);
|
||||
// 针对群聊消息和群通知添加详细日志
|
||||
if (message.type === 'group_message') {
|
||||
console.log('[WebSocket] 群聊消息详情:', JSON.stringify(processedMessage, null, 2));
|
||||
// 收到群聊消息时触发震动
|
||||
vibrateOnMessage('group_message').catch(err => {
|
||||
console.error('[WebSocket] 群聊消息震动反馈失败:', err);
|
||||
});
|
||||
}
|
||||
if (message.type === 'group_notice') {
|
||||
console.log('[WebSocket] 群通知详情:', JSON.stringify(message, null, 2));
|
||||
}
|
||||
handlers.forEach(handler => handler(processedMessage));
|
||||
} else {
|
||||
console.log('[WebSocket] 未找到处理器,类型:', message.type, '可用类型:', Array.from(this.messageHandlers.keys()));
|
||||
}
|
||||
|
||||
// 处理通知和公告消息时调用系统通知服务
|
||||
if (message.type === 'notification' || message.type === 'announcement') {
|
||||
console.log('[WebSocket] 收到通知/公告消息,调用系统通知服务');
|
||||
// 收到通知时触发震动
|
||||
vibrateOnMessage('notification').catch(err => {
|
||||
console.error('[WebSocket] 通知震动反馈失败:', err);
|
||||
@@ -615,7 +592,6 @@ private handleMessage(rawMessage: any): void {
|
||||
private handleNewEventFormat(message: any): void {
|
||||
const { type, detail_type, id, time, seq, message: segments, conversation_id, user_id } = message;
|
||||
|
||||
console.log('[WebSocket] 处理新事件格式:', { type, detail_type, id, time, seq, conversation_id, user_id });
|
||||
|
||||
// 根据 type 和 detail_type 路由消息
|
||||
switch (type) {
|
||||
@@ -642,7 +618,6 @@ private handleNewEventFormat(message: any): void {
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('[WebSocket] 未知事件类型:', type);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,7 +645,6 @@ private handleNewMessageEvent(message: any): void {
|
||||
|
||||
const groupHandlers = this.messageHandlers.get('group_message');
|
||||
if (groupHandlers) {
|
||||
console.log('[WebSocket] 新格式群聊消息事件, 处理器数量:', groupHandlers.length);
|
||||
groupHandlers.forEach(handler => handler(groupChatMessage));
|
||||
}
|
||||
|
||||
@@ -695,7 +669,6 @@ private handleNewMessageEvent(message: any): void {
|
||||
|
||||
const chatHandlers = this.messageHandlers.get('chat');
|
||||
if (chatHandlers) {
|
||||
console.log('[WebSocket] 新格式私聊消息事件, 处理器数量:', chatHandlers.length);
|
||||
chatHandlers.forEach(handler => handler(chatMessage));
|
||||
}
|
||||
|
||||
@@ -713,7 +686,6 @@ private handleNewMessageEvent(message: any): void {
|
||||
private handleNewNoticeEvent(message: any): void {
|
||||
const { detail_type, id, time, user_id, message: segments } = message;
|
||||
|
||||
console.log('[WebSocket] 收到新格式通知事件, detail_type:', detail_type, 'user_id:', user_id);
|
||||
|
||||
// 调用 notice 类型的处理器
|
||||
const handlers = this.messageHandlers.get('notice');
|
||||
@@ -734,7 +706,6 @@ private handleNewNoticeEvent(message: any): void {
|
||||
private handleNewRequestEvent(message: any): void {
|
||||
const { detail_type, id, time, user_id, message: segments } = message;
|
||||
|
||||
console.log('[WebSocket] 收到新格式请求事件, detail_type:', detail_type, 'user_id:', user_id);
|
||||
|
||||
// 调用 request 类型的处理器
|
||||
const handlers = this.messageHandlers.get('request');
|
||||
@@ -755,12 +726,10 @@ private handleNewRequestEvent(message: any): void {
|
||||
private handleNewMetaEvent(message: any): void {
|
||||
const { detail_type, id, time, conversation_id, user_id, seq } = message;
|
||||
|
||||
console.log('[WebSocket] 收到新格式元事件, detail_type:', detail_type);
|
||||
|
||||
switch (detail_type) {
|
||||
case 'heartbeat':
|
||||
// 心跳事件,不需要特殊处理
|
||||
console.log('[WebSocket] 收到心跳');
|
||||
break;
|
||||
|
||||
case 'typing':
|
||||
@@ -793,8 +762,6 @@ private handleNewMetaEvent(message: any): void {
|
||||
|
||||
case 'ack':
|
||||
// 消息发送确认事件 - 转换为对应消息格式并路由到处理器
|
||||
console.log('[WebSocket][DEBUG] 收到 ack 确认消息, 完整消息:', JSON.stringify(message));
|
||||
console.log('[WebSocket][DEBUG] ack 消息字段: id=', message.id, 'group_id=', message.group_id, 'conversation_id=', message.conversation_id, 'sender_id=', message.sender_id, 'seq=', message.seq, 'segments=', message.segments);
|
||||
|
||||
// 【重要】ACK消息是发送确认,不应该增加未读数
|
||||
// 在转换为消息格式时,添加标记以便MessageManager识别
|
||||
@@ -813,7 +780,6 @@ private handleNewMetaEvent(message: any): void {
|
||||
if (message.group_id) {
|
||||
// 群聊消息确认 - 转换为群聊消息格式
|
||||
const ackHandlers = this.messageHandlers.get('group_message');
|
||||
console.log('[WebSocket][DEBUG] 群聊 ack 处理器数量:', ackHandlers?.length || 0);
|
||||
if (ackHandlers) {
|
||||
const ackAsGroupMessage: WSGroupChatMessage & { _isAck?: boolean } = {
|
||||
type: 'group_message',
|
||||
@@ -826,17 +792,11 @@ private handleNewMetaEvent(message: any): void {
|
||||
created_at: message.created_at ? new Date(message.created_at).toISOString() : new Date().toISOString(),
|
||||
_isAck: true, // 标记这是ACK消息
|
||||
};
|
||||
console.log('[WebSocket][DEBUG] 转换 ack -> group_message:', {
|
||||
id: message.id,
|
||||
sender_id: message.sender_id,
|
||||
_isAck: true
|
||||
});
|
||||
ackHandlers.forEach(handler => handler(ackAsGroupMessage));
|
||||
}
|
||||
} else if (message.conversation_id) {
|
||||
// 私聊消息确认 - 转换为私聊消息格式
|
||||
const chatHandlers = this.messageHandlers.get('chat');
|
||||
console.log('[WebSocket][DEBUG] 私聊 ack 处理器数量:', chatHandlers?.length || 0);
|
||||
if (chatHandlers) {
|
||||
const ackAsChatMessage: WSChatMessage & { _isAck?: boolean } = {
|
||||
type: 'chat',
|
||||
@@ -848,20 +808,13 @@ private handleNewMetaEvent(message: any): void {
|
||||
created_at: message.created_at ? new Date(message.created_at).toISOString() : new Date().toISOString(),
|
||||
_isAck: true, // 标记这是ACK消息
|
||||
};
|
||||
console.log('[WebSocket][DEBUG] 转换 ack -> chat:', {
|
||||
id: message.id,
|
||||
sender_id: message.user_id || message.sender_id,
|
||||
_isAck: true
|
||||
});
|
||||
chatHandlers.forEach(handler => handler(ackAsChatMessage));
|
||||
}
|
||||
} else {
|
||||
console.log('[WebSocket][DEBUG] 跳过 ack 处理: 缺少 group_id 和 conversation_id');
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('[WebSocket] 未知 meta 详细类型:', detail_type);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1059,7 +1012,6 @@ private extractTextFromSegments(segments?: any[]): string {
|
||||
this.stopReconnect();
|
||||
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
console.log(`WebSocket 正在重连 (${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`);
|
||||
this.reconnectAttempts++;
|
||||
this.connect();
|
||||
}, this.reconnectDelay);
|
||||
@@ -1108,9 +1060,7 @@ private extractTextFromSegments(segments?: any[]): string {
|
||||
this.lastAppState.match(/inactive|background/) &&
|
||||
nextAppState === 'active'
|
||||
) {
|
||||
console.log('[WebSocket] App 从后台恢复,检查连接状态');
|
||||
if (!this.isConnected()) {
|
||||
console.log('[WebSocket] 连接已断开,尝试重连');
|
||||
// 重置重连计数,允许重新开始重连
|
||||
this.reconnectAttempts = 0;
|
||||
this.connect();
|
||||
|
||||
@@ -95,7 +95,6 @@ function resolveLoginError(error: any): string {
|
||||
async function startWebSocket(): Promise<void> {
|
||||
try {
|
||||
await websocketService.start();
|
||||
console.log('[AuthStore] WebSocket 服务启动成功');
|
||||
} catch (error) {
|
||||
console.error('[AuthStore] 启动 WebSocket 服务失败:', error);
|
||||
}
|
||||
|
||||
@@ -250,7 +250,6 @@ class MessageManager {
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
if (this.state.isInitialized) {
|
||||
console.log('[MessageManager] 已经初始化,跳过');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -259,7 +258,6 @@ class MessageManager {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[MessageManager] 开始初始化');
|
||||
|
||||
this.initializePromise = (async () => {
|
||||
try {
|
||||
@@ -280,7 +278,6 @@ class MessageManager {
|
||||
await this.fetchUnreadCount();
|
||||
|
||||
this.state.isInitialized = true;
|
||||
console.log('[MessageManager] 初始化完成');
|
||||
|
||||
this.notifySubscribers({
|
||||
type: 'conversations_updated',
|
||||
@@ -310,7 +307,6 @@ class MessageManager {
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
console.log('[MessageManager] 销毁资源');
|
||||
if (this.wsUnsubscribe) {
|
||||
this.wsUnsubscribe();
|
||||
this.wsUnsubscribe = null;
|
||||
@@ -328,41 +324,34 @@ class MessageManager {
|
||||
this.wsUnsubscribe();
|
||||
}
|
||||
|
||||
console.log('[MessageManager] 初始化WebSocket监听');
|
||||
|
||||
// 监听私聊消息
|
||||
websocketService.on('chat', (message: WSChatMessage) => {
|
||||
console.log('[MessageManager] 收到私聊消息:', message.id);
|
||||
this.handleNewMessage(message);
|
||||
});
|
||||
|
||||
// 监听群聊消息
|
||||
websocketService.on('group_message', (message: WSGroupChatMessage) => {
|
||||
console.log('[MessageManager] 收到群聊消息:', message.id);
|
||||
this.handleNewMessage(message);
|
||||
});
|
||||
|
||||
// 监听私聊已读回执
|
||||
websocketService.on('read', (message: WSReadMessage) => {
|
||||
console.log('[MessageManager] 收到已读回执:', message);
|
||||
this.handleReadReceipt(message);
|
||||
});
|
||||
|
||||
// 监听群聊已读回执
|
||||
websocketService.on('group_read', (message: WSGroupReadMessage) => {
|
||||
console.log('[MessageManager] 收到群聊已读回执:', message);
|
||||
this.handleGroupReadReceipt(message);
|
||||
});
|
||||
|
||||
// 监听私聊消息撤回
|
||||
websocketService.on('recall', (message: WSRecallMessage) => {
|
||||
console.log('[MessageManager] 收到私聊撤回:', message);
|
||||
this.handleRecallMessage(message);
|
||||
});
|
||||
|
||||
// 监听群聊消息撤回
|
||||
websocketService.on('group_recall', (message: WSGroupRecallMessage) => {
|
||||
console.log('[MessageManager] 收到群聊撤回:', message);
|
||||
this.handleGroupRecallMessage(message);
|
||||
});
|
||||
|
||||
@@ -373,13 +362,11 @@ class MessageManager {
|
||||
|
||||
// 监听群通知
|
||||
websocketService.on('group_notice', (message: WSGroupNoticeMessage) => {
|
||||
console.log('[MessageManager] 收到群通知:', message);
|
||||
this.handleGroupNotice(message);
|
||||
});
|
||||
|
||||
// 监听连接状态
|
||||
websocketService.onConnect(() => {
|
||||
console.log('[MessageManager] WebSocket已连接');
|
||||
this.state.isWebSocketConnected = true;
|
||||
this.notifySubscribers({
|
||||
type: 'connection_changed',
|
||||
@@ -403,7 +390,6 @@ class MessageManager {
|
||||
});
|
||||
|
||||
websocketService.onDisconnect(() => {
|
||||
console.log('[MessageManager] WebSocket已断开');
|
||||
this.state.isWebSocketConnected = false;
|
||||
this.notifySubscribers({
|
||||
type: 'connection_changed',
|
||||
@@ -595,29 +581,15 @@ class MessageManager {
|
||||
const currentUserId = this.getCurrentUserId();
|
||||
|
||||
// 【调试日志】追踪消息来源和重复问题
|
||||
console.log('[MessageManager][DEBUG] 处理新消息:', {
|
||||
messageId: id,
|
||||
conversationId: normalizedConversationId,
|
||||
senderId: sender_id,
|
||||
seq,
|
||||
currentUserId,
|
||||
messageType: message.type,
|
||||
isAck: _isAck,
|
||||
currentConversationId: this.state.currentConversationId,
|
||||
isActiveConversation: normalizedConversationId === this.state.currentConversationId,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 0. 如果是ACK消息,直接跳过不增加未读数(ACK是发送确认,不是新消息)
|
||||
if (_isAck) {
|
||||
console.log('[MessageManager][DEBUG] ACK消息,跳过未读数处理:', id);
|
||||
// 但仍然需要更新消息列表(因为ACK包含完整消息内容)
|
||||
// 继续处理但不增加未读数
|
||||
}
|
||||
|
||||
// 1. 消息去重检查 - 防止ACK消息和正常消息重复处理
|
||||
if (this.isMessageProcessed(id)) {
|
||||
console.log('[MessageManager][DEBUG] 消息已处理,跳过:', id);
|
||||
return;
|
||||
}
|
||||
this.markMessageAsProcessed(id);
|
||||
@@ -627,7 +599,6 @@ class MessageManager {
|
||||
// 异步获取发送者信息,不阻塞消息显示
|
||||
this.getSenderInfo(sender_id).then(user => {
|
||||
if (user) {
|
||||
console.log('[MessageManager][DEBUG] 获取到发送者信息:', { userId: sender_id, nickname: user.nickname });
|
||||
// 更新消息对象中的发送者信息
|
||||
const messages = this.state.messagesMap.get(normalizedConversationId);
|
||||
if (messages) {
|
||||
@@ -636,7 +607,6 @@ class MessageManager {
|
||||
m.id === id ? { ...m, sender: user } : m
|
||||
);
|
||||
this.state.messagesMap.set(normalizedConversationId, updatedMessages);
|
||||
console.log('[MessageManager][DEBUG] 更新消息发送者信息:', { messageId: id, sender: user.nickname });
|
||||
// 通知订阅者消息已更新
|
||||
this.notifySubscribers({
|
||||
type: 'messages_updated',
|
||||
@@ -648,10 +618,9 @@ class MessageManager {
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.log('[MessageManager][DEBUG] 未能获取到发送者信息:', { userId: sender_id });
|
||||
}
|
||||
}).catch(error => {
|
||||
console.error('[MessageManager][DEBUG] 获取发送者信息失败:', { userId: sender_id, error });
|
||||
console.error('[MessageManager][ERROR] 获取发送者信息失败:', { userId: sender_id, error });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -694,15 +663,6 @@ class MessageManager {
|
||||
const isActiveConversation = normalizedConversationId === this.state.currentConversationId;
|
||||
|
||||
// 【调试日志】追踪未读数增加逻辑
|
||||
console.log('[MessageManager][DEBUG] 未读数判断:', {
|
||||
messageId: id,
|
||||
sender_id,
|
||||
currentUserId,
|
||||
isCurrentUserMessage,
|
||||
isActiveConversation,
|
||||
currentConversationId: this.state.currentConversationId,
|
||||
shouldIncrement: !isCurrentUserMessage && !isActiveConversation,
|
||||
});
|
||||
|
||||
// 修复:确保当前用户发送的消息不会增加未读数
|
||||
// 同时确保currentUserId有效(避免undefined === undefined的情况)
|
||||
@@ -710,15 +670,8 @@ class MessageManager {
|
||||
const shouldIncrementUnread = !isCurrentUserMessage && !isActiveConversation && !!currentUserId && !_isAck;
|
||||
|
||||
if (shouldIncrementUnread) {
|
||||
console.log('[MessageManager][DEBUG] 增加未读数:', { conversationId: conversation_id, messageId: id });
|
||||
this.incrementUnreadCount(normalizedConversationId);
|
||||
} else {
|
||||
console.log('[MessageManager][DEBUG] 跳过未读数增加:', {
|
||||
isCurrentUserMessage,
|
||||
isActiveConversation,
|
||||
hasCurrentUserId: !!currentUserId,
|
||||
isAck: _isAck,
|
||||
});
|
||||
}
|
||||
|
||||
// 6. 如果是当前活动会话,自动标记已读
|
||||
@@ -766,11 +719,6 @@ class MessageManager {
|
||||
const conversation = this.state.conversations.get(conversationId);
|
||||
|
||||
if (conversation) {
|
||||
console.log('[MessageManager][DEBUG] updateConversationWithNewMessage - 更新前:', {
|
||||
conversationId,
|
||||
prevUnreadCount: conversation.unread_count,
|
||||
conversationRef: conversation,
|
||||
});
|
||||
|
||||
// 更新现有会话
|
||||
const updatedConv: ConversationResponse = {
|
||||
@@ -783,13 +731,6 @@ class MessageManager {
|
||||
|
||||
this.state.conversations.set(conversationId, updatedConv);
|
||||
|
||||
console.log('[MessageManager][DEBUG] updateConversationWithNewMessage - 更新后:', {
|
||||
conversationId,
|
||||
newUnreadCount: updatedConv.unread_count,
|
||||
updatedConvRef: updatedConv,
|
||||
conversationInMap: this.state.conversations.get(conversationId),
|
||||
isSameRef: updatedConv === this.state.conversations.get(conversationId),
|
||||
});
|
||||
} else {
|
||||
// 新会话,需要获取详情
|
||||
// 异步获取会话详情
|
||||
@@ -812,14 +753,12 @@ class MessageManager {
|
||||
*/
|
||||
private handleReadReceipt(message: WSReadMessage): void {
|
||||
// 可以在这里处理对方已读的状态更新
|
||||
console.log('[MessageManager] 处理已读回执:', message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理群聊已读回执
|
||||
*/
|
||||
private handleGroupReadReceipt(message: WSGroupReadMessage): void {
|
||||
console.log('[MessageManager] 处理群聊已读回执:', message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1001,12 +940,10 @@ class MessageManager {
|
||||
*/
|
||||
async fetchConversations(forceRefresh = false): Promise<void> {
|
||||
if (this.state.isLoadingConversations && !forceRefresh) {
|
||||
console.log('[MessageManager] 会话列表正在加载中,跳过');
|
||||
return;
|
||||
}
|
||||
|
||||
this.state.isLoadingConversations = true;
|
||||
console.log('[MessageManager] 获取会话列表');
|
||||
|
||||
try {
|
||||
const response = await messageService.getConversations(1, 20, forceRefresh);
|
||||
@@ -1022,12 +959,6 @@ class MessageManager {
|
||||
// 如果服务器返回的 unread_count > 0,但本地有更晚的已读记录,则保留本地状态
|
||||
const shouldPreserveLocalRead = conv.unread_count > 0;
|
||||
if (shouldPreserveLocalRead) {
|
||||
console.log('[MessageManager] fetchConversations 保护已读状态:', {
|
||||
conversationId: conv.id,
|
||||
serverUnread: conv.unread_count,
|
||||
readTimestamp: readRecord.timestamp,
|
||||
version: readRecord.version,
|
||||
});
|
||||
this.state.conversations.set(conv.id, { ...conv, unread_count: 0 });
|
||||
} else {
|
||||
this.state.conversations.set(conv.id, conv);
|
||||
@@ -1056,10 +987,6 @@ class MessageManager {
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[MessageManager] 会话列表获取完成:', {
|
||||
count: conversations.length,
|
||||
totalUnread,
|
||||
});
|
||||
|
||||
// 通知更新
|
||||
this.notifySubscribers({
|
||||
@@ -1134,12 +1061,10 @@ class MessageManager {
|
||||
async fetchMessages(conversationId: string, afterSeq?: number): Promise<void> {
|
||||
// 防止重复加载
|
||||
if (this.state.loadingMessagesSet.has(conversationId)) {
|
||||
console.log('[MessageManager] 消息正在加载中,跳过:', conversationId);
|
||||
return;
|
||||
}
|
||||
|
||||
this.state.loadingMessagesSet.add(conversationId);
|
||||
console.log('[MessageManager][DEBUG] 获取消息开始:', { conversationId, afterSeq, currentConversationId: this.state.currentConversationId, timestamp: Date.now() });
|
||||
|
||||
try {
|
||||
const mergeMessages = (base: MessageResponse[], incoming: MessageResponse[]): MessageResponse[] => {
|
||||
@@ -1163,7 +1088,6 @@ class MessageManager {
|
||||
console.warn('[MessageManager] 读取本地消息失败,回退到服务端同步:', error);
|
||||
}
|
||||
|
||||
console.log('[MessageManager] 本地消息:', { count: localMessages.length, maxSeq: localMaxSeq });
|
||||
|
||||
if (localMessages.length > 0) {
|
||||
// 转换格式
|
||||
@@ -1179,7 +1103,6 @@ class MessageManager {
|
||||
|
||||
// 立即更新内存和通知(关键:解决竞态条件)
|
||||
this.state.messagesMap.set(conversationId, formattedMessages);
|
||||
console.log('[MessageManager][DEBUG] 本地消息已加载,通知订阅者:', { conversationId, messageCount: formattedMessages.length, timestamp: Date.now() });
|
||||
this.notifySubscribers({
|
||||
type: 'messages_updated',
|
||||
payload: {
|
||||
@@ -1283,7 +1206,6 @@ class MessageManager {
|
||||
// 2.2 再基于 localMaxSeq 做增量补齐(防止快照窗口不足导致漏更老的新消息)
|
||||
const snapshotMaxSeq = snapshotMessages.reduce((max, m) => Math.max(max, m.seq || 0), 0);
|
||||
if (snapshotMaxSeq > localMaxSeq) {
|
||||
console.log('[MessageManager] 增量补齐:', { localMaxSeq, snapshotMaxSeq });
|
||||
const incrementalResp = await messageService.getMessages(conversationId, localMaxSeq);
|
||||
const newMessages = incrementalResp?.messages || [];
|
||||
if (newMessages.length > 0) {
|
||||
@@ -1378,7 +1300,6 @@ class MessageManager {
|
||||
* 加载更多历史消息
|
||||
*/
|
||||
async loadMoreMessages(conversationId: string, beforeSeq: number, limit = 20): Promise<MessageResponse[]> {
|
||||
console.log('[MessageManager] 加载更多历史消息:', { conversationId, beforeSeq, limit });
|
||||
|
||||
try {
|
||||
// 先从本地获取
|
||||
@@ -1468,10 +1389,6 @@ class MessageManager {
|
||||
this.state.totalUnreadCount = unreadData?.total_unread_count ?? 0;
|
||||
this.state.systemUnreadCount = systemUnreadData?.unread_count ?? 0;
|
||||
|
||||
console.log('[MessageManager] 未读数更新:', {
|
||||
total: this.state.totalUnreadCount,
|
||||
system: this.state.systemUnreadCount,
|
||||
});
|
||||
|
||||
this.notifySubscribers({
|
||||
type: 'unread_count_updated',
|
||||
@@ -1496,7 +1413,6 @@ class MessageManager {
|
||||
segments: MessageSegment[],
|
||||
options?: { replyToId?: string }
|
||||
): Promise<MessageResponse | null> {
|
||||
console.log('[MessageManager] 发送消息:', { conversationId, segmentCount: segments.length });
|
||||
|
||||
try {
|
||||
// 调用API发送
|
||||
@@ -1583,7 +1499,6 @@ class MessageManager {
|
||||
* 3. fetchConversations 使用版本号判断数据新旧
|
||||
*/
|
||||
async markAsRead(conversationId: string, seq: number): Promise<void> {
|
||||
console.log('[MessageManager] 标记已读:', { conversationId, seq });
|
||||
|
||||
const conversation = this.state.conversations.get(conversationId);
|
||||
if (!conversation) {
|
||||
@@ -1596,11 +1511,6 @@ class MessageManager {
|
||||
|
||||
// 使用 seq 去重:同一会话若已上报到更大/相同 seq,则跳过重复上报
|
||||
if (existingRecord && seq <= existingRecord.lastReadSeq) {
|
||||
console.log('[MessageManager] 已读seq未前进,跳过重复上报:', {
|
||||
conversationId,
|
||||
seq,
|
||||
lastReadSeq: existingRecord.lastReadSeq,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1620,7 +1530,6 @@ class MessageManager {
|
||||
version: currentVersion,
|
||||
lastReadSeq: seq,
|
||||
});
|
||||
console.log('[MessageManager] 已读保护开始:', { conversationId, version: currentVersion });
|
||||
|
||||
// 2. 乐观更新本地状态(立即反映到UI)
|
||||
const updatedConv: ConversationResponse = {
|
||||
@@ -1663,7 +1572,6 @@ class MessageManager {
|
||||
// 5. 调用 API,完成后设置延迟清除保护
|
||||
try {
|
||||
await messageService.markAsRead(conversationId, seq);
|
||||
console.log('[MessageManager] 标记已读API调用成功:', { conversationId, version: currentVersion });
|
||||
} catch (error) {
|
||||
console.error('[MessageManager] 标记已读API失败:', error);
|
||||
// 失败时回滚状态
|
||||
@@ -1692,7 +1600,6 @@ class MessageManager {
|
||||
// 只有版本号匹配时才清除(防止清除新的已读请求的保护)
|
||||
if (record && record.version === currentVersion) {
|
||||
this.pendingReadMap.delete(conversationId);
|
||||
console.log('[MessageManager] 已读保护结束:', { conversationId, version: currentVersion });
|
||||
}
|
||||
}, READ_STATE_PROTECTION_DELAY);
|
||||
|
||||
@@ -1709,7 +1616,6 @@ class MessageManager {
|
||||
* 标记所有消息已读
|
||||
*/
|
||||
async markAllAsRead(): Promise<void> {
|
||||
console.log('[MessageManager] 标记所有已读');
|
||||
|
||||
// 乐观更新
|
||||
const prevConversations = new Map(this.state.conversations);
|
||||
@@ -1766,7 +1672,6 @@ class MessageManager {
|
||||
* 创建私聊会话
|
||||
*/
|
||||
async createConversation(userId: string): Promise<ConversationResponse | null> {
|
||||
console.log('[MessageManager] 创建私聊会话:', userId);
|
||||
|
||||
try {
|
||||
const conversation = await messageService.createConversation(userId);
|
||||
@@ -1860,7 +1765,6 @@ class MessageManager {
|
||||
* 设置系统消息未读数
|
||||
*/
|
||||
setSystemUnreadCount(count: number): void {
|
||||
console.log('[MessageManager] 设置系统未读数:', count);
|
||||
this.state.systemUnreadCount = count;
|
||||
|
||||
this.notifySubscribers({
|
||||
@@ -1878,7 +1782,6 @@ class MessageManager {
|
||||
*/
|
||||
incrementSystemUnreadCount(): void {
|
||||
this.state.systemUnreadCount += 1;
|
||||
console.log('[MessageManager] 系统未读数增加:', this.state.systemUnreadCount);
|
||||
|
||||
this.notifySubscribers({
|
||||
type: 'unread_count_updated',
|
||||
@@ -1895,7 +1798,6 @@ class MessageManager {
|
||||
*/
|
||||
decrementSystemUnreadCount(count = 1): void {
|
||||
this.state.systemUnreadCount = Math.max(0, this.state.systemUnreadCount - count);
|
||||
console.log('[MessageManager] 系统未读数减少:', this.state.systemUnreadCount);
|
||||
|
||||
this.notifySubscribers({
|
||||
type: 'unread_count_updated',
|
||||
@@ -1953,7 +1855,6 @@ class MessageManager {
|
||||
* 清空会话列表
|
||||
*/
|
||||
clearConversations(): void {
|
||||
console.log('[MessageManager] 清空会话列表');
|
||||
this.state.conversations.clear();
|
||||
this.state.conversationList = [];
|
||||
this.state.totalUnreadCount = 0;
|
||||
@@ -1980,7 +1881,6 @@ class MessageManager {
|
||||
* 实际 MessageManager 使用内存状态,此方法用于兼容性
|
||||
*/
|
||||
invalidateCache(type: 'all' | 'list' | 'unread' = 'all'): void {
|
||||
console.log('[MessageManager] 使缓存失效:', type);
|
||||
// MessageManager 不使用外部缓存,内存状态始终是最新的
|
||||
// 此方法仅用于 API 兼容性
|
||||
}
|
||||
@@ -1994,14 +1894,6 @@ class MessageManager {
|
||||
const prevUnreadCount = conversation.unread_count || 0;
|
||||
const newUnreadCount = prevUnreadCount + 1;
|
||||
|
||||
console.log('[MessageManager][DEBUG] incrementUnreadCount:', {
|
||||
conversationId,
|
||||
prevUnreadCount,
|
||||
newUnreadCount,
|
||||
conversationRef: conversation,
|
||||
conversationInMap: this.state.conversations.get(conversationId),
|
||||
isSameRef: conversation === this.state.conversations.get(conversationId),
|
||||
});
|
||||
|
||||
// 创建新对象而不是直接修改,确保状态一致性
|
||||
const updatedConv: ConversationResponse = {
|
||||
@@ -2095,7 +1987,6 @@ class MessageManager {
|
||||
*/
|
||||
setActiveConversation(conversationId: string | null): void {
|
||||
const normalizedConversationId = conversationId ? this.normalizeConversationId(conversationId) : null;
|
||||
console.log('[MessageManager] 设置活动会话:', normalizedConversationId);
|
||||
this.state.currentConversationId = normalizedConversationId;
|
||||
}
|
||||
|
||||
@@ -2157,7 +2048,6 @@ class MessageManager {
|
||||
*/
|
||||
subscribe(subscriber: MessageSubscriber): () => void {
|
||||
this.state.subscribers.add(subscriber);
|
||||
console.log('[MessageManager] 新订阅者,当前数量:', this.state.subscribers.size);
|
||||
|
||||
// 立即发送当前状态给新订阅者
|
||||
subscriber({
|
||||
@@ -2186,10 +2076,6 @@ class MessageManager {
|
||||
if (this.state.currentConversationId) {
|
||||
const currentMessages = this.state.messagesMap.get(this.state.currentConversationId);
|
||||
if (currentMessages && currentMessages.length > 0) {
|
||||
console.log('[MessageManager][DEBUG] 新订阅者,发送当前活动会话消息:', {
|
||||
conversationId: this.state.currentConversationId,
|
||||
messageCount: currentMessages.length,
|
||||
});
|
||||
subscriber({
|
||||
type: 'messages_updated',
|
||||
payload: {
|
||||
@@ -2205,7 +2091,6 @@ class MessageManager {
|
||||
// 返回取消订阅函数
|
||||
return () => {
|
||||
this.state.subscribers.delete(subscriber);
|
||||
console.log('[MessageManager] 订阅者移除,当前数量:', this.state.subscribers.size);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -100,7 +100,6 @@ export function useMessages(conversationId: string | null): UseMessagesReturn {
|
||||
}
|
||||
|
||||
const normalizedConversationId = String(conversationId);
|
||||
console.log('[useMessages][DEBUG] useEffect 开始执行:', { conversationId: normalizedConversationId, timestamp: Date.now() });
|
||||
|
||||
setIsLoading(true);
|
||||
setHasMore(true);
|
||||
|
||||
@@ -275,8 +275,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
|
||||
// 点赞帖子 - 乐观更新
|
||||
likePost: async (postId: string) => {
|
||||
console.log('[userStore] likePost called:', postId);
|
||||
|
||||
// 先乐观更新本地状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p =>
|
||||
@@ -288,7 +286,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
try {
|
||||
const updatedPost = await postService.likePost(postId);
|
||||
if (updatedPost) {
|
||||
console.log('[userStore] likePost success, updated post:', updatedPost);
|
||||
// 使用后端返回的更新后数据更新状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p =>
|
||||
@@ -316,8 +313,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
|
||||
// 取消点赞 - 乐观更新
|
||||
unlikePost: async (postId: string) => {
|
||||
console.log('[userStore] unlikePost called:', postId);
|
||||
|
||||
// 先乐观更新本地状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p =>
|
||||
@@ -329,7 +324,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
try {
|
||||
const updatedPost = await postService.unlikePost(postId);
|
||||
if (updatedPost) {
|
||||
console.log('[userStore] unlikePost success, updated post:', updatedPost);
|
||||
// 使用后端返回的更新后数据更新状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p =>
|
||||
@@ -357,8 +351,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
|
||||
// 收藏帖子 - 乐观更新
|
||||
favoritePost: async (postId: string) => {
|
||||
console.log('[userStore] favoritePost called:', postId);
|
||||
|
||||
// 先乐观更新本地状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p =>
|
||||
@@ -370,7 +362,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
try {
|
||||
const updatedPost = await postService.favoritePost(postId);
|
||||
if (updatedPost) {
|
||||
console.log('[userStore] favoritePost success, updated post:', updatedPost);
|
||||
// 使用后端返回的更新后数据更新状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p =>
|
||||
@@ -398,8 +389,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
|
||||
// 取消收藏 - 乐观更新
|
||||
unfavoritePost: async (postId: string) => {
|
||||
console.log('[userStore] unfavoritePost called:', postId);
|
||||
|
||||
// 先乐观更新本地状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p =>
|
||||
@@ -411,7 +400,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
try {
|
||||
const updatedPost = await postService.unfavoritePost(postId);
|
||||
if (updatedPost) {
|
||||
console.log('[userStore] unfavoritePost success, updated post:', updatedPost);
|
||||
// 使用后端返回的更新后数据更新状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p =>
|
||||
@@ -439,7 +427,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
|
||||
// 点赞评论
|
||||
likeComment: async (commentId: string) => {
|
||||
console.log('[userStore] likeComment called:', commentId);
|
||||
// 先更新本地状态(更新posts中的帖子的评论点赞状态)
|
||||
set(state => ({
|
||||
posts: state.posts.map(p => ({
|
||||
@@ -453,7 +440,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
// 调用API
|
||||
try {
|
||||
await commentService.likeComment(commentId);
|
||||
console.log('[userStore] likeComment success:', commentId);
|
||||
} catch (error) {
|
||||
console.error('点赞评论失败:', error);
|
||||
// 失败回滚状态
|
||||
@@ -470,7 +456,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
|
||||
// 取消点赞评论
|
||||
unlikeComment: async (commentId: string) => {
|
||||
console.log('[userStore] unlikeComment called:', commentId);
|
||||
// 先更新本地状态
|
||||
set(state => ({
|
||||
posts: state.posts.map(p => ({
|
||||
@@ -484,7 +469,6 @@ export const useUserStore = create<UserState>((set, get) => ({
|
||||
// 调用API
|
||||
try {
|
||||
await commentService.unlikeComment(commentId);
|
||||
console.log('[userStore] unlikeComment success:', commentId);
|
||||
} catch (error) {
|
||||
console.error('取消点赞评论失败:', error);
|
||||
// 失败回滚状态
|
||||
|
||||
Reference in New Issue
Block a user