saw-go/dao/im.go

101 lines
2.9 KiB
Go
Raw Normal View History

package dao
import (
"StuAcaWorksAI/proto"
"gorm.io/gorm"
)
type Session struct {
gorm.Model
2025-03-23 13:17:03 +08:00
UserID int `gorm:"column:user_id"` //只能由用户创建
Name string `gorm:"column:name"`
Context []int `gorm:"column:context"` //会话上下文
}
type Message struct {
gorm.Model
Type int `gorm:"column:type"` //1用户之间的消息2为与模型消息
SessionID int `gorm:"column:session_id"`
FromID int `gorm:"column:from_id"` //发送者,可以为用户或者模型
ToID int `gorm:"column:to_id"` //接收者,可以为用户或者模型,如果为模型则为模型id根据type判断
Msg string `gorm:"column:msg"` //消息内容
Status int `gorm:"column:status"` //0为未读1为已读
}
func CreateSession(userID int, name string) (error, uint) {
session := Session{UserID: userID, Name: name}
var res *gorm.DB
if proto.Config.SERVER_SQL_LOG {
res = DB.Debug().Create(&session)
} else {
res = DB.Create(&session)
}
return res.Error, session.ID
}
func FindSessionByID(id int) Session {
var session Session
if proto.Config.SERVER_SQL_LOG {
DB.Debug().Where("id = ?", id).First(&session)
} else {
DB.Where("id = ?", id).First(&session)
}
return session
}
// 获取用户最新的创建时间会话列表 50个
func FindSessionByUserID(userID int) []Session {
var sessions []Session
if proto.Config.SERVER_SQL_LOG {
DB.Debug().Where("user_id = ?", userID).Order("created_at DESC").Limit(50).Find(&sessions)
} else {
DB.Where("user_id = ?", userID).Order("created_at DESC").Limit(50).Find(&sessions)
}
return sessions
}
// 更新会话的名字
2025-03-23 13:17:03 +08:00
func UpdateSessionByID(id int, userId int, name string, context []int) error {
var res *gorm.DB
if proto.Config.SERVER_SQL_LOG {
2025-03-23 13:17:03 +08:00
res = DB.Debug().Model(&Session{}).Where("id = ? AND user_id = ?", id, userId).Updates(Session{Name: name, Context: context})
} else {
2025-03-23 13:17:03 +08:00
res = DB.Model(&Session{}).Where("id = ? AND user_id = ?", id, userId).Updates(Session{Name: name, Context: context})
}
return res.Error
}
// 删除会话
2025-03-21 16:20:24 +08:00
func DeleteSessionByID(id int) error {
var res *gorm.DB
if proto.Config.SERVER_SQL_LOG {
res = DB.Debug().Delete(&Session{}, id)
} else {
res = DB.Delete(&Session{}, id)
}
return res.Error
}
// 创建消息
func CreateMessage(sessionID, fromID, toID, msgType, status int, msg string) (error, uint) {
message := Message{SessionID: sessionID, FromID: fromID, ToID: toID, Type: msgType, Status: status, Msg: msg}
var res *gorm.DB
if proto.Config.SERVER_SQL_LOG {
res = DB.Debug().Create(&message)
} else {
res = DB.Create(&message)
}
return res.Error, message.ID
}
// 根据会话id获取消息
func FindMessageBySessionID(sessionID int) []Message {
var messages []Message
if proto.Config.SERVER_SQL_LOG {
DB.Debug().Where("session_id = ?", sessionID).Order("created_at DESC").Find(&messages)
} else {
DB.Where("session_id = ?", sessionID).Order("created_at DESC").Find(&messages)
}
return messages
}