121 lines
2.9 KiB
TypeScript
121 lines
2.9 KiB
TypeScript
import { RespMessage } from "../../constant/message"
|
|
import prisma from "../../prisma"
|
|
import { Context } from "../../types"
|
|
|
|
/**
|
|
* 注册消息总结的订阅
|
|
* @returns
|
|
*/
|
|
const subscribe = async ({
|
|
app,
|
|
larkService,
|
|
logger,
|
|
larkBody,
|
|
larkCard,
|
|
}: Context.Data) => {
|
|
try {
|
|
const cardGender = larkCard.child("groupAgent")
|
|
// 判断是否有 chatId 和 userId
|
|
if (!larkBody.chatId || !larkBody.userId) {
|
|
logger.error(`chatId or userId is empty`)
|
|
return
|
|
}
|
|
// 先查询是否已经存在订阅
|
|
const subscription = await prisma.chat_agent_summary_subscription.findFirst(
|
|
{
|
|
where: {
|
|
chat_id: larkBody.chatId,
|
|
terminator: "",
|
|
},
|
|
}
|
|
)
|
|
// 如果已经存在订阅,则返回已经注册过了
|
|
if (subscription) {
|
|
logger.info(`chatId: ${larkBody.chatId} has been registered`)
|
|
// 发送已经注册过的消息
|
|
await larkService.message.sendCard2Chat(
|
|
larkBody.chatId,
|
|
cardGender.genSuccessCard(RespMessage.hasRegistered)
|
|
)
|
|
return
|
|
}
|
|
// 注册订阅
|
|
await prisma.chat_agent_summary_subscription.create({
|
|
data: {
|
|
chat_id: larkBody.chatId,
|
|
robot_id: app,
|
|
initiator: larkBody.userId,
|
|
},
|
|
})
|
|
// 发送成功消息
|
|
await larkService.message.sendCard2Chat(
|
|
larkBody.chatId,
|
|
cardGender.genSuccessCard(RespMessage.registerSuccess)
|
|
)
|
|
} catch (e: any) {
|
|
logger.error(`Subscribe error: ${e.message}`)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 取消消息总结的订阅
|
|
* @returns
|
|
*/
|
|
const unsubscribe = async ({
|
|
logger,
|
|
larkBody,
|
|
larkService,
|
|
larkCard,
|
|
}: Context.Data) => {
|
|
try {
|
|
const cardGender = larkCard.child("groupAgent")
|
|
// 判断是否有 chatId 和 userId
|
|
if (!larkBody.chatId || !larkBody.userId) {
|
|
logger.error(`chatId or userId is empty`)
|
|
return
|
|
}
|
|
// 查找现有的订阅
|
|
const subscription = await prisma.chat_agent_summary_subscription.findFirst(
|
|
{
|
|
where: {
|
|
chat_id: larkBody.chatId,
|
|
terminator: "",
|
|
},
|
|
}
|
|
)
|
|
// 如果没有找到订阅,则返回错误
|
|
if (!subscription) {
|
|
logger.info(`chatId: ${larkBody.chatId} has not been registered`)
|
|
// 发送已经取消订阅的消息
|
|
await larkService.message.sendCard2Chat(
|
|
larkBody.chatId,
|
|
cardGender.genSuccessCard(RespMessage.cancelSuccess)
|
|
)
|
|
return
|
|
}
|
|
// 更新订阅,设置终止者和终止时间
|
|
await prisma.chat_agent_summary_subscription.update({
|
|
where: {
|
|
id: subscription.id,
|
|
},
|
|
data: {
|
|
terminator: larkBody.userId,
|
|
},
|
|
})
|
|
// 发送成功消息
|
|
await larkService.message.sendCard2Chat(
|
|
larkBody.chatId,
|
|
cardGender.genSuccessCard(RespMessage.cancelSuccess)
|
|
)
|
|
} catch (e: any) {
|
|
logger.error(`Unsubscribe error: ${e.message}`)
|
|
}
|
|
}
|
|
|
|
const subscription = {
|
|
subscribe,
|
|
unsubscribe,
|
|
}
|
|
|
|
export default subscription
|