56 lines
2.0 KiB
TypeScript
56 lines
2.0 KiB
TypeScript
import { allow, deny } from "@/lib/policy/assert"
|
|
import { useChatStore } from "@/store/chat"
|
|
import { useAuthStore } from "@/store/auth"
|
|
|
|
export function listChatSessions() {
|
|
return useChatStore.getState().sessions
|
|
}
|
|
|
|
export function getChatSessionById(sessionId: string) {
|
|
return useChatStore.getState().sessions.find((session) => session.id === sessionId)
|
|
}
|
|
|
|
export function listChatMessages(sessionId: string) {
|
|
return useChatStore.getState().messages.filter((message) => message.sessionId === sessionId)
|
|
}
|
|
|
|
export function sendTextMessage(sessionId: string, content: string) {
|
|
const userId = useAuthStore.getState().user?.id
|
|
if (!userId) return deny("AUTH_REQUIRED", "请先登录")
|
|
|
|
const chatState = useChatStore.getState()
|
|
const session = chatState.sessions.find((item) => item.id === sessionId)
|
|
if (!session) return deny("NOT_FOUND", "会话不存在")
|
|
if (session.readonly) return deny("INVALID_STATUS", "当前会话只读")
|
|
if (!session.participants.some((participant) => participant.id === userId)) {
|
|
return deny("NOT_PARTICIPANT", "仅会话参与方可发送消息")
|
|
}
|
|
|
|
if (!content.trim()) {
|
|
return deny("VALIDATION_FAILED", "消息不能为空")
|
|
}
|
|
|
|
chatState.sendTextMessage(sessionId, userId, content)
|
|
return allow()
|
|
}
|
|
|
|
export function sendImageMessage(sessionId: string, imageUrl: string) {
|
|
const userId = useAuthStore.getState().user?.id
|
|
if (!userId) return deny("AUTH_REQUIRED", "请先登录")
|
|
|
|
const chatState = useChatStore.getState()
|
|
const session = chatState.sessions.find((item) => item.id === sessionId)
|
|
if (!session) return deny("NOT_FOUND", "会话不存在")
|
|
if (session.readonly) return deny("INVALID_STATUS", "当前会话只读")
|
|
if (!session.participants.some((participant) => participant.id === userId)) {
|
|
return deny("NOT_PARTICIPANT", "仅会话参与方可发送消息")
|
|
}
|
|
|
|
if (!imageUrl.trim()) {
|
|
return deny("VALIDATION_FAILED", "图片地址无效")
|
|
}
|
|
|
|
chatState.sendImageMessage(sessionId, userId, imageUrl)
|
|
return allow()
|
|
}
|