/** * Chat API * * 聊天相关接口 * */ import { httpClient } from "./http_client"; import { ApiPath } from "./api_path"; import { ApiEnvelope, unwrap } from "./response_helper"; import { ChatHistoryResponse, ChatSendResponse, ChatSyncData, ChatSyncRequest, ImageUploadResponse, SendMessageRequest, SttData, SyncMessage, UnlockHistoryResponse, UnlockPrivateRequest, UnlockPrivateResponse, } from "@/data/dto/chat"; export class ChatApi { /** * 发送消息 */ async sendMessage(body: SendMessageRequest): Promise { const env = await httpClient>(ApiPath.chatSend, { method: "POST", body: body.toJson(), }); return ChatSendResponse.fromJson(unwrap(env) as Record); } /** * 获取聊天历史 */ async getHistory(limit = 50, offset = 0): Promise { const env = await httpClient>(ApiPath.chatHistory, { query: { limit, offset }, }); return ChatHistoryResponse.fromJson( unwrap(env) as Record ); } /** * 语音转文字(multipart 上传) */ async speechToText(audio: Blob | File): Promise { const formData = new FormData(); formData.append("audio", audio); const env = await httpClient>(ApiPath.chatStt, { method: "POST", body: formData, }); return SttData.fromJson(unwrap(env) as Record); } /** * 同步游客消息 */ async syncMessages(messages: SyncMessage[]): Promise { const body = ChatSyncRequest.from({ messages }); const env = await httpClient>(ApiPath.chatSync, { method: "POST", body: body.toJson(), }); return ChatSyncData.fromJson(unwrap(env) as Record); } /** * 上传图片 */ async uploadImage(image: Blob | File): Promise { const formData = new FormData(); formData.append("image", image); const env = await httpClient>( ApiPath.chatUploadImage, { method: "POST", body: formData } ); return ImageUploadResponse.fromJson( unwrap(env) as Record ); } /** * 解锁单条历史付费 / 私密消息 */ async unlockPrivateMessage( body: UnlockPrivateRequest, ): Promise { const env = await httpClient>( ApiPath.chatUnlockPrivate, { method: "POST", body: body.toJson(), }, ); return UnlockPrivateResponse.fromJson( unwrap(env) as Record, ); } /** * 一键解锁历史锁定消息 */ async unlockHistory(): Promise { const env = await httpClient>( ApiPath.chatUnlockHistory, { method: "POST", }, ); return UnlockHistoryResponse.fromJson( unwrap(env) as Record, ); } } /** * 全局单例 */ export const chatApi = new ChatApi();