2 Commits

Author SHA1 Message Date
2014be28c4 Merge pull request 'dev' (#5) from dev into master
Some checks failed
Frontend CI / build-and-push-web (push) Successful in 39s
Frontend CI / build-android-apk (push) Has been cancelled
Frontend CI / ota-android (push) Has been cancelled
Reviewed-on: #5
2026-03-25 20:54:09 +08:00
cf466a3959 Merge pull request 'dev' (#3) from dev into master
All checks were successful
Frontend CI / ota-android (push) Successful in 13m19s
Frontend CI / build-android-apk (push) Successful in 56m46s
Frontend CI / build-and-push-web (push) Successful in 5m46s
Reviewed-on: #3
2026-03-19 01:00:14 +08:00
56 changed files with 989 additions and 4247 deletions

View File

@@ -272,42 +272,6 @@ jobs:
name: carrot-bbs-android-release-apk
path: android/app/build/outputs/apk/release/app-release.apk
- name: Resolve runtime version
id: runtime
run: |
RUNTIME_VERSION="$(node -p "require('./app.json').expo.version")"
echo "runtime_version=${RUNTIME_VERSION}" >> "$GITHUB_OUTPUT"
echo "Resolved runtimeVersion: ${RUNTIME_VERSION}"
- name: Upload APK to Updates Server
env:
OTA_AUTH_TOKEN: ${{ secrets.OTA_AUTH_TOKEN }}
UPDATES_SERVER_URL: https://updates.littlelan.cn
run: |
test -n "${OTA_AUTH_TOKEN}" || (echo "Missing secret OTA_AUTH_TOKEN" && exit 1)
APK_PATH="android/app/build/outputs/apk/release/app-release.apk"
RUNTIME_VERSION="${{ steps.runtime.outputs.runtime_version }}"
echo "Uploading APK for runtime version: ${RUNTIME_VERSION}"
HTTP_CODE=$(curl -s -o response.json -w "%{http_code}" \
-X POST \
"${UPDATES_SERVER_URL}/admin/apk/upload?runtimeVersion=${RUNTIME_VERSION}" \
-H "Authorization: Bearer ${OTA_AUTH_TOKEN}" \
-H "Content-Type: application/vnd.android.package-archive" \
--data-binary @"${APK_PATH}")
echo "HTTP Response Code: ${HTTP_CODE}"
cat response.json
if [ "${HTTP_CODE}" -ne 200 ]; then
echo "Failed to upload APK"
exit 1
fi
echo "APK uploaded successfully!"
build-and-push-web:
runs-on: ubuntu-latest
permissions:

View File

@@ -59,7 +59,6 @@
"favicon": "./assets/favicon.png"
},
"plugins": [
"./plugins/withMainActivityConfigChange",
[
"expo-router",
{

View File

@@ -1,4 +1,4 @@
import { useMemo, useCallback } from 'react';
import { useMemo } from 'react';
import { Platform, useWindowDimensions } from 'react-native';
import { Tabs, usePathname } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
@@ -6,7 +6,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useAppColors, shadows } from '../../../src/theme';
import { BREAKPOINTS } from '../../../src/hooks/useResponsive';
import { useHomeTabBarVisibilityStore, useTotalUnreadCount, useHomeTabPressStore } from '../../../src/stores';
import { useHomeTabBarVisibilityStore, useTotalUnreadCount } from '../../../src/stores';
const TAB_BAR_HEIGHT = 56;
const TAB_BAR_FLOATING_MARGIN = 12;
@@ -19,17 +19,10 @@ export default function TabsLayout() {
const pathname = usePathname();
const unreadCount = useTotalUnreadCount();
const scrollHideTabBar = useHomeTabBarVisibilityStore((s) => s.bottomTabBarHiddenByScroll);
const triggerHomeTabPress = useHomeTabPressStore((s) => s.triggerPress);
const hideTabBar = Platform.OS === 'web' && width >= BREAKPOINTS.desktop;
const isHomeStackRoute = pathname === '/home' || pathname.startsWith('/home/');
const handleHomeTabPress = useCallback(() => {
if (pathname === '/home') {
triggerHomeTabPress();
}
}, [pathname, triggerHomeTabPress]);
const tabBarStyle = useMemo(() => {
if (hideTabBar) {
return { display: 'none' as const, height: 0, overflow: 'hidden' as const };
@@ -88,9 +81,6 @@ export default function TabsLayout() {
/>
),
}}
listeners={{
tabPress: handleHomeTabPress,
}}
/>
<Tabs.Screen
name="apps"

View File

@@ -1,11 +0,0 @@
import { Stack } from 'expo-router';
export default function MaterialsStackLayout() {
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" />
<Stack.Screen name="subject" />
<Stack.Screen name="detail" />
</Stack>
);
}

View File

@@ -1,5 +0,0 @@
import { MaterialDetailScreen } from '../../../../../src/screens/material';
export default function MaterialDetailRoute() {
return <MaterialDetailScreen />;
}

View File

@@ -1,5 +0,0 @@
import { MaterialsScreen } from '../../../../../src/screens/material';
export default function MaterialsRoute() {
return <MaterialsScreen />;
}

View File

@@ -1,5 +0,0 @@
import { SubjectMaterialsScreen } from '../../../../../src/screens/material';
export default function SubjectMaterialsRoute() {
return <SubjectMaterialsScreen />;
}

View File

@@ -21,7 +21,6 @@ import AppPromptBar from '../src/components/common/AppPromptBar';
import AppDialogHost from '../src/components/common/AppDialogHost';
import { installAlertOverride } from '../src/services/alertOverride';
import { useAuthStore } from '../src/stores';
import { checkForAPKUpdate } from '../src/services/apkUpdateService';
registerNotificationPresentationHandler();
@@ -138,26 +137,6 @@ function NotificationBootstrap() {
return null;
}
function APKUpdateBootstrap() {
const hasChecked = useRef(false);
useEffect(() => {
if (hasChecked.current) return;
hasChecked.current = true;
// 延迟执行,避免与启动流程冲突
const timer = setTimeout(() => {
checkForAPKUpdate().catch((error) => {
console.error('APK update check failed:', error);
});
}, 3000);
return () => clearTimeout(timer);
}, []);
return null;
}
function ThemedStack() {
const router = useRouter();
const colors = useAppColors();
@@ -169,7 +148,6 @@ function ThemedStack() {
<SystemChrome />
<SessionGate>
<NotificationBootstrap />
<APKUpdateBootstrap />
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" options={{ headerShown: false }} />
<Stack.Screen name="(auth)" options={{ headerShown: false }} />

10
package-lock.json generated
View File

@@ -29,7 +29,6 @@
"expo-haptics": "~55.0.8",
"expo-image": "^55.0.5",
"expo-image-picker": "^55.0.10",
"expo-intent-launcher": "~55.0.9",
"expo-linear-gradient": "^55.0.8",
"expo-media-library": "~55.0.9",
"expo-notifications": "^55.0.10",
@@ -5748,15 +5747,6 @@
"expo": "*"
}
},
"node_modules/expo-intent-launcher": {
"version": "55.0.9",
"resolved": "https://registry.npmmirror.com/expo-intent-launcher/-/expo-intent-launcher-55.0.9.tgz",
"integrity": "sha512-s8k8dF8PfgzN0c+xzNTd9ceHh+/6mt2ncnMuqFaIIry2BeDGITbsgVijHr39eB5vS+KopCcOYYBYr+O1epx4TA==",
"license": "MIT",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-json-utils": {
"version": "55.0.0",
"resolved": "https://registry.npmmirror.com/expo-json-utils/-/expo-json-utils-55.0.0.tgz",

View File

@@ -35,7 +35,6 @@
"expo-haptics": "~55.0.8",
"expo-image": "^55.0.5",
"expo-image-picker": "^55.0.10",
"expo-intent-launcher": "~55.0.9",
"expo-linear-gradient": "^55.0.8",
"expo-media-library": "~55.0.9",
"expo-notifications": "^55.0.10",

View File

@@ -1,73 +0,0 @@
const { withMainActivity } = require('@expo/config-plugins');
/**
* 在 MainActivity 中添加 onConfigurationChanged 方法
* 用于监听系统深色模式变化并通知 React Native
*/
const withMainActivityConfigChange = (config) => {
return withMainActivity(config, async (config) => {
const { contents } = config.modResults;
// 检查是否已经添加了 onConfigurationChanged
if (contents.includes('onConfigurationChanged')) {
return config;
}
// 需要添加的 imports
const importsToAdd = `import android.content.Intent
import android.content.res.Configuration`;
// 需要添加的方法
const methodToAdd = `
/**
* 监听系统配置变化(包括深色模式切换),并广播给 React Native
* 这对于 Appearance API 正确检测系统主题至关重要
*/
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
val intent = Intent("onConfigurationChanged")
intent.putExtra("newConfig", newConfig)
sendBroadcast(intent)
}
`;
let newContents = contents;
// 添加 imports在已有 imports 后面)
if (!newContents.includes('import android.content.Intent')) {
// 找到最后一个 import 语句
const importRegex = /import [^\n]+\n/g;
const imports = newContents.match(importRegex);
if (imports && imports.length > 0) {
const lastImport = imports[imports.length - 1];
const lastImportIndex = newContents.lastIndexOf(lastImport);
const insertPosition = lastImportIndex + lastImport.length;
newContents =
newContents.slice(0, insertPosition) +
importsToAdd +
'\n' +
newContents.slice(insertPosition);
}
}
// 在类体的开头添加 onConfigurationChanged 方法
// 找到类定义后的第一个方法或属性
const classBodyRegex = /class MainActivity\s*:\s*ReactActivity\s*\(\)\s*\{([\s\S]*)/;
const match = newContents.match(classBodyRegex);
if (match) {
// 找到 onCreate 方法之前插入
const onCreateIndex = newContents.indexOf('override fun onCreate');
if (onCreateIndex !== -1) {
newContents =
newContents.slice(0, onCreateIndex) +
methodToAdd +
newContents.slice(onCreateIndex);
}
}
config.modResults.contents = newContents;
return config;
});
};
module.exports = withMainActivityConfigChange;

View File

@@ -18,7 +18,7 @@ interface CommentItemProps {
comment: Comment;
onUserPress: () => void;
onReply: () => void;
onLike: (comment: Comment) => void; // 点赞回调,传入评论对象
onLike: () => void;
floorNumber?: number; // 楼层号
isAuthor?: boolean; // 是否是楼主
replyToUser?: string; // 回复给哪位用户
@@ -504,25 +504,6 @@ const CommentItem: React.FC<CommentItemProps> = ({
</Text>
</TouchableOpacity>
{/* 点赞按钮 */}
<TouchableOpacity
style={styles.subActionButton}
onPress={() => onLike?.(reply)}
activeOpacity={0.7}
>
<MaterialCommunityIcons
name={reply.is_liked ? 'heart' : 'heart-outline'}
size={12}
color={reply.is_liked ? colors.error.main : colors.text.hint}
/>
<Text
variant="caption"
color={reply.is_liked ? colors.error.main : colors.text.hint}
style={styles.subActionText}
>
{reply.likes_count > 0 ? formatNumber(reply.likes_count) : '赞'}
</Text>
</TouchableOpacity>
{/* 删除按钮 - 子评论作者可见 */}
{isSubReplyAuthor && (
<TouchableOpacity
@@ -611,7 +592,7 @@ const CommentItem: React.FC<CommentItemProps> = ({
{/* 操作按钮 - 更紧凑 */}
<View style={styles.actions}>
{/* 点赞 */}
<TouchableOpacity style={styles.actionButton} onPress={() => onLike(comment)}>
<TouchableOpacity style={styles.actionButton} onPress={onLike}>
<MaterialCommunityIcons
name={comment.is_liked ? 'heart' : 'heart-outline'}
size={14}

View File

@@ -4,8 +4,8 @@
*/
import React from 'react';
import { Text as RNText, TextProps, StyleSheet, TextStyle, ViewStyle, Platform } from 'react-native';
import { useAppColors, fontSizes, fontWeights } from '../../theme';
import { Text as RNText, TextProps, StyleSheet, TextStyle, ViewStyle } from 'react-native';
import { useAppColors, fontSizes } from '../../theme';
type TextVariant = 'h1' | 'h2' | 'h3' | 'body' | 'caption' | 'label';
@@ -16,45 +16,38 @@ interface CustomTextProps extends Omit<TextProps, 'style'> {
numberOfLines?: number;
onPress?: () => void;
style?: TextStyle | TextStyle[];
weight?: 'regular' | 'medium' | 'semibold' | 'bold';
}
const variantStyles: Record<TextVariant, object> = {
h1: {
fontSize: fontSizes['4xl'],
fontWeight: fontWeights.bold,
lineHeight: fontSizes['4xl'] * 1.3,
letterSpacing: -0.5,
fontWeight: '700',
lineHeight: fontSizes['4xl'] * 1.4,
},
h2: {
fontSize: fontSizes['3xl'],
fontWeight: fontWeights.semibold,
lineHeight: fontSizes['3xl'] * 1.3,
letterSpacing: -0.3,
fontWeight: '600',
lineHeight: fontSizes['3xl'] * 1.4,
},
h3: {
fontSize: fontSizes['2xl'],
fontWeight: fontWeights.semibold,
fontWeight: '600',
lineHeight: fontSizes['2xl'] * 1.3,
letterSpacing: -0.2,
},
body: {
fontSize: fontSizes.md,
fontWeight: fontWeights.regular,
lineHeight: fontSizes.md * 1.6,
letterSpacing: 0.1,
fontWeight: '400',
lineHeight: fontSizes.md * 1.5,
},
caption: {
fontSize: fontSizes.sm,
fontWeight: fontWeights.regular,
lineHeight: fontSizes.sm * 1.5,
letterSpacing: 0.2,
fontWeight: '400',
lineHeight: fontSizes.sm * 1.4,
},
label: {
fontSize: fontSizes.xs,
fontWeight: fontWeights.medium,
fontWeight: '500',
lineHeight: fontSizes.xs * 1.4,
letterSpacing: 0.3,
},
};
@@ -62,7 +55,6 @@ const Text: React.FC<CustomTextProps> = ({
children,
variant = 'body',
color,
weight,
numberOfLines,
onPress,
style,
@@ -72,7 +64,6 @@ const Text: React.FC<CustomTextProps> = ({
const textStyle = [
styles.base,
variantStyles[variant],
weight ? { fontWeight: fontWeights[weight] } : null,
color ? { color } : { color: colors.text.primary },
style,
];

View File

@@ -5,7 +5,7 @@
*/
import { messageRepository } from '../../data/repositories/MessageRepository';
import { wsClient, WSEventType } from '../../data/datasources/WSClient';
import { sseClient, SSEEventType } from '../../data/datasources/SSEClient';
import {
Message,
Conversation,
@@ -62,7 +62,7 @@ class ProcessMessageUseCase {
*/
initialize(currentUserId: string | null): void {
this.currentUserId = currentUserId;
this.setupWSListeners();
this.setupSSEListeners();
}
/**
@@ -81,49 +81,49 @@ class ProcessMessageUseCase {
/**
* 设置SSE监听器
*/
private setupWSListeners(): void {
private setupSSEListeners(): void {
// 监听私聊消息
const unsubChat = wsClient.on('chat', (message) => {
const unsubChat = sseClient.on('chat', (message) => {
this.handleNewMessage(message);
});
// 监听群聊消息
const unsubGroupMessage = wsClient.on('group_message', (message) => {
const unsubGroupMessage = sseClient.on('group_message', (message) => {
this.handleNewMessage(message);
});
// 监听私聊已读回执
const unsubRead = wsClient.on('read', (message) => {
const unsubRead = sseClient.on('read', (message) => {
this.handleReadReceipt(message);
});
// 监听群聊已读回执
const unsubGroupRead = wsClient.on('group_read', (message) => {
const unsubGroupRead = sseClient.on('group_read', (message) => {
this.handleGroupReadReceipt(message);
});
// 监听私聊消息撤回
const unsubRecall = wsClient.on('recall', (message) => {
const unsubRecall = sseClient.on('recall', (message) => {
this.handleRecallMessage(message);
});
// 监听群聊消息撤回
const unsubGroupRecall = wsClient.on('group_recall', (message) => {
const unsubGroupRecall = sseClient.on('group_recall', (message) => {
this.handleGroupRecallMessage(message);
});
// 监听群聊输入状态
const unsubGroupTyping = wsClient.on('group_typing', (message) => {
const unsubGroupTyping = sseClient.on('group_typing', (message) => {
this.handleGroupTyping(message);
});
// 监听群通知
const unsubGroupNotice = wsClient.on('group_notice', (message) => {
const unsubGroupNotice = sseClient.on('group_notice', (message) => {
this.handleGroupNotice(message);
});
// 监听连接状态
const unsubConnected = wsClient.on('connected', () => {
const unsubConnected = sseClient.on('connected', () => {
this.notifySubscribers({
type: 'connection_changed',
payload: { connected: true },
@@ -131,7 +131,7 @@ class ProcessMessageUseCase {
});
});
const unsubDisconnected = wsClient.on('disconnected', () => {
const unsubDisconnected = sseClient.on('disconnected', () => {
this.notifySubscribers({
type: 'connection_changed',
payload: { connected: false },

View File

@@ -1,10 +1,10 @@
/**
* WSClient - WebSocket连接管理
* WebSocket连接管理
* SSEClient - SSE连接管理
* SSE连接管理
*/
import {
wsService,
sseService,
WSChatMessage,
WSGroupChatMessage,
WSReadMessage,
@@ -14,13 +14,13 @@ import {
WSGroupTypingMessage,
WSGroupNoticeMessage,
WSMessageType,
} from '../../services/wsService';
} from '../../services/sseService';
// 事件处理器类型
type EventHandler<T> = (data: T) => void;
// WS事件类型
export interface WSEvents {
// SSE事件类型
export interface SSEEvents {
'chat': WSChatMessage;
'group_message': WSGroupChatMessage;
'read': WSReadMessage;
@@ -34,65 +34,65 @@ export interface WSEvents {
'error': Error;
}
export type WSEventType = keyof WSEvents;
export type SSEEventType = keyof SSEEvents;
class WSClient {
private handlers: Map<WSEventType, Set<EventHandler<any>>> = new Map();
class SSEClient {
private handlers: Map<SSEEventType, Set<EventHandler<any>>> = new Map();
private unsubscribeFns: Array<() => void> = [];
private isInitialized = false;
/**
* WebSocket监听
* SSE监听
*/
initialize(): void {
if (this.isInitialized) return;
// 监听私聊消息
const unsubChat = wsService.on('chat', (message) => {
const unsubChat = sseService.on('chat', (message) => {
this.emit('chat', message);
});
// 监听群聊消息
const unsubGroupMessage = wsService.on('group_message', (message) => {
const unsubGroupMessage = sseService.on('group_message', (message) => {
this.emit('group_message', message);
});
// 监听私聊已读回执
const unsubRead = wsService.on('read', (message) => {
const unsubRead = sseService.on('read', (message) => {
this.emit('read', message);
});
// 监听群聊已读回执
const unsubGroupRead = wsService.on('group_read', (message) => {
const unsubGroupRead = sseService.on('group_read', (message) => {
this.emit('group_read', message);
});
// 监听私聊消息撤回
const unsubRecall = wsService.on('recall', (message) => {
const unsubRecall = sseService.on('recall', (message) => {
this.emit('recall', message);
});
// 监听群聊消息撤回
const unsubGroupRecall = wsService.on('group_recall', (message) => {
const unsubGroupRecall = sseService.on('group_recall', (message) => {
this.emit('group_recall', message);
});
// 监听群聊输入状态
const unsubGroupTyping = wsService.on('group_typing', (message) => {
const unsubGroupTyping = sseService.on('group_typing', (message) => {
this.emit('group_typing', message);
});
// 监听群通知
const unsubGroupNotice = wsService.on('group_notice', (message) => {
const unsubGroupNotice = sseService.on('group_notice', (message) => {
this.emit('group_notice', message);
});
// 监听连接状态
const unsubConnect = wsService.onConnect(() => {
const unsubConnect = sseService.onConnect(() => {
this.emit('connected', undefined);
});
const unsubDisconnect = wsService.onDisconnect(() => {
const unsubDisconnect = sseService.onDisconnect(() => {
this.emit('disconnected', undefined);
});
@@ -113,7 +113,7 @@ class WSClient {
}
/**
* WebSocket监听
* SSE监听
*/
destroy(): void {
this.unsubscribeFns.forEach((fn) => fn());
@@ -125,9 +125,9 @@ class WSClient {
/**
*
*/
on<T extends WSEventType>(
on<T extends SSEEventType>(
event: T,
handler: EventHandler<WSEvents[T]>
handler: EventHandler<SSEEvents[T]>
): () => void {
if (!this.handlers.has(event)) {
this.handlers.set(event, new Set());
@@ -142,9 +142,9 @@ class WSClient {
/**
*
*/
private emit<T extends WSEventType>(
private emit<T extends SSEEventType>(
event: T,
data: WSEvents[T]
data: SSEEvents[T]
): void {
const handlers = this.handlers.get(event);
if (handlers) {
@@ -152,7 +152,7 @@ class WSClient {
try {
handler(data);
} catch (error) {
console.error(`[WSClient] 事件处理器执行失败: ${event}`, error);
console.error(`[SSEClient] 事件处理器执行失败: ${event}`, error);
}
});
}
@@ -162,23 +162,23 @@ class WSClient {
*
*/
isConnected(): boolean {
return wsService.isConnected();
return sseService.isConnected();
}
/**
* WebSocket连接
* SSE连接
*/
async connect(): Promise<boolean> {
return wsService.start();
return sseService.start();
}
/**
* WebSocket连接
* SSE连接
*/
disconnect(): void {
wsService.stop();
sseService.stop();
}
}
export const wsClient = new WSClient();
export default wsClient;
export const sseClient = new SSEClient();
export default sseClient;

View File

@@ -1,289 +0,0 @@
/**
* 学习资料 Repository
* 提供学习资料的数据访问接口
*/
import type {
MaterialSubject,
MaterialFile,
MaterialFileType,
} from '../../types/material';
import { api } from '../../services/api';
// ==================== 接口定义 ====================
export interface GetMaterialsParams {
subjectId?: string;
fileType?: MaterialFileType;
keyword?: string;
sortBy?: 'createdAt' | 'downloadCount' | 'title';
sortOrder?: 'asc' | 'desc';
page?: number;
pageSize?: number;
}
export interface MaterialsResult {
materials: MaterialFile[];
total: number;
page: number;
pageSize: number;
hasMore: boolean;
}
// ==================== API 响应类型 ====================
interface SubjectResponse {
id: string;
name: string;
icon: string;
color: string;
description: string;
sort_order: number;
is_active: boolean;
material_count: number;
created_at: string;
updated_at: string;
}
interface MaterialFileResponse {
id: string;
subject_id: string;
title: string;
description: string;
file_type: string;
file_size: number;
file_url: string;
file_name: string;
download_count: number;
author_id: string;
tags: string[];
status: string;
created_at: string;
updated_at: string;
subject?: SubjectResponse;
}
// ==================== 转换函数 ====================
function toMaterialSubject(res: SubjectResponse): MaterialSubject {
return {
id: res.id,
name: res.name,
icon: res.icon,
color: res.color,
description: res.description,
sort_order: res.sort_order,
is_active: res.is_active,
material_count: res.material_count,
created_at: res.created_at,
updated_at: res.updated_at,
};
}
function toMaterialFile(res: MaterialFileResponse): MaterialFile {
return {
id: res.id,
subject_id: res.subject_id,
title: res.title,
description: res.description,
file_type: res.file_type as MaterialFileType,
file_size: res.file_size,
file_url: res.file_url,
file_name: res.file_name,
download_count: res.download_count,
author_id: res.author_id,
tags: res.tags || [],
status: res.status as 'active' | 'inactive',
created_at: res.created_at,
updated_at: res.updated_at,
subject: res.subject ? toMaterialSubject(res.subject) : undefined,
};
}
// ==================== Repository 实现 ====================
/**
* 学习资料数据仓库
* 使用真实 API
*/
export class MaterialRepository {
private static instance: MaterialRepository;
private constructor() {}
static getInstance(): MaterialRepository {
if (!MaterialRepository.instance) {
MaterialRepository.instance = new MaterialRepository();
}
return MaterialRepository.instance;
}
/**
* 获取学科分类列表
*/
async getSubjects(): Promise<MaterialSubject[]> {
try {
const response = await api.get<{ list: SubjectResponse[] }>('/materials/subjects');
return response.data.list.map(toMaterialSubject);
} catch (error) {
console.error('获取学科列表失败:', error);
return [];
}
}
/**
* 根据ID获取学科详情
*/
async getSubjectById(id: string): Promise<MaterialSubject | null> {
try {
const response = await api.get<SubjectResponse>(`/materials/subjects/${id}`);
return toMaterialSubject(response.data);
} catch (error) {
console.error('获取学科详情失败:', error);
return null;
}
}
/**
* 获取资料列表
*/
async getMaterials(params: GetMaterialsParams): Promise<MaterialsResult> {
const {
subjectId,
fileType,
keyword,
sortBy = 'createdAt',
sortOrder = 'desc',
page = 1,
pageSize = 20,
} = params;
try {
const queryParams: Record<string, any> = {
page,
page_size: pageSize,
};
if (subjectId) {
queryParams.subject_id = subjectId;
}
if (fileType) {
queryParams.file_type = fileType;
}
if (keyword) {
queryParams.keyword = keyword;
}
const response = await api.get<{
list: MaterialFileResponse[];
total: number;
page: number;
page_size: number;
has_more: boolean;
}>('/materials', queryParams);
return {
materials: response.data.list.map(toMaterialFile),
total: response.data.total,
page: response.data.page,
pageSize: response.data.page_size,
hasMore: response.data.has_more,
};
} catch (error) {
console.error('获取资料列表失败:', error);
return {
materials: [],
total: 0,
page: 1,
pageSize,
hasMore: false,
};
}
}
/**
* 根据ID获取资料详情
*/
async getMaterialById(id: string): Promise<MaterialFile | null> {
try {
const response = await api.get<MaterialFileResponse>(`/materials/${id}`);
return toMaterialFile(response.data);
} catch (error) {
console.error('获取资料详情失败:', error);
return null;
}
}
/**
* 搜索资料
*/
async searchMaterials(keyword: string, params?: { fileType?: MaterialFileType }): Promise<MaterialsResult> {
return this.getMaterials({
keyword,
fileType: params?.fileType,
});
}
/**
* 获取热门资料
*/
async getHotMaterials(limit: number = 10): Promise<MaterialFile[]> {
try {
const response = await api.get<{
list: MaterialFileResponse[];
total: number;
page: number;
page_size: number;
has_more: boolean;
}>('/materials', {
page: 1,
page_size: limit,
sort_by: 'download_count',
sort_order: 'desc',
});
return response.data.list.map(toMaterialFile);
} catch (error) {
console.error('获取热门资料失败:', error);
return [];
}
}
/**
* 获取最新资料
*/
async getLatestMaterials(limit: number = 10): Promise<MaterialFile[]> {
try {
const response = await api.get<{
list: MaterialFileResponse[];
total: number;
page: number;
page_size: number;
has_more: boolean;
}>('/materials', {
page: 1,
page_size: limit,
sort_by: 'created_at',
sort_order: 'desc',
});
return response.data.list.map(toMaterialFile);
} catch (error) {
console.error('获取最新资料失败:', error);
return [];
}
}
/**
* 获取资料的下载链接(增加下载次数)
*/
async downloadMaterial(id: string): Promise<{ file_url: string; file_name: string } | null> {
try {
const response = await api.get<{ file_url: string; file_name: string }>(`/materials/${id}/download`);
return response.data;
} catch (error) {
console.error('获取下载链接失败:', error);
return null;
}
}
}
// 导出单例
export const materialRepository = MaterialRepository.getInstance();

View File

@@ -14,7 +14,6 @@ import { postManager } from '../stores/postManager';
import { groupManager } from '../stores/groupManager';
import { userManager } from '../stores/userManager';
import { messageManager } from '../stores/messageManager';
import type { PostListTab } from '../stores/postListSources';
// ==================== 预取配置 ====================
@@ -135,7 +134,7 @@ const prefetchService = new PrefetchService();
* 预取帖子数据
* @param types 帖子类型数组
*/
function prefetchPosts(types: PostListTab[] = ['latest', 'hot']): void {
function prefetchPosts(types: string[] = ['latest', 'hot']): void {
types.forEach((type, index) => {
prefetchService.schedule({
key: `posts:${type}:1`,
@@ -280,7 +279,7 @@ export function usePrefetch() {
const hasInitialPrefetched = useRef(false);
/** 预取帖子 */
const prefetchPostsData = useCallback((types?: PostListTab[]) => {
const prefetchPostsData = useCallback((types?: string[]) => {
prefetchPosts(types);
}, []);

View File

@@ -155,17 +155,3 @@ export function hrefAuthRegister(): string {
export function hrefAuthForgot(): string {
return '/forgot-password';
}
// ==================== Materials (学习资料) ====================
export function hrefMaterials(): string {
return '/apps/materials';
}
export function hrefMaterialSubject(subjectId: string): string {
return `/apps/materials/subject?subjectId=${encodeURIComponent(subjectId)}`;
}
export function hrefMaterialDetail(materialId: string): string {
return `/apps/materials/detail?materialId=${encodeURIComponent(materialId)}`;
}

View File

@@ -37,13 +37,6 @@ const APP_ENTRIES: AppItem[] = [
icon: 'calendar-week',
href: hrefs.hrefSchedule(),
},
{
id: 'materials',
title: '学习资料',
subtitle: '按学科分类的学习资源网盘',
icon: 'folder-multiple',
href: hrefs.hrefMaterials(),
},
];
export const AppsScreen: React.FC = () => {

View File

@@ -26,7 +26,7 @@ import { MaterialCommunityIcons } from '@expo/vector-icons';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import { useAppColors, useResolvedColorScheme, spacing, borderRadius, shadows, type AppColors } from '../../theme';
import { Post } from '../../types';
import { useUserStore, useHomeTabBarVisibilityStore, useHomeTabPressStore } from '../../stores';
import { useUserStore, useHomeTabBarVisibilityStore } from '../../stores';
import { useCurrentUser } from '../../stores/authStore';
import { channelService, postService } from '../../services';
import { PostCard, TabBar, SearchBar } from '../../components/business';
@@ -212,14 +212,9 @@ export const HomeScreen: React.FC = () => {
const setBottomTabBarHiddenByScroll = useHomeTabBarVisibilityStore((s) => s.setBottomTabBarHiddenByScroll);
const bottomTabBarHiddenByScroll = useHomeTabBarVisibilityStore((s) => s.bottomTabBarHiddenByScroll);
const homeTabPressCount = useHomeTabPressStore((s) => s.pressCount);
const homeListScrollYRef = useRef(0);
const tabBarIdleRestoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// FlatList 和 ScrollView 的 ref用于滚动到顶部
const flatListRef = useRef<FlatList<Post> | null>(null);
const scrollViewRef = useRef<ScrollView | null>(null);
const clearTabBarIdleRestoreTimer = useCallback(() => {
if (tabBarIdleRestoreTimerRef.current != null) {
clearTimeout(tabBarIdleRestoreTimerRef.current);
@@ -274,19 +269,6 @@ export const HomeScreen: React.FC = () => {
}
}, [showSearch, clearTabBarIdleRestoreTimer, setBottomTabBarHiddenByScroll]);
// 监听首页 Tab 点击事件,滚动到顶部
useEffect(() => {
if (homeTabPressCount > 0) {
// 滚动 FlatList 到顶部
flatListRef.current?.scrollToOffset({ offset: 0, animated: true });
// 滚动 ScrollView 到顶部(网格模式)
scrollViewRef.current?.scrollTo({ y: 0, animated: true });
// 重置底部 Tab 栏状态
setBottomTabBarHiddenByScroll(false);
homeListScrollYRef.current = 0;
}
}, [homeTabPressCount, setBottomTabBarHiddenByScroll]);
/** 横向胶囊条滚动位置:切换频道刷新列表时不重置 */
const capsuleHScrollRef = useRef<ScrollView | null>(null);
const capsuleScrollXRef = useRef(0);
@@ -837,7 +819,6 @@ export const HomeScreen: React.FC = () => {
// 移动端使用瀑布流布局2列
return (
<ScrollView
ref={scrollViewRef}
style={styles.waterfallScroll}
contentContainerStyle={[
styles.waterfallContainer,
@@ -918,7 +899,6 @@ export const HomeScreen: React.FC = () => {
// 移动端和宽屏都使用单列 FlatList宽屏下居中显示
return (
<FlatList
ref={flatListRef}
data={displayPosts}
renderItem={renderPostList}
keyExtractor={keyExtractor}

View File

@@ -895,48 +895,61 @@ export const PostDetailScreen: React.FC = () => {
}
};
// 点赞评论(包括回复)- 优化版
// 点赞评论(包括回复)
const handleLikeComment = async (comment: Comment) => {
const { id, is_liked, likes_count } = comment;
// 先保存旧状态用于回滚
const oldIsLiked = comment.is_liked;
const oldLikesCount = comment.likes_count;
// 乐观更新:切换点赞状态
const newIsLiked = !is_liked;
const newLikesCount = newIsLiked ? likes_count + 1 : Math.max(0, likes_count - 1);
// 递归更新评论树中的点赞状态
const updateLikeInTree = (c: Comment): Comment => {
if (c.id === id) {
return { ...c, is_liked: newIsLiked, likes_count: newLikesCount };
// 乐观更新本地状态 - 辅助函数用于更新评论或回复
const updateCommentLike = (c: Comment): Comment => {
// 如果是目标评论/回复
if (c.id === comment.id) {
return {
...c,
is_liked: !c.is_liked,
likes_count: c.is_liked ? c.likes_count - 1 : c.likes_count + 1
};
}
if (c.replies?.length) {
return { ...c, replies: c.replies.map(r => updateLikeInTree(r)) };
// 如果有回复,递归查找
if (c.replies && c.replies.length > 0) {
return {
...c,
replies: c.replies.map(r => updateCommentLike(r))
};
}
return c;
};
setComments(prev => prev.map(c => updateLikeInTree(c)));
// 更新本地状态
setComments(prev => prev.map(c => updateCommentLike(c)));
try {
const success = newIsLiked
? await commentService.likeComment(id)
: await commentService.unlikeComment(id);
if (!success) {
throw new Error('点赞操作失败');
if (oldIsLiked) {
await commentService.unlikeComment(comment.id);
} else {
await commentService.likeComment(comment.id);
}
} catch (error) {
console.error('评论点赞操作失败:', error);
// 回滚状态
const rollbackLikeInTree = (c: Comment): Comment => {
if (c.id === id) {
return { ...c, is_liked, likes_count };
// 失败时回滚状态
const rollbackCommentLike = (c: Comment): Comment => {
if (c.id === comment.id) {
return {
...c,
is_liked: oldIsLiked,
likes_count: oldLikesCount
};
}
if (c.replies?.length) {
return { ...c, replies: c.replies.map(r => rollbackLikeInTree(r)) };
if (c.replies && c.replies.length > 0) {
return {
...c,
replies: c.replies.map(r => rollbackCommentLike(r))
};
}
return c;
};
setComments(prev => prev.map(c => rollbackLikeInTree(c)));
setComments(prev => prev.map(c => rollbackCommentLike(c)));
}
};
@@ -1360,7 +1373,7 @@ export const PostDetailScreen: React.FC = () => {
return (
<CommentItem
comment={item}
onLike={handleLikeComment}
onLike={() => handleLikeComment(item)}
onReply={() => handleReply(item)}
onUserPress={() => authorId && handleUserPress(authorId)}
floorNumber={index + 1}

View File

@@ -1,500 +0,0 @@
/**
* 资料详情页:展示资料详细信息
*/
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
View,
StyleSheet,
ScrollView,
TouchableOpacity,
StatusBar,
Alert,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import {
spacing,
fontSizes,
borderRadius,
shadows,
useAppColors,
useResolvedColorScheme,
type AppColors,
} from '../../theme';
import { Text, ResponsiveContainer, Loading } from '../../components/common';
import { useResponsive, useResponsiveSpacing, useBreakpointGTE } from '../../hooks/useResponsive';
import type { MaterialFile } from '../../types/material';
import { materialRepository } from '../../data/repositories/MaterialRepository';
import {
MATERIAL_FILE_TYPE_ICONS,
MATERIAL_FILE_TYPE_COLORS,
MATERIAL_FILE_TYPE_NAMES,
formatFileSize,
} from '../../types/material';
export const MaterialDetailScreen: React.FC = () => {
const colors = useAppColors();
const resolvedScheme = useResolvedColorScheme();
const statusBarStyle = resolvedScheme === 'dark' ? 'light-content' : 'dark-content';
const styles = useMemo(() => createMaterialDetailStyles(colors), [colors]);
const router = useRouter();
const params = useLocalSearchParams<{ materialId: string }>();
const insets = useSafeAreaInsets();
const { isMobile } = useResponsive();
const isWideScreen = useBreakpointGTE('lg');
const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });
const [material, setMaterial] = useState<MaterialFile | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const scrollBottomInset = isMobile ? 88 + insets.bottom + spacing.md : spacing['3xl'];
const loadMaterial = useCallback(async () => {
if (!params.materialId) {
setError('缺少资料ID');
setIsLoading(false);
return;
}
try {
setError(null);
const data = await materialRepository.getMaterialById(params.materialId);
setMaterial(data);
} catch (err) {
setError('加载资料详情失败');
console.error('Failed to load material:', err);
} finally {
setIsLoading(false);
}
}, [params.materialId]);
useEffect(() => {
loadMaterial();
}, [loadMaterial]);
const handleDownload = useCallback(() => {
if (!material) return;
Alert.alert(
'下载资料',
`确定要下载「${material.title}」吗?`,
[
{ text: '取消', style: 'cancel' },
{
text: '下载',
onPress: () => {
// Mock下载逻辑
Alert.alert('提示', '下载功能开发中,请稍后再试');
},
},
]
);
}, [material]);
const handlePreview = useCallback(() => {
if (!material?.file_url) return;
Alert.alert(
'在线预览',
'在线预览功能开发中,请稍后再试',
[{ text: '确定', style: 'default' }]
);
}, [material]);
const formatDate = useCallback((dateStr: string) => {
const date = new Date(dateStr);
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
}, []);
const cardStyle = useMemo(
() => ({
backgroundColor: colors.background.paper,
borderRadius: 16,
overflow: 'hidden' as const,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.06,
shadowRadius: 8,
elevation: 2,
}),
[colors]
);
const renderContent = () => {
if (isLoading) {
return (
<View style={styles.centerContainer}>
<Loading size="lg" />
</View>
);
}
if (error || !material) {
return (
<View style={styles.centerContainer}>
<MaterialCommunityIcons name="alert-circle-outline" size={48} color={colors.text.hint} />
<Text variant="body" color={colors.text.secondary} style={styles.errorText}>
{error || '资料不存在'}
</Text>
<TouchableOpacity onPress={() => router.back()} style={styles.retryButton}>
<Text variant="body" color={colors.primary.main}>
</Text>
</TouchableOpacity>
</View>
);
}
const fileColor = MATERIAL_FILE_TYPE_COLORS[material.file_type];
const iconName = MATERIAL_FILE_TYPE_ICONS[material.file_type];
const fileTypeName = MATERIAL_FILE_TYPE_NAMES[material.file_type];
return (
<>
{/* 文件信息卡片 */}
<View style={[styles.fileCard, cardStyle]}>
<View style={[styles.fileTypeBanner, { backgroundColor: fileColor }]}>
<MaterialCommunityIcons name={iconName as any} size={48} color="#FFFFFF" />
<Text variant="body" style={styles.fileTypeName}>
{fileTypeName}
</Text>
</View>
<View style={styles.fileInfo}>
<Text variant="h3" style={styles.fileName}>
{material.title}
</Text>
{material.description && (
<Text variant="body" color={colors.text.secondary} style={styles.fileDescription}>
{material.description}
</Text>
)}
<View style={styles.fileMetaRow}>
<View style={styles.metaItem}>
<MaterialCommunityIcons name="file-outline" size={16} color={colors.text.hint} />
<Text variant="caption" color={colors.text.hint}>
{formatFileSize(material.file_size)}
</Text>
</View>
<View style={styles.metaItem}>
<MaterialCommunityIcons name="download" size={16} color={colors.text.hint} />
<Text variant="caption" color={colors.text.hint}>
{material.download_count}
</Text>
</View>
</View>
</View>
</View>
{/* 详细信息 */}
<View style={[styles.detailCard, cardStyle]}>
<Text variant="body" style={styles.sectionTitle}>
</Text>
<View style={styles.detailRow}>
<Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
</Text>
<Text variant="body" color={colors.text.primary} style={styles.detailValue}>
{material.file_name}
</Text>
</View>
<View style={styles.detailRow}>
<Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
</Text>
<Text variant="body" color={colors.text.primary} style={styles.detailValue}>
{formatDate(material.created_at)}
</Text>
</View>
{material.author_name && (
<View style={styles.detailRow}>
<Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
</Text>
<Text variant="body" color={colors.text.primary} style={styles.detailValue}>
{material.author_name}
</Text>
</View>
)}
{material.tags && material.tags.length > 0 && (
<View style={styles.tagContainer}>
<Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
</Text>
<View style={styles.tags}>
{material.tags.map((tag, index) => (
<View key={index} style={styles.tag}>
<Text variant="caption" color={colors.primary.main}>
{tag}
</Text>
</View>
))}
</View>
</View>
)}
</View>
{/* 操作按钮 */}
<View style={styles.actionButtons}>
<TouchableOpacity
style={[styles.previewButton, { backgroundColor: colors.background.paper }]}
onPress={handlePreview}
activeOpacity={0.8}
>
<MaterialCommunityIcons name="eye-outline" size={20} color={colors.text.primary} />
<Text variant="body" color={colors.text.primary} style={styles.actionButtonText}>
线
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.downloadButton, { backgroundColor: colors.primary.main }]}
onPress={handleDownload}
activeOpacity={0.8}
>
<MaterialCommunityIcons name="download" size={20} color={colors.primary.contrast} />
<Text variant="body" color={colors.primary.contrast} style={styles.actionButtonText}>
</Text>
</TouchableOpacity>
</View>
</>
);
};
return (
<SafeAreaView style={styles.container} edges={['top', 'bottom']}>
<StatusBar barStyle={statusBarStyle} backgroundColor={colors.background.default} />
{/* Header */}
<View style={[styles.header, isWideScreen && styles.headerWide]}>
<View style={styles.headerLeft}>
<TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
<MaterialCommunityIcons name="arrow-left" size={24} color={colors.text.primary} />
</TouchableOpacity>
</View>
<View style={styles.headerCenter}>
<Text style={isWideScreen ? [styles.headerTitle, styles.headerTitleWide] : styles.headerTitle}>
</Text>
</View>
<View style={styles.headerRight}>
<TouchableOpacity style={styles.shareButton}>
<MaterialCommunityIcons name="share-variant" size={22} color={colors.text.primary} />
</TouchableOpacity>
</View>
</View>
{/* Content */}
{isWideScreen ? (
<ResponsiveContainer maxWidth={800}>
<ScrollView
style={styles.scroll}
contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset }]}
showsVerticalScrollIndicator={false}
>
{renderContent()}
</ScrollView>
</ResponsiveContainer>
) : (
<ScrollView
style={styles.scroll}
contentContainerStyle={[
styles.scrollContent,
{ paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding },
]}
showsVerticalScrollIndicator={false}
>
{renderContent()}
</ScrollView>
)}
</SafeAreaView>
);
};
export default MaterialDetailScreen;
function createMaterialDetailStyles(colors: AppColors) {
const headerBg = colors.background.default;
return StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background.default,
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: spacing.md,
paddingVertical: spacing.md,
backgroundColor: headerBg,
...shadows.sm,
},
headerWide: {
paddingHorizontal: spacing.lg,
paddingVertical: spacing.lg,
},
headerLeft: {
width: 44,
alignItems: 'flex-start',
},
backButton: {
padding: spacing.xs,
},
headerCenter: {
flexDirection: 'row',
alignItems: 'center',
},
headerTitle: {
fontSize: 19,
fontWeight: '700',
color: colors.text.primary,
},
headerTitleWide: {
fontSize: 22,
},
headerRight: {
width: 44,
alignItems: 'flex-end',
},
shareButton: {
padding: spacing.xs,
},
scroll: {
flex: 1,
backgroundColor: headerBg,
},
scrollContent: {
paddingTop: spacing.md,
flexGrow: 1,
backgroundColor: headerBg,
},
centerContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingVertical: spacing['3xl'],
},
errorText: {
marginTop: spacing.md,
textAlign: 'center',
},
retryButton: {
marginTop: spacing.md,
paddingVertical: spacing.sm,
paddingHorizontal: spacing.lg,
},
fileCard: {
marginBottom: spacing.md,
},
fileTypeBanner: {
height: 100,
alignItems: 'center',
justifyContent: 'center',
},
fileTypeName: {
color: '#FFFFFF',
fontWeight: '700',
fontSize: fontSizes.lg,
marginTop: spacing.sm,
},
fileInfo: {
padding: spacing.lg,
},
fileName: {
color: colors.text.primary,
fontWeight: '700',
fontSize: fontSizes.lg,
},
fileDescription: {
marginTop: spacing.sm,
lineHeight: fontSizes.md * 1.5,
},
fileMetaRow: {
flexDirection: 'row',
marginTop: spacing.md,
gap: spacing.md,
},
metaItem: {
flexDirection: 'row',
alignItems: 'center',
gap: spacing.xs,
},
detailCard: {
padding: spacing.lg,
marginBottom: spacing.md,
},
sectionTitle: {
fontWeight: '700',
fontSize: fontSizes.md,
color: colors.text.primary,
marginBottom: spacing.md,
},
detailRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: spacing.sm,
borderBottomWidth: 1,
borderBottomColor: colors.divider,
},
detailLabel: {
width: 80,
},
detailValue: {
flex: 1,
textAlign: 'right',
},
tagContainer: {
flexDirection: 'row',
alignItems: 'center',
marginTop: spacing.sm,
},
tags: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: spacing.xs,
flex: 1,
},
tag: {
paddingVertical: spacing.xs,
paddingHorizontal: spacing.sm,
backgroundColor: colors.background.paper,
borderRadius: borderRadius.sm,
borderWidth: 1,
borderColor: colors.primary.main,
},
actionButtons: {
flexDirection: 'row',
gap: spacing.md,
marginTop: spacing.lg,
},
previewButton: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
paddingVertical: spacing.md,
borderRadius: borderRadius.lg,
gap: spacing.xs,
},
downloadButton: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
paddingVertical: spacing.md,
borderRadius: borderRadius.lg,
gap: spacing.xs,
},
actionButtonText: {
fontWeight: '600',
},
});
}

View File

@@ -1,331 +0,0 @@
/**
* 学习资料主页:学科分类网格
*/
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
View,
StyleSheet,
ScrollView,
TouchableOpacity,
StatusBar,
RefreshControl,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import {
spacing,
fontSizes,
borderRadius,
shadows,
useAppColors,
useResolvedColorScheme,
type AppColors,
} from '../../theme';
import * as hrefs from '../../navigation/hrefs';
import { Text, ResponsiveContainer, Loading } from '../../components/common';
import { useResponsive, useResponsiveSpacing, useBreakpointGTE } from '../../hooks/useResponsive';
import type { MaterialSubject } from '../../types/material';
import { materialRepository } from '../../data/repositories/MaterialRepository';
export const MaterialsScreen: React.FC = () => {
const colors = useAppColors();
const resolvedScheme = useResolvedColorScheme();
const statusBarStyle = resolvedScheme === 'dark' ? 'light-content' : 'dark-content';
const styles = useMemo(() => createMaterialsStyles(colors), [colors]);
const router = useRouter();
const insets = useSafeAreaInsets();
const { isMobile } = useResponsive();
const isWideScreen = useBreakpointGTE('lg');
const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });
const [subjects, setSubjects] = useState<MaterialSubject[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const [error, setError] = useState<string | null>(null);
const scrollBottomInset = isMobile ? 88 + insets.bottom + spacing.md : spacing['3xl'];
const loadSubjects = useCallback(async () => {
try {
setError(null);
const data = await materialRepository.getSubjects();
setSubjects(data);
} catch (err) {
setError('加载学科列表失败');
console.error('Failed to load subjects:', err);
} finally {
setIsLoading(false);
setIsRefreshing(false);
}
}, []);
useEffect(() => {
loadSubjects();
}, [loadSubjects]);
const handleRefresh = useCallback(() => {
setIsRefreshing(true);
loadSubjects();
}, [loadSubjects]);
const onOpenSubject = useCallback(
(subjectId: string) => {
router.push(hrefs.hrefMaterialSubject(subjectId));
},
[router]
);
const cardStyle = useMemo(
() => ({
backgroundColor: colors.background.paper,
borderRadius: 16,
overflow: 'hidden' as const,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.06,
shadowRadius: 8,
elevation: 2,
}),
[colors]
);
const renderSubjectCard = (subject: MaterialSubject) => (
<TouchableOpacity
key={subject.id}
style={[styles.subjectCard, cardStyle]}
onPress={() => onOpenSubject(subject.id)}
activeOpacity={0.85}
>
<View style={[styles.subjectIconCircle, { backgroundColor: subject.color }]}>
<MaterialCommunityIcons name={subject.icon as any} size={28} color="#FFFFFF" />
</View>
<View style={styles.subjectContent}>
<Text variant="body" style={styles.subjectName}>
{subject.name}
</Text>
<Text variant="caption" color={colors.text.secondary} style={styles.subjectDesc}>
{subject.description || `${subject.material_count} 份资料`}
</Text>
</View>
<View style={styles.subjectMeta}>
<Text variant="caption" color={colors.text.hint}>
{subject.material_count}
</Text>
<MaterialCommunityIcons name="chevron-right" size={20} color={colors.text.hint} />
</View>
</TouchableOpacity>
);
const renderContent = () => {
if (isLoading) {
return (
<View style={styles.centerContainer}>
<Loading size="lg" />
</View>
);
}
if (error) {
return (
<View style={styles.centerContainer}>
<MaterialCommunityIcons name="alert-circle-outline" size={48} color={colors.text.hint} />
<Text variant="body" color={colors.text.secondary} style={styles.errorText}>
{error}
</Text>
<TouchableOpacity onPress={loadSubjects} style={styles.retryButton}>
<Text variant="body" color={colors.primary.main}>
</Text>
</TouchableOpacity>
</View>
);
}
return (
<>
<Text variant="caption" color={colors.text.secondary} style={styles.pageSubtitle}>
</Text>
<View style={styles.subjectsGrid}>{subjects.map(renderSubjectCard)}</View>
</>
);
};
return (
<SafeAreaView style={styles.container} edges={['top', 'bottom']}>
<StatusBar barStyle={statusBarStyle} backgroundColor={colors.background.default} />
{/* Header */}
<View style={[styles.header, isWideScreen && styles.headerWide]}>
<View style={styles.headerLeft}>
<TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
<MaterialCommunityIcons name="arrow-left" size={24} color={colors.text.primary} />
</TouchableOpacity>
</View>
<View style={styles.headerCenter}>
<Text style={isWideScreen ? [styles.headerTitle, styles.headerTitleWide] : styles.headerTitle}>
</Text>
</View>
<View style={styles.headerRight}>
<TouchableOpacity style={styles.searchButton}>
<MaterialCommunityIcons name="magnify" size={24} color={colors.text.primary} />
</TouchableOpacity>
</View>
</View>
{/* Content */}
{isWideScreen ? (
<ResponsiveContainer maxWidth={800}>
<ScrollView
style={styles.scroll}
contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset }]}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={handleRefresh}
tintColor={colors.primary.main}
/>
}
>
{renderContent()}
</ScrollView>
</ResponsiveContainer>
) : (
<ScrollView
style={styles.scroll}
contentContainerStyle={[
styles.scrollContent,
{ paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding },
]}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={handleRefresh}
tintColor={colors.primary.main}
/>
}
>
{renderContent()}
</ScrollView>
)}
</SafeAreaView>
);
};
export default MaterialsScreen;
function createMaterialsStyles(colors: AppColors) {
const headerBg = colors.background.default;
return StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background.default,
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: spacing.md,
paddingVertical: spacing.md,
backgroundColor: headerBg,
...shadows.sm,
},
headerWide: {
paddingHorizontal: spacing.lg,
paddingVertical: spacing.lg,
},
headerLeft: {
width: 44,
alignItems: 'flex-start',
},
backButton: {
padding: spacing.xs,
},
headerCenter: {
flexDirection: 'row',
alignItems: 'center',
},
headerTitle: {
fontSize: 19,
fontWeight: '700',
color: colors.text.primary,
},
headerTitleWide: {
fontSize: 22,
},
headerRight: {
width: 44,
alignItems: 'flex-end',
},
searchButton: {
padding: spacing.xs,
},
scroll: {
flex: 1,
backgroundColor: headerBg,
},
scrollContent: {
paddingTop: spacing.md,
flexGrow: 1,
backgroundColor: headerBg,
},
pageSubtitle: {
marginBottom: spacing.lg,
lineHeight: fontSizes.sm * 1.45,
},
subjectsGrid: {
gap: spacing.md,
},
subjectCard: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: spacing.lg,
paddingHorizontal: spacing.lg,
},
subjectIconCircle: {
width: 56,
height: 56,
borderRadius: borderRadius.full,
alignItems: 'center',
justifyContent: 'center',
},
subjectContent: {
flex: 1,
marginLeft: spacing.md,
marginRight: spacing.sm,
},
subjectName: {
fontWeight: '700',
fontSize: fontSizes.md + 1,
color: colors.text.primary,
},
subjectDesc: {
marginTop: 4,
},
subjectMeta: {
flexDirection: 'row',
alignItems: 'center',
gap: spacing.xs,
},
centerContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingVertical: spacing['3xl'],
},
errorText: {
marginTop: spacing.md,
textAlign: 'center',
},
retryButton: {
marginTop: spacing.md,
paddingVertical: spacing.sm,
paddingHorizontal: spacing.lg,
},
});
}

View File

@@ -1,404 +0,0 @@
/**
* 学科资料列表页:展示某个学科下的所有资料
*/
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
View,
StyleSheet,
ScrollView,
TouchableOpacity,
StatusBar,
RefreshControl,
FlatList,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import {
spacing,
fontSizes,
borderRadius,
shadows,
useAppColors,
useResolvedColorScheme,
type AppColors,
} from '../../theme';
import * as hrefs from '../../navigation/hrefs';
import { Text, ResponsiveContainer, Loading } from '../../components/common';
import { useResponsive, useResponsiveSpacing, useBreakpointGTE } from '../../hooks/useResponsive';
import type { MaterialSubject, MaterialFile, MaterialFileType } from '../../types/material';
import {
materialRepository,
} from '../../data/repositories/MaterialRepository';
import {
MATERIAL_FILE_TYPE_ICONS,
MATERIAL_FILE_TYPE_COLORS,
formatFileSize,
} from '../../types/material';
export const SubjectMaterialsScreen: React.FC = () => {
const colors = useAppColors();
const resolvedScheme = useResolvedColorScheme();
const statusBarStyle = resolvedScheme === 'dark' ? 'light-content' : 'dark-content';
const styles = useMemo(() => createSubjectMaterialsStyles(colors), [colors]);
const router = useRouter();
const params = useLocalSearchParams<{ subjectId: string }>();
const insets = useSafeAreaInsets();
const { isMobile } = useResponsive();
const isWideScreen = useBreakpointGTE('lg');
const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });
const [subject, setSubject] = useState<MaterialSubject | null>(null);
const [materials, setMaterials] = useState<MaterialFile[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedFileType, setSelectedFileType] = useState<MaterialFileType | null>(null);
const scrollBottomInset = isMobile ? 88 + insets.bottom + spacing.md : spacing['3xl'];
const loadData = useCallback(async () => {
if (!params.subjectId) {
setError('缺少学科ID');
setIsLoading(false);
return;
}
try {
setError(null);
const [subjectData, materialsData] = await Promise.all([
materialRepository.getSubjectById(params.subjectId),
materialRepository.getMaterials({ subjectId: params.subjectId }),
]);
setSubject(subjectData);
setMaterials(materialsData.materials);
} catch (err) {
setError('加载资料列表失败');
console.error('Failed to load materials:', err);
} finally {
setIsLoading(false);
setIsRefreshing(false);
}
}, [params.subjectId]);
useEffect(() => {
loadData();
}, [loadData]);
const handleRefresh = useCallback(() => {
setIsRefreshing(true);
loadData();
}, [loadData]);
const onOpenMaterial = useCallback(
(materialId: string) => {
router.push(hrefs.hrefMaterialDetail(materialId));
},
[router]
);
const filteredMaterials = useMemo(() => {
if (!selectedFileType) return materials;
return materials.filter((m) => m.file_type === selectedFileType);
}, [materials, selectedFileType]);
const fileTypes: { type: MaterialFileType | null; label: string }[] = [
{ type: null, label: '全部' },
{ type: 'pdf', label: 'PDF' },
{ type: 'word', label: 'Word' },
{ type: 'ppt', label: 'PPT' },
];
const cardStyle = useMemo(
() => ({
backgroundColor: colors.background.paper,
borderRadius: 12,
overflow: 'hidden' as const,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.05,
shadowRadius: 4,
elevation: 1,
}),
[colors]
);
const renderMaterialItem = ({ item }: { item: MaterialFile }) => {
const fileColor = MATERIAL_FILE_TYPE_COLORS[item.file_type];
const iconName = MATERIAL_FILE_TYPE_ICONS[item.file_type];
return (
<TouchableOpacity
style={[styles.materialCard, cardStyle]}
onPress={() => onOpenMaterial(item.id)}
activeOpacity={0.85}
>
<View style={[styles.fileTypeIcon, { backgroundColor: fileColor }]}>
<MaterialCommunityIcons name={iconName as any} size={24} color="#FFFFFF" />
</View>
<View style={styles.materialContent}>
<Text variant="body" style={styles.materialTitle} numberOfLines={2}>
{item.title}
</Text>
<View style={styles.materialMeta}>
<Text variant="caption" color={colors.text.hint}>
{formatFileSize(item.file_size)}
</Text>
<Text variant="caption" color={colors.text.hint}>
{' · '}
</Text>
<Text variant="caption" color={colors.text.hint}>
{item.download_count}
</Text>
</View>
{item.description && (
<Text variant="caption" color={colors.text.secondary} numberOfLines={1}>
{item.description}
</Text>
)}
</View>
<MaterialCommunityIcons name="chevron-right" size={20} color={colors.text.hint} />
</TouchableOpacity>
);
};
const renderFilterTabs = () => (
<View style={styles.filterContainer}>
{fileTypes.map(({ type, label }) => (
<TouchableOpacity
key={label}
style={[
styles.filterTab,
selectedFileType === type && styles.filterTabActive,
selectedFileType === type && { backgroundColor: colors.primary.main },
]}
onPress={() => setSelectedFileType(type)}
activeOpacity={0.7}
>
<Text
variant="caption"
color={selectedFileType === type ? colors.primary.contrast : colors.text.secondary}
style={styles.filterTabText}
>
{label}
</Text>
</TouchableOpacity>
))}
</View>
);
const renderEmptyComponent = () => (
<View style={styles.centerContainer}>
<MaterialCommunityIcons name="file-document-outline" size={64} color={colors.text.hint} />
<Text variant="body" color={colors.text.secondary} style={styles.emptyText}>
{selectedFileType ? '该类型暂无资料' : '暂无资料'}
</Text>
</View>
);
const renderContent = () => {
if (isLoading) {
return (
<View style={styles.centerContainer}>
<Loading size="lg" />
</View>
);
}
if (error) {
return (
<View style={styles.centerContainer}>
<MaterialCommunityIcons name="alert-circle-outline" size={48} color={colors.text.hint} />
<Text variant="body" color={colors.text.secondary} style={styles.errorText}>
{error}
</Text>
<TouchableOpacity onPress={loadData} style={styles.retryButton}>
<Text variant="body" color={colors.primary.main}>
</Text>
</TouchableOpacity>
</View>
);
}
return (
<FlatList
data={filteredMaterials}
keyExtractor={(item) => item.id}
renderItem={renderMaterialItem}
ListHeaderComponent={renderFilterTabs}
ListEmptyComponent={renderEmptyComponent}
contentContainerStyle={styles.listContent}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={handleRefresh}
tintColor={colors.primary.main}
/>
}
/>
);
};
return (
<SafeAreaView style={styles.container} edges={['top', 'bottom']}>
<StatusBar barStyle={statusBarStyle} backgroundColor={colors.background.default} />
{/* Header */}
<View style={[styles.header, isWideScreen && styles.headerWide]}>
<View style={styles.headerLeft}>
<TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
<MaterialCommunityIcons name="arrow-left" size={24} color={colors.text.primary} />
</TouchableOpacity>
</View>
<View style={styles.headerCenter}>
<Text style={isWideScreen ? [styles.headerTitle, styles.headerTitleWide] : styles.headerTitle}>
{subject?.name || '资料列表'}
</Text>
</View>
<View style={styles.headerRight}>
<TouchableOpacity style={styles.searchButton}>
<MaterialCommunityIcons name="magnify" size={24} color={colors.text.primary} />
</TouchableOpacity>
</View>
</View>
{/* Content */}
{isWideScreen ? (
<ResponsiveContainer maxWidth={800}>
<View style={[styles.contentWrapper, { paddingBottom: scrollBottomInset }]}>
{renderContent()}
</View>
</ResponsiveContainer>
) : (
<View style={[styles.contentWrapper, { paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding }]}>
{renderContent()}
</View>
)}
</SafeAreaView>
);
};
export default SubjectMaterialsScreen;
function createSubjectMaterialsStyles(colors: AppColors) {
const headerBg = colors.background.default;
return StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background.default,
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: spacing.md,
paddingVertical: spacing.md,
backgroundColor: headerBg,
...shadows.sm,
},
headerWide: {
paddingHorizontal: spacing.lg,
paddingVertical: spacing.lg,
},
headerLeft: {
width: 44,
alignItems: 'flex-start',
},
backButton: {
padding: spacing.xs,
},
headerCenter: {
flexDirection: 'row',
alignItems: 'center',
},
headerTitle: {
fontSize: 19,
fontWeight: '700',
color: colors.text.primary,
},
headerTitleWide: {
fontSize: 22,
},
headerRight: {
width: 44,
alignItems: 'flex-end',
},
searchButton: {
padding: spacing.xs,
},
contentWrapper: {
flex: 1,
},
listContent: {
paddingTop: spacing.md,
},
filterContainer: {
flexDirection: 'row',
gap: spacing.sm,
marginBottom: spacing.md,
},
filterTab: {
paddingVertical: spacing.sm,
paddingHorizontal: spacing.md,
borderRadius: borderRadius.full,
backgroundColor: colors.background.paper,
},
filterTabActive: {
// backgroundColor set inline
},
filterTabText: {
fontWeight: '600',
},
materialCard: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: spacing.md,
paddingHorizontal: spacing.md,
marginBottom: spacing.sm,
},
fileTypeIcon: {
width: 44,
height: 44,
borderRadius: borderRadius.md,
alignItems: 'center',
justifyContent: 'center',
},
materialContent: {
flex: 1,
marginLeft: spacing.md,
marginRight: spacing.sm,
},
materialTitle: {
fontWeight: '600',
fontSize: fontSizes.md,
color: colors.text.primary,
},
materialMeta: {
flexDirection: 'row',
alignItems: 'center',
marginTop: 4,
},
centerContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingVertical: spacing['3xl'],
},
errorText: {
marginTop: spacing.md,
textAlign: 'center',
},
emptyText: {
marginTop: spacing.md,
textAlign: 'center',
},
retryButton: {
marginTop: spacing.md,
paddingVertical: spacing.sm,
paddingHorizontal: spacing.lg,
},
});
}

View File

@@ -1,6 +0,0 @@
/**
* 学习资料屏幕导出
*/
export { MaterialsScreen } from './MaterialsScreen';
export { SubjectMaterialsScreen } from './SubjectMaterialsScreen';
export { MaterialDetailScreen } from './MaterialDetailScreen';

View File

@@ -404,7 +404,7 @@ export const MessageBubble: React.FC<MessageBubbleProps> = ({
>
<Avatar
source={senderInfo.avatar}
size={40}
size={36}
name={senderInfo.nickname}
/>
</TouchableOpacity>
@@ -418,7 +418,7 @@ export const MessageBubble: React.FC<MessageBubbleProps> = ({
>
<Avatar
source={otherUser?.avatar || null}
size={40}
size={36}
name={otherUser?.nickname || ''}
/>
</TouchableOpacity>
@@ -452,7 +452,7 @@ export const MessageBubble: React.FC<MessageBubbleProps> = ({
<View style={styles.avatarWrapper}>
<Avatar
source={currentUser?.avatar || null}
size={40}
size={36}
name={currentUser?.nickname || ''}
/>
</View>

View File

@@ -847,11 +847,11 @@ function createSegmentStyles(colors: AppColors) {
marginTop: 2,
},
// 文本 - 适配暗色模式
// 文本 - Telegram风格统一深色字体
textContent: {
fontSize: 17.5,
lineHeight: 25,
letterSpacing: 0.1,
fontSize: 16,
lineHeight: 23,
letterSpacing: 0.2,
fontWeight: '400',
},
textMe: {
@@ -861,22 +861,27 @@ function createSegmentStyles(colors: AppColors) {
color: colors.chat.textPrimary,
},
// @提及 - 微信/QQ 风格:更精致的高亮
// @提及 - Telegram风格蓝色高亮
atText: {
fontSize: 16,
lineHeight: 22,
fontWeight: '500',
lineHeight: 23,
fontWeight: '600',
paddingHorizontal: 2,
},
atTextMe: {
color: '#1A5F9E', // 深蓝色,在绿色背景上更清晰
color: '#4A88C7',
backgroundColor: 'rgba(74, 136, 199, 0.12)',
borderRadius: 4,
},
atTextOther: {
color: colors.chat.link,
backgroundColor: 'rgba(74, 136, 199, 0.12)',
borderRadius: 4,
},
atHighlight: {
backgroundColor: 'rgba(74, 136, 199, 0.15)',
backgroundColor: 'rgba(74, 136, 199, 0.2)',
borderRadius: 4,
paddingHorizontal: 3,
paddingHorizontal: 4,
},
// 图片 - QQ风格保持原始宽高比

View File

@@ -201,7 +201,7 @@ export function createChatScreenStyles(colors: AppColors) {
alignItems: 'flex-start',
},
// 头像 - 更大一点
// 头像
avatarWrapper: {
marginHorizontal: 2,
shadowColor: colors.chat.shadow,
@@ -226,43 +226,43 @@ export function createChatScreenStyles(colors: AppColors) {
alignItems: 'flex-start',
},
senderName: {
fontSize: 14,
color: colors.chat.textSecondary, // 使用主题次要文字颜色
fontSize: 13,
color: colors.chat.link,
marginBottom: 4,
marginLeft: 4,
fontWeight: '600',
},
// 消息气泡 - 微信风格:更小的圆角 + 更紧凑的内边距
// 消息气泡 - 外层极轻阴影(纯文字气泡更接近扁平 IM
messageBubbleOuter: {
borderRadius: 12,
minWidth: 44,
borderRadius: 16,
minWidth: 60,
shadowColor: colors.chat.shadow,
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.06,
shadowRadius: 2,
shadowOffset: { width: 0, height: 0.5 },
shadowOpacity: 0.04,
shadowRadius: 1,
elevation: 1,
},
myBubbleOuter: {
borderBottomRightRadius: 4, // 微信的小尾巴更尖
borderBottomRightRadius: 4,
},
theirBubbleOuter: {
borderTopLeftRadius: 4,
},
// 内层:更紧凑的微信风格内边距
// 内层:背景 + 裁剪,防止回复条/@ 高亮在圆角外露出颜色
messageBubbleInner: {
borderRadius: 12,
borderRadius: 16,
overflow: 'hidden',
paddingHorizontal: 10, // 微信:更窄的左右边距
paddingVertical: 7, // 微信:更紧的上下边距
minWidth: 44,
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm + 4,
minWidth: 60,
},
myBubbleInner: {
backgroundColor: colors.chat.bubbleOutgoing,
backgroundColor: colors.chat.replyTint,
borderBottomRightRadius: 4,
},
theirBubbleInner: {
backgroundColor: colors.chat.bubbleIncoming,
backgroundColor: colors.chat.card,
borderTopLeftRadius: 4,
},
recalledBubble: {
@@ -272,17 +272,17 @@ export function createChatScreenStyles(colors: AppColors) {
borderStyle: 'dashed',
},
myBubbleText: {
color: colors.chat.textPrimary, // 使用主题文字颜色
fontSize: 18,
lineHeight: 25,
letterSpacing: 0.1,
color: colors.chat.textPrimary, // 主文案
fontSize: 16,
lineHeight: 23,
letterSpacing: 0.2,
fontWeight: '400',
},
theirBubbleText: {
color: colors.chat.textPrimary, // 使用主题文字颜色
fontSize: 18,
lineHeight: 25,
letterSpacing: 0.1,
color: colors.chat.textPrimary, // 主文案
fontSize: 16,
lineHeight: 23,
letterSpacing: 0.2,
fontWeight: '400',
},
// 选中状态
@@ -312,21 +312,21 @@ export function createChatScreenStyles(colors: AppColors) {
fontStyle: 'italic',
},
// 图片消息 - QQ/微信风格:更大的圆角,更柔和的阴影
// 图片消息 - QQ风格更大的图片,更明显的圆角
imageBubble: {
borderRadius: 18,
overflow: 'hidden',
shadowColor: colors.chat.shadow,
shadowOffset: { width: 0, height: 3 },
shadowOpacity: 0.12,
shadowOpacity: 0.15,
shadowRadius: 6,
elevation: 4,
elevation: 5,
},
myImageBubble: {
borderBottomRightRadius: 8,
borderBottomRightRadius: 6, // 右下角尖,箭头在右下
},
theirImageBubble: {
borderTopLeftRadius: 8,
borderTopLeftRadius: 6, // 左上角尖,箭头在左上
},
messageImage: {
width: 220,

View File

@@ -23,7 +23,6 @@ import {
borderRadius,
useThemePreference,
useSetThemePreference,
useThemeStore,
type AppColors,
} from '../../theme';
import { useAuthStore } from '../../stores';
@@ -205,41 +204,29 @@ export const SettingsScreen: React.FC = () => {
const handleItemPress = (key: string) => {
switch (key) {
case 'theme': {
// 获取调试信息
const { Appearance } = require('react-native');
const systemScheme = Appearance?.getColorScheme?.() || 'undefined';
const resolvedScheme = useThemeStore.getState().resolvedScheme;
const storedPref = useThemeStore.getState().preference;
const storedSystem = useThemeStore.getState().systemScheme;
Alert.alert(
'主题模式',
`选择应用界面明暗\n\n[调试信息]\n系统主题: ${systemScheme}\n存储偏好: ${storedPref}\n存储系统: ${storedSystem}\n实际应用: ${resolvedScheme}`,
[
{ text: '取消', style: 'cancel' },
{
text: '跟随系统',
onPress: () => {
void setThemePreference('system');
},
case 'theme':
Alert.alert('主题模式', '选择应用界面明暗', [
{ text: '取消', style: 'cancel' },
{
text: '跟随系统',
onPress: () => {
void setThemePreference('system');
},
{
text: '浅色',
onPress: () => {
void setThemePreference('light');
},
},
{
text: '浅色',
onPress: () => {
void setThemePreference('light');
},
{
text: '深色',
onPress: () => {
void setThemePreference('dark');
},
},
{
text: '深色',
onPress: () => {
void setThemePreference('dark');
},
]
);
},
]);
break;
}
case 'edit_profile':
router.push(hrefs.hrefProfileEdit());
break;

View File

@@ -20,7 +20,7 @@ const getBaseUrl = () => {
};
const BASE_URL = getBaseUrl();
const WS_URL = `${BASE_URL.replace(/^https?:\/\//, 'wss://').replace(/\/api\/v1$/, '/api/v1')}/realtime/ws`;
const SSE_URL = `${BASE_URL.replace(/\/+$/, '')}/realtime/sse`;
// Token 存储键
const TOKEN_KEY = 'auth_token';
@@ -441,4 +441,4 @@ class ApiClient {
// 导出 API 客户端实例
export const api = new ApiClient(BASE_URL);
export { WS_URL, TOKEN_KEY, REFRESH_TOKEN_KEY };
export { SSE_URL, TOKEN_KEY, REFRESH_TOKEN_KEY };

View File

@@ -1,290 +0,0 @@
/**
* APK 更新检查服务
* 用于检查最新版本并提示用户下载更新
*/
import { Platform, Linking, Alert } from 'react-native';
import Constants from 'expo-constants';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { showConfirm } from './dialogService';
// 条件导入原生模块(仅在 Android 上可用)
// eslint-disable-next-line @typescript-eslint/no-var-requires
const FileSystem = Platform.OS === 'android' ? require('expo-file-system/legacy') : null;
// eslint-disable-next-line @typescript-eslint/no-var-requires
const IntentLauncher = Platform.OS === 'android' ? require('expo-intent-launcher') : null;
// 更新服务器地址
const UPDATES_SERVER_URL = Constants.expoConfig?.extra?.updatesUrl
? Constants.expoConfig.extra.updatesUrl.replace('/api/manifest', '')
: 'https://updates.littlelan.cn';
// 检查间隔毫秒24小时
const CHECK_INTERVAL = 24 * 60 * 60 * 1000;
// 最后检查时间存储键
const LAST_CHECK_KEY = 'apk_update_last_check';
// APK 版本信息
export interface APKVersionInfo {
runtimeVersion: string;
versionName: string;
size: number;
downloadUrl: string;
createdAt: string;
}
// 版本比较结果
export interface VersionCheckResult {
hasUpdate: boolean;
currentVersion: string;
latestVersion: string;
downloadUrl: string;
size: number;
}
/**
* 比较版本号
* 返回: 1 表示 v1 > v2, -1 表示 v1 < v2, 0 表示相等
*/
function compareVersions(v1: string, v2: string): number {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0;
const p2 = parts2[i] || 0;
if (p1 > p2) return 1;
if (p1 < p2) return -1;
}
return 0;
}
/**
* 获取最新 APK 版本信息
*/
async function fetchLatestAPKVersion(): Promise<APKVersionInfo | null> {
try {
const response = await fetch(`${UPDATES_SERVER_URL}/api/apk/latest`, {
method: 'GET',
headers: {
'Accept': 'application/json',
},
});
if (!response.ok) {
console.warn('Failed to fetch latest APK version:', response.status);
return null;
}
const data: APKVersionInfo = await response.json();
return data;
} catch (error) {
console.error('Error fetching latest APK version:', error);
return null;
}
}
/**
* 获取当前应用版本
*/
function getCurrentVersion(): string {
return Constants.expoConfig?.version || '1.0.0';
}
/**
* 格式化文件大小
*/
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}
/**
* 检查是否应该执行检查(避免频繁检查)
*/
async function shouldCheck(): Promise<boolean> {
try {
const lastCheck = await AsyncStorage.getItem(LAST_CHECK_KEY);
if (!lastCheck) return true;
const lastCheckTime = parseInt(lastCheck, 10);
return Date.now() - lastCheckTime > CHECK_INTERVAL;
} catch {
return true;
}
}
/**
* 记录检查时间
*/
async function recordCheckTime(): Promise<void> {
try {
await AsyncStorage.setItem(LAST_CHECK_KEY, Date.now().toString());
} catch (error) {
console.error('Failed to record check time:', error);
}
}
/**
* 下载并安装 APK
*/
async function downloadAndInstallAPK(downloadUrl: string, version: string): Promise<void> {
if (Platform.OS !== 'android') {
Alert.alert('提示', '此功能仅支持 Android 设备');
return;
}
if (!FileSystem) {
Alert.alert('提示', '当前环境不支持 APK 更新,请在浏览器中下载');
Linking.openURL(downloadUrl);
return;
}
try {
const downloadPath = `${FileSystem.documentDirectory}carrot-bbs-${version}.apk`;
// 显示下载进度
showConfirm({
title: '正在下载',
message: `正在下载新版本 ${version},请稍候...`,
confirmText: '后台下载',
cancelText: '取消',
onConfirm: () => {
// 用户选择后台下载,继续
},
onCancel: () => {
// 用户取消
},
});
// 下载 APK
const downloadResult = await FileSystem.downloadAsync(downloadUrl, downloadPath);
if (!downloadResult.uri) {
Alert.alert('下载失败', '无法下载安装包,请稍后重试');
return;
}
// 安装 APK
await installAPK(downloadResult.uri);
} catch (error) {
console.error('Download/Install error:', error);
Alert.alert('更新失败', '下载或安装过程中出错,请稍后重试');
}
}
/**
* 安装 APK
*/
async function installAPK(apkUri: string): Promise<void> {
try {
if (!FileSystem || !IntentLauncher) {
throw new Error('Native modules not available');
}
// 获取文件的 content URI
const contentUri = await FileSystem.getContentUriAsync(apkUri);
// 使用 Intent 安装 APK
await IntentLauncher.startActivityAsync('android.intent.action.INSTALL_PACKAGE', {
data: contentUri,
flags: 1, // FLAG_GRANT_READ_URI_PERMISSION
});
} catch (error) {
console.error('Install APK error:', error);
// 尝试使用浏览器下载
Linking.openURL(apkUri.replace('file://', ''));
}
}
/**
* 显示更新提示对话框
*/
function showUpdateDialog(result: VersionCheckResult): void {
const sizeText = formatFileSize(result.size);
showConfirm({
title: '发现新版本',
message: `当前版本: ${result.currentVersion}\n最新版本: ${result.latestVersion}\n安装包大小: ${sizeText}\n\n是否立即下载更新`,
confirmText: '立即更新',
cancelText: '稍后提醒',
onConfirm: () => {
downloadAndInstallAPK(result.downloadUrl, result.latestVersion);
},
});
}
/**
* 检查 APK 更新(主入口)
* @param force 是否强制检查(忽略时间间隔)
*/
export async function checkForAPKUpdate(force: boolean = false): Promise<VersionCheckResult | null> {
// 仅在 Android 平台检查
if (Platform.OS !== 'android') {
return null;
}
// 检查是否应该执行检查
if (!force) {
const should = await shouldCheck();
if (!should) {
console.log('APK update check skipped (too frequent)');
return null;
}
}
// 记录检查时间
await recordCheckTime();
// 获取最新版本信息
const latestAPK = await fetchLatestAPKVersion();
if (!latestAPK) {
console.log('No APK version info available');
return null;
}
const currentVersion = getCurrentVersion();
const latestVersion = latestAPK.versionName || latestAPK.runtimeVersion;
// 比较版本
const comparison = compareVersions(currentVersion, latestVersion);
const result: VersionCheckResult = {
hasUpdate: comparison < 0,
currentVersion,
latestVersion,
downloadUrl: latestAPK.downloadUrl,
size: latestAPK.size,
};
// 如果有更新,显示对话框
if (result.hasUpdate) {
showUpdateDialog(result);
}
return result;
}
/**
* 手动检查更新(用户主动触发)
*/
export async function manualCheckForUpdate(): Promise<void> {
const result = await checkForAPKUpdate(true);
if (!result) {
Alert.alert('检查失败', '无法获取版本信息,请检查网络连接');
return;
}
if (!result.hasUpdate) {
Alert.alert('已是最新', `当前版本 ${result.currentVersion} 已是最新版本`);
}
}
export const apkUpdateService = {
checkForAPKUpdate,
manualCheckForUpdate,
};

View File

@@ -11,7 +11,7 @@
import { AppState, AppStateStatus, Platform } from 'react-native';
import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';
import { wsService } from './wsService';
import { sseService } from './sseService';
import {
triggerVibration,
vibrateOnMessage,
@@ -36,8 +36,8 @@ let appStateSubscription: any = null;
TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
try {
// 检查 SSE 连接状态
if (!wsService.isConnected()) {
await wsService.connect();
if (!sseService.isConnected()) {
await sseService.connect();
}
// 返回收到新数据
@@ -51,8 +51,8 @@ TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
// SSE 保活任务
TaskManager.defineTask(REALTIME_KEEPALIVE_TASK, async () => {
try {
if (!wsService.isConnected()) {
await wsService.connect();
if (!sseService.isConnected()) {
await sseService.connect();
}
return BackgroundFetch.BackgroundFetchResult.NewData;
} catch (error) {
@@ -120,8 +120,8 @@ function setupAppStateListener(): void {
void nextAppState;
if (nextAppState === 'active') {
// App 回到前台,确保连接
if (!wsService.isConnected()) {
wsService.connect();
if (!sseService.isConnected()) {
sseService.connect();
}
}
});

View File

@@ -78,13 +78,7 @@ function normalizeAnnouncementCursor(
// 群组服务类(纯 API 层)
// SQLite/内存缓存编排由 groupManager 统一处理
class GroupService {
// ==================== 群组管理 ====================
/**
* 获取群组列表
* GET /api/v1/groups
*/
async getGroups(page = 1, pageSize = 20): Promise<GroupListResponse> {
async fetchGroupsFromApi(page = 1, pageSize = 20): Promise<GroupListResponse> {
const response = await api.get<GroupListResponse>('/groups', {
page,
page_size: pageSize,
@@ -92,20 +86,16 @@ class GroupService {
return normalizeGroupListResponse(response.data);
}
/**
* 获取群组详情
* GET /api/v1/groups/:id
*/
async getGroup(id: string): Promise<GroupResponse> {
async fetchGroupFromApi(id: string): Promise<GroupResponse> {
const response = await api.get<GroupResponse>(`/groups/${encodeURIComponent(id)}`);
return normalizeGroup(response.data);
}
/**
* 获取群组成员列表
* GET /api/v1/groups/:id/members
*/
async getMembers(groupId: string, page = 1, pageSize = 50): Promise<GroupMemberListResponse> {
async fetchMembersFromApi(
groupId: string,
page = 1,
pageSize = 50
): Promise<GroupMemberListResponse> {
const response = await api.get<GroupMemberListResponse>(
`/groups/${encodeURIComponent(groupId)}/members`,
{
@@ -116,6 +106,8 @@ class GroupService {
return normalizeMemberListResponse(response.data);
}
// ==================== 群组管理 ====================
/**
* 创建群组
* POST /api/v1/groups
@@ -125,6 +117,22 @@ class GroupService {
return normalizeGroup(response.data);
}
/**
* 获取群组列表
* GET /api/v1/groups
*/
async getGroups(page = 1, pageSize = 20): Promise<GroupListResponse> {
return this.fetchGroupsFromApi(page, pageSize);
}
/**
* 获取群组详情
* GET /api/v1/groups/:id
*/
async getGroup(id: string): Promise<GroupResponse> {
return this.fetchGroupFromApi(id);
}
/**
* 获取当前用户在群组中的成员信息
* GET /api/v1/groups/:id/me
@@ -203,6 +211,14 @@ class GroupService {
await api.post(`/groups/${encodeURIComponent(groupId)}/leave`);
}
/**
* 获取群组成员列表
* GET /api/v1/groups/:id/members
*/
async getMembers(groupId: string, page = 1, pageSize = 50): Promise<GroupMemberListResponse> {
return this.fetchMembersFromApi(groupId, page, pageSize);
}
/**
* 移除群成员(踢人)
* POST /api/v1/groups/:id/members/kick

View File

@@ -4,7 +4,7 @@
*/
// API 客户端
export { api, WS_URL, TOKEN_KEY, REFRESH_TOKEN_KEY } from './api';
export { api, SSE_URL, TOKEN_KEY, REFRESH_TOKEN_KEY } from './api';
export type { ApiResponse, PaginatedData, ApiError } from './api';
// 认证服务
@@ -47,8 +47,8 @@ export { voteService } from './voteService';
export { channelService } from './channelService';
export type { ChannelItem } from './channelService';
// WebSocket 实时服务
export { wsService } from './wsService';
// SSE 实时服务
export { sseService } from './sseService';
export type {
WSMessage,
WSMessageType,
@@ -65,7 +65,7 @@ export type {
WSGroupMentionMessage,
WSGroupReadMessage,
WSGroupRecallMessage
} from './wsService';
} from './sseService';
// 系统通知服务
export { systemNotificationService, getNotificationTitle } from './systemNotificationService';
@@ -110,7 +110,3 @@ export {
// 统一提示/弹窗服务
export { showPrompt } from './promptService';
export { showConfirm } from './dialogService';
// APK 更新检查服务
export { apkUpdateService, checkForAPKUpdate, manualCheckForUpdate } from './apkUpdateService';
export type { APKVersionInfo, VersionCheckResult } from './apkUpdateService';

View File

@@ -5,7 +5,6 @@
*/
import { api } from './api';
import { wsService } from './wsService';
import {
ConversationListResponse,
ConversationResponse,
@@ -28,7 +27,6 @@ import {
saveConversationCache,
saveConversationsWithRelatedCache,
updateConversationCacheUnreadCount,
saveUsersCache,
} from './database';
/** 远端会话列表分页offset / cursor统一结果拉取成功后均已执行本地缓存同步 */
@@ -345,7 +343,6 @@ class MessageService {
/**
* 发送消息(新格式)
* 优先使用WebSocket发送失败时降级到HTTP
* POST /api/v1/conversations/:id/messages
* Body: { detail_type, segments }
*/
@@ -359,25 +356,12 @@ class MessageService {
throw new Error('消息内容不能为空');
}
// 优先使用WebSocket发送
try {
const result = await wsService.sendMessage(
conversationId,
detailType,
data.segments,
data.reply_to_id
);
return result;
} catch (error) {
console.log('WebSocket发送失败降级到HTTP:', error);
// 降级到HTTP发送
return this.sendMessageByAction(
detailType,
conversationId,
data.segments,
data.reply_to_id
);
}
return this.sendMessageByAction(
detailType,
conversationId,
data.segments,
data.reply_to_id
);
}
/**
@@ -509,19 +493,13 @@ class MessageService {
/**
* 撤回/删除消息
* 优先使用WebSocket失败时降级到HTTP
* POST /api/v1/messages/delete_msg
* Body: { "message_id": "xxx" }
*/
async recallMessage(messageId: string): Promise<void> {
try {
await wsService.recallMessage(messageId);
} catch (error) {
console.log('WebSocket撤回失败降级到HTTP:', error);
await api.post('/messages/delete_msg', {
message_id: messageId,
});
}
await api.post('/messages/delete_msg', {
message_id: messageId,
});
}
/**
@@ -536,16 +514,11 @@ class MessageService {
/**
* 标记已读
* 优先使用WebSocket失败时降级到HTTP
* POST /api/v1/conversations/:id/read
* @param conversationId 会话ID
* @param seq 已读到的消息序号
*/
async markAsRead(conversationId: string, seq: number): Promise<void> {
// 使用WebSocket发送已读标记不等待响应
wsService.markRead(conversationId, seq).catch(() => {});
// 同时通过HTTP确保可靠性
await api.post(`/conversations/${encodeURIComponent(conversationId)}/read`, {
last_read_seq: Number(seq),
});
@@ -557,14 +530,9 @@ class MessageService {
/**
* 上报输入状态
* 优先使用WebSocket失败时降级到HTTP
* POST /api/v1/conversations/:id/typing
*/
async sendTyping(conversationId: string): Promise<void> {
// 使用WebSocket发送输入状态
wsService.sendTyping(conversationId, true);
// 同时通过HTTP确保可靠性
await api.post(`/conversations/${encodeURIComponent(conversationId)}/typing`);
}

517
src/services/sseService.ts Normal file
View File

@@ -0,0 +1,517 @@
import { AppState, AppStateStatus } from 'react-native';
import EventSource from 'react-native-sse';
import { api, SSE_URL } from './api';
import { MessageCategory, SystemMessageType, SystemMessageExtraData, MessageSegment } from '../types/dto';
import { systemNotificationService } from './systemNotificationService';
export type WSMessageType =
| 'chat'
| 'message'
| 'read'
| 'typing'
| 'recall'
| 'notification'
| 'announcement'
| 'group_message'
| 'group_typing'
| 'group_notice'
| 'group_mention'
| 'group_read'
| 'group_recall'
| 'notice'
| 'request'
| 'meta'
| 'private'
| 'group'
| 'follow'
| 'like'
| 'comment'
| 'heartbeat';
export interface WSChatMessage {
type: 'chat';
conversation_id: string;
id: string;
sender_id: string;
seq: number;
segments?: MessageSegment[];
created_at: string;
}
export interface WSReadMessage {
type: 'read';
conversation_id: string;
user_id: string;
seq: number;
}
export interface WSTypingMessage {
type: 'typing';
conversation_id: string;
user_id: string;
is_typing: boolean;
}
export interface WSRecallMessage {
type: 'recall';
conversation_id: string;
message_id: string;
}
export interface WSNotificationMessage {
type: 'notification';
id: string;
sender_id?: string;
receiver_id?: string;
content: string;
category?: MessageCategory;
system_type?: SystemMessageType;
extra_data?: SystemMessageExtraData;
created_at: string;
}
export interface WSAnnouncementMessage {
type: 'announcement';
id: string;
sender_id?: string;
receiver_id?: string;
content: string;
category?: MessageCategory;
system_type?: SystemMessageType;
extra_data?: SystemMessageExtraData;
created_at: string;
}
export interface WSGroupMentionMessage {
type: 'group_mention';
group_id: string;
conversation_id: string;
message_id: string;
from_user_id: string;
content: string;
mention_all: boolean;
created_at: string;
}
export interface WSGroupChatMessage {
type: 'group_message';
conversation_id: string;
group_id: string;
id: string;
sender_id: string;
seq: number;
segments?: MessageSegment[];
created_at: string;
}
export interface WSGroupTypingMessage {
type: 'group_typing';
group_id: string;
user_id: string;
is_typing: boolean;
}
export type GroupNoticeType = 'member_join' | 'member_leave' | 'member_removed' | 'role_changed' | 'muted' | 'unmuted';
export interface WSGroupNoticeMessage {
type: 'group_notice';
notice_type: GroupNoticeType;
group_id: string;
data: {
user_id?: string;
operator_id?: string;
role?: string;
[key: string]: any;
};
timestamp: number;
message_id?: string;
seq?: number;
}
export interface WSGroupReadMessage {
type: 'group_read';
group_id: string;
conversation_id: string;
user_id: string;
seq: number;
}
export interface WSGroupRecallMessage {
type: 'group_recall';
group_id: string;
conversation_id: string;
message_id: string;
}
export type WSMessage =
| WSChatMessage
| WSReadMessage
| WSTypingMessage
| WSRecallMessage
| WSNotificationMessage
| WSAnnouncementMessage
| WSGroupChatMessage
| WSGroupTypingMessage
| WSGroupNoticeMessage
| WSGroupMentionMessage
| WSGroupReadMessage
| WSGroupRecallMessage;
type MessageHandler<T extends WSMessage = WSMessage> = (message: T) => void;
type ConnectionHandler = () => void;
interface SSEEnvelope {
event_id?: number;
event?: string;
ts?: number;
payload?: any;
}
class SSEService {
private source: EventSource | null = null;
private isConnecting = false;
private connected = false;
private reconnectAttempts = 0;
private maxReconnectAttempts = 20;
private reconnectDelay = 3000;
private reconnectTimer: NodeJS.Timeout | null = null;
private connectionWatchdogTimer: NodeJS.Timeout | null = null;
private readonly CONNECTION_IDLE_TIMEOUT_MS = 70000;
private messageHandlers: Map<WSMessageType, MessageHandler[]> = new Map();
private connectionHandlers: ConnectionHandler[] = [];
private disconnectionHandlers: ConnectionHandler[] = [];
private appStateSubscription: any = null;
private lastAppState: AppStateStatus = 'active';
private lastEventId = '';
private lastActivityAt = 0;
private shouldRun = false;
private toSSEUrl(): string {
return `${SSE_URL}?last_event_id=${encodeURIComponent(this.lastEventId)}`;
}
async connect(): Promise<boolean> {
this.shouldRun = true;
if (this.isConnecting || this.isConnected()) return true;
this.isConnecting = true;
try {
const token = await api.getToken();
if (!token) {
this.isConnecting = false;
return false;
}
const url = this.toSSEUrl();
this.source = new EventSource(url, {
headers: {
Authorization: `Bearer ${token}`,
},
// Use one reconnect strategy only (manual), avoid library auto-reconnect fighting with us.
pollingInterval: 0,
// Be explicit to prevent platform-level short idle timeout behavior.
timeout: this.CONNECTION_IDLE_TIMEOUT_MS,
});
this.source.addEventListener('open', () => {
this.isConnecting = false;
this.connected = true;
this.reconnectAttempts = 0;
this.markActivity();
this.startConnectionWatchdog();
this.connectionHandlers.forEach(h => h());
});
this.source.addEventListener('error', () => {
this.handleDisconnected();
});
this.source.addEventListener('done' as any, () => {
this.handleDisconnected();
});
this.source.addEventListener('close' as any, () => {
this.handleDisconnected();
});
const events = ['chat_message', 'message_read', 'typing', 'system_notification', 'group_notice', 'message_recall', 'heartbeat'];
events.forEach(eventName => {
this.source?.addEventListener(eventName as any, (evt: any) => this.handleIncoming(eventName, evt));
});
return true;
} catch {
this.isConnecting = false;
this.scheduleReconnect();
return false;
}
}
private handleIncoming(eventName: string, evt: any): void {
this.markActivity();
const rawData = typeof evt?.data === 'string' ? evt.data : '{}';
const lastEventId = evt?.lastEventId;
if (lastEventId) {
this.lastEventId = String(lastEventId);
}
let payload: any = {};
try {
payload = JSON.parse(rawData);
} catch {
payload = {};
}
this.dispatchEvent(eventName, payload);
}
private dispatchEvent(eventName: string, payload: any): void {
if (eventName === 'chat_message') {
const detailType = payload?.detail_type || 'private';
const m = payload?.message || payload;
if (detailType === 'group') {
const gm: WSGroupChatMessage = {
type: 'group_message',
conversation_id: m.conversation_id,
group_id: String(m.group_id ?? ''),
id: m.id,
sender_id: m.sender_id,
seq: Number(m.seq || 0),
segments: m.segments || [],
created_at: m.created_at || new Date().toISOString(),
};
this.emit('group_message', gm);
} else {
const cm: WSChatMessage = {
type: 'chat',
conversation_id: m.conversation_id,
id: m.id,
sender_id: m.sender_id,
seq: Number(m.seq || 0),
segments: m.segments || [],
created_at: m.created_at || new Date().toISOString(),
};
this.emit('chat', cm);
}
return;
}
if (eventName === 'message_read') {
const detailType = payload?.detail_type || 'private';
if (detailType === 'group') {
const m: WSGroupReadMessage = {
type: 'group_read',
group_id: String(payload.group_id ?? ''),
conversation_id: payload.conversation_id,
user_id: payload.user_id,
seq: Number(payload.seq || 0),
};
this.emit('group_read', m);
} else {
const m: WSReadMessage = {
type: 'read',
conversation_id: payload.conversation_id,
user_id: payload.user_id,
seq: Number(payload.seq || 0),
};
this.emit('read', m);
}
return;
}
if (eventName === 'typing') {
const detailType = payload?.detail_type || 'private';
if (detailType === 'group') {
const m: WSGroupTypingMessage = {
type: 'group_typing',
group_id: String(payload.group_id ?? ''),
user_id: payload.user_id,
is_typing: payload.is_typing !== false,
};
this.emit('group_typing', m);
} else {
const m: WSTypingMessage = {
type: 'typing',
conversation_id: payload.conversation_id,
user_id: payload.user_id,
is_typing: payload.is_typing !== false,
};
this.emit('typing', m);
}
return;
}
if (eventName === 'message_recall') {
const detailType = payload?.detail_type || 'private';
if (detailType === 'group') {
const m: WSGroupRecallMessage = {
type: 'group_recall',
group_id: String(payload.group_id ?? ''),
conversation_id: payload.conversation_id,
message_id: payload.message_id,
};
this.emit('group_recall', m);
} else {
const m: WSRecallMessage = {
type: 'recall',
conversation_id: payload.conversation_id,
message_id: payload.message_id,
};
this.emit('recall', m);
}
return;
}
if (eventName === 'group_notice') {
const m: WSGroupNoticeMessage = {
type: 'group_notice',
notice_type: payload.notice_type,
group_id: String(payload.group_id ?? ''),
data: payload.data || {},
timestamp: payload.timestamp || Date.now(),
message_id: payload.message_id,
seq: payload.seq,
};
this.emit('group_notice', m);
return;
}
if (eventName === 'system_notification') {
const m: WSNotificationMessage = {
type: 'notification',
id: String(payload.id ?? ''),
content: payload.content || '',
created_at: payload.created_at || new Date().toISOString(),
};
this.emit('notification', m);
systemNotificationService.handleWSMessage(m as any).catch(() => {});
}
}
private emit<T extends WSMessageType>(type: T, message: Extract<WSMessage, { type: T }>) {
const handlers = this.messageHandlers.get(type) || [];
handlers.forEach(h => h(message as WSMessage));
}
disconnect(): void {
this.shouldRun = false;
this.connected = false;
this.isConnecting = false;
if (this.source) {
this.source.close();
this.source = null;
}
this.stopConnectionWatchdog();
this.stopReconnect();
}
private scheduleReconnect(): void {
if (this.reconnectAttempts >= this.maxReconnectAttempts) return;
this.stopReconnect();
this.reconnectTimer = setTimeout(() => {
this.reconnectAttempts += 1;
this.connect();
}, this.reconnectDelay);
}
private stopReconnect() {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
}
isConnected(): boolean {
return this.connected;
}
on<T extends WSMessageType>(type: T, handler: MessageHandler<Extract<WSMessage, { type: T }>>): () => void {
const list = this.messageHandlers.get(type) || [];
list.push(handler as MessageHandler);
this.messageHandlers.set(type, list);
return () => {
const current = this.messageHandlers.get(type) || [];
const idx = current.indexOf(handler as MessageHandler);
if (idx >= 0) current.splice(idx, 1);
};
}
onConnect(handler: ConnectionHandler): () => void {
this.connectionHandlers.push(handler);
return () => {
const i = this.connectionHandlers.indexOf(handler);
if (i >= 0) this.connectionHandlers.splice(i, 1);
};
}
onDisconnect(handler: ConnectionHandler): () => void {
this.disconnectionHandlers.push(handler);
return () => {
const i = this.disconnectionHandlers.indexOf(handler);
if (i >= 0) this.disconnectionHandlers.splice(i, 1);
};
}
private setupAppStateListener(): void {
if (this.appStateSubscription) return;
this.lastAppState = AppState.currentState;
this.appStateSubscription = AppState.addEventListener('change', (nextState: AppStateStatus) => {
if (this.lastAppState.match(/inactive|background/) && nextState === 'active' && !this.isConnected()) {
this.reconnectAttempts = 0;
this.connect();
}
this.lastAppState = nextState;
});
}
async start(): Promise<boolean> {
this.setupAppStateListener();
return this.connect();
}
stop(): void {
if (this.appStateSubscription) {
this.appStateSubscription.remove();
this.appStateSubscription = null;
}
this.disconnect();
}
private markActivity(): void {
this.lastActivityAt = Date.now();
}
private startConnectionWatchdog(): void {
this.stopConnectionWatchdog();
this.connectionWatchdogTimer = setInterval(() => {
// During active app usage, if no SSE activity for too long, reconnect proactively.
if (!this.connected || this.lastActivityAt <= 0) return;
if (Date.now() - this.lastActivityAt > this.CONNECTION_IDLE_TIMEOUT_MS) {
this.handleDisconnected();
}
}, 10000);
}
private stopConnectionWatchdog(): void {
if (this.connectionWatchdogTimer) {
clearInterval(this.connectionWatchdogTimer);
this.connectionWatchdogTimer = null;
}
}
private handleDisconnected(): void {
const wasActive = this.connected || this.source != null || this.isConnecting;
this.isConnecting = false;
this.connected = false;
if (this.source) {
this.source.close();
this.source = null;
}
this.stopConnectionWatchdog();
if (wasActive) {
this.disconnectionHandlers.forEach(h => h());
}
if (this.shouldRun) {
this.scheduleReconnect();
}
}
}
export const sseService = new SSEService();

View File

@@ -6,7 +6,7 @@
import * as Notifications from 'expo-notifications';
import { Platform, AppState, AppStateStatus } from 'react-native';
import type { WSChatMessage, WSNotificationMessage, WSAnnouncementMessage } from './wsService';
import type { WSChatMessage, WSNotificationMessage, WSAnnouncementMessage } from './sseService';
import { extractTextFromSegments } from '../types/dto';
import { getNotificationPreferencesSync } from './notificationPreferences';
import { vibrateOnMessage } from './messageVibrationService';

View File

@@ -1,828 +0,0 @@
import { AppState, AppStateStatus } from 'react-native';
import { api, WS_URL } from './api';
import { MessageCategory, SystemMessageType, SystemMessageExtraData, MessageSegment } from '../types/dto';
import { systemNotificationService } from './systemNotificationService';
export type WSMessageType =
| 'chat'
| 'message'
| 'read'
| 'typing'
| 'recall'
| 'notification'
| 'announcement'
| 'group_message'
| 'group_typing'
| 'group_notice'
| 'group_mention'
| 'group_read'
| 'group_recall'
| 'notice'
| 'request'
| 'meta'
| 'private'
| 'group'
| 'follow'
| 'like'
| 'comment'
| 'heartbeat'
| 'pong'
| 'message_sent'
| 'message_recalled'
| 'error';
export interface WSChatMessage {
type: 'chat';
conversation_id: string;
id: string;
sender_id: string;
seq: number;
segments?: MessageSegment[];
created_at: string;
}
export interface WSReadMessage {
type: 'read';
conversation_id: string;
user_id: string;
seq: number;
}
export interface WSTypingMessage {
type: 'typing';
conversation_id: string;
user_id: string;
is_typing: boolean;
}
export interface WSRecallMessage {
type: 'recall';
conversation_id: string;
message_id: string;
}
export interface WSNotificationMessage {
type: 'notification';
id: string;
sender_id?: string;
receiver_id?: string;
content: string;
category?: MessageCategory;
system_type?: SystemMessageType;
extra_data?: SystemMessageExtraData;
created_at: string;
}
export interface WSAnnouncementMessage {
type: 'announcement';
id: string;
sender_id?: string;
receiver_id?: string;
content: string;
category?: MessageCategory;
system_type?: SystemMessageType;
extra_data?: SystemMessageExtraData;
created_at: string;
}
export interface WSGroupMentionMessage {
type: 'group_mention';
group_id: string;
conversation_id: string;
message_id: string;
from_user_id: string;
content: string;
mention_all: boolean;
created_at: string;
}
export interface WSGroupChatMessage {
type: 'group_message';
conversation_id: string;
group_id: string;
id: string;
sender_id: string;
seq: number;
segments?: MessageSegment[];
created_at: string;
}
export interface WSGroupTypingMessage {
type: 'group_typing';
group_id: string;
user_id: string;
is_typing: boolean;
}
export type GroupNoticeType = 'member_join' | 'member_leave' | 'member_removed' | 'role_changed' | 'muted' | 'unmuted';
export interface WSGroupNoticeMessage {
type: 'group_notice';
notice_type: GroupNoticeType;
group_id: string;
data: {
user_id?: string;
operator_id?: string;
role?: string;
[key: string]: any;
};
timestamp: number;
message_id?: string;
seq?: number;
}
export interface WSGroupReadMessage {
type: 'group_read';
group_id: string;
conversation_id: string;
user_id: string;
seq: number;
}
export interface WSGroupRecallMessage {
type: 'group_recall';
group_id: string;
conversation_id: string;
message_id: string;
}
export interface WSServerMessage {
event_id?: number;
type: string;
ts?: number;
payload?: any;
}
export type WSMessage =
| WSChatMessage
| WSReadMessage
| WSTypingMessage
| WSRecallMessage
| WSNotificationMessage
| WSAnnouncementMessage
| WSGroupChatMessage
| WSGroupTypingMessage
| WSGroupNoticeMessage
| WSGroupMentionMessage
| WSGroupReadMessage
| WSGroupRecallMessage;
type MessageHandler<T extends WSMessage = WSMessage> = (message: T) => void;
type ConnectionHandler = () => void;
// 发送队列中的消息
interface PendingMessage {
id: string;
type: string;
payload: any;
resolve: (value: any) => void;
reject: (reason: any) => void;
timestamp: number;
}
class WebSocketService {
private ws: WebSocket | null = null;
private isConnecting = false;
private connected = false;
private reconnectAttempts = 0;
private maxReconnectAttempts = 20;
private reconnectDelay = 3000;
private reconnectTimer: NodeJS.Timeout | null = null;
private heartbeatTimer: NodeJS.Timeout | null = null;
private heartbeatInterval = 30000; // 30秒心跳
private messageHandlers: Map<WSMessageType, MessageHandler[]> = new Map();
private connectionHandlers: ConnectionHandler[] = [];
private disconnectionHandlers: ConnectionHandler[] = [];
private appStateSubscription: any = null;
private lastAppState: AppStateStatus = 'active';
private shouldRun = false;
private lastEventId = '';
private lastActivityAt = 0;
// 发送队列
private pendingMessages: PendingMessage[] = [];
private messageIdCounter = 0;
// 降级状态
private isFallbackMode = false;
private fallbackCheckTimer: NodeJS.Timeout | null = null;
private getWSUrl(token: string | null): string {
return `${WS_URL}?token=${encodeURIComponent(token || '')}`;
}
async connect(): Promise<boolean> {
this.shouldRun = true;
if (this.isConnecting || this.isConnected()) {
console.log('[WebSocket] Already connected or connecting');
return true;
}
this.isConnecting = true;
console.log('[WebSocket] Connecting...');
try {
const token = await api.getToken();
if (!token) {
console.error('[WebSocket] No token available');
this.isConnecting = false;
this.scheduleReconnect();
return false;
}
const url = this.getWSUrl(token);
console.log('[WebSocket] Connecting to:', url.replace(token, '***'));
this.ws = new WebSocket(url);
this.ws.onopen = () => {
console.log('[WebSocket] Connected successfully');
this.isConnecting = false;
this.connected = true;
this.reconnectAttempts = 0;
this.isFallbackMode = false;
this.markActivity();
this.startHeartbeat();
this.connectionHandlers.forEach(h => h());
// 发送队列中的消息
this.flushPendingMessages();
};
this.ws.onmessage = (event) => {
this.markActivity();
this.handleIncoming(event.data);
};
this.ws.onerror = (error) => {
console.error('[WebSocket] Error:', error);
};
this.ws.onclose = (event) => {
console.log('[WebSocket] Closed:', event.code, event.reason);
this.handleDisconnected();
};
return true;
} catch (error) {
console.error('[WebSocket] Connection error:', error);
this.isConnecting = false;
this.scheduleReconnect();
return false;
}
}
private handleIncoming(data: string): void {
try {
const msg: WSServerMessage = JSON.parse(data);
// 处理pong响应
if (msg.type === 'pong') {
return;
}
// 处理错误消息
if (msg.type === 'error') {
console.error('WebSocket error:', msg.payload);
return;
}
// 处理消息发送成功响应
if (msg.type === 'message_sent') {
this.handleMessageSent(msg.payload);
return;
}
// 处理消息撤回响应
if (msg.type === 'message_recalled') {
this.handleMessageRecalled(msg.payload);
return;
}
// 保存事件ID用于断线重连
if (msg.event_id) {
this.lastEventId = String(msg.event_id);
}
// 分发事件
this.dispatchServerMessage(msg);
} catch (error) {
console.error('Failed to parse WebSocket message:', error);
}
}
private dispatchServerMessage(msg: WSServerMessage): void {
const { type, payload } = msg;
switch (type) {
case 'chat_message':
this.handleChatMessage(payload);
break;
case 'message_read':
this.handleMessageRead(payload);
break;
case 'typing':
this.handleTyping(payload);
break;
case 'message_recall':
this.handleMessageRecall(payload);
break;
case 'group_notice':
this.handleGroupNotice(payload);
break;
case 'system_notification':
this.handleSystemNotification(payload);
break;
default:
console.log('Unknown message type:', type);
}
}
private handleChatMessage(payload: any): void {
const detailType = payload?.detail_type || 'private';
const m = payload?.message || payload;
if (detailType === 'group') {
const gm: WSGroupChatMessage = {
type: 'group_message',
conversation_id: m.conversation_id,
group_id: String(m.group_id ?? ''),
id: m.id,
sender_id: m.sender_id,
seq: Number(m.seq || 0),
segments: m.segments || [],
created_at: m.created_at || new Date().toISOString(),
};
this.emit('group_message', gm);
} else {
const cm: WSChatMessage = {
type: 'chat',
conversation_id: m.conversation_id,
id: m.id,
sender_id: m.sender_id,
seq: Number(m.seq || 0),
segments: m.segments || [],
created_at: m.created_at || new Date().toISOString(),
};
this.emit('chat', cm);
}
}
private handleMessageRead(payload: any): void {
const detailType = payload?.detail_type || 'private';
if (detailType === 'group') {
const m: WSGroupReadMessage = {
type: 'group_read',
group_id: String(payload.group_id ?? ''),
conversation_id: payload.conversation_id,
user_id: payload.user_id,
seq: Number(payload.seq || 0),
};
this.emit('group_read', m);
} else {
const m: WSReadMessage = {
type: 'read',
conversation_id: payload.conversation_id,
user_id: payload.user_id,
seq: Number(payload.seq || 0),
};
this.emit('read', m);
}
}
private handleTyping(payload: any): void {
const detailType = payload?.detail_type || 'private';
if (detailType === 'group') {
const m: WSGroupTypingMessage = {
type: 'group_typing',
group_id: String(payload.group_id ?? ''),
user_id: payload.user_id,
is_typing: payload.is_typing !== false,
};
this.emit('group_typing', m);
} else {
const m: WSTypingMessage = {
type: 'typing',
conversation_id: payload.conversation_id,
user_id: payload.user_id,
is_typing: payload.is_typing !== false,
};
this.emit('typing', m);
}
}
private handleMessageRecall(payload: any): void {
const detailType = payload?.detail_type || 'private';
if (detailType === 'group') {
const m: WSGroupRecallMessage = {
type: 'group_recall',
group_id: String(payload.group_id ?? ''),
conversation_id: payload.conversation_id,
message_id: payload.message_id,
};
this.emit('group_recall', m);
} else {
const m: WSRecallMessage = {
type: 'recall',
conversation_id: payload.conversation_id,
message_id: payload.message_id,
};
this.emit('recall', m);
}
}
private handleGroupNotice(payload: any): void {
const m: WSGroupNoticeMessage = {
type: 'group_notice',
notice_type: payload.notice_type,
group_id: String(payload.group_id ?? ''),
data: payload.data || {},
timestamp: payload.timestamp || Date.now(),
message_id: payload.message_id,
seq: payload.seq,
};
this.emit('group_notice', m);
}
private handleSystemNotification(payload: any): void {
const m: WSNotificationMessage = {
type: 'notification',
id: String(payload.id ?? ''),
content: payload.content || '',
created_at: payload.created_at || new Date().toISOString(),
};
this.emit('notification', m);
systemNotificationService.handleWSMessage(m as any).catch(() => {});
}
private handleMessageSent(payload: any): void {
// 找到对应的发送请求并resolve
const pendingMsg = this.pendingMessages.find(p =>
p.type === 'chat' && p.payload.conversation_id === payload.conversation_id
);
if (pendingMsg) {
pendingMsg.resolve(payload);
this.removePendingMessage(pendingMsg.id);
}
}
private handleMessageRecalled(payload: any): void {
const pendingMsg = this.pendingMessages.find(p =>
p.type === 'recall' && p.payload.message_id === payload.message_id
);
if (pendingMsg) {
pendingMsg.resolve(payload);
this.removePendingMessage(pendingMsg.id);
}
}
// 发送消息支持降级到HTTP
async sendMessage(
conversationId: string,
detailType: 'private' | 'group',
segments: MessageSegment[],
replyToId?: string
): Promise<any> {
const payload = {
conversation_id: conversationId,
detail_type: detailType,
segments,
reply_to_id: replyToId,
};
// 如果WebSocket连接正常优先使用WebSocket发送
if (this.isConnected() && !this.isFallbackMode) {
return this.sendViaWebSocket('chat', payload);
}
// 降级到HTTP发送
return this.sendViaHTTP(conversationId, detailType, segments, replyToId);
}
// 标记已读
async markRead(conversationId: string, seq: number): Promise<void> {
const payload = {
conversation_id: conversationId,
seq,
};
if (this.isConnected() && !this.isFallbackMode) {
this.sendViaWebSocket('read', payload).catch(() => {});
}
// 已读不需要等待响应,失败也不影响
}
// 发送输入状态
sendTyping(conversationId: string, isTyping: boolean): void {
const payload = {
conversation_id: conversationId,
is_typing: isTyping,
};
if (this.isConnected() && !this.isFallbackMode) {
this.sendViaWebSocket('typing', payload).catch(() => {});
}
}
// 撤回消息
async recallMessage(messageId: string): Promise<any> {
const payload = { message_id: messageId };
if (this.isConnected() && !this.isFallbackMode) {
return this.sendViaWebSocket('recall', payload);
}
// 降级到HTTP
const { api } = await import('./api');
return api.post('/messages/delete_msg', { message_id: messageId });
}
// 通过WebSocket发送
private sendViaWebSocket(type: string, payload: any): Promise<any> {
return new Promise((resolve, reject) => {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
reject(new Error('WebSocket not connected'));
return;
}
const messageId = `msg_${++this.messageIdCounter}_${Date.now()}`;
const message = {
type,
payload,
};
// 添加到待处理队列
const pendingMsg: PendingMessage = {
id: messageId,
type,
payload,
resolve,
reject,
timestamp: Date.now(),
};
this.pendingMessages.push(pendingMsg);
// 发送消息
this.ws.send(JSON.stringify(message));
// 设置超时
setTimeout(() => {
const index = this.pendingMessages.findIndex(p => p.id === messageId);
if (index >= 0) {
this.pendingMessages[index].reject(new Error('Message timeout'));
this.removePendingMessage(messageId);
}
}, 10000);
});
}
// 通过HTTP发送降级方案
private async sendViaHTTP(
conversationId: string,
detailType: 'private' | 'group',
segments: MessageSegment[],
replyToId?: string
): Promise<any> {
const { api } = await import('./api');
const body: any = {
detail_type: detailType,
segments,
};
if (replyToId) {
body.reply_to_id = replyToId;
}
return api.post(`/conversations/${conversationId}/messages`, body);
}
// 刷新待发送消息队列
private flushPendingMessages(): void {
if (this.pendingMessages.length === 0) return;
const now = Date.now();
const expiredMessages: PendingMessage[] = [];
const validMessages: PendingMessage[] = [];
// 分离过期和有效的消息
for (const msg of this.pendingMessages) {
if (now - msg.timestamp > 30000) {
expiredMessages.push(msg);
} else {
validMessages.push(msg);
}
}
// 拒绝过期消息
expiredMessages.forEach(msg => {
msg.reject(new Error('Message expired'));
});
// 重新发送有效消息
this.pendingMessages = [];
validMessages.forEach(msg => {
this.sendViaWebSocket(msg.type, msg.payload)
.then(msg.resolve)
.catch(msg.reject);
});
}
private removePendingMessage(id: string): void {
const index = this.pendingMessages.findIndex(p => p.id === id);
if (index >= 0) {
this.pendingMessages.splice(index, 1);
}
}
disconnect(): void {
this.shouldRun = false;
this.connected = false;
this.isConnecting = false;
this.isFallbackMode = false;
if (this.ws) {
this.ws.close();
this.ws = null;
}
this.stopHeartbeat();
this.stopReconnect();
this.stopFallbackCheck();
// 拒绝所有待处理消息
this.pendingMessages.forEach(msg => {
msg.reject(new Error('WebSocket disconnected'));
});
this.pendingMessages = [];
}
private scheduleReconnect(): void {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
// 超过最大重试次数,进入降级模式
this.enterFallbackMode();
return;
}
this.stopReconnect();
console.log(`[WebSocket] Reconnecting in ${this.reconnectDelay}ms (attempt ${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`);
this.reconnectTimer = setTimeout(() => {
this.reconnectAttempts += 1;
this.connect();
}, this.reconnectDelay);
}
private stopReconnect() {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
}
isConnected(): boolean {
return this.connected && this.ws?.readyState === WebSocket.OPEN;
}
isInFallbackMode(): boolean {
return this.isFallbackMode;
}
// 进入降级模式
private enterFallbackMode(): void {
if (this.isFallbackMode) return;
this.isFallbackMode = true;
console.log('WebSocket entering fallback mode, using HTTP API');
// 启动降级模式检查定时器定期尝试重连WebSocket
this.startFallbackCheck();
}
// 启动降级模式检查
private startFallbackCheck(): void {
this.stopFallbackCheck();
this.fallbackCheckTimer = setInterval(() => {
if (!this.isConnected()) {
this.reconnectAttempts = 0;
this.connect();
}
}, 30000); // 每30秒尝试重连
}
private stopFallbackCheck(): void {
if (this.fallbackCheckTimer) {
clearInterval(this.fallbackCheckTimer);
this.fallbackCheckTimer = null;
}
}
private emit<T extends WSMessageType>(type: T, message: Extract<WSMessage, { type: T }>) {
const handlers = this.messageHandlers.get(type) || [];
handlers.forEach(h => h(message as WSMessage));
}
on<T extends WSMessageType>(type: T, handler: MessageHandler<Extract<WSMessage, { type: T }>>): () => void {
const list = this.messageHandlers.get(type) || [];
list.push(handler as MessageHandler);
this.messageHandlers.set(type, list);
return () => {
const current = this.messageHandlers.get(type) || [];
const idx = current.indexOf(handler as MessageHandler);
if (idx >= 0) current.splice(idx, 1);
};
}
onConnect(handler: ConnectionHandler): () => void {
this.connectionHandlers.push(handler);
return () => {
const i = this.connectionHandlers.indexOf(handler);
if (i >= 0) this.connectionHandlers.splice(i, 1);
};
}
onDisconnect(handler: ConnectionHandler): () => void {
this.disconnectionHandlers.push(handler);
return () => {
const i = this.disconnectionHandlers.indexOf(handler);
if (i >= 0) this.disconnectionHandlers.splice(i, 1);
};
}
private setupAppStateListener(): void {
if (this.appStateSubscription) return;
this.lastAppState = AppState.currentState;
this.appStateSubscription = AppState.addEventListener('change', (nextState: AppStateStatus) => {
if (this.lastAppState.match(/inactive|background/) && nextState === 'active' && !this.isConnected()) {
this.reconnectAttempts = 0;
this.connect();
}
this.lastAppState = nextState;
});
}
async start(): Promise<boolean> {
this.setupAppStateListener();
return this.connect();
}
stop(): void {
if (this.appStateSubscription) {
this.appStateSubscription.remove();
this.appStateSubscription = null;
}
this.disconnect();
}
private markActivity(): void {
this.lastActivityAt = Date.now();
}
private startHeartbeat(): void {
this.stopHeartbeat();
this.heartbeatTimer = setInterval(() => {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ type: 'ping' }));
}
}, this.heartbeatInterval);
}
private stopHeartbeat(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
private handleDisconnected(): void {
// 防止重复调用
if (!this.connected && !this.ws && !this.isConnecting) {
console.log('[WebSocket] Already disconnected, ignoring');
return;
}
console.log('[WebSocket] Handling disconnect...');
const wasActive = this.connected || this.ws != null || this.isConnecting;
this.isConnecting = false;
this.connected = false;
if (this.ws) {
this.ws.close();
this.ws = null;
}
this.stopHeartbeat();
if (wasActive) {
this.disconnectionHandlers.forEach(h => h());
}
if (this.shouldRun) {
this.scheduleReconnect();
} else {
console.log('[WebSocket] shouldRun is false, not reconnecting');
}
}
}
export const wsService = new WebSocketService();

View File

@@ -14,7 +14,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage';
import { create } from 'zustand';
import { User } from '../types';
import { authService, resolveAuthApiError, LoginRequest, RegisterRequest } from '../services';
import { wsService } from '../services/wsService';
import { sseService } from '../services/sseService';
import {
initDatabase,
closeDatabase,
@@ -95,7 +95,7 @@ function resolveLoginError(error: any): string {
// ── 启动 SSE 实时服务 ──
async function startRealtime(): Promise<void> {
try {
await wsService.start();
await sseService.start();
} catch (error) {
console.error('[AuthStore] 启动 SSE 服务失败:', error);
}
@@ -212,7 +212,7 @@ export const useAuthStore = create<AuthState>((set) => ({
// 1. 通知服务端Token 清理在 authService 内部完成)
await authService.logout();
// 2. 停止 SSE
wsService.stop();
sseService.stop();
// 3. 清除 DB 中的用户缓存DB 此时一定已初始化)
await clearCurrentUserCache().catch(() => {});
// 4. 关闭数据库连接

View File

@@ -1,127 +0,0 @@
/**
* BaseManager - 通用 Manager 基类
*
* 提取自 postManager/groupManager/userManager 的重复逻辑:
* - 请求去重 (dedupe)
* - 缓存条目管理 (CacheEntry)
* - 过期检查 (isExpired)
*/
import { CacheBus, CacheEvent } from './cacheBus';
/** 缓存条目结构 */
export interface CacheEntry<T> {
data: T;
timestamp: number;
ttl: number;
}
/** 创建缓存条目 */
export function createCacheEntry<T>(data: T, ttl: number): CacheEntry<T> {
return { data, timestamp: Date.now(), ttl };
}
/** 检查缓存是否过期 */
export function isCacheExpired(entry: CacheEntry<any>): boolean {
return Date.now() - entry.timestamp > entry.ttl;
}
/**
* 通用 Manager 基类
*
* 子类只需关注业务逻辑,无需重复实现缓存和去重机制
*/
export abstract class BaseManager<
TSnapshot,
TEvent extends CacheEvent = CacheEvent
> extends CacheBus<TSnapshot, TEvent> {
/** 待处理请求 Map用于去重 */
protected pendingRequests = new Map<string, Promise<any>>();
/**
* 请求去重:相同 key 的并发请求会被合并为一个
* @param key 唯一标识
* @param fetcher 实际请求函数
*/
protected async dedupe<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
const pending = this.pendingRequests.get(key) as Promise<T> | undefined;
if (pending) return pending;
const request = fetcher().finally(() => {
this.pendingRequests.delete(key);
});
this.pendingRequests.set(key, request);
return request;
}
/** 清除所有待处理请求 */
protected clearPendingRequests(): void {
this.pendingRequests.clear();
}
}
/**
* 带缓存的 Manager 基类
*
* 进一步封装内存缓存逻辑
*/
export abstract class CachedManager<
TSnapshot,
TEvent extends CacheEvent = CacheEvent
> extends BaseManager<TSnapshot, TEvent> {
/** 内存缓存 Map */
protected memoryCache = new Map<string, CacheEntry<any>>();
/**
* 获取缓存
* @param key 缓存 key
* @returns 缓存数据,过期或不存在返回 null
*/
protected getFromCache<T>(key: string): T | null {
const entry = this.memoryCache.get(key) as CacheEntry<T> | undefined;
if (!entry) return null;
if (isCacheExpired(entry)) {
this.memoryCache.delete(key);
return null;
}
return entry.data;
}
/**
* 设置缓存
* @param key 缓存 key
* @param data 数据
* @param ttl 过期时间(毫秒)
*/
protected setCache<T>(key: string, data: T, ttl: number): void {
this.memoryCache.set(key, createCacheEntry(data, ttl));
}
/**
* 检查缓存是否存在且未过期
*/
protected hasValidCache(key: string): boolean {
const entry = this.memoryCache.get(key);
if (!entry) return false;
return !isCacheExpired(entry);
}
/**
* 检查缓存是否存在但已过期
*/
protected hasExpiredCache(key: string): boolean {
const entry = this.memoryCache.get(key);
if (!entry) return false;
return isCacheExpired(entry);
}
/** 清除所有缓存 */
protected clearCache(): void {
this.memoryCache.clear();
}
/** 清除指定 key 的缓存 */
protected deleteCache(key: string): void {
this.memoryCache.delete(key);
}
}

View File

@@ -1,301 +0,0 @@
/**
* 群组列表数据源抽象游标、偏移分页实现同一契约GroupManager 只依赖接口。
*/
import {
GroupResponse,
GroupMemberResponse,
GroupListResponse,
GroupMemberListResponse,
CursorPaginationRequest,
} from '../types/dto';
import { groupService } from '../services/groupService';
import { getAllGroupsCache, getGroupMembersCache } from '../services/database';
export const GROUP_LIST_PAGE_SIZE = 20;
export const GROUP_MEMBER_LIST_PAGE_SIZE = 50;
// ==================== 群组列表数据源 ====================
/** 单次拉取结果(一页或一批) */
export interface GroupListPage {
items: GroupResponse[];
/** 在当前源上是否还能再 loadNext 一页 */
hasMore: boolean;
}
/**
* 分页式群组列表源restart 后开始新序列;首次 loadNext 为第一页,之后为后续页。
*/
export interface IGroupListPagedSource {
restart(): void;
loadNext(): Promise<GroupListPage>;
/** 至少成功 loadNext 过一次且仍有下一页时为 true */
readonly hasMore: boolean;
}
/**
* 远端群组列表(游标分页)
*/
export class NetworkCursorGroupListPagedSource implements IGroupListPagedSource {
private nextCursor: string | null = null;
private hasMoreAfterLastLoad = false;
private loadedOnce = false;
private readonly pageSize: number;
constructor(pageSize: number = GROUP_LIST_PAGE_SIZE) {
this.pageSize = pageSize;
}
restart(): void {
this.nextCursor = null;
this.hasMoreAfterLastLoad = false;
this.loadedOnce = false;
}
get hasMore(): boolean {
return this.loadedOnce && this.hasMoreAfterLastLoad;
}
async loadNext(): Promise<GroupListPage> {
const params: CursorPaginationRequest = {
cursor: this.nextCursor ?? '',
page_size: this.pageSize,
};
const result = await groupService.getGroupsCursor(params);
this.hasMoreAfterLastLoad = result.has_more ?? false;
this.nextCursor = result.next_cursor ?? null;
this.loadedOnce = true;
return { items: result.list ?? [], hasMore: this.hasMoreAfterLastLoad };
}
}
/**
* 远端群组列表(偏移分页)
*/
export class NetworkOffsetGroupListPagedSource implements IGroupListPagedSource {
private nextPage = 1;
private hasMoreAfterLastLoad = false;
private loadedOnce = false;
private readonly pageSize: number;
constructor(pageSize: number = GROUP_LIST_PAGE_SIZE) {
this.pageSize = pageSize;
}
restart(): void {
this.nextPage = 1;
this.hasMoreAfterLastLoad = false;
this.loadedOnce = false;
}
get hasMore(): boolean {
return this.loadedOnce && this.hasMoreAfterLastLoad;
}
async loadNext(): Promise<GroupListPage> {
const result = await groupService.getGroups(this.nextPage, this.pageSize);
const items = result.list ?? [];
const totalPages = result.total_pages ?? 1;
this.hasMoreAfterLastLoad = this.nextPage < totalPages;
this.nextPage++;
this.loadedOnce = true;
return { items, hasMore: this.hasMoreAfterLastLoad };
}
}
/**
* SQLite 群组列表缓存(单批,无后续页)
*/
export class SqliteGroupListPagedSource implements IGroupListPagedSource {
private consumed = false;
restart(): void {
this.consumed = false;
}
get hasMore(): boolean {
return false;
}
async loadNext(): Promise<GroupListPage> {
if (this.consumed) {
return { items: [], hasMore: false };
}
this.consumed = true;
try {
const items = await getAllGroupsCache();
return { items, hasMore: false };
} catch (e) {
console.warn('[SqliteGroupListPagedSource] 读取群组列表缓存失败:', e);
return { items: [], hasMore: false };
}
}
}
// ==================== 群组成员列表数据源 ====================
/** 成员列表单次拉取结果 */
export interface GroupMemberListPage {
items: GroupMemberResponse[];
hasMore: boolean;
}
/**
* 分页式群组成员列表源
*/
export interface IGroupMemberListPagedSource {
restart(): void;
loadNext(): Promise<GroupMemberListPage>;
readonly hasMore: boolean;
}
/**
* 远端群组成员列表(游标分页)
*/
export class NetworkCursorGroupMemberListPagedSource implements IGroupMemberListPagedSource {
private nextCursor: string | null = null;
private hasMoreAfterLastLoad = false;
private loadedOnce = false;
private readonly pageSize: number;
private readonly groupId: string;
constructor(groupId: string, pageSize: number = GROUP_MEMBER_LIST_PAGE_SIZE) {
this.groupId = groupId;
this.pageSize = pageSize;
}
restart(): void {
this.nextCursor = null;
this.hasMoreAfterLastLoad = false;
this.loadedOnce = false;
}
get hasMore(): boolean {
return this.loadedOnce && this.hasMoreAfterLastLoad;
}
async loadNext(): Promise<GroupMemberListPage> {
const params: CursorPaginationRequest = {
cursor: this.nextCursor ?? '',
page_size: this.pageSize,
};
const result = await groupService.getGroupMembersCursor(this.groupId, params);
this.hasMoreAfterLastLoad = result.has_more ?? false;
this.nextCursor = result.next_cursor ?? null;
this.loadedOnce = true;
return { items: result.list ?? [], hasMore: this.hasMoreAfterLastLoad };
}
}
/**
* 远端群组成员列表(偏移分页)
*/
export class NetworkOffsetGroupMemberListPagedSource implements IGroupMemberListPagedSource {
private nextPage = 1;
private hasMoreAfterLastLoad = false;
private loadedOnce = false;
private readonly pageSize: number;
private readonly groupId: string;
constructor(groupId: string, pageSize: number = GROUP_MEMBER_LIST_PAGE_SIZE) {
this.groupId = groupId;
this.pageSize = pageSize;
}
restart(): void {
this.nextPage = 1;
this.hasMoreAfterLastLoad = false;
this.loadedOnce = false;
}
get hasMore(): boolean {
return this.loadedOnce && this.hasMoreAfterLastLoad;
}
async loadNext(): Promise<GroupMemberListPage> {
const result = await groupService.getMembers(
this.groupId,
this.nextPage,
this.pageSize
);
const items = result.list ?? [];
const totalPages = result.total_pages ?? 1;
this.hasMoreAfterLastLoad = this.nextPage < totalPages;
this.nextPage++;
this.loadedOnce = true;
return { items, hasMore: this.hasMoreAfterLastLoad };
}
}
/**
* SQLite 群组成员列表缓存(单批,无后续页)
*/
export class SqliteGroupMemberListPagedSource implements IGroupMemberListPagedSource {
private consumed = false;
private readonly groupId: string;
constructor(groupId: string) {
this.groupId = groupId;
}
restart(): void {
this.consumed = false;
}
get hasMore(): boolean {
return false;
}
async loadNext(): Promise<GroupMemberListPage> {
if (this.consumed) {
return { items: [], hasMore: false };
}
this.consumed = true;
try {
const items = await getGroupMembersCache(this.groupId);
return { items, hasMore: false };
} catch (e) {
console.warn('[SqliteGroupMemberListPagedSource] 读取成员列表缓存失败:', e);
return { items: [], hasMore: false };
}
}
}
// ==================== 工厂函数 ====================
/** 远端群组列表分页策略 */
export type RemoteGroupListSourceKind = 'cursor' | 'offset';
export function createRemoteGroupListSource(
kind: RemoteGroupListSourceKind = 'cursor',
pageSize: number = GROUP_LIST_PAGE_SIZE
): IGroupListPagedSource {
if (kind === 'offset') {
return new NetworkOffsetGroupListPagedSource(pageSize);
}
return new NetworkCursorGroupListPagedSource(pageSize);
}
export function createRemoteGroupMemberListSource(
groupId: string,
kind: RemoteGroupListSourceKind = 'cursor',
pageSize: number = GROUP_MEMBER_LIST_PAGE_SIZE
): IGroupMemberListPagedSource {
if (kind === 'offset') {
return new NetworkOffsetGroupMemberListPagedSource(groupId, pageSize);
}
return new NetworkCursorGroupMemberListPagedSource(groupId, pageSize);
}

View File

@@ -1,11 +1,3 @@
/**
* GroupManager - 群组管理核心模块
*
* 架构特点:
* - 使用 CachedManager 基类,消除重复的缓存/去重逻辑
* - 支持 Sources 模式进行分页加载
*/
import {
GroupListResponse,
GroupMemberListResponse,
@@ -22,19 +14,7 @@ import {
saveGroupsCache,
saveUsersCache,
} from '../services/database';
import { CacheEvent } from './cacheBus';
import { CachedManager, CacheEntry, createCacheEntry, isCacheExpired } from './baseManager';
import {
IGroupListPagedSource,
IGroupMemberListPagedSource,
createRemoteGroupListSource,
createRemoteGroupMemberListSource,
RemoteGroupListSourceKind,
GROUP_LIST_PAGE_SIZE,
GROUP_MEMBER_LIST_PAGE_SIZE,
} from './groupListSources';
// ==================== 类型定义 ====================
import { CacheBus, CacheEvent } from './cacheBus';
interface GroupManagerSnapshot {
groupIds: string[];
@@ -48,18 +28,20 @@ type GroupManagerEvent =
| CacheEvent<GroupManagerSnapshot>
| CacheEvent<{ error: unknown; context: string }>;
// ==================== 常量 ====================
const GROUP_TTL = 60 * 1000;
const MEMBERS_TTL = 120 * 1000;
// ==================== Manager 实现 ====================
interface CacheEntry<T> {
data: T;
timestamp: number;
ttl: number;
}
class GroupManager extends CachedManager<GroupManagerSnapshot, GroupManagerEvent> {
/** 群组详情缓存 */
class GroupManager extends CacheBus<GroupManagerSnapshot, GroupManagerEvent> {
private groupsListCache: CacheEntry<GroupResponse[]> | null = null;
private groupDetailCache = new Map<string, CacheEntry<GroupResponse | null>>();
/** 群组成员缓存 */
private groupMembersCache = new Map<string, CacheEntry<GroupMemberResponse[]>>();
private pendingRequests = new Map<string, Promise<any>>();
protected getSnapshot(): GroupManagerSnapshot {
return {
@@ -68,48 +50,67 @@ class GroupManager extends CachedManager<GroupManagerSnapshot, GroupManagerEvent
};
}
// ==================== 群组列表相关 ====================
private isExpired(entry: CacheEntry<any>): boolean {
return Date.now() - entry.timestamp > entry.ttl;
}
/**
* 获取群组列表
*/
async getGroups(page = 1, pageSize = GROUP_LIST_PAGE_SIZE, forceRefresh = false): Promise<GroupListResponse> {
const key = `list:${page}:${pageSize}`;
private async dedupe<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
const pending = this.pendingRequests.get(key) as Promise<T> | undefined;
if (pending) return pending;
const request = fetcher().finally(() => {
this.pendingRequests.delete(key);
});
this.pendingRequests.set(key, request);
return request;
}
// 第一页且有有效缓存
if (page === 1 && !forceRefresh && this.hasValidCache(key)) {
const groups = this.getFromCache<GroupResponse[]>(key)!;
return this.buildGroupListResponse(groups, pageSize);
async getGroups(page = 1, pageSize = 20, forceRefresh = false): Promise<GroupListResponse> {
if (page === 1 && !forceRefresh && this.groupsListCache && !this.isExpired(this.groupsListCache)) {
return {
list: this.groupsListCache.data,
total: this.groupsListCache.data.length,
page: 1,
page_size: pageSize,
total_pages: 1,
};
}
// 第一页且缓存过期:后台刷新
if (page === 1 && !forceRefresh && this.hasExpiredCache(key)) {
if (page === 1 && !forceRefresh && this.groupsListCache && this.isExpired(this.groupsListCache)) {
this.refreshGroupsInBackground(page, pageSize);
const groups = this.getFromCache<GroupResponse[]>(key)!;
return this.buildGroupListResponse(groups, pageSize);
return {
list: this.groupsListCache.data,
total: this.groupsListCache.data.length,
page: 1,
page_size: pageSize,
total_pages: 1,
};
}
// 第一页:尝试本地缓存
if (page === 1 && !forceRefresh) {
const localGroups = await getAllGroupsCache();
if (localGroups.length > 0) {
this.setCache(key, localGroups, GROUP_TTL);
this.groupsListCache = { data: localGroups, timestamp: Date.now(), ttl: GROUP_TTL };
this.notify({
type: 'list_updated',
payload: { groups: localGroups },
timestamp: Date.now(),
});
this.refreshGroupsInBackground(page, pageSize);
return this.buildGroupListResponse(localGroups, pageSize);
return {
list: localGroups,
total: localGroups.length,
page: 1,
page_size: pageSize,
total_pages: 1,
};
}
}
// 发起请求
return this.dedupe(`groups:list:${page}:${pageSize}`, async () => {
const response = await groupService.getGroups(page, pageSize);
const response = await groupService.fetchGroupsFromApi(page, pageSize);
const groups = response.list || [];
if (page === 1) {
this.setCache(key, groups, GROUP_TTL);
this.groupsListCache = { data: groups, timestamp: Date.now(), ttl: GROUP_TTL };
}
await saveGroupsCache(groups).catch(() => {});
this.notify({
@@ -121,23 +122,12 @@ class GroupManager extends CachedManager<GroupManagerSnapshot, GroupManagerEvent
});
}
private buildGroupListResponse(groups: GroupResponse[], pageSize: number): GroupListResponse {
return {
list: groups,
total: groups.length,
page: 1,
page_size: pageSize,
total_pages: 1,
};
}
private refreshGroupsInBackground(page = 1, pageSize = GROUP_LIST_PAGE_SIZE): void {
const key = `list:${page}:${pageSize}`;
this.dedupe(`groups:bg:${key}`, async () => {
const response = await groupService.getGroups(page, pageSize);
private refreshGroupsInBackground(page = 1, pageSize = 20): void {
this.dedupe(`groups:list:bg:${page}:${pageSize}`, async () => {
const response = await groupService.fetchGroupsFromApi(page, pageSize);
const groups = response.list || [];
if (page === 1) {
this.setCache(key, groups, GROUP_TTL);
this.groupsListCache = { data: groups, timestamp: Date.now(), ttl: GROUP_TTL };
saveGroupsCache(groups).catch(() => {});
}
this.notify({
@@ -155,58 +145,39 @@ class GroupManager extends CachedManager<GroupManagerSnapshot, GroupManagerEvent
});
}
/**
* 创建群组列表数据源(用于 Sources 模式)
*/
createGroupListSource(
kind: RemoteGroupListSourceKind = 'cursor',
pageSize: number = GROUP_LIST_PAGE_SIZE
): IGroupListPagedSource {
return createRemoteGroupListSource(kind, pageSize);
}
// ==================== 群组详情相关 ====================
/**
* 获取群组详情
*/
async getGroup(groupId: string, forceRefresh = false): Promise<GroupResponse> {
const cached = this.groupDetailCache.get(groupId);
// 有效缓存
if (!forceRefresh && cached && !isCacheExpired(cached) && cached.data) {
const id = groupId;
const cached = this.groupDetailCache.get(id);
if (!forceRefresh && cached && !this.isExpired(cached) && cached.data) {
return cached.data;
}
// 过期缓存:后台刷新
if (!forceRefresh && cached && isCacheExpired(cached) && cached.data) {
this.refreshGroupInBackground(groupId);
if (!forceRefresh && cached && this.isExpired(cached) && cached.data) {
this.refreshGroupInBackground(id);
return cached.data;
}
// 尝试本地缓存
if (!forceRefresh) {
const localGroup = await getGroupCache(groupId);
const localGroup = await getGroupCache(id);
if (localGroup) {
this.groupDetailCache.set(groupId, createCacheEntry(localGroup, GROUP_TTL));
this.groupDetailCache.set(id, { data: localGroup, timestamp: Date.now(), ttl: GROUP_TTL });
this.notify({
type: 'detail_updated',
payload: { groupId, group: localGroup },
payload: { groupId: id, group: localGroup },
timestamp: Date.now(),
});
this.refreshGroupInBackground(groupId);
this.refreshGroupInBackground(id);
return localGroup;
}
}
// 发起请求
return this.dedupe(`groups:detail:${groupId}`, async () => {
const group = await groupService.getGroup(groupId);
this.groupDetailCache.set(groupId, createCacheEntry(group, GROUP_TTL));
return this.dedupe(`groups:detail:${id}`, async () => {
const group = await groupService.fetchGroupFromApi(id);
this.groupDetailCache.set(id, { data: group, timestamp: Date.now(), ttl: GROUP_TTL });
await saveGroupCache(group).catch(() => {});
this.notify({
type: 'detail_updated',
payload: { groupId, group },
payload: { groupId: id, group },
timestamp: Date.now(),
});
return group;
@@ -215,8 +186,8 @@ class GroupManager extends CachedManager<GroupManagerSnapshot, GroupManagerEvent
private refreshGroupInBackground(groupId: string): void {
this.dedupe(`groups:detail:bg:${groupId}`, async () => {
const group = await groupService.getGroup(groupId);
this.groupDetailCache.set(groupId, createCacheEntry(group, GROUP_TTL));
const group = await groupService.fetchGroupFromApi(groupId);
this.groupDetailCache.set(groupId, { data: group, timestamp: Date.now(), ttl: GROUP_TTL });
saveGroupCache(group).catch(() => {});
this.notify({
type: 'detail_updated',
@@ -233,53 +204,61 @@ class GroupManager extends CachedManager<GroupManagerSnapshot, GroupManagerEvent
});
}
// ==================== 群组成员相关 ====================
/**
* 获取群组成员列表
*/
async getMembers(
groupId: string,
page = 1,
pageSize = GROUP_MEMBER_LIST_PAGE_SIZE,
forceRefresh = false
): Promise<GroupMemberListResponse> {
const key = `members:${groupId}:${page}:${pageSize}`;
async getMembers(groupId: string, page = 1, pageSize = 50, forceRefresh = false): Promise<GroupMemberListResponse> {
const id = groupId;
const key = `${id}:${page}:${pageSize}`;
const cached = this.groupMembersCache.get(key);
// 有效缓存
if (!forceRefresh && cached && !isCacheExpired(cached)) {
return this.buildMemberListResponse(cached.data, page, pageSize);
if (!forceRefresh && cached && !this.isExpired(cached)) {
return {
list: cached.data,
total: cached.data.length,
page,
page_size: pageSize,
total_pages: 1,
};
}
// 过期缓存:后台刷新
if (!forceRefresh && cached && isCacheExpired(cached)) {
this.refreshMembersInBackground(groupId, page, pageSize);
return this.buildMemberListResponse(cached.data, page, pageSize);
if (!forceRefresh && cached && this.isExpired(cached)) {
this.refreshMembersInBackground(id, page, pageSize);
return {
list: cached.data,
total: cached.data.length,
page,
page_size: pageSize,
total_pages: 1,
};
}
// 第一页:尝试本地缓存
if (page === 1 && !forceRefresh) {
const localMembers = await getGroupMembersCache(groupId);
const localMembers = await getGroupMembersCache(id);
if (localMembers.length > 0) {
this.groupMembersCache.set(key, createCacheEntry(localMembers, MEMBERS_TTL));
this.groupMembersCache.set(key, {
data: localMembers,
timestamp: Date.now(),
ttl: MEMBERS_TTL,
});
this.notify({
type: 'detail_updated',
payload: { groupId, members: localMembers },
payload: { groupId: id, members: localMembers },
timestamp: Date.now(),
});
this.refreshMembersInBackground(groupId, page, pageSize);
return this.buildMemberListResponse(localMembers, page, pageSize);
this.refreshMembersInBackground(id, page, pageSize);
return {
list: localMembers,
total: localMembers.length,
page,
page_size: pageSize,
total_pages: 1,
};
}
}
// 发起请求
return this.dedupe(`groups:members:${key}`, async () => {
const response = await groupService.getMembers(groupId, page, pageSize);
const response = await groupService.fetchMembersFromApi(id, page, pageSize);
const members = response.list || [];
this.groupMembersCache.set(key, createCacheEntry(members, MEMBERS_TTL));
this.groupMembersCache.set(key, { data: members, timestamp: Date.now(), ttl: MEMBERS_TTL });
if (page === 1) {
await saveGroupMembersCache(groupId, members).catch(() => {});
await saveGroupMembersCache(id, members).catch(() => {});
}
await saveUsersCache(
members
@@ -288,37 +267,19 @@ class GroupManager extends CachedManager<GroupManagerSnapshot, GroupManagerEvent
).catch(() => {});
this.notify({
type: 'detail_updated',
payload: { groupId, members },
payload: { groupId: id, members },
timestamp: Date.now(),
});
return response;
});
}
private buildMemberListResponse(
members: GroupMemberResponse[],
page: number,
pageSize: number
): GroupMemberListResponse {
return {
list: members,
total: members.length,
page,
page_size: pageSize,
total_pages: 1,
};
}
private refreshMembersInBackground(
groupId: string,
page = 1,
pageSize = GROUP_MEMBER_LIST_PAGE_SIZE
): void {
const key = `members:${groupId}:${page}:${pageSize}`;
this.dedupe(`groups:members:bg:${key}`, async () => {
const response = await groupService.getMembers(groupId, page, pageSize);
private refreshMembersInBackground(groupId: string, page = 1, pageSize = 50): void {
this.dedupe(`groups:members:bg:${groupId}:${page}:${pageSize}`, async () => {
const response = await groupService.fetchMembersFromApi(groupId, page, pageSize);
const members = response.list || [];
this.groupMembersCache.set(key, createCacheEntry(members, MEMBERS_TTL));
const key = `${groupId}:${page}:${pageSize}`;
this.groupMembersCache.set(key, { data: members, timestamp: Date.now(), ttl: MEMBERS_TTL });
if (page === 1) {
saveGroupMembersCache(groupId, members).catch(() => {});
}
@@ -342,46 +303,21 @@ class GroupManager extends CachedManager<GroupManagerSnapshot, GroupManagerEvent
});
}
/**
* 创建群组成员列表数据源(用于 Sources 模式)
*/
createGroupMemberListSource(
groupId: string,
kind: RemoteGroupListSourceKind = 'cursor',
pageSize: number = GROUP_MEMBER_LIST_PAGE_SIZE
): IGroupMemberListPagedSource {
return createRemoteGroupMemberListSource(groupId, kind, pageSize);
}
// ==================== 缓存管理 ====================
/**
* 使缓存失效
*/
invalidate(groupId?: string): void {
if (!groupId) {
this.clearCache();
this.groupsListCache = null;
this.groupDetailCache.clear();
this.groupMembersCache.clear();
return;
}
this.groupDetailCache.delete(groupId);
[...this.groupMembersCache.keys()].forEach((key) => {
if (key.startsWith(`members:${groupId}:`)) {
if (key.startsWith(`${groupId}:`)) {
this.groupMembersCache.delete(key);
}
});
}
/**
* 清除所有数据
*/
clear(): void {
this.clearCache();
this.groupDetailCache.clear();
this.groupMembersCache.clear();
this.clearPendingRequests();
}
}
export const groupManager = new GroupManager();

View File

@@ -1,13 +0,0 @@
import { create } from 'zustand';
interface HomeTabPressState {
/** 用于触发首页回到顶部的事件计数器 */
pressCount: number;
/** 触发首页 Tab 点击事件 */
triggerPress: () => void;
}
export const useHomeTabPressStore = create<HomeTabPressState>((set) => ({
pressCount: 0,
triggerPress: () => set((state) => ({ pressCount: state.pressCount + 1 })),
}));

View File

@@ -44,9 +44,6 @@ export { userManager } from './userManager';
export {
useHomeTabBarVisibilityStore,
} from './homeTabBarVisibilityStore';
export {
useHomeTabPressStore,
} from './homeTabPressStore';
export {
useAppColors,
useThemePreference,

View File

@@ -4,7 +4,7 @@
*/
import { messageStateManager, MessageStateManager } from './MessageStateManager';
import { wsMessageHandler, WSMessageHandler } from './WSMessageHandler';
import { sseMessageHandler, SSEMessageHandler } from './SSEMessageHandler';
import { messageSyncService, MessageSyncService } from './MessageSyncService';
import { readReceiptManager, ReadReceiptManager } from './ReadReceiptManager';
import { messageRepository } from '../../data/repositories/MessageRepository';
@@ -20,23 +20,23 @@ export type {
export class MessageManager {
private stateManager: MessageStateManager;
private wsHandler: WSMessageHandler;
private sseHandler: SSEMessageHandler;
private syncService: MessageSyncService;
private readManager: ReadReceiptManager;
private initialized: boolean = false;
private authUnsubscribe: (() => void) | null = null;
private wsUnsubscribe: (() => void) | null = null;
private sseUnsubscribe: (() => void) | null = null;
private currentUserId: string | null = null;
constructor() {
this.stateManager = messageStateManager;
this.wsHandler = wsMessageHandler;
this.sseHandler = sseMessageHandler;
this.syncService = messageSyncService;
this.readManager = readReceiptManager;
this.readManager.setStateManager(this.stateManager);
this.setupWSHandlers();
this.setupSSEHandlers();
this.initAuthListener();
}
@@ -58,8 +58,8 @@ export class MessageManager {
});
}
private setupWSHandlers(): void {
this.wsUnsubscribe = this.wsHandler.subscribe((event) => {
private setupSSEHandlers(): void {
this.sseUnsubscribe = this.sseHandler.subscribe((event) => {
switch (event.type) {
case 'chat_message':
case 'group_message':
@@ -89,7 +89,7 @@ export class MessageManager {
try {
console.log('[MessageManager] Initializing...');
this.wsHandler.connect();
this.sseHandler.connect();
const conversations = await this.syncService.syncConversations();
this.stateManager.setConversations(conversations);
@@ -224,14 +224,14 @@ export class MessageManager {
}
isConnected(): boolean {
return this.wsHandler.isConnected();
return this.sseHandler.isConnected();
}
reset(): void {
this.initialized = false;
this.stateManager.reset();
this.readManager.reset();
this.wsHandler.disconnect();
this.sseHandler.disconnect();
}
destroy(): void {
@@ -239,9 +239,9 @@ export class MessageManager {
this.authUnsubscribe();
this.authUnsubscribe = null;
}
if (this.wsUnsubscribe) {
this.wsUnsubscribe();
this.wsUnsubscribe = null;
if (this.sseUnsubscribe) {
this.sseUnsubscribe();
this.sseUnsubscribe = null;
}
this.reset();
}

View File

@@ -1,12 +1,12 @@
/**
* WS
* WS
* SSE
* SSE
*/
import { wsService, WSChatMessage, WSGroupChatMessage, WSReadMessage, WSGroupReadMessage, WSRecallMessage, WSGroupRecallMessage, WSGroupTypingMessage, WSGroupNoticeMessage, GroupNoticeType, WSMessage } from '../../services/wsService';
import { sseService, WSChatMessage, WSGroupChatMessage, WSReadMessage, WSGroupReadMessage, WSRecallMessage, WSGroupRecallMessage, WSGroupTypingMessage, WSGroupNoticeMessage, GroupNoticeType, WSMessage } from '../../services/sseService';
import type { Message, GroupNotice } from '../../core/entities/Message';
export type WSEventType =
export type SSEEventType =
| 'chat_message'
| 'group_message'
| 'read_receipt'
@@ -16,58 +16,58 @@ export type WSEventType =
| 'typing'
| 'group_notice';
export interface WSEvent {
type: WSEventType;
export interface SSEEvent {
type: SSEEventType;
payload: any;
raw: any;
}
export type WSEventHandler = (event: WSEvent) => void;
export type SSEEventHandler = (event: SSEEvent) => void;
export class WSMessageHandler {
export class SSEMessageHandler {
private unsubscribeFns: Array<() => void> = [];
private handlers: Set<WSEventHandler> = new Set();
private handlers: Set<SSEEventHandler> = new Set();
connect(): void {
if (this.unsubscribeFns.length > 0) return;
// 监听私聊消息
const unsubChat = wsService.on('chat', (message) => {
const unsubChat = sseService.on('chat', (message) => {
this.emit('chat_message', this.parseChatMessage(message), message);
});
// 监听群聊消息
const unsubGroupMessage = wsService.on('group_message', (message) => {
const unsubGroupMessage = sseService.on('group_message', (message) => {
this.emit('group_message', this.parseGroupMessage(message), message);
});
// 监听私聊已读回执
const unsubRead = wsService.on('read', (message) => {
const unsubRead = sseService.on('read', (message) => {
this.emit('read_receipt', message, message);
});
// 监听群聊已读回执
const unsubGroupRead = wsService.on('group_read', (message) => {
const unsubGroupRead = sseService.on('group_read', (message) => {
this.emit('group_read_receipt', message, message);
});
// 监听私聊消息撤回
const unsubRecall = wsService.on('recall', (message) => {
const unsubRecall = sseService.on('recall', (message) => {
this.emit('message_recalled', message, message);
});
// 监听群聊消息撤回
const unsubGroupRecall = wsService.on('group_recall', (message) => {
const unsubGroupRecall = sseService.on('group_recall', (message) => {
this.emit('group_message_recalled', message, message);
});
// 监听群聊输入状态
const unsubGroupTyping = wsService.on('group_typing', (message) => {
const unsubGroupTyping = sseService.on('group_typing', (message) => {
this.emit('typing', message, message);
});
// 监听群通知
const unsubGroupNotice = wsService.on('group_notice', (message) => {
const unsubGroupNotice = sseService.on('group_notice', (message) => {
this.emit('group_notice', this.parseGroupNotice(message), message);
});
@@ -89,18 +89,18 @@ export class WSMessageHandler {
this.handlers.clear();
}
subscribe(handler: WSEventHandler): () => void {
subscribe(handler: SSEEventHandler): () => void {
this.handlers.add(handler);
return () => this.handlers.delete(handler);
}
private emit(type: WSEventType, payload: any, raw: any): void {
const event: WSEvent = { type, payload, raw };
private emit(type: SSEEventType, payload: any, raw: any): void {
const event: SSEEvent = { type, payload, raw };
this.handlers.forEach(handler => {
try {
handler(event);
} catch (error) {
console.error('[WSMessageHandler] Handler error:', error);
console.error('[SSEMessageHandler] Handler error:', error);
}
});
}
@@ -141,8 +141,8 @@ export class WSMessageHandler {
}
isConnected(): boolean {
return wsService.isConnected();
return sseService.isConnected();
}
}
export const wsMessageHandler = new WSMessageHandler();
export const sseMessageHandler = new SSEMessageHandler();

View File

@@ -12,8 +12,8 @@ export type { MessageState, MessageEvent, MessageSubscriber, MessageEventType }
// 导出同步服务
export { messageSyncService, MessageSyncService } from './MessageSyncService';
// 导出WS处理器
export { wsMessageHandler, WSMessageHandler } from './WSMessageHandler';
// 导出SSE处理器
export { sseMessageHandler, SSEMessageHandler } from './SSEMessageHandler';
// 导出已读管理器
export { readReceiptManager, ReadReceiptManager } from './ReadReceiptManager';

View File

@@ -18,7 +18,7 @@
import { ConversationResponse, MessageResponse, MessageSegment, UserDTO } from '../types/dto';
import { messageService } from '../services/messageService';
import {
wsService,
sseService,
WSChatMessage,
WSGroupChatMessage,
WSReadMessage,
@@ -28,7 +28,7 @@ import {
WSGroupTypingMessage,
WSGroupNoticeMessage,
GroupNoticeType,
} from '../services/wsService';
} from '../services/sseService';
import {
saveMessage,
saveMessagesBatch,
@@ -94,7 +94,7 @@ interface MessageManagerState {
systemUnreadCount: number;
// 连接状态
isWSConnected: boolean;
isSSEConnected: boolean;
// 当前活动会话ID用户正在查看的会话
currentConversationId: string | null;
@@ -210,7 +210,7 @@ class MessageManager {
messagesMap: new Map(),
totalUnreadCount: 0,
systemUnreadCount: 0,
isWSConnected: false,
isSSEConnected: false,
currentConversationId: null,
isLoadingConversations: false,
loadingMessagesSet: new Set(),
@@ -582,7 +582,7 @@ class MessageManager {
// 监听私聊消息
wsService.on('chat', (message: WSChatMessage) => {
sseService.on('chat', (message: WSChatMessage) => {
if (!this.state.isInitialized || this.isBootstrapping) {
this.bufferedChatMessages.push(message);
return;
@@ -591,7 +591,7 @@ class MessageManager {
});
// 监听群聊消息
wsService.on('group_message', (message: WSGroupChatMessage) => {
sseService.on('group_message', (message: WSGroupChatMessage) => {
if (!this.state.isInitialized || this.isBootstrapping) {
this.bufferedChatMessages.push(message);
return;
@@ -600,7 +600,7 @@ class MessageManager {
});
// 监听私聊已读回执
wsService.on('read', (message: WSReadMessage) => {
sseService.on('read', (message: WSReadMessage) => {
if (!this.state.isInitialized || this.isBootstrapping) {
this.bufferedReadReceipts.push(message);
return;
@@ -609,7 +609,7 @@ class MessageManager {
});
// 监听群聊已读回执
wsService.on('group_read', (message: WSGroupReadMessage) => {
sseService.on('group_read', (message: WSGroupReadMessage) => {
if (!this.state.isInitialized || this.isBootstrapping) {
this.bufferedReadReceipts.push(message);
return;
@@ -618,28 +618,28 @@ class MessageManager {
});
// 监听私聊消息撤回
wsService.on('recall', (message: WSRecallMessage) => {
sseService.on('recall', (message: WSRecallMessage) => {
this.handleRecallMessage(message);
});
// 监听群聊消息撤回
wsService.on('group_recall', (message: WSGroupRecallMessage) => {
sseService.on('group_recall', (message: WSGroupRecallMessage) => {
this.handleGroupRecallMessage(message);
});
// 监听群聊输入状态
wsService.on('group_typing', (message: WSGroupTypingMessage) => {
sseService.on('group_typing', (message: WSGroupTypingMessage) => {
this.handleGroupTyping(message);
});
// 监听群通知
wsService.on('group_notice', (message: WSGroupNoticeMessage) => {
sseService.on('group_notice', (message: WSGroupNoticeMessage) => {
this.handleGroupNotice(message);
});
// 监听连接状态
wsService.onConnect(() => {
this.state.isWSConnected = true;
sseService.onConnect(() => {
this.state.isSSEConnected = true;
this.notifySubscribers({
type: 'connection_changed',
payload: { connected: true },
@@ -668,8 +668,8 @@ class MessageManager {
}
});
wsService.onDisconnect(() => {
this.state.isWSConnected = false;
sseService.onDisconnect(() => {
this.state.isSSEConnected = false;
this.notifySubscribers({
type: 'connection_changed',
payload: { connected: false },
@@ -2375,7 +2375,7 @@ class MessageManager {
* 获取SSE连接状态
*/
isConnected(): boolean {
return this.state.isWSConnected;
return this.state.isSSEConnected;
}
/**
@@ -2486,7 +2486,7 @@ class MessageManager {
subscriber({
type: 'connection_changed',
payload: { connected: this.state.isWSConnected },
payload: { connected: this.state.isSSEConnected },
timestamp: Date.now(),
});

View File

@@ -1,137 +0,0 @@
/**
* 帖子列表数据源抽象游标、偏移分页实现同一契约PostManager 只依赖接口。
*/
import { Post } from '../types';
import { postService } from '../services/postService';
import type { CursorPaginationRequest } from '../types/dto';
export const POST_LIST_PAGE_SIZE = 20;
/** 帖子列表类型 */
export type PostListTab = 'hot' | 'latest' | 'follow';
/** 单次拉取结果(一页或一批) */
export interface PostListPage {
items: Post[];
/** 在当前源上是否还能再 loadNext 一页 */
hasMore: boolean;
}
/**
* 分页式帖子列表源restart 后开始新序列;首次 loadNext 为第一页,之后为后续页。
*/
export interface IPostListPagedSource {
restart(): void;
loadNext(): Promise<PostListPage>;
/** 至少成功 loadNext 过一次且仍有下一页时为 true */
readonly hasMore: boolean;
}
/**
* 远端帖子列表(游标分页)
*/
export class NetworkCursorPostListPagedSource implements IPostListPagedSource {
private nextCursor: string | null = null;
private hasMoreAfterLastLoad = false;
private loadedOnce = false;
private readonly pageSize: number;
private readonly tab?: PostListTab;
private readonly channelId?: string;
constructor(
options: { tab?: PostListTab; channelId?: string; pageSize?: number } = {}
) {
this.tab = options.tab;
this.channelId = options.channelId;
this.pageSize = options.pageSize ?? POST_LIST_PAGE_SIZE;
}
restart(): void {
this.nextCursor = null;
this.hasMoreAfterLastLoad = false;
this.loadedOnce = false;
}
get hasMore(): boolean {
return this.loadedOnce && this.hasMoreAfterLastLoad;
}
async loadNext(): Promise<PostListPage> {
const params: CursorPaginationRequest = {
cursor: this.nextCursor ?? '',
page_size: this.pageSize,
post_type: this.tab,
};
const result = await postService.getPostsCursor(params);
this.hasMoreAfterLastLoad = result.has_more ?? false;
this.nextCursor = result.next_cursor ?? null;
this.loadedOnce = true;
return { items: result.list ?? [], hasMore: this.hasMoreAfterLastLoad };
}
}
/**
* 远端帖子列表(偏移分页)
*/
export class NetworkOffsetPostListPagedSource implements IPostListPagedSource {
private nextPage = 1;
private hasMoreAfterLastLoad = false;
private loadedOnce = false;
private readonly pageSize: number;
private readonly tab?: PostListTab;
private readonly channelId?: string;
constructor(
options: { tab?: PostListTab; channelId?: string; pageSize?: number } = {}
) {
this.tab = options.tab;
this.channelId = options.channelId;
this.pageSize = options.pageSize ?? POST_LIST_PAGE_SIZE;
}
restart(): void {
this.nextPage = 1;
this.hasMoreAfterLastLoad = false;
this.loadedOnce = false;
}
get hasMore(): boolean {
return this.loadedOnce && this.hasMoreAfterLastLoad;
}
async loadNext(): Promise<PostListPage> {
const result = await postService.getPosts(
this.nextPage,
this.pageSize,
this.tab,
this.channelId
);
const items = result.list ?? [];
const total = result.total ?? 0;
const totalPages = result.total_pages ?? 1;
this.hasMoreAfterLastLoad = this.nextPage < totalPages;
this.nextPage++;
this.loadedOnce = true;
return { items, hasMore: this.hasMoreAfterLastLoad };
}
}
/** 远端帖子列表分页策略 */
export type RemotePostListSourceKind = 'cursor' | 'offset';
export function createRemotePostListSource(
kind: RemotePostListSourceKind = 'cursor',
options: { tab?: PostListTab; channelId?: string; pageSize?: number } = {}
): IPostListPagedSource {
if (kind === 'offset') {
return new NetworkOffsetPostListPagedSource(options);
}
return new NetworkCursorPostListPagedSource(options);
}

View File

@@ -1,24 +1,6 @@
/**
* PostManager - 帖子管理核心模块
*
* 架构特点:
* - 使用 CachedManager 基类,消除重复的缓存/去重逻辑
* - 支持 Sources 模式进行分页加载
*/
import { Post } from '../types';
import { postService } from '../services/postService';
import { CacheEvent } from './cacheBus';
import { CachedManager, CacheEntry, createCacheEntry, isCacheExpired } from './baseManager';
import {
IPostListPagedSource,
PostListTab,
createRemotePostListSource,
RemotePostListSourceKind,
POST_LIST_PAGE_SIZE,
} from './postListSources';
// ==================== 类型定义 ====================
import { CacheBus, CacheEvent } from './cacheBus';
interface PostListPayload {
key: string;
@@ -41,57 +23,66 @@ type PostManagerEvent =
| CacheEvent<PostManagerSnapshot>
| CacheEvent<{ error: unknown; context: string }>;
// ==================== 常量 ====================
const LIST_TTL = 30 * 1000;
const DETAIL_TTL = 60 * 1000;
// ==================== Manager 实现 ====================
interface CacheEntry<T> {
data: T;
timestamp: number;
ttl: number;
}
class PostManager extends CachedManager<PostManagerSnapshot, PostManagerEvent> {
/** 详情缓存 */
class PostManager extends CacheBus<PostManagerSnapshot, PostManagerEvent> {
private listCache = new Map<string, CacheEntry<Post[]>>();
private detailCache = new Map<string, CacheEntry<Post | null>>();
private pendingRequests = new Map<string, Promise<any>>();
protected getSnapshot(): PostManagerSnapshot {
return {
listKeys: [...this.memoryCache.keys()],
listKeys: [...this.listCache.keys()],
detailKeys: [...this.detailCache.keys()],
};
}
// ==================== 列表相关 ====================
private listKey(type: string, page: number, pageSize: number): string {
return `list:${type}:${page}:${pageSize}`;
private isExpired(entry: CacheEntry<any>): boolean {
return Date.now() - entry.timestamp > entry.ttl;
}
private async dedupe<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
const pending = this.pendingRequests.get(key) as Promise<T> | undefined;
if (pending) return pending;
const request = fetcher().finally(() => {
this.pendingRequests.delete(key);
});
this.pendingRequests.set(key, request);
return request;
}
private listKey(type: string, page: number, pageSize: number): string {
return `${type}:${page}:${pageSize}`;
}
/**
* 获取帖子列表(传统分页模式)
*/
async getPosts(
type: PostListTab = 'hot',
type = 'hot',
page = 1,
pageSize = POST_LIST_PAGE_SIZE,
pageSize = 20,
forceRefresh = false
): Promise<Post[]> {
const key = this.listKey(type, page, pageSize);
// 检查有效缓存
if (!forceRefresh && this.hasValidCache(key)) {
return this.getFromCache<Post[]>(key)!;
const cached = this.listCache.get(key);
if (!forceRefresh && cached && !this.isExpired(cached)) {
return cached.data;
}
// 过期缓存:后台刷新,立即返回旧数据
if (!forceRefresh && this.hasExpiredCache(key)) {
if (!forceRefresh && cached && this.isExpired(cached)) {
this.refreshPostsInBackground(key, type, page, pageSize);
return this.getFromCache<Post[]>(key)!;
return cached.data;
}
// 无缓存:发起请求
return this.dedupe(`posts:${key}`, async () => {
return this.dedupe(`posts:list:${key}`, async () => {
const response = await postService.getPosts(page, pageSize, type);
const posts = response.list || [];
this.setCache(key, posts, LIST_TTL);
this.listCache.set(key, { data: posts, timestamp: Date.now(), ttl: LIST_TTL });
this.notify({
type: 'list_updated',
payload: { key, posts },
@@ -101,16 +92,11 @@ class PostManager extends CachedManager<PostManagerSnapshot, PostManagerEvent> {
});
}
private refreshPostsInBackground(
key: string,
type: PostListTab,
page: number,
pageSize: number
): void {
this.dedupe(`posts:bg:${key}`, async () => {
private refreshPostsInBackground(key: string, type: string, page: number, pageSize: number): void {
this.dedupe(`posts:list:bg:${key}`, async () => {
const response = await postService.getPosts(page, pageSize, type);
const posts = response.list || [];
this.setCache(key, posts, LIST_TTL);
this.listCache.set(key, { data: posts, timestamp: Date.now(), ttl: LIST_TTL });
this.notify({
type: 'list_updated',
payload: { key, posts },
@@ -126,39 +112,20 @@ class PostManager extends CachedManager<PostManagerSnapshot, PostManagerEvent> {
});
}
/**
* 创建帖子列表数据源(用于 Sources 模式)
*/
createPostListSource(
options: { tab?: PostListTab; channelId?: string; pageSize?: number } = {},
kind: RemotePostListSourceKind = 'cursor'
): IPostListPagedSource {
return createRemotePostListSource(kind, options);
}
// ==================== 详情相关 ====================
/**
* 获取帖子详情
*/
async getPostDetail(postId: string, forceRefresh = false): Promise<Post | null> {
const cached = this.detailCache.get(postId);
// 有效缓存
if (!forceRefresh && cached && !isCacheExpired(cached)) {
if (!forceRefresh && cached && !this.isExpired(cached)) {
return cached.data;
}
// 过期缓存:后台刷新
if (!forceRefresh && cached && isCacheExpired(cached) && cached.data) {
if (!forceRefresh && cached && this.isExpired(cached)) {
this.refreshPostDetailInBackground(postId);
return cached.data;
}
// 无缓存:发起请求
return this.dedupe(`posts:detail:${postId}`, async () => {
const post = await postService.getPost(postId);
this.detailCache.set(postId, createCacheEntry(post, DETAIL_TTL));
this.detailCache.set(postId, { data: post, timestamp: Date.now(), ttl: DETAIL_TTL });
this.notify({
type: 'detail_updated',
payload: { postId, post },
@@ -171,7 +138,7 @@ class PostManager extends CachedManager<PostManagerSnapshot, PostManagerEvent> {
private refreshPostDetailInBackground(postId: string): void {
this.dedupe(`posts:detail:bg:${postId}`, async () => {
const post = await postService.getPost(postId);
this.detailCache.set(postId, createCacheEntry(post, DETAIL_TTL));
this.detailCache.set(postId, { data: post, timestamp: Date.now(), ttl: DETAIL_TTL });
this.notify({
type: 'detail_updated',
payload: { postId, post },
@@ -187,28 +154,21 @@ class PostManager extends CachedManager<PostManagerSnapshot, PostManagerEvent> {
});
}
// ==================== 缓存管理 ====================
/**
* 使缓存失效
*/
invalidate(postId?: string): void {
if (postId) {
this.detailCache.delete(postId);
return;
}
this.clearCache();
this.listCache.clear();
this.detailCache.clear();
}
/**
* 清除所有数据
*/
clear(): void {
this.clearCache();
this.listCache.clear();
this.detailCache.clear();
this.clearPendingRequests();
this.pendingRequests.clear();
}
}
export const postManager = new PostManager();

View File

@@ -1,7 +1,7 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Appearance, AppState, AppStateStatus } from 'react-native';
import { useColorScheme } from 'react-native';
import { create } from 'zustand';
import { useEffect, useRef } from 'react';
import { useEffect } from 'react';
import { lightColors, darkColors, type AppColors } from '../theme/palettes';
import { buildPaperTheme } from '../theme/paperTheme';
import type { MD3Theme } from 'react-native-paper';
@@ -46,19 +46,13 @@ type ThemeState = {
hydrate: () => Promise<void>;
};
/** 获取系统主题 */
function getSystemScheme(): ResolvedScheme {
const scheme = Appearance.getColorScheme();
return scheme === 'dark' ? 'dark' : 'light';
}
const initialSystemScheme = getSystemScheme();
const initialSystem: ResolvedScheme = 'light';
export const useThemeStore = create<ThemeState>((set, get) => ({
preference: 'system',
systemScheme: initialSystemScheme,
systemScheme: initialSystem,
hydrated: false,
...buildState('system', initialSystemScheme),
...buildState('system', initialSystem),
setSystemScheme: (systemScheme) => {
const { preference, systemScheme: cur } = get();
@@ -92,11 +86,10 @@ export const useThemeStore = create<ThemeState>((set, get) => ({
} catch {
/* ignore */
}
const systemScheme = getSystemScheme();
const { systemScheme } = get();
set({
preference,
hydrated: true,
systemScheme,
...buildState(preference, systemScheme),
});
},
@@ -104,42 +97,17 @@ export const useThemeStore = create<ThemeState>((set, get) => ({
/** 在根布局中同步系统配色并恢复持久化偏好 */
export function ThemeBootstrap() {
const system = useColorScheme();
const setSystemScheme = useThemeStore((s) => s.setSystemScheme);
const hydrate = useThemeStore((s) => s.hydrate);
const appState = useRef<AppStateStatus>(AppState.currentState);
useEffect(() => {
void hydrate();
}, [hydrate]);
// 监听系统主题变化
useEffect(() => {
const subscription = Appearance.addChangeListener(({ colorScheme }) => {
const newScheme = colorScheme === 'dark' ? 'dark' : 'light';
setSystemScheme(newScheme);
});
return () => {
subscription.remove();
};
}, [setSystemScheme]);
// 监听应用状态变化,从后台恢复时重新检测系统主题
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === 'active'
) {
setSystemScheme(getSystemScheme());
}
appState.current = nextAppState;
});
return () => {
subscription.remove();
};
}, [setSystemScheme]);
setSystemScheme(system === 'dark' ? 'dark' : 'light');
}, [system, setSystemScheme]);
return null;
}
@@ -163,6 +131,3 @@ export function useSetThemePreference() {
export function usePaperThemeFromStore() {
return useThemeStore((s) => s.paperTheme);
}
// 导出调试函数
export { getSystemScheme };

View File

@@ -76,8 +76,8 @@ export const lightColors = {
link: '#4A88C7',
success: '#34C759',
danger: '#FF3B30',
bubbleOutgoing: '#E8E8E8', // 柔和的淡灰色
bubbleIncoming: '#FFFFFF', // 对方发的消息 - 纯白
bubbleOutgoing: '#E8E8E8',
bubbleIncoming: '#FFFFFF',
replyTint: '#DFF2FF',
replyTintActive: '#CFEAFF',
replyBorder: '#7FB6E6',
@@ -168,8 +168,8 @@ export const darkColors = {
link: '#5AC8FA',
success: '#32D74B',
danger: '#FF453A',
bubbleOutgoing: '#3A3A3C', // 暗色模式:深灰色
bubbleIncoming: '#2C2C2E', // 暗色模式:灰色气泡
bubbleOutgoing: '#3A3A3C',
bubbleIncoming: '#2C2C2E',
replyTint: '#1A3A52',
replyTintActive: '#224060',
replyBorder: '#4A88C7',

View File

@@ -2,39 +2,6 @@
* 与明暗无关的设计 token
*/
// 字体配置 - 使用系统字体栈,优化字重
export const fontFamily = {
// iOS 系统字体
ios: {
regular: 'System',
medium: 'System',
semibold: 'System',
bold: 'System',
},
// Android 系统字体
android: {
regular: 'Roboto',
medium: 'Roboto',
semibold: 'Roboto',
bold: 'Roboto',
},
// 通用字体栈
system: {
regular: 'System',
medium: 'System',
semibold: 'System',
bold: 'System',
},
};
// 字体字重 - 使用数值更精确控制
export const fontWeights = {
regular: '400' as const,
medium: '500' as const,
semibold: '600' as const,
bold: '700' as const,
};
export const fontSizes = {
xs: 10,
sm: 12,

View File

@@ -684,37 +684,31 @@ export interface GroupAnnouncementListResponse {
total_pages: number;
}
// ==================== WS Event Types ====================
// ==================== SSE Event Types ====================
// WS 事件类型
export type WSEventType = 'message' | 'notice' | 'request' | 'meta';
// SSE 事件类型
export type SSEEventType = 'message' | 'notice' | 'request' | 'meta';
// WS 消息详细类型
export type WSDetailType = 'private' | 'group' | 'follow' | 'like' | 'comment' | 'request' | 'typing' | 'heartbeat' | 'read';
// SSE 消息详细类型
export type SSEDetailType = 'private' | 'group' | 'follow' | 'like' | 'comment' | 'request' | 'typing' | 'heartbeat' | 'read';
// WS 事件消息段(与后端 message 字段一致)
export interface WSSegment {
// SSE 事件消息段(与后端 message 字段一致)
export interface SSESegment {
type: string;
data: Record<string, any>;
}
// WS 事件(后端推送的事件格式)
export interface WSEvent {
// SSE 事件(后端推送的事件格式)
export interface SSEEvent {
id: string; // 事件唯一ID
time: number; // 事件时间戳(毫秒)
type: WSEventType; // 事件类型: message(消息), notice(通知), request(请求), meta(元事件)
detail_type: WSDetailType; // 详细类型: private(私聊), group(群聊), follow(关注), like(点赞)等
type: SSEEventType; // 事件类型: message(消息), notice(通知), request(请求), meta(元事件)
detail_type: SSEDetailType; // 详细类型: private(私聊), group(群聊), follow(关注), like(点赞)等
seq: string; // 消息序号
message?: WSSegment[]; // 消息内容数组
message?: SSESegment[]; // 消息内容数组
conversation_id: string; // 会话ID
}
// 旧的类型名称,保持向后兼容
export type SSEEventType = WSEventType;
export type SSEDetailType = WSDetailType;
export interface SSESegment extends WSSegment {}
export interface SSEEvent extends WSEvent {}
/**
* 从消息segments中提取纯文本内容
* 用于消息列表显示、通知等场景

View File

@@ -6,7 +6,6 @@
// 导出DTO类型作为主要类型
export * from './dto';
export * from './schedule';
export * from './material';
// 兼容旧类型(用于内部组件)
import type {

View File

@@ -1,103 +0,0 @@
/**
* 学习资料类型定义
*/
// 文件类型枚举
export type MaterialFileType = 'pdf' | 'word' | 'ppt';
// 学科分类
export interface MaterialSubject {
id: string;
name: string;
icon: string; // MaterialCommunityIcons name
color: string; // 主题色
description?: string;
sort_order: number;
is_active: boolean;
material_count: number;
created_at: string;
updated_at: string;
}
// 文件资料
export interface MaterialFile {
id: string;
subject_id: string;
title: string;
description?: string;
file_type: MaterialFileType;
file_size: number; // 字节数
file_url: string;
file_name: string;
download_count: number;
author_id?: string;
author_name?: string;
tags?: string[];
status: 'active' | 'inactive';
created_at: string;
updated_at: string;
subject?: MaterialSubject;
}
// 学科资料列表响应
export interface SubjectMaterialsResponse {
subject: MaterialSubject;
materials: MaterialFile[];
total: number;
page: number;
page_size: number;
}
// 搜索结果响应
export interface SearchMaterialsResponse {
materials: MaterialFile[];
total: number;
page: number;
page_size: number;
}
// 文件类型图标映射
export const MATERIAL_FILE_TYPE_ICONS: Record<MaterialFileType, string> = {
pdf: 'file-pdf-box',
word: 'file-word-box',
ppt: 'file-powerpoint-box',
};
// 文件类型颜色映射
export const MATERIAL_FILE_TYPE_COLORS: Record<MaterialFileType, string> = {
pdf: '#E53935',
word: '#1E88E5',
ppt: '#FF9800',
};
// 文件类型名称映射
export const MATERIAL_FILE_TYPE_NAMES: Record<MaterialFileType, string> = {
pdf: 'PDF',
word: 'Word',
ppt: 'PPT',
};
// 文件大小格式化
export function formatFileSize(bytes: number): string {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
}
// 学科颜色预设
export const SUBJECT_COLORS = [
'#FF6B6B', // 红色
'#4ECDC4', // 青色
'#45B7D1', // 蓝色
'#96CEB4', // 绿色
'#FFEAA7', // 黄色
'#DDA0DD', // 紫色
'#F39C12', // 橙色
'#3498DB', // 深蓝
'#27AE60', // 深绿
'#9B59B6', // 深紫
'#1ABC9C', // 青绿
'#E74C3C', // 深红
];