From 329e3eee213a105dd2b3f12dfe2639b08a619eda Mon Sep 17 00:00:00 2001 From: RockYang Date: Thu, 17 Aug 2023 14:20:16 +0800 Subject: [PATCH] opt:Optimize the algorithm to check whether Midjourney images can continue to variation --- api/core/app_server.go | 6 +++--- api/core/types/locked_map.go | 2 +- api/handler/chat_handler.go | 9 +++------ api/handler/mj_handler.go | 2 +- api/handler/user_handler.go | 6 +----- docker/docker-compose.yaml | 2 +- web/src/components/ChatMidJourney.vue | 6 ++++-- web/src/store/session.js | 15 +++++++++++---- web/src/utils/http.js | 3 ++- web/src/views/ChatPlus.vue | 6 +++--- web/src/views/Login.vue | 4 +--- 11 files changed, 31 insertions(+), 30 deletions(-) diff --git a/api/core/app_server.go b/api/core/app_server.go index 99b1d2cd..fd25ed00 100644 --- a/api/core/app_server.go +++ b/api/core/app_server.go @@ -30,7 +30,7 @@ type AppServer struct { // 保存 Websocket 会话 UserId, 每个 UserId 只能连接一次 // 防止第三方直接连接 socket 调用 OpenAI API - ChatSession *types.LMap[string, types.ChatSession] //map[sessionId]UserId + ChatSession *types.LMap[string, *types.ChatSession] //map[sessionId]UserId ChatClients *types.LMap[string, *types.WsClient] // map[sessionId]Websocket 连接集合 ReqCancelFunc *types.LMap[string, context.CancelFunc] // HttpClient 请求取消 handle function Functions map[string]function.Function @@ -45,7 +45,7 @@ func NewServer(appConfig *types.AppConfig, functions map[string]function.Functio Config: appConfig, Engine: gin.Default(), ChatContexts: types.NewLMap[string, []interface{}](), - ChatSession: types.NewLMap[string, types.ChatSession](), + ChatSession: types.NewLMap[string, *types.ChatSession](), ChatClients: types.NewLMap[string, *types.WsClient](), ReqCancelFunc: types.NewLMap[string, context.CancelFunc](), MjTaskClients: types.NewLMap[string, *types.WsClient](), @@ -151,7 +151,7 @@ func corsMiddleware() gin.HandlerFunc { c.Header("Access-Control-Allow-Origin", origin) c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") //允许跨域设置可以返回其他子段,可以自定义字段 - c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type") + c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, Chat-Token") // 允许浏览器(客户端)可以解析的头部 (重要) c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers") //设置缓存时间 diff --git a/api/core/types/locked_map.go b/api/core/types/locked_map.go index 11d19d84..c69098ff 100644 --- a/api/core/types/locked_map.go +++ b/api/core/types/locked_map.go @@ -9,7 +9,7 @@ type MKey interface { string | int } type MValue interface { - *WsClient | ChatSession | context.CancelFunc | []interface{} | MjTask + *WsClient | *ChatSession | context.CancelFunc | []interface{} | MjTask } type LMap[K MKey, T MValue] struct { lock sync.RWMutex diff --git a/api/handler/chat_handler.go b/api/handler/chat_handler.go index 94a44061..5bbff3fd 100644 --- a/api/handler/chat_handler.go +++ b/api/handler/chat_handler.go @@ -49,9 +49,6 @@ func (h *ChatHandler) ChatHandle(c *gin.Context) { logger.Error(err) return } - // 设置读写超时时间 - //_ = ws.SetWriteDeadline(time.Now().Add(300 * time.Second)) - //_ = ws.SetReadDeadline(time.Now().Add(300 * time.Second)) sessionId := c.Query("session_id") roleId := h.GetInt(c, "role_id", 0) @@ -59,14 +56,14 @@ func (h *ChatHandler) ChatHandle(c *gin.Context) { chatModel := c.Query("model") session := h.App.ChatSession.Get(sessionId) - if session.SessionId == "" { + if session == nil { user, err := utils.GetLoginUser(c, h.db) if err != nil { logger.Info("用户未登录") c.Abort() return } - session = types.ChatSession{ + session = &types.ChatSession{ SessionId: sessionId, ClientIP: c.ClientIP(), Username: user.Username, @@ -137,7 +134,7 @@ func (h *ChatHandler) ChatHandle(c *gin.Context) { } // 将消息发送给 ChatGPT 并获取结果,通过 WebSocket 推送到客户端 -func (h *ChatHandler) sendMessage(ctx context.Context, session types.ChatSession, role model.ChatRole, prompt string, ws *types.WsClient) error { +func (h *ChatHandler) sendMessage(ctx context.Context, session *types.ChatSession, role model.ChatRole, prompt string, ws *types.WsClient) error { promptCreatedAt := time.Now() // 记录提问时间 var user model.User diff --git a/api/handler/mj_handler.go b/api/handler/mj_handler.go index ec55da48..790770ba 100644 --- a/api/handler/mj_handler.go +++ b/api/handler/mj_handler.go @@ -67,7 +67,7 @@ func (h *MidJourneyHandler) Notify(c *gin.Context) { return } - logger.Infof("收到 MidJourney 回调请求:%+v", data) + logger.Debugf("收到 MidJourney 回调请求:%+v", data) // the job is saved var job model.MidJourneyJob diff --git a/api/handler/user_handler.go b/api/handler/user_handler.go index 88d5c4e5..772c5edc 100644 --- a/api/handler/user_handler.go +++ b/api/handler/user_handler.go @@ -157,7 +157,6 @@ func (h *UserHandler) Login(c *gin.Context) { user.LastLoginAt = time.Now().Unix() h.db.Model(&user).Updates(user) - sessionId := utils.RandString(42) err := utils.SetLoginUser(c, user) if err != nil { resp.ERROR(c, "保存会话失败") @@ -165,9 +164,6 @@ func (h *UserHandler) Login(c *gin.Context) { return } - // 记录登录信息在服务端 - h.App.ChatSession.Put(sessionId, types.ChatSession{ClientIP: c.ClientIP(), UserId: user.Id, Username: data.Username, SessionId: sessionId}) - h.db.Create(&model.UserLoginLog{ UserId: user.Id, Username: user.Username, @@ -175,7 +171,7 @@ func (h *UserHandler) Login(c *gin.Context) { LoginAddress: utils.Ip2Region(h.searcher, c.ClientIP()), }) - resp.SUCCESS(c, sessionId) + resp.SUCCESS(c) } // Logout 注 销 diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml index fd4837ae..71602449 100644 --- a/docker/docker-compose.yaml +++ b/docker/docker-compose.yaml @@ -6,7 +6,7 @@ services: container_name: chatgpt-plus-go restart: always environment: - - DEBUG=false + - LOG_LEVEL=info - CONFIG_FILE=config.toml ports: - "5678:5678" diff --git a/web/src/components/ChatMidJourney.vue b/web/src/components/ChatMidJourney.vue index b64710c5..89f98e23 100644 --- a/web/src/components/ChatMidJourney.vue +++ b/web/src/components/ChatMidJourney.vue @@ -7,7 +7,7 @@
-
+
-
+
  • U1
  • @@ -86,6 +86,8 @@ if (data.value["image"]?.width > 0) { height.value = 350 * data.value["image"]?.height / data.value["image"]?.width localStorage.setItem(cacheKey, height.value) } +data.value["showOpt"] = data.value["content"]?.indexOf("- Image #") === -1; +// console.log(data.value) watch(() => props.content, (newVal) => { data.value = newVal; diff --git a/web/src/store/session.js b/web/src/store/session.js index 6a7b1b88..906b3566 100644 --- a/web/src/store/session.js +++ b/web/src/store/session.js @@ -1,19 +1,26 @@ /* eslint-disable no-constant-condition */ +import {randString} from "@/utils/libs"; + /** * storage handler */ -const SessionUserKey = 'SESSION_ID'; +const SessionIDKey = 'SESSION_ID'; export function getSessionId() { - return sessionStorage.getItem(SessionUserKey) + let sessionId = sessionStorage.getItem(SessionIDKey) + if (!sessionId) { + sessionId = randString(42) + setSessionId(sessionId) + } + return sessionId } export function removeLoginUser() { - sessionStorage.removeItem(SessionUserKey) + sessionStorage.removeItem(SessionIDKey) } export function setSessionId(sessionId) { - sessionStorage.setItem(SessionUserKey, sessionId) + sessionStorage.setItem(SessionIDKey, sessionId) } diff --git a/web/src/utils/http.js b/web/src/utils/http.js index 3dc3acd5..7500b080 100644 --- a/web/src/utils/http.js +++ b/web/src/utils/http.js @@ -1,4 +1,5 @@ import axios from 'axios' +import {getSessionId} from "@/store/session"; axios.defaults.timeout = 10000 axios.defaults.baseURL = process.env.VUE_APP_API_HOST @@ -9,7 +10,7 @@ axios.defaults.headers.post['Content-Type'] = 'application/json' axios.interceptors.request.use( config => { // set token - // config.headers['ChatGPT-TOKEN'] = getSessionId(); + config.headers['Chat-Token'] = getSessionId(); return config }, error => { return Promise.reject(error) diff --git a/web/src/views/ChatPlus.vue b/web/src/views/ChatPlus.vue index 02cac56a..212a4a9b 100644 --- a/web/src/views/ChatPlus.vue +++ b/web/src/views/ChatPlus.vue @@ -534,7 +534,7 @@ const connect = function (chat_id, role_id) { } else { // 加载聊天记录 loadChatHistory(chat_id); } - + }); _socket.addEventListener('message', event => { @@ -554,7 +554,7 @@ const connect = function (chat_id, role_id) { disableInput(true) const content = data.content; const md = require('markdown-it')({breaks: true}); - content.content = md.render(content.content) + content.html = md.render(content.content) let key = content.key // fixed bug: 执行 Upscale 和 Variation 操作的时候覆盖之前的绘画 if (content.status === "Finished") { @@ -773,7 +773,7 @@ const loadChatHistory = function (chatId) { continue; } else if (data[i].type === "mj") { data[i].content = JSON.parse(data[i].content) - data[i].content.content = md.render(data[i].content?.content) + data[i].content.html = md.render(data[i].content?.content) chatData.value.push(data[i]); continue; } diff --git a/web/src/views/Login.vue b/web/src/views/Login.vue index 3a73a987..69a850de 100644 --- a/web/src/views/Login.vue +++ b/web/src/views/Login.vue @@ -52,7 +52,6 @@ import {onMounted, ref} from "vue"; import {Lock, UserFilled} from "@element-plus/icons-vue"; import {httpPost} from "@/utils/http"; import {ElMessage} from "element-plus"; -import {setSessionId} from "@/store/session"; import {useRouter} from "vue-router"; import FooterBar from "@/components/FooterBar.vue"; import {isMobile} from "@/utils/libs"; @@ -78,8 +77,7 @@ const login = function () { return ElMessage.error('请输入密码'); } - httpPost('/api/user/login', {username: username.value.trim(), password: password.value.trim()}).then((res) => { - setSessionId(res.data) + httpPost('/api/user/login', {username: username.value.trim(), password: password.value.trim()}).then(() => { if (isMobile()) { router.push('/mobile') } else {