Initial frontend repository commit.

Include app source and update .gitignore to exclude local release artifacts and signing files.

Made-with: Cursor
This commit is contained in:
2026-03-09 21:29:03 +08:00
commit 3968660048
129 changed files with 55599 additions and 0 deletions

View File

@@ -0,0 +1,597 @@
/**
* 消息服务
* 处理私信/聊天消息功能
* 使用新的 API 接口: /api/v1/conversations (RESTful action 风格)
*/
import { api } from './api';
import {
ConversationListResponse,
ConversationResponse,
ConversationDetailResponse,
MessageListResponse,
MessageResponse,
SendMessageRequest,
UnreadCountResponse,
ConversationUnreadCountResponse,
SystemMessageListResponse,
SystemUnreadCountResponse,
MessageSegment,
} from '../types/dto';
import {
getConversationCache,
getConversationListCache,
saveConversationCache,
saveConversationsCache,
saveGroupsCache,
saveUsersCache,
updateConversationCacheUnreadCount,
} from './database';
// 消息服务类
class MessageService {
private async refreshConversationsFromServer(
page = 1,
pageSize = 20
): Promise<ConversationListResponse> {
const response = await api.get<ConversationListResponse>('/conversations/list', {
page,
page_size: pageSize,
});
const list = response.data.list || [];
await saveConversationsCache(list);
await saveUsersCache(
list.flatMap(conv => [
...(conv.participants || []),
...(conv.last_message?.sender ? [conv.last_message.sender] : []),
])
);
await saveGroupsCache(
list
.map(conv => conv.group)
.filter((group): group is NonNullable<typeof group> => Boolean(group))
);
return response.data;
}
private async refreshConversationDetailFromServer(id: string): Promise<ConversationDetailResponse> {
const response = await api.get<ConversationDetailResponse>(
'/conversations/get',
{ conversation_id: id }
);
await saveConversationCache(response.data);
if (response.data.participants?.length) {
await saveUsersCache(response.data.participants);
}
if (response.data.last_message?.sender) {
await saveUsersCache([response.data.last_message.sender]);
}
return response.data;
}
private normalizeCachedDetail(
id: string,
cached: any
): ConversationDetailResponse {
return {
id: String(cached?.id || id),
type: cached?.type || 'private',
is_pinned: Boolean(cached?.is_pinned),
last_seq: Number(cached?.last_seq || 0),
last_message: cached?.last_message,
last_message_at: cached?.last_message_at || cached?.updated_at || new Date().toISOString(),
unread_count: Number(cached?.unread_count || 0),
participants: Array.isArray(cached?.participants) ? cached.participants : [],
my_last_read_seq: Number(cached?.my_last_read_seq || 0),
other_last_read_seq: Number(cached?.other_last_read_seq || 0),
created_at: cached?.created_at || new Date().toISOString(),
updated_at: cached?.updated_at || new Date().toISOString(),
};
}
// ==================== 会话相关 ====================
/**
* 获取会话列表
* GET /api/v1/conversations/list
*/
async getConversations(
page = 1,
pageSize = 20,
forceRefresh = false
): Promise<ConversationListResponse> {
// 如果强制刷新,直接从服务器获取,不使用缓存
if (!forceRefresh) {
const cachedList = await getConversationListCache();
if (cachedList.length > 0) {
// 后台刷新数据,但不阻塞当前返回
this.refreshConversationsFromServer(page, pageSize).catch(error => {
console.error('后台刷新会话列表失败:', error);
});
return {
list: cachedList,
total: cachedList.length,
page: 1,
page_size: cachedList.length,
total_pages: 1,
};
}
}
// 强制刷新或没有缓存时,直接从服务器获取
try {
return await this.refreshConversationsFromServer(page, pageSize);
} catch (error) {
console.error('获取会话列表失败:', error);
return {
list: [],
total: 0,
page: 1,
page_size: pageSize,
total_pages: 0,
};
}
}
/**
* 创建私聊会话
* POST /api/v1/conversations/create
* @param userId 目标用户ID (UUID格式)
*/
async createConversation(userId: string): Promise<ConversationResponse> {
const response = await api.post<ConversationResponse>('/conversations/create', {
user_id: userId,
});
await saveConversationCache(response.data);
if (response.data.participants?.length) {
await saveUsersCache(response.data.participants);
}
return response.data;
}
/**
* 获取会话详情
* GET /api/v1/conversations/get?conversation_id=xxx
*/
async getConversationById(id: string): Promise<ConversationDetailResponse> {
const cached = await getConversationCache(id);
if (cached) {
this.refreshConversationDetailFromServer(id).catch(error => {
console.error('后台刷新会话详情失败:', error);
});
return this.normalizeCachedDetail(id, cached);
}
try {
return await this.refreshConversationDetailFromServer(id);
} catch (error) {
console.error('获取会话详情失败:', error);
throw error;
}
}
/**
* 仅自己删除会话
* DELETE /api/v1/conversations/:id/self
*/
async deleteConversationForSelf(conversationId: string): Promise<void> {
await api.delete(`/conversations/${encodeURIComponent(conversationId)}/self`);
}
/**
* 设置会话置顶
* POST /api/v1/conversations/set_pinned
*/
async setConversationPinned(conversationId: string, isPinned: boolean): Promise<void> {
await api.post('/conversations/set_pinned', {
conversation_id: conversationId,
is_pinned: isPinned,
});
}
// ==================== 消息相关 ====================
/**
* 获取消息列表(支持增量同步和历史消息加载)
* GET /api/v1/conversations/get_messages?conversation_id=xxx
* @param conversationId 会话ID
* @param afterSeq 获取此序号之后的消息(增量同步,获取新消息)
* @param beforeSeq 获取此序号之前的历史消息(下拉加载更多,获取旧消息)
* @param limit 返回消息数量限制
*/
async getMessages(
conversationId: string,
afterSeq?: number,
beforeSeq?: number,
limit?: number
): Promise<MessageListResponse> {
const params: Record<string, any> = {
conversation_id: conversationId,
};
if (afterSeq !== undefined) {
params.after_seq = afterSeq;
}
if (beforeSeq !== undefined) {
params.before_seq = beforeSeq;
}
if (limit !== undefined) {
params.limit = limit;
}
try {
const response = await api.get<any>(
'/conversations/get_messages',
params
);
// 处理增量同步响应after_seq 或 before_seq
if ((afterSeq !== undefined || beforeSeq !== undefined) && response.data.messages !== undefined) {
return {
messages: response.data.messages,
total: response.data.messages.length,
page: 1,
page_size: limit || 100,
};
}
// 处理分页响应(后端返回 list 字段)
const data = response.data;
return {
messages: data.list || [],
total: data.total || 0,
page: data.page || 1,
page_size: data.page_size || 20,
};
} catch (error) {
console.error('获取消息列表失败:', error);
return {
messages: [],
total: 0,
page: 1,
page_size: 20,
};
}
}
/**
* 发送消息(新格式)
* POST /api/v1/conversations/send_message
* Body: { detail_type, conversation_id, message }
*/
async sendMessage(
conversationId: string,
data: SendMessageRequest,
detailType: 'private' | 'group' = 'private'
): Promise<MessageResponse> {
// 直接使用传入的 segments
if (!data.segments || data.segments.length === 0) {
throw new Error('消息内容不能为空');
}
return this.sendMessageByAction(
detailType,
conversationId,
data.segments
);
}
/**
* 通过 HTTP POST 发送消息(新格式)
* 请求格式: POST /api/v1/conversations/send_message
* Body: { "detail_type": "private", "conversation_id": "xxx", "segments": [...] }
* @param detailType 消息类型: 'private' 私聊, 'group' 群聊
* @param conversationId 会话ID
* @param message 消息段数组 [{"type": "text", "data": {"text": "xxx"}}]
* @returns 消息响应
*/
async sendMessageByAction(
detailType: 'private' | 'group',
conversationId: string,
message: MessageSegment[]
): Promise<MessageResponse> {
try {
const response = await api.post<MessageResponse>(
'/conversations/send_message',
{
detail_type: detailType,
conversation_id: conversationId,
segments: message,
}
);
return response.data;
} catch (error) {
console.error('发送消息失败:', error);
throw error;
}
}
/**
* 发送文本消息(便捷方法)
*/
async sendTextMessage(
conversationId: string,
content: string,
detailType: 'private' | 'group' = 'private'
): Promise<MessageResponse> {
return this.sendTextMessageByAction(detailType, conversationId, content);
}
/**
* 通过 HTTP POST 发送文本消息
* @param detailType 消息类型: 'private' 私聊, 'group' 群聊
* @param conversationId 会话ID
* @param text 文本内容
* @returns 消息响应
*/
async sendTextMessageByAction(
detailType: 'private' | 'group',
conversationId: string,
text: string
): Promise<MessageResponse> {
const message: MessageSegment[] = [
{
type: 'text',
data: {
text: text,
},
},
];
return this.sendMessageByAction(detailType, conversationId, message);
}
/**
* 发送图片消息(便捷方法)
*/
async sendImageMessage(
conversationId: string,
mediaUrl: string,
content?: string,
detailType: 'private' | 'group' = 'private'
): Promise<MessageResponse> {
const message: MessageSegment[] = [
{
type: 'image',
data: {
url: mediaUrl,
},
},
];
// 如果有文本说明,添加一个文本段
if (content) {
message.unshift({
type: 'text',
data: { text: content },
});
}
return this.sendMessageByAction(detailType, conversationId, message);
}
/**
* 发送 segments 格式消息(新版统一格式)
* @param conversationId 会话ID
* @param segments 消息链数组
* @param detailType 消息类型
*/
async sendSegmentsMessage(
conversationId: string,
segments: MessageSegment[],
detailType: 'private' | 'group' = 'private'
): Promise<MessageResponse> {
return this.sendMessageByAction(detailType, conversationId, segments);
}
/**
* 发送带回复的 segments 消息
* @param conversationId 会话ID
* @param segments 消息链数组
* @param replyToId 被回复消息的ID
* @param detailType 消息类型
*/
async sendReplySegmentsMessage(
conversationId: string,
segments: MessageSegment[],
replyToId: string,
detailType: 'private' | 'group' = 'private'
): Promise<MessageResponse> {
// 添加回复段到消息开头
const replySegment: MessageSegment = {
type: 'reply',
data: {
id: replyToId,
},
};
return this.sendMessageByAction(detailType, conversationId, [replySegment, ...segments]);
}
/**
* 撤回/删除消息
* POST /api/v1/messages/delete_msg
* Body: { "message_id": "xxx" }
*/
async recallMessage(messageId: string): Promise<void> {
await api.post('/messages/delete_msg', {
message_id: messageId,
});
}
/**
* 删除消息(同撤回)
* POST /api/v1/messages/delete_msg
*/
async deleteMessage(messageId: string): Promise<void> {
await this.recallMessage(messageId);
}
// ==================== 已读相关 ====================
/**
* 标记已读
* POST /api/v1/conversations/mark_read
* @param conversationId 会话ID
* @param seq 已读到的消息序号
*/
async markAsRead(conversationId: string, seq: number): Promise<void> {
await api.post('/conversations/mark_read', {
conversation_id: conversationId,
last_read_seq: Number(seq),
});
// 立即清零本地缓存中的 unread_count避免回到列表时仍显示旧红点
updateConversationCacheUnreadCount(conversationId, 0).catch(error => {
console.error('更新本地会话未读数失败:', error);
});
}
/**
* 获取未读总数
* GET /api/v1/conversations/unread/count
*/
async getUnreadCount(): Promise<UnreadCountResponse> {
try {
const response = await api.get<UnreadCountResponse>(
'/conversations/unread/count'
);
return response.data;
} catch (error) {
console.error('获取未读总数失败:', error);
return { total_unread_count: 0 };
}
}
/**
* 获取单个会话未读数
* GET /api/v1/conversations/unread/count?conversation_id=xxx
*/
async getConversationUnreadCount(
conversationId: string
): Promise<ConversationUnreadCountResponse> {
try {
const response = await api.get<ConversationUnreadCountResponse>(
'/conversations/unread/count',
{ conversation_id: conversationId }
);
return response.data;
} catch (error) {
console.error('获取会话未读数失败:', error);
return {
conversation_id: conversationId,
unread_count: 0,
};
}
}
// ==================== 系统消息相关 ====================
/**
* 获取系统消息列表
* GET /api/v1/messages/system
* @param limit 返回数量限制
* @param beforeId 获取此ID之前的消息用于分页
*/
async getSystemMessages(
pageSize: number = 20,
page: number = 1
): Promise<SystemMessageListResponse> {
try {
const response = await api.get<{
list: any[];
total: number;
page: number;
page_size: number;
total_pages: number;
}>('/messages/system', {
page,
page_size: pageSize,
});
const data = response.data;
return {
messages: data.list || [],
total: data.total || 0,
has_more: data.page < data.total_pages,
};
} catch (error) {
console.error('获取系统消息列表失败:', error);
return {
messages: [],
total: 0,
has_more: false,
};
}
}
/**
* 获取系统消息未读数
* GET /api/v1/messages/system/unread-count
*/
async getSystemUnreadCount(): Promise<SystemUnreadCountResponse> {
try {
const response = await api.get<SystemUnreadCountResponse>(
'/messages/system/unread-count'
);
return response.data;
} catch (error) {
console.error('获取系统消息未读数失败:', error);
return { unread_count: 0 };
}
}
/**
* 标记单条系统消息已读
* PUT /api/v1/messages/system/:messageId/read
* @param messageId 消息ID
*/
async markSystemMessageRead(messageId: string): Promise<void> {
await api.put(`/messages/system/${encodeURIComponent(messageId)}/read`);
}
/**
* 标记所有系统消息已读
* PUT /api/v1/messages/system/read-all
*/
async markAllSystemMessagesRead(): Promise<void> {
await api.put('/messages/system/read-all');
}
// ==================== 兼容旧API的方法将逐步废弃 ====================
/**
* @deprecated 使用 getConversations 代替
*/
async getConversation(conversationId: string): Promise<ConversationDetailResponse | null> {
try {
return await this.getConversationById(conversationId);
} catch (error) {
console.error('获取会话详情失败:', error);
return null;
}
}
/**
* @deprecated 使用 createConversation(userId: string) 代替
*/
async createConversationByString(userId: string): Promise<ConversationResponse | null> {
try {
return await this.createConversation(userId);
} catch (error) {
console.error('创建会话失败:', error);
return null;
}
}
}
// 导出消息服务实例
export const messageService = new MessageService();
// 导出类型以方便使用
export type {
ConversationListResponse,
ConversationResponse,
ConversationDetailResponse,
MessageListResponse,
MessageResponse,
SendMessageRequest,
UnreadCountResponse,
ConversationUnreadCountResponse,
SystemMessageListResponse,
SystemUnreadCountResponse,
};