mirror of
				https://github.com/yangjian102621/geekai.git
				synced 2025-11-04 08:13:43 +08:00 
			
		
		
		
	feat: allow to view chat message in manager console
This commit is contained in:
		@@ -10,6 +10,8 @@
 | 
			
		||||
* Bug修复:对话输入HTML标签不显示的问题
 | 
			
		||||
* 功能优化:gpt-4-all/gpts/midjourney-plus 支持第三方平台的 API KEY
 | 
			
		||||
* 功能新增:新增删除文件功能
 | 
			
		||||
* Bug修复:解决 MJ-Plus discord 图片下载失败问题,使用第三方平台中转地址下载
 | 
			
		||||
* 功能新增:后台管理新怎对话查看和检索功能
 | 
			
		||||
 | 
			
		||||
## v3.2.6
 | 
			
		||||
* 功能优化:恢复关闭注册系统配置项,管理员可以在后台关闭用户注册,只允许内部添加账号
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										244
									
								
								api/handler/admin/chat_handler.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										244
									
								
								api/handler/admin/chat_handler.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,244 @@
 | 
			
		||||
package admin
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"chatplus/core"
 | 
			
		||||
	"chatplus/core/types"
 | 
			
		||||
	"chatplus/handler"
 | 
			
		||||
	"chatplus/store/model"
 | 
			
		||||
	"chatplus/store/vo"
 | 
			
		||||
	"chatplus/utils"
 | 
			
		||||
	"chatplus/utils/resp"
 | 
			
		||||
	"github.com/gin-gonic/gin"
 | 
			
		||||
	"gorm.io/gorm"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type ChatHandler struct {
 | 
			
		||||
	handler.BaseHandler
 | 
			
		||||
	db *gorm.DB
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func NewChatHandler(app *core.AppServer, db *gorm.DB) *ChatHandler {
 | 
			
		||||
	h := ChatHandler{db: db}
 | 
			
		||||
	h.App = app
 | 
			
		||||
	return &h
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type chatItemVo struct {
 | 
			
		||||
	Username  string `json:"username"`
 | 
			
		||||
	UserId    uint   `json:"user_id"`
 | 
			
		||||
	ChatId    string `json:"chat_id"`
 | 
			
		||||
	Title     string `json:"title"`
 | 
			
		||||
	Model     string `json:"model"`
 | 
			
		||||
	Token     int    `json:"token"`
 | 
			
		||||
	CreatedAt int64  `json:"created_at"`
 | 
			
		||||
	MsgNum    int    `json:"msg_num"` // 消息数量
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (h *ChatHandler) List(c *gin.Context) {
 | 
			
		||||
	var data struct {
 | 
			
		||||
		Title    string   `json:"title"`
 | 
			
		||||
		UserId   uint     `json:"user_id"`
 | 
			
		||||
		Model    string   `json:"model"`
 | 
			
		||||
		CreateAt []string `json:"created_time"`
 | 
			
		||||
		Page     int      `json:"page"`
 | 
			
		||||
		PageSize int      `json:"page_size"`
 | 
			
		||||
	}
 | 
			
		||||
	if err := c.ShouldBindJSON(&data); err != nil {
 | 
			
		||||
		resp.ERROR(c, types.InvalidArgs)
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	session := h.db.Session(&gorm.Session{})
 | 
			
		||||
	if data.Title != "" {
 | 
			
		||||
		session = session.Where("title LIKE ?", "%"+data.Title+"%")
 | 
			
		||||
	}
 | 
			
		||||
	if data.UserId > 0 {
 | 
			
		||||
		session = session.Where("user_id = ?", data.UserId)
 | 
			
		||||
	}
 | 
			
		||||
	if data.Model != "" {
 | 
			
		||||
		session = session.Where("model = ?", data.Model)
 | 
			
		||||
	}
 | 
			
		||||
	if len(data.CreateAt) == 2 {
 | 
			
		||||
		start := utils.Str2stamp(data.CreateAt[0] + " 00:00:00")
 | 
			
		||||
		end := utils.Str2stamp(data.CreateAt[1] + " 00:00:00")
 | 
			
		||||
		session = session.Where("created_at >= ? AND created_at <= ?", start, end)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	var total int64
 | 
			
		||||
	session.Model(&model.ChatItem{}).Count(&total)
 | 
			
		||||
	var items []model.ChatItem
 | 
			
		||||
	var list = make([]chatItemVo, 0)
 | 
			
		||||
	offset := (data.Page - 1) * data.PageSize
 | 
			
		||||
	res := session.Order("id DESC").Offset(offset).Limit(data.PageSize).Find(&items)
 | 
			
		||||
	if res.Error == nil {
 | 
			
		||||
		userIds := make([]uint, 0)
 | 
			
		||||
		chatIds := make([]string, 0)
 | 
			
		||||
		for _, item := range items {
 | 
			
		||||
			userIds = append(userIds, item.UserId)
 | 
			
		||||
			chatIds = append(chatIds, item.ChatId)
 | 
			
		||||
		}
 | 
			
		||||
		var messages []model.ChatMessage
 | 
			
		||||
		var users []model.User
 | 
			
		||||
		h.db.Where("chat_id IN ?", chatIds).Find(&messages)
 | 
			
		||||
		h.db.Where("id IN ?", userIds).Find(&users)
 | 
			
		||||
 | 
			
		||||
		tokenMap := make(map[string]int)
 | 
			
		||||
		userMap := make(map[uint]string)
 | 
			
		||||
		msgMap := make(map[string]int)
 | 
			
		||||
		for _, msg := range messages {
 | 
			
		||||
			tokenMap[msg.ChatId] += msg.Tokens
 | 
			
		||||
			msgMap[msg.ChatId] += 1
 | 
			
		||||
		}
 | 
			
		||||
		for _, user := range users {
 | 
			
		||||
			userMap[user.Id] = user.Username
 | 
			
		||||
		}
 | 
			
		||||
		for _, item := range items {
 | 
			
		||||
			list = append(list, chatItemVo{
 | 
			
		||||
				UserId:    item.UserId,
 | 
			
		||||
				Username:  userMap[item.UserId],
 | 
			
		||||
				ChatId:    item.ChatId,
 | 
			
		||||
				Title:     item.Title,
 | 
			
		||||
				Model:     item.Model,
 | 
			
		||||
				Token:     tokenMap[item.ChatId],
 | 
			
		||||
				MsgNum:    msgMap[item.ChatId],
 | 
			
		||||
				CreatedAt: item.CreatedAt.Unix(),
 | 
			
		||||
			})
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	resp.SUCCESS(c, vo.NewPage(total, data.Page, data.PageSize, list))
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type chatMessageVo struct {
 | 
			
		||||
	Id        uint   `json:"id"`
 | 
			
		||||
	UserId    uint   `json:"user_id"`
 | 
			
		||||
	Username  string `json:"username"`
 | 
			
		||||
	Content   string `json:"content"`
 | 
			
		||||
	Type      string `json:"type"`
 | 
			
		||||
	Model     string `json:"model"`
 | 
			
		||||
	Token     int    `json:"token"`
 | 
			
		||||
	Icon      string `json:"icon"`
 | 
			
		||||
	CreatedAt int64  `json:"created_at"`
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Messages 读取聊天记录列表
 | 
			
		||||
func (h *ChatHandler) Messages(c *gin.Context) {
 | 
			
		||||
	var data struct {
 | 
			
		||||
		UserId   uint     `json:"user_id"`
 | 
			
		||||
		Content  string   `json:"content"`
 | 
			
		||||
		Model    string   `json:"model"`
 | 
			
		||||
		CreateAt []string `json:"created_time"`
 | 
			
		||||
		Page     int      `json:"page"`
 | 
			
		||||
		PageSize int      `json:"page_size"`
 | 
			
		||||
	}
 | 
			
		||||
	if err := c.ShouldBindJSON(&data); err != nil {
 | 
			
		||||
		resp.ERROR(c, types.InvalidArgs)
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	session := h.db.Session(&gorm.Session{})
 | 
			
		||||
	if data.Content != "" {
 | 
			
		||||
		session = session.Where("content LIKE ?", "%"+data.Content+"%")
 | 
			
		||||
	}
 | 
			
		||||
	if data.UserId > 0 {
 | 
			
		||||
		session = session.Where("user_id = ?", data.UserId)
 | 
			
		||||
	}
 | 
			
		||||
	if data.Model != "" {
 | 
			
		||||
		session = session.Where("model = ?", data.Model)
 | 
			
		||||
	}
 | 
			
		||||
	if len(data.CreateAt) == 2 {
 | 
			
		||||
		start := utils.Str2stamp(data.CreateAt[0] + " 00:00:00")
 | 
			
		||||
		end := utils.Str2stamp(data.CreateAt[1] + " 00:00:00")
 | 
			
		||||
		session = session.Where("created_at >= ? AND created_at <= ?", start, end)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	var total int64
 | 
			
		||||
	session.Model(&model.ChatMessage{}).Count(&total)
 | 
			
		||||
	var items []model.ChatMessage
 | 
			
		||||
	var list = make([]chatMessageVo, 0)
 | 
			
		||||
	offset := (data.Page - 1) * data.PageSize
 | 
			
		||||
	res := session.Order("id DESC").Offset(offset).Limit(data.PageSize).Find(&items)
 | 
			
		||||
	if res.Error == nil {
 | 
			
		||||
		userIds := make([]uint, 0)
 | 
			
		||||
		for _, item := range items {
 | 
			
		||||
			userIds = append(userIds, item.UserId)
 | 
			
		||||
		}
 | 
			
		||||
		var users []model.User
 | 
			
		||||
		h.db.Where("id IN ?", userIds).Find(&users)
 | 
			
		||||
		userMap := make(map[uint]string)
 | 
			
		||||
		for _, user := range users {
 | 
			
		||||
			userMap[user.Id] = user.Username
 | 
			
		||||
		}
 | 
			
		||||
		for _, item := range items {
 | 
			
		||||
			list = append(list, chatMessageVo{
 | 
			
		||||
				Id:        item.Id,
 | 
			
		||||
				UserId:    item.UserId,
 | 
			
		||||
				Username:  userMap[item.UserId],
 | 
			
		||||
				Content:   item.Content,
 | 
			
		||||
				Model:     item.Model,
 | 
			
		||||
				Token:     item.Tokens,
 | 
			
		||||
				Icon:      item.Icon,
 | 
			
		||||
				Type:      item.Type,
 | 
			
		||||
				CreatedAt: item.CreatedAt.Unix(),
 | 
			
		||||
			})
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	resp.SUCCESS(c, vo.NewPage(total, data.Page, data.PageSize, list))
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// History 获取聊天历史记录
 | 
			
		||||
func (h *ChatHandler) History(c *gin.Context) {
 | 
			
		||||
	chatId := c.Query("chat_id") // 会话 ID
 | 
			
		||||
	var items []model.ChatMessage
 | 
			
		||||
	var messages = make([]vo.HistoryMessage, 0)
 | 
			
		||||
	res := h.db.Where("chat_id = ?", chatId).Find(&items)
 | 
			
		||||
	if res.Error != nil {
 | 
			
		||||
		resp.ERROR(c, "No history message")
 | 
			
		||||
		return
 | 
			
		||||
	} else {
 | 
			
		||||
		for _, item := range items {
 | 
			
		||||
			var v vo.HistoryMessage
 | 
			
		||||
			err := utils.CopyObject(item, &v)
 | 
			
		||||
			v.CreatedAt = item.CreatedAt.Unix()
 | 
			
		||||
			v.UpdatedAt = item.UpdatedAt.Unix()
 | 
			
		||||
			if err == nil {
 | 
			
		||||
				messages = append(messages, v)
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	resp.SUCCESS(c, messages)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// RemoveChat 删除对话
 | 
			
		||||
func (h *ChatHandler) RemoveChat(c *gin.Context) {
 | 
			
		||||
	chatId := h.GetTrim(c, "chat_id")
 | 
			
		||||
	tx := h.db.Begin()
 | 
			
		||||
	// 删除聊天记录
 | 
			
		||||
	res := tx.Unscoped().Where("chat_id = ?", chatId).Delete(&model.ChatMessage{})
 | 
			
		||||
	if res.Error != nil {
 | 
			
		||||
		resp.ERROR(c, "failed to remove chat message")
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// 删除对话
 | 
			
		||||
	res = tx.Unscoped().Where("chat_id = ?", chatId).Delete(model.ChatItem{})
 | 
			
		||||
	if res.Error != nil {
 | 
			
		||||
		tx.Rollback() // 回滚
 | 
			
		||||
		resp.ERROR(c, "failed to remove chat")
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	tx.Commit()
 | 
			
		||||
	resp.SUCCESS(c)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// RemoveMessage 删除聊天记录
 | 
			
		||||
func (h *ChatHandler) RemoveMessage(c *gin.Context) {
 | 
			
		||||
	id := h.GetInt(c, "id", 0)
 | 
			
		||||
	tx := h.db.Unscoped().Delete(&model.ChatMessage{}, id)
 | 
			
		||||
	if tx.Error != nil {
 | 
			
		||||
		resp.ERROR(c, "更新数据库失败!")
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
	resp.SUCCESS(c)
 | 
			
		||||
}
 | 
			
		||||
@@ -48,7 +48,7 @@ func (h *DashboardHandler) Stats(c *gin.Context) {
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// tokens took stats
 | 
			
		||||
	var historyMessages []model.HistoryMessage
 | 
			
		||||
	var historyMessages []model.ChatMessage
 | 
			
		||||
	res = h.db.Where("created_at > ?", zeroTime).Find(&historyMessages)
 | 
			
		||||
	for _, item := range historyMessages {
 | 
			
		||||
		stats.Tokens += item.Tokens
 | 
			
		||||
 
 | 
			
		||||
@@ -176,7 +176,7 @@ func (h *UserHandler) Remove(c *gin.Context) {
 | 
			
		||||
			return
 | 
			
		||||
		}
 | 
			
		||||
		// 删除聊天历史记录
 | 
			
		||||
		res = h.db.Where("user_id = ?", id).Delete(&model.HistoryMessage{})
 | 
			
		||||
		res = h.db.Where("user_id = ?", id).Delete(&model.ChatMessage{})
 | 
			
		||||
		if res.Error != nil {
 | 
			
		||||
			tx.Rollback()
 | 
			
		||||
			resp.ERROR(c, "删除失败")
 | 
			
		||||
 
 | 
			
		||||
@@ -126,7 +126,7 @@ func (h *ChatHandler) sendAzureMessage(
 | 
			
		||||
				if err != nil {
 | 
			
		||||
					logger.Error(err)
 | 
			
		||||
				}
 | 
			
		||||
				historyUserMsg := model.HistoryMessage{
 | 
			
		||||
				historyUserMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
@@ -148,7 +148,7 @@ func (h *ChatHandler) sendAzureMessage(
 | 
			
		||||
				totalTokens, _ := utils.CalcTokens(message.Content, req.Model)
 | 
			
		||||
				totalTokens += getTotalTokens(req)
 | 
			
		||||
 | 
			
		||||
				historyReplyMsg := model.HistoryMessage{
 | 
			
		||||
				historyReplyMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
 
 | 
			
		||||
@@ -151,7 +151,7 @@ func (h *ChatHandler) sendBaiduMessage(
 | 
			
		||||
				if err != nil {
 | 
			
		||||
					logger.Error(err)
 | 
			
		||||
				}
 | 
			
		||||
				historyUserMsg := model.HistoryMessage{
 | 
			
		||||
				historyUserMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
@@ -173,7 +173,7 @@ func (h *ChatHandler) sendBaiduMessage(
 | 
			
		||||
				// 计算本次对话消耗的总 token 数量
 | 
			
		||||
				replyToken, _ := utils.CalcTokens(message.Content, req.Model)
 | 
			
		||||
				totalTokens := replyToken + getTotalTokens(req)
 | 
			
		||||
				historyReplyMsg := model.HistoryMessage{
 | 
			
		||||
				historyReplyMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
 
 | 
			
		||||
@@ -325,7 +325,7 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session *types.ChatSessio
 | 
			
		||||
 | 
			
		||||
			// loading recent chat history as chat context
 | 
			
		||||
			if chatConfig.ContextDeep > 0 {
 | 
			
		||||
				var historyMessages []model.HistoryMessage
 | 
			
		||||
				var historyMessages []model.ChatMessage
 | 
			
		||||
				res := h.db.Debug().Where("chat_id = ? and use_context = 1", session.ChatId).Limit(chatConfig.ContextDeep).Order("id desc").Find(&historyMessages)
 | 
			
		||||
				if res.Error == nil {
 | 
			
		||||
					for i := len(historyMessages) - 1; i >= 0; i-- {
 | 
			
		||||
@@ -390,7 +390,7 @@ func (h *ChatHandler) Tokens(c *gin.Context) {
 | 
			
		||||
 | 
			
		||||
	// 如果没有传入 text 字段,则说明是获取当前 reply 总的 token 消耗(带上下文)
 | 
			
		||||
	if data.Text == "" && data.ChatId != "" {
 | 
			
		||||
		var item model.HistoryMessage
 | 
			
		||||
		var item model.ChatMessage
 | 
			
		||||
		userId, _ := c.Get(types.LoginUserID)
 | 
			
		||||
		res := h.db.Where("user_id = ?", userId).Where("chat_id = ?", data.ChatId).Last(&item)
 | 
			
		||||
		if res.Error != nil {
 | 
			
		||||
 
 | 
			
		||||
@@ -95,7 +95,7 @@ func (h *ChatHandler) Clear(c *gin.Context) {
 | 
			
		||||
			return res.Error
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		res = h.db.Where("user_id = ? AND chat_id IN ?", user.Id, chatIds).Delete(&model.HistoryMessage{})
 | 
			
		||||
		res = h.db.Where("user_id = ? AND chat_id IN ?", user.Id, chatIds).Delete(&model.ChatMessage{})
 | 
			
		||||
		if res.Error != nil {
 | 
			
		||||
			return res.Error
 | 
			
		||||
		}
 | 
			
		||||
@@ -116,7 +116,7 @@ func (h *ChatHandler) Clear(c *gin.Context) {
 | 
			
		||||
// History 获取聊天历史记录
 | 
			
		||||
func (h *ChatHandler) History(c *gin.Context) {
 | 
			
		||||
	chatId := c.Query("chat_id") // 会话 ID
 | 
			
		||||
	var items []model.HistoryMessage
 | 
			
		||||
	var items []model.ChatMessage
 | 
			
		||||
	var messages = make([]vo.HistoryMessage, 0)
 | 
			
		||||
	res := h.db.Where("chat_id = ?", chatId).Find(&items)
 | 
			
		||||
	if res.Error != nil {
 | 
			
		||||
 
 | 
			
		||||
@@ -130,7 +130,7 @@ func (h *ChatHandler) sendChatGLMMessage(
 | 
			
		||||
				if err != nil {
 | 
			
		||||
					logger.Error(err)
 | 
			
		||||
				}
 | 
			
		||||
				historyUserMsg := model.HistoryMessage{
 | 
			
		||||
				historyUserMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
@@ -152,7 +152,7 @@ func (h *ChatHandler) sendChatGLMMessage(
 | 
			
		||||
				// 计算本次对话消耗的总 token 数量
 | 
			
		||||
				replyToken, _ := utils.CalcTokens(message.Content, req.Model)
 | 
			
		||||
				totalTokens := replyToken + getTotalTokens(req)
 | 
			
		||||
				historyReplyMsg := model.HistoryMessage{
 | 
			
		||||
				historyReplyMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
 
 | 
			
		||||
@@ -46,6 +46,8 @@ func (h *ChatHandler) sendOpenAiMessage(
 | 
			
		||||
 | 
			
		||||
		utils.ReplyMessage(ws, ErrorMsg)
 | 
			
		||||
		utils.ReplyMessage(ws, ErrImg)
 | 
			
		||||
		all, _ := io.ReadAll(response.Body)
 | 
			
		||||
		logger.Error(string(all))
 | 
			
		||||
		return err
 | 
			
		||||
	} else {
 | 
			
		||||
		defer response.Body.Close()
 | 
			
		||||
@@ -197,7 +199,7 @@ func (h *ChatHandler) sendOpenAiMessage(
 | 
			
		||||
				if err != nil {
 | 
			
		||||
					logger.Error(err)
 | 
			
		||||
				}
 | 
			
		||||
				historyUserMsg := model.HistoryMessage{
 | 
			
		||||
				historyUserMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
@@ -227,7 +229,7 @@ func (h *ChatHandler) sendOpenAiMessage(
 | 
			
		||||
				}
 | 
			
		||||
				totalTokens += getTotalTokens(req)
 | 
			
		||||
 | 
			
		||||
				historyReplyMsg := model.HistoryMessage{
 | 
			
		||||
				historyReplyMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
 
 | 
			
		||||
@@ -151,7 +151,7 @@ func (h *ChatHandler) sendQWenMessage(
 | 
			
		||||
				if err != nil {
 | 
			
		||||
					logger.Error(err)
 | 
			
		||||
				}
 | 
			
		||||
				historyUserMsg := model.HistoryMessage{
 | 
			
		||||
				historyUserMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
@@ -173,7 +173,7 @@ func (h *ChatHandler) sendQWenMessage(
 | 
			
		||||
				// 计算本次对话消耗的总 token 数量
 | 
			
		||||
				replyToken, _ := utils.CalcTokens(message.Content, req.Model)
 | 
			
		||||
				totalTokens := replyToken + getTotalTokens(req)
 | 
			
		||||
				historyReplyMsg := model.HistoryMessage{
 | 
			
		||||
				historyReplyMsg := model.ChatMessage{
 | 
			
		||||
					UserId:     userVo.Id,
 | 
			
		||||
					ChatId:     session.ChatId,
 | 
			
		||||
					RoleId:     role.Id,
 | 
			
		||||
 
 | 
			
		||||
@@ -189,7 +189,7 @@ func (h *ChatHandler) sendXunFeiMessage(
 | 
			
		||||
			if err != nil {
 | 
			
		||||
				logger.Error(err)
 | 
			
		||||
			}
 | 
			
		||||
			historyUserMsg := model.HistoryMessage{
 | 
			
		||||
			historyUserMsg := model.ChatMessage{
 | 
			
		||||
				UserId:     userVo.Id,
 | 
			
		||||
				ChatId:     session.ChatId,
 | 
			
		||||
				RoleId:     role.Id,
 | 
			
		||||
@@ -211,7 +211,7 @@ func (h *ChatHandler) sendXunFeiMessage(
 | 
			
		||||
			// 计算本次对话消耗的总 token 数量
 | 
			
		||||
			replyToken, _ := utils.CalcTokens(message.Content, req.Model)
 | 
			
		||||
			totalTokens := replyToken + getTotalTokens(req)
 | 
			
		||||
			historyReplyMsg := model.HistoryMessage{
 | 
			
		||||
			historyReplyMsg := model.ChatMessage{
 | 
			
		||||
				UserId:     userVo.Id,
 | 
			
		||||
				ChatId:     session.ChatId,
 | 
			
		||||
				RoleId:     role.Id,
 | 
			
		||||
 
 | 
			
		||||
@@ -247,7 +247,7 @@ func (h *FunctionHandler) Dall3(c *gin.Context) {
 | 
			
		||||
	} else {
 | 
			
		||||
		request = req.C().R()
 | 
			
		||||
	}
 | 
			
		||||
	logger.Debugf("Sending %s request, ApiURL:%s, Password:%s, PROXY: %s", apiKey.Platform, apiKey.ApiURL, apiKey.Value, h.proxyURL)
 | 
			
		||||
	logger.Debugf("Sending %s request, ApiURL:%s, API KEY:%s, PROXY: %s", apiKey.Platform, apiKey.ApiURL, apiKey.Value, h.proxyURL)
 | 
			
		||||
	r, err := request.SetHeader("Content-Type", "application/json").
 | 
			
		||||
		SetHeader("Authorization", "Bearer "+apiKey.Value).
 | 
			
		||||
		SetBody(imgReq{
 | 
			
		||||
@@ -264,6 +264,7 @@ func (h *FunctionHandler) Dall3(c *gin.Context) {
 | 
			
		||||
	}
 | 
			
		||||
	// 更新 API KEY 的最后使用时间
 | 
			
		||||
	h.db.Model(&apiKey).UpdateColumn("last_used_at", time.Now().Unix())
 | 
			
		||||
	logger.Debugf("%+v", res)
 | 
			
		||||
	// 存储图片
 | 
			
		||||
	imgURL, err := h.uploadManager.GetUploadHandler().PutImg(res.Data[0].Url, false)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										10
									
								
								api/main.go
									
									
									
									
									
								
							
							
						
						
									
										10
									
								
								api/main.go
									
									
									
									
									
								
							@@ -136,6 +136,7 @@ func main() {
 | 
			
		||||
		fx.Provide(admin.NewChatModelHandler),
 | 
			
		||||
		fx.Provide(admin.NewProductHandler),
 | 
			
		||||
		fx.Provide(admin.NewOrderHandler),
 | 
			
		||||
		fx.Provide(admin.NewChatHandler),
 | 
			
		||||
 | 
			
		||||
		// 创建服务
 | 
			
		||||
		fx.Provide(sms.NewSendServiceManager),
 | 
			
		||||
@@ -372,7 +373,14 @@ func main() {
 | 
			
		||||
			group.POST("zaobao", h.ZaoBao)
 | 
			
		||||
			group.POST("dalle3", h.Dall3)
 | 
			
		||||
		}),
 | 
			
		||||
 | 
			
		||||
		fx.Invoke(func(s *core.AppServer, h *admin.ChatHandler) {
 | 
			
		||||
			group := s.Engine.Group("/api/admin/chat/")
 | 
			
		||||
			group.POST("list", h.List)
 | 
			
		||||
			group.POST("message", h.Messages)
 | 
			
		||||
			group.GET("history", h.History)
 | 
			
		||||
			group.GET("remove", h.RemoveChat)
 | 
			
		||||
			group.GET("message/remove", h.RemoveMessage)
 | 
			
		||||
		}),
 | 
			
		||||
		fx.Provide(handler.NewTestHandler),
 | 
			
		||||
		fx.Invoke(func(s *core.AppServer, h *handler.TestHandler) {
 | 
			
		||||
			s.Engine.GET("/api/test", h.Test)
 | 
			
		||||
 
 | 
			
		||||
@@ -90,6 +90,8 @@ func (c *Client) Imagine(task types.MjTask) (ImageRes, error) {
 | 
			
		||||
		SetErrorResult(&errRes).
 | 
			
		||||
		Post(apiURL)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		errStr, _ := io.ReadAll(r.Body)
 | 
			
		||||
		logger.Errorf("API 返回:%s, API URL: %s", string(errStr), apiURL)
 | 
			
		||||
		return ImageRes{}, fmt.Errorf("请求 API 出错:%v", err)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
@@ -14,7 +14,7 @@ var logger = logger2.GetLogger()
 | 
			
		||||
 | 
			
		||||
func NewSendServiceManager(config *types.AppConfig) (*ServiceManager, error) {
 | 
			
		||||
	active := Ali
 | 
			
		||||
	if config.OSS.Active != "" {
 | 
			
		||||
	if config.SMS.Active != "" {
 | 
			
		||||
		active = strings.ToUpper(config.SMS.Active)
 | 
			
		||||
	}
 | 
			
		||||
	var handler Service
 | 
			
		||||
 
 | 
			
		||||
@@ -2,7 +2,7 @@ package model
 | 
			
		||||
 | 
			
		||||
import "gorm.io/gorm"
 | 
			
		||||
 | 
			
		||||
type HistoryMessage struct {
 | 
			
		||||
type ChatMessage struct {
 | 
			
		||||
	BaseModel
 | 
			
		||||
	ChatId     string // 会话 ID
 | 
			
		||||
	UserId     uint   // 用户 ID
 | 
			
		||||
@@ -16,6 +16,6 @@ type HistoryMessage struct {
 | 
			
		||||
	DeletedAt  gorm.DeletedAt
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (HistoryMessage) TableName() string {
 | 
			
		||||
func (ChatMessage) TableName() string {
 | 
			
		||||
	return "chatgpt_chat_history"
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -116,6 +116,11 @@ const items = [
 | 
			
		||||
    index: '/admin/functions',
 | 
			
		||||
    title: '函数管理',
 | 
			
		||||
  },
 | 
			
		||||
  {
 | 
			
		||||
    icon: 'prompt',
 | 
			
		||||
    index: '/admin/chats',
 | 
			
		||||
    title: '对话管理',
 | 
			
		||||
  },
 | 
			
		||||
  {
 | 
			
		||||
    icon: 'config',
 | 
			
		||||
    index: '/admin/system',
 | 
			
		||||
 
 | 
			
		||||
@@ -156,6 +156,12 @@ const routes = [
 | 
			
		||||
                meta: {title: '函数管理'},
 | 
			
		||||
                component: () => import('@/views/admin/Functions.vue'),
 | 
			
		||||
            },
 | 
			
		||||
            {
 | 
			
		||||
                path: '/admin/chats',
 | 
			
		||||
                name: 'admin-chats',
 | 
			
		||||
                meta: {title: '对话管理'},
 | 
			
		||||
                component: () => import('@/views/admin/ChatList.vue'),
 | 
			
		||||
            },
 | 
			
		||||
        ]
 | 
			
		||||
    },
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
@@ -262,7 +262,6 @@ import 'highlight.js/styles/a11y-dark.css'
 | 
			
		||||
import {
 | 
			
		||||
  dateFormat,
 | 
			
		||||
  escapeHTML,
 | 
			
		||||
  isImage,
 | 
			
		||||
  isMobile,
 | 
			
		||||
  processContent,
 | 
			
		||||
  randString,
 | 
			
		||||
 
 | 
			
		||||
@@ -1,6 +1,6 @@
 | 
			
		||||
<template>
 | 
			
		||||
  <div class="custom-scroll">
 | 
			
		||||
    <div class="page-invitation" :style="{height: listBoxHeight + 'px'}">
 | 
			
		||||
    <div class="page-invitation">
 | 
			
		||||
      <div class="inner">
 | 
			
		||||
        <h2>会员推广计划</h2>
 | 
			
		||||
        <div class="share-box">
 | 
			
		||||
@@ -97,7 +97,6 @@ import InviteList from "@/components/InviteList.vue";
 | 
			
		||||
import {checkSession} from "@/action/session";
 | 
			
		||||
import {useRouter} from "vue-router";
 | 
			
		||||
 | 
			
		||||
const listBoxHeight = window.innerHeight
 | 
			
		||||
const inviteURL = ref("")
 | 
			
		||||
const qrImg = ref("")
 | 
			
		||||
const inviteChatCalls = ref(0)
 | 
			
		||||
@@ -163,6 +162,8 @@ onMounted(() => {
 | 
			
		||||
  overflow-y visible
 | 
			
		||||
 | 
			
		||||
  .inner {
 | 
			
		||||
    display flex
 | 
			
		||||
    flex-flow column
 | 
			
		||||
    max-width 1000px
 | 
			
		||||
    width 100%
 | 
			
		||||
    color #e1e1e1
 | 
			
		||||
@@ -251,6 +252,10 @@ onMounted(() => {
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
    .invite-logs {
 | 
			
		||||
      padding-bottom 20px
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										386
									
								
								web/src/views/admin/ChatList.vue
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										386
									
								
								web/src/views/admin/ChatList.vue
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,386 @@
 | 
			
		||||
<template>
 | 
			
		||||
  <div class="container chat-list">
 | 
			
		||||
    <el-tabs v-model="activeName" @tab-change="handleChange">
 | 
			
		||||
      <el-tab-pane label="对话列表" name="chat" v-loading="data.chat.loading">
 | 
			
		||||
        <div class="handle-box">
 | 
			
		||||
          <el-input v-model.number="data.chat.query.user_id" placeholder="账户ID" class="handle-input mr10"
 | 
			
		||||
                    @keyup="searchChat($event)"></el-input>
 | 
			
		||||
          <el-input v-model="data.chat.query.title" placeholder="对话标题" class="handle-input mr10"
 | 
			
		||||
                    @keyup="searchChat($event)"></el-input>
 | 
			
		||||
          <el-date-picker
 | 
			
		||||
              v-model="data.chat.query.created_at"
 | 
			
		||||
              type="daterange"
 | 
			
		||||
              start-placeholder="开始日期"
 | 
			
		||||
              end-placeholder="结束日期"
 | 
			
		||||
              format="YYYY-MM-DD"
 | 
			
		||||
              value-format="YYYY-MM-DD"
 | 
			
		||||
              style="margin-right: 10px;width: 200px; position: relative;top:3px;"
 | 
			
		||||
          />
 | 
			
		||||
          <el-button type="primary" :icon="Search" @click="fetchChatData">搜索</el-button>
 | 
			
		||||
        </div>
 | 
			
		||||
 | 
			
		||||
        <el-row>
 | 
			
		||||
          <el-table :data="data.chat.items" :row-key="row => row.id" table-layout="auto">
 | 
			
		||||
            <el-table-column prop="user_id" label="账户ID"/>
 | 
			
		||||
            <el-table-column prop="username" label="账户"/>
 | 
			
		||||
            <el-table-column prop="title" label="标题"/>
 | 
			
		||||
            <el-table-column prop="model" label="模型"/>
 | 
			
		||||
            <el-table-column prop="msg_num" label="消息数量"/>
 | 
			
		||||
            <el-table-column prop="token" label="消耗算力"/>
 | 
			
		||||
 | 
			
		||||
            <el-table-column label="创建时间">
 | 
			
		||||
              <template #default="scope">
 | 
			
		||||
                <span>{{ dateFormat(scope.row['created_at']) }}</span>
 | 
			
		||||
              </template>
 | 
			
		||||
            </el-table-column>
 | 
			
		||||
 | 
			
		||||
            <el-table-column label="操作" width="180">
 | 
			
		||||
              <template #default="scope">
 | 
			
		||||
                <el-button size="small" type="primary" @click="showMessages(scope.row)">查看</el-button>
 | 
			
		||||
                <el-popconfirm title="确定要删除当前记录吗?" @confirm="removeChat(scope.row)">
 | 
			
		||||
                  <template #reference>
 | 
			
		||||
                    <el-button size="small" type="danger">删除</el-button>
 | 
			
		||||
                  </template>
 | 
			
		||||
                </el-popconfirm>
 | 
			
		||||
              </template>
 | 
			
		||||
            </el-table-column>
 | 
			
		||||
          </el-table>
 | 
			
		||||
        </el-row>
 | 
			
		||||
 | 
			
		||||
        <div class="pagination">
 | 
			
		||||
          <el-pagination v-if="data.chat.total > 0" background
 | 
			
		||||
                         layout="total,prev, pager, next"
 | 
			
		||||
                         :hide-on-single-page="true"
 | 
			
		||||
                         v-model:current-page="data.chat.page"
 | 
			
		||||
                         v-model:page-size="data.chat.pageSize"
 | 
			
		||||
                         @current-change="fetchChatData()"
 | 
			
		||||
                         :total="data.chat.total"/>
 | 
			
		||||
 | 
			
		||||
        </div>
 | 
			
		||||
      </el-tab-pane>
 | 
			
		||||
      <el-tab-pane label="消息记录" name="message">
 | 
			
		||||
        <div class="handle-box">
 | 
			
		||||
          <el-input v-model.number="data.message.query.user_id" placeholder="账户ID" class="handle-input mr10"
 | 
			
		||||
                    @keyup="searchMessage($event)"></el-input>
 | 
			
		||||
          <el-input v-model="data.message.query.content" placeholder="消息内容" class="handle-input mr10"
 | 
			
		||||
                    @keyup="searchMessage($event)"></el-input>
 | 
			
		||||
          <el-input v-model="data.message.query.model" placeholder="模型" class="handle-input mr10"
 | 
			
		||||
                    @keyup="searchMessage($event)"></el-input>
 | 
			
		||||
          <el-date-picker
 | 
			
		||||
              v-model="data.message.query.created_at"
 | 
			
		||||
              type="daterange"
 | 
			
		||||
              start-placeholder="开始日期"
 | 
			
		||||
              end-placeholder="结束日期"
 | 
			
		||||
              format="YYYY-MM-DD"
 | 
			
		||||
              value-format="YYYY-MM-DD"
 | 
			
		||||
              style="margin-right: 10px;width: 200px; position: relative;top:3px;"
 | 
			
		||||
          />
 | 
			
		||||
          <el-button type="primary" :icon="Search" @click="fetchMessageData">搜索</el-button>
 | 
			
		||||
        </div>
 | 
			
		||||
 | 
			
		||||
        <el-row>
 | 
			
		||||
          <el-table :data="data.message.items" :row-key="row => row.id" table-layout="auto">
 | 
			
		||||
            <el-table-column prop="user_id" label="账户ID"/>
 | 
			
		||||
            <el-table-column prop="username" label="账户"/>
 | 
			
		||||
            <el-table-column label="角色">
 | 
			
		||||
              <template #default="scope">
 | 
			
		||||
                <el-avatar :size="30" :src="scope.row.icon"/>
 | 
			
		||||
              </template>
 | 
			
		||||
            </el-table-column>
 | 
			
		||||
            <el-table-column prop="model" label="模型"/>
 | 
			
		||||
 | 
			
		||||
            <el-table-column label="消息内容">
 | 
			
		||||
              <template #default="scope">
 | 
			
		||||
                <el-text style="width: 200px" truncated @click="showContent(scope.row.content)">
 | 
			
		||||
                  {{ scope.row.content }}
 | 
			
		||||
                </el-text>
 | 
			
		||||
              </template>
 | 
			
		||||
            </el-table-column>
 | 
			
		||||
 | 
			
		||||
            <el-table-column prop="token" label="算力"/>
 | 
			
		||||
 | 
			
		||||
            <el-table-column label="创建时间">
 | 
			
		||||
              <template #default="scope">
 | 
			
		||||
                <span>{{ dateFormat(scope.row['created_at']) }}</span>
 | 
			
		||||
              </template>
 | 
			
		||||
            </el-table-column>
 | 
			
		||||
 | 
			
		||||
            <el-table-column label="操作" width="180">
 | 
			
		||||
              <template #default="scope">
 | 
			
		||||
                <el-button size="small" type="primary" @click="showContent(scope.row.content)">查看</el-button>
 | 
			
		||||
                <el-popconfirm title="确定要删除当前记录吗?" @confirm="removeMessage(scope.row)">
 | 
			
		||||
                  <template #reference>
 | 
			
		||||
                    <el-button size="small" type="danger">删除</el-button>
 | 
			
		||||
                  </template>
 | 
			
		||||
                </el-popconfirm>
 | 
			
		||||
              </template>
 | 
			
		||||
            </el-table-column>
 | 
			
		||||
          </el-table>
 | 
			
		||||
        </el-row>
 | 
			
		||||
 | 
			
		||||
        <div class="pagination">
 | 
			
		||||
          <el-pagination v-if="data.message.total > 0" background
 | 
			
		||||
                         layout="total,prev, pager, next"
 | 
			
		||||
                         :hide-on-single-page="true"
 | 
			
		||||
                         v-model:current-page="data.message.page"
 | 
			
		||||
                         v-model:page-size="data.message.pageSize"
 | 
			
		||||
                         @current-change="fetchMessageData()"
 | 
			
		||||
                         :total="data.message.total"/>
 | 
			
		||||
 | 
			
		||||
        </div>
 | 
			
		||||
      </el-tab-pane>
 | 
			
		||||
    </el-tabs>
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
    <el-dialog
 | 
			
		||||
        v-model="showContentDialog"
 | 
			
		||||
        title="消息详情"
 | 
			
		||||
    >
 | 
			
		||||
      <div v-html="dialogContent" style="overflow: auto; max-height: 300px"></div>
 | 
			
		||||
    </el-dialog>
 | 
			
		||||
 | 
			
		||||
    <el-dialog
 | 
			
		||||
        v-model="showChatItemDialog"
 | 
			
		||||
        title="对话详情"
 | 
			
		||||
    >
 | 
			
		||||
      <div class="chat-box common-layout">
 | 
			
		||||
        <div v-for="item in messages" :key="item.id">
 | 
			
		||||
          <chat-prompt
 | 
			
		||||
              v-if="item.type==='prompt'"
 | 
			
		||||
              :icon="item.icon"
 | 
			
		||||
              :created-at="dateFormat(item['created_at'])"
 | 
			
		||||
              :tokens="item['tokens']"
 | 
			
		||||
              :model="item.model"
 | 
			
		||||
              :content="item.content"/>
 | 
			
		||||
          <chat-reply v-else-if="item.type==='reply'"
 | 
			
		||||
                      :icon="item.icon"
 | 
			
		||||
                      :org-content="item.orgContent"
 | 
			
		||||
                      :created-at="dateFormat(item['created_at'])"
 | 
			
		||||
                      :tokens="item['tokens']"
 | 
			
		||||
                      :content="item.content"/>
 | 
			
		||||
        </div>
 | 
			
		||||
      </div><!-- end chat box -->
 | 
			
		||||
    </el-dialog>
 | 
			
		||||
  </div>
 | 
			
		||||
</template>
 | 
			
		||||
 | 
			
		||||
<script setup>
 | 
			
		||||
import {onMounted, ref} from "vue";
 | 
			
		||||
import {httpGet, httpPost} from "@/utils/http";
 | 
			
		||||
import {ElMessage} from "element-plus";
 | 
			
		||||
import {dateFormat, processContent, removeArrayItem} from "@/utils/libs";
 | 
			
		||||
import {Search} from "@element-plus/icons-vue";
 | 
			
		||||
import 'highlight.js/styles/a11y-dark.css'
 | 
			
		||||
import hl from "highlight.js";
 | 
			
		||||
import ChatPrompt from "@/components/ChatPrompt.vue";
 | 
			
		||||
import ChatReply from "@/components/ChatReply.vue";
 | 
			
		||||
 | 
			
		||||
// 变量定义
 | 
			
		||||
const data = ref({
 | 
			
		||||
  "chat": {
 | 
			
		||||
    items: [],
 | 
			
		||||
    query: {title: "", created_at: [], page: 1, page_size: 15},
 | 
			
		||||
    total: 0,
 | 
			
		||||
    page: 1,
 | 
			
		||||
    pageSize: 15,
 | 
			
		||||
    loading: true
 | 
			
		||||
  },
 | 
			
		||||
  "message": {
 | 
			
		||||
    items: [],
 | 
			
		||||
    query: {title: "", created_at: [], page: 1, page_size: 15},
 | 
			
		||||
    total: 0,
 | 
			
		||||
    page: 1,
 | 
			
		||||
    pageSize: 15,
 | 
			
		||||
    loading: true
 | 
			
		||||
  }
 | 
			
		||||
})
 | 
			
		||||
const items = ref([])
 | 
			
		||||
const query = ref({title: "", created_at: []})
 | 
			
		||||
const total = ref(0)
 | 
			
		||||
const page = ref(1)
 | 
			
		||||
const pageSize = ref(15)
 | 
			
		||||
const loading = ref(true)
 | 
			
		||||
const activeName = ref("chat")
 | 
			
		||||
 | 
			
		||||
onMounted(() => {
 | 
			
		||||
  fetchChatData()
 | 
			
		||||
})
 | 
			
		||||
 | 
			
		||||
const handleChange = (tab) => {
 | 
			
		||||
  if (tab === "chat") {
 | 
			
		||||
    fetchChatData()
 | 
			
		||||
  } else if (tab === "message") {
 | 
			
		||||
    fetchMessageData()
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// 搜索对话
 | 
			
		||||
const searchChat = (evt) => {
 | 
			
		||||
  if (evt.keyCode === 13) {
 | 
			
		||||
    fetchChatData()
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// 搜索消息
 | 
			
		||||
const searchMessage = (evt) => {
 | 
			
		||||
  if (evt.keyCode === 13) {
 | 
			
		||||
    fetchMessageData()
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// 获取数据
 | 
			
		||||
const fetchChatData = () => {
 | 
			
		||||
  const d = data.value.chat
 | 
			
		||||
  d.query.page = d.page
 | 
			
		||||
  d.query.page_size = d.pageSize
 | 
			
		||||
  httpPost('/api/admin/chat/list', d.query).then((res) => {
 | 
			
		||||
    if (res.data) {
 | 
			
		||||
      d.items = res.data.items
 | 
			
		||||
      d.total = res.data.total
 | 
			
		||||
      d.page = res.data.page
 | 
			
		||||
      d.pageSize = res.data.page_size
 | 
			
		||||
    }
 | 
			
		||||
    d.loading = false
 | 
			
		||||
  }).catch(e => {
 | 
			
		||||
    ElMessage.error("获取数据失败:" + e.message);
 | 
			
		||||
  })
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
const fetchMessageData = () => {
 | 
			
		||||
  const d = data.value.message
 | 
			
		||||
  d.query.page = d.page
 | 
			
		||||
  d.query.page_size = d.pageSize
 | 
			
		||||
  httpPost('/api/admin/chat/message', d.query).then((res) => {
 | 
			
		||||
    if (res.data) {
 | 
			
		||||
      d.items = res.data.items
 | 
			
		||||
      d.total = res.data.total
 | 
			
		||||
      d.page = res.data.page
 | 
			
		||||
      d.pageSize = res.data.page_size
 | 
			
		||||
    }
 | 
			
		||||
    d.loading = false
 | 
			
		||||
  }).catch(e => {
 | 
			
		||||
    ElMessage.error("获取数据失败:" + e.message);
 | 
			
		||||
  })
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
const removeChat = function (row) {
 | 
			
		||||
  httpGet('/api/admin/chat/remove?chat_id=' + row.chat_id).then(() => {
 | 
			
		||||
    ElMessage.success("删除成功!")
 | 
			
		||||
    fetchChatData()
 | 
			
		||||
  }).catch((e) => {
 | 
			
		||||
    ElMessage.error("删除失败:" + e.message)
 | 
			
		||||
  })
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
const removeMessage = function (row) {
 | 
			
		||||
  httpGet('/api/admin/chat/message/remove?id=' + row.id).then(() => {
 | 
			
		||||
    ElMessage.success("删除成功!")
 | 
			
		||||
    fetchMessageData()
 | 
			
		||||
  }).catch((e) => {
 | 
			
		||||
    ElMessage.error("删除失败:" + e.message)
 | 
			
		||||
  })
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
const latexPlugin = require('markdown-it-latex2img')
 | 
			
		||||
const mathjaxPlugin = require('markdown-it-mathjax')
 | 
			
		||||
const md = require('markdown-it')({
 | 
			
		||||
  breaks: true,
 | 
			
		||||
  html: true,
 | 
			
		||||
  linkify: true,
 | 
			
		||||
  typographer: true,
 | 
			
		||||
  highlight: function (str, lang) {
 | 
			
		||||
    if (lang && hl.getLanguage(lang)) {
 | 
			
		||||
      // 处理代码高亮
 | 
			
		||||
      const preCode = hl.highlight(lang, str, true).value
 | 
			
		||||
      // 将代码包裹在 pre 中
 | 
			
		||||
      return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code></pre>`
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // 处理代码高亮
 | 
			
		||||
    const preCode = md.utils.escapeHtml(str)
 | 
			
		||||
    // 将代码包裹在 pre 中
 | 
			
		||||
    return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code></pre>`
 | 
			
		||||
  }
 | 
			
		||||
});
 | 
			
		||||
md.use(latexPlugin)
 | 
			
		||||
md.use(mathjaxPlugin)
 | 
			
		||||
 | 
			
		||||
const showContentDialog = ref(false)
 | 
			
		||||
const dialogContent = ref("")
 | 
			
		||||
const showContent = (content) => {
 | 
			
		||||
  showContentDialog.value = true
 | 
			
		||||
  dialogContent.value = md.render(processContent(content))
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
const showChatItemDialog = ref(false)
 | 
			
		||||
const messages = ref([])
 | 
			
		||||
const showMessages = (row) => {
 | 
			
		||||
  showChatItemDialog.value = true
 | 
			
		||||
  messages.value = []
 | 
			
		||||
  httpGet('/api/admin/chat/history?chat_id=' + row.chat_id).then(res => {
 | 
			
		||||
    const data = res.data
 | 
			
		||||
    for (let i = 0; i < data.length; i++) {
 | 
			
		||||
      data[i].orgContent = data[i].content;
 | 
			
		||||
      data[i].content = md.render(processContent(data[i].content))
 | 
			
		||||
      messages.value.push(data[i]);
 | 
			
		||||
    }
 | 
			
		||||
  }).catch(e => {
 | 
			
		||||
    // TODO: 显示重新加载按钮
 | 
			
		||||
    ElMessage.error('加载聊天记录失败:' + e.message);
 | 
			
		||||
  })
 | 
			
		||||
}
 | 
			
		||||
</script>
 | 
			
		||||
 | 
			
		||||
<style lang="stylus" scoped>
 | 
			
		||||
.chat-list {
 | 
			
		||||
 | 
			
		||||
  .handle-box {
 | 
			
		||||
    .handle-input {
 | 
			
		||||
      max-width 150px;
 | 
			
		||||
      margin-right 10px;
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  .opt-box {
 | 
			
		||||
    padding-bottom: 10px;
 | 
			
		||||
    display flex;
 | 
			
		||||
    justify-content flex-end
 | 
			
		||||
 | 
			
		||||
    .el-icon {
 | 
			
		||||
      margin-right: 5px;
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  .el-select {
 | 
			
		||||
    width: 100%
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  .chat-box {
 | 
			
		||||
    overflow-y: auto;
 | 
			
		||||
    overflow-x hidden
 | 
			
		||||
 | 
			
		||||
    // 变量定义
 | 
			
		||||
    --content-font-size: 16px;
 | 
			
		||||
    --content-color: #c1c1c1;
 | 
			
		||||
 | 
			
		||||
    font-family: 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
 | 
			
		||||
    height 90vh
 | 
			
		||||
 | 
			
		||||
    .chat-line {
 | 
			
		||||
      // 隐藏滚动条
 | 
			
		||||
 | 
			
		||||
      ::-webkit-scrollbar {
 | 
			
		||||
        width: 0;
 | 
			
		||||
        height: 0;
 | 
			
		||||
        background-color: transparent;
 | 
			
		||||
      }
 | 
			
		||||
 | 
			
		||||
      font-size: 14px;
 | 
			
		||||
      display: flex;
 | 
			
		||||
      align-items: flex-start;
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
</style>
 | 
			
		||||
@@ -76,6 +76,8 @@ const login = function () {
 | 
			
		||||
 | 
			
		||||
  httpPost('/api/admin/login', {username: username.value.trim(), password: password.value.trim()}).then(res => {
 | 
			
		||||
    setAdminToken(res.data)
 | 
			
		||||
    // 解除事件绑定
 | 
			
		||||
    document.removeEventListener('keyup')
 | 
			
		||||
    router.push("/admin")
 | 
			
		||||
  }).catch((e) => {
 | 
			
		||||
    ElMessage.error('登录失败,' + e.message)
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user