mirror of
https://github.com/yangjian102621/geekai.git
synced 2025-10-28 21:03:42 +08:00
Compare commits
25 Commits
v3.0.3
...
feat-plugi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9806d5ff4c | ||
|
|
d1d13a72e4 | ||
|
|
00c520d066 | ||
|
|
797ff66474 | ||
|
|
9d51a478b9 | ||
|
|
1d4179df75 | ||
|
|
917b6012e8 | ||
|
|
da14632794 | ||
|
|
a868a8a8b7 | ||
|
|
5037df744f | ||
|
|
da88a501ad | ||
|
|
b9885e8de4 | ||
|
|
22efe81080 | ||
|
|
2926717aef | ||
|
|
a49d54d66c | ||
|
|
ce0267e25b | ||
|
|
9088d22a66 | ||
|
|
1ff32d5d0a | ||
|
|
adf6916598 | ||
|
|
31c14bf748 | ||
|
|
5395385d1e | ||
|
|
0035da548b | ||
|
|
9bceaade05 | ||
|
|
3194becdad | ||
|
|
6174b17c24 |
18
README.md
18
README.md
@@ -6,9 +6,6 @@
|
||||
* 聊天体验跟 ChatGPT 官方版本完全一致。
|
||||
* 内置了各种预训练好的角色,比如小红书写手,英语翻译大师,苏格拉底,孔子,乔布斯,周报助手等。轻松满足你的各种聊天和应用需求。
|
||||
|
||||
**本项目基于 MIT 协议,免费开放全部源代码,可以作为个人学习使用或者商用。如需商用建议联系作者登记,仅做统计使用,
|
||||
优秀项目我们将在项目首页为您展示。**
|
||||
|
||||
## 功能截图
|
||||
|
||||
### 1.PC 端聊天界面
|
||||
@@ -41,8 +38,13 @@
|
||||
|
||||
### 7. 体验地址
|
||||
|
||||
> 体验地址:[https://www.chat-plus.net/chat](https://www.chat-plus.net/chat) <br/>
|
||||
> 涉及到数据隐私问题,没有提供共享账号,大家自己快速注册一个账号就可以免费体验
|
||||
> 免费体验地址:[https://www.chat-plus.net/chat](https://www.chat-plus.net/chat) <br/>
|
||||
> **注意:请合法使用,禁止输出任何敏感、不友好或违规的内容!!!**
|
||||
|
||||
## 使用须知
|
||||
|
||||
1. 本项目基于 MIT 协议,免费开放全部源代码,可以作为个人学习使用或者商用。
|
||||
2. 如需商用必须保留版权信息,请自觉遵守。确保合法合规使用,在运营过程中产生的一切任何后果自负,与作者无关。
|
||||
|
||||
## 项目介绍
|
||||
|
||||
@@ -182,7 +184,7 @@ docker-compose up -d
|
||||
|
||||
### 2. 修改配置文档
|
||||
|
||||
先拷贝项目中的 `api/go/config.sample.toml` 配置文档,修改代理地址和管理员密码:
|
||||
先拷贝项目中的 `api/config.sample.toml` 配置文档,修改代理地址和管理员密码:
|
||||
|
||||
如何修改请参考[修改配置文档](#2-修改配置文档)
|
||||
|
||||
@@ -285,7 +287,7 @@ server {
|
||||
3. 运行后端程序:
|
||||
|
||||
```shell
|
||||
cd api/go
|
||||
cd api
|
||||
# 1. 先下载依赖
|
||||
go mod tidy
|
||||
# 2. 运行程序
|
||||
@@ -338,7 +340,7 @@ npm run build
|
||||
你可以根据个人需求将项目打包成 windows/linux/darwin 平台项目。
|
||||
|
||||
```shell
|
||||
cd api/go
|
||||
cd api
|
||||
# for all platforms
|
||||
make all
|
||||
# for linux only
|
||||
|
||||
0
api/go/.gitignore → api/.gitignore
vendored
0
api/go/.gitignore → api/.gitignore
vendored
@@ -20,7 +20,7 @@ import (
|
||||
|
||||
type AppServer struct {
|
||||
Debug bool
|
||||
AppConfig *types.AppConfig
|
||||
Config *types.AppConfig
|
||||
Engine *gin.Engine
|
||||
ChatContexts *types.LMap[string, []types.Message] // 聊天上下文 Map [chatId] => []Message
|
||||
ChatConfig *types.ChatConfig // 聊天配置
|
||||
@@ -28,7 +28,7 @@ type AppServer struct {
|
||||
// 保存 Websocket 会话 UserId, 每个 UserId 只能连接一次
|
||||
// 防止第三方直接连接 socket 调用 OpenAI API
|
||||
ChatSession *types.LMap[string, types.ChatSession] //map[sessionId]UserId
|
||||
ChatClients *types.LMap[string, *types.WsClient] // Websocket 连接集合
|
||||
ChatClients *types.LMap[string, *types.WsClient] // map[sessionId]Websocket 连接集合
|
||||
ReqCancelFunc *types.LMap[string, context.CancelFunc] // HttpClient 请求取消 handle function
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ func NewServer(appConfig *types.AppConfig) *AppServer {
|
||||
gin.DefaultWriter = io.Discard
|
||||
return &AppServer{
|
||||
Debug: false,
|
||||
AppConfig: appConfig,
|
||||
Config: appConfig,
|
||||
Engine: gin.Default(),
|
||||
ChatContexts: types.NewLMap[string, []types.Message](),
|
||||
ChatSession: types.NewLMap[string, types.ChatSession](),
|
||||
@@ -53,11 +53,11 @@ func (s *AppServer) Init(debug bool) {
|
||||
s.Engine.Use(corsMiddleware())
|
||||
}
|
||||
|
||||
s.Engine.Use(sessionMiddleware(s.AppConfig))
|
||||
s.Engine.Use(sessionMiddleware(s.Config))
|
||||
s.Engine.Use(authorizeMiddleware(s))
|
||||
s.Engine.Use(errorHandler)
|
||||
// 添加静态资源访问
|
||||
s.Engine.Static("/static", s.AppConfig.StaticDir)
|
||||
s.Engine.Static("/static", s.Config.StaticDir)
|
||||
}
|
||||
|
||||
func (s *AppServer) Run(db *gorm.DB) error {
|
||||
@@ -71,15 +71,15 @@ func (s *AppServer) Run(db *gorm.DB) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof("http://%s", s.AppConfig.Listen)
|
||||
return s.Engine.Run(s.AppConfig.Listen)
|
||||
logger.Infof("http://%s", s.Config.Listen)
|
||||
return s.Engine.Run(s.Config.Listen)
|
||||
}
|
||||
|
||||
// 全局异常处理
|
||||
func errorHandler(c *gin.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger.Error("Handler Panic: %v\n", r)
|
||||
logger.Errorf("Handler Panic: %v", r)
|
||||
debug.PrintStack()
|
||||
c.JSON(http.StatusOK, types.BizVo{Code: types.Failed, Message: types.ErrorMsg})
|
||||
c.Abort()
|
||||
@@ -164,6 +164,7 @@ func authorizeMiddleware(s *AppServer) gin.HandlerFunc {
|
||||
if c.Request.URL.Path == "/api/user/login" ||
|
||||
c.Request.URL.Path == "/api/admin/login" ||
|
||||
c.Request.URL.Path == "/api/user/register" ||
|
||||
strings.HasPrefix(c.Request.URL.Path, "/api/verify/") ||
|
||||
strings.HasPrefix(c.Request.URL.Path, "/static/") ||
|
||||
c.Request.URL.Path == "/api/admin/config/get" {
|
||||
c.Next()
|
||||
@@ -183,7 +184,7 @@ func authorizeMiddleware(s *AppServer) gin.HandlerFunc {
|
||||
}
|
||||
session := sessions.Default(c)
|
||||
var value interface{}
|
||||
if strings.Contains(c.Request.URL.Path, "/api/admin/") {
|
||||
if strings.Contains(c.Request.URL.Path, "/api/admin/") { // 后台管理 API
|
||||
value = session.Get(types.SessionAdmin)
|
||||
} else {
|
||||
value = session.Get(types.SessionUser)
|
||||
@@ -15,13 +15,13 @@ var logger = logger2.GetLogger()
|
||||
|
||||
func NewDefaultConfig() *types.AppConfig {
|
||||
return &types.AppConfig{
|
||||
Listen: "0.0.0.0:5678",
|
||||
ProxyURL: "",
|
||||
Manager: types.Manager{Username: "admin", Password: "admin123"},
|
||||
StaticDir: "./static",
|
||||
StaticUrl: "http://localhost/5678/static",
|
||||
Redis: types.RedisConfig{Host: "localhost", Port: 6379, Password: ""},
|
||||
|
||||
Listen: "0.0.0.0:5678",
|
||||
ProxyURL: "",
|
||||
Manager: types.Manager{Username: "admin", Password: "admin123"},
|
||||
StaticDir: "./static",
|
||||
StaticUrl: "http://localhost/5678/static",
|
||||
Redis: types.RedisConfig{Host: "localhost", Port: 6379, Password: ""},
|
||||
AesEncryptKey: utils.RandString(24),
|
||||
Session: types.Session{
|
||||
Driver: types.SessionDriverCookie,
|
||||
SecretKey: utils.RandString(64),
|
||||
@@ -10,8 +10,9 @@ type ApiRequest struct {
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
FunctionCall FunctionCall `json:"function_call"`
|
||||
}
|
||||
|
||||
type ApiResponse struct {
|
||||
@@ -15,6 +15,16 @@ type AppConfig struct {
|
||||
StaticDir string // 静态资源目录
|
||||
StaticUrl string // 静态资源 URL
|
||||
Redis RedisConfig // redis 连接信息
|
||||
|
||||
AesEncryptKey string
|
||||
SmsConfig AliYunSmsConfig // 短信发送配置
|
||||
}
|
||||
|
||||
type AliYunSmsConfig struct {
|
||||
AccessKey string
|
||||
AccessSecret string
|
||||
Product string
|
||||
Domain string
|
||||
}
|
||||
|
||||
type RedisConfig struct {
|
||||
18
api/core/types/function.go
Normal file
18
api/core/types/function.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package types
|
||||
|
||||
type FunctionCall struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
}
|
||||
|
||||
type Function struct {
|
||||
Name string
|
||||
Description string
|
||||
Parameters []Parameter
|
||||
}
|
||||
|
||||
type Parameter struct {
|
||||
Type string
|
||||
Required []string
|
||||
Properties map[string]interface{}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ go 1.19
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.1.0
|
||||
github.com/aliyun/alibaba-cloud-sdk-go v1.62.405
|
||||
github.com/gin-contrib/sessions v0.0.5
|
||||
github.com/gin-gonic/gin v1.9.0
|
||||
github.com/gorilla/websocket v1.5.0
|
||||
@@ -24,15 +25,18 @@ require (
|
||||
github.com/gomodule/redigo v2.0.0+incompatible // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
|
||||
github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
go.uber.org/dig v1.16.1 // indirect
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
|
||||
golang.org/x/net v0.7.0 // indirect
|
||||
golang.org/x/text v0.7.0 // indirect
|
||||
golang.org/x/net v0.9.0 // indirect
|
||||
golang.org/x/text v0.9.0 // indirect
|
||||
google.golang.org/protobuf v1.28.1 // indirect
|
||||
gopkg.in/ini.v1 v1.66.2 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -48,13 +52,13 @@ require (
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/leodido/go-urn v1.2.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.17 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/ugorji/go/codec v1.2.9 // indirect
|
||||
go.uber.org/atomic v1.7.0 // indirect
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/fx v1.19.3
|
||||
go.uber.org/multierr v1.6.0 // indirect
|
||||
golang.org/x/crypto v0.6.0
|
||||
golang.org/x/sys v0.5.0 // indirect
|
||||
golang.org/x/sys v0.7.0 // indirect
|
||||
gorm.io/gorm v1.25.1
|
||||
)
|
||||
@@ -1,5 +1,7 @@
|
||||
github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I=
|
||||
github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
|
||||
github.com/aliyun/alibaba-cloud-sdk-go v1.62.405 h1:cKNFQmeCQFN0WNfjScKoVrGi7vXxTVbkCvCqSrOf+P4=
|
||||
github.com/aliyun/alibaba-cloud-sdk-go v1.62.405/go.mod h1:Api2AkmMgGaSUAhmk76oaFObkoeCPc/bKAqcyplPODs=
|
||||
github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04=
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw=
|
||||
@@ -32,6 +34,7 @@ github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ
|
||||
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||
github.com/goccy/go-json v0.10.0 h1:mXKd9Qw4NuzShiRlOXKews24ufknHO7gx30lsDyokKA=
|
||||
github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
@@ -58,11 +61,17 @@ github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkr
|
||||
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM=
|
||||
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
|
||||
github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
|
||||
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
|
||||
@@ -70,8 +79,10 @@ github.com/lionsoul2014/ip2region/binding/golang v0.0.0-20230415042440-a5e3d8259
|
||||
github.com/lionsoul2014/ip2region/binding/golang v0.0.0-20230415042440-a5e3d8259ae0/go.mod h1:C5LA5UO2ZXJrLaPLYtE1wUJMiyd/nwWaCO5cw/2pSHs=
|
||||
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
|
||||
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
@@ -79,9 +90,12 @@ github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
|
||||
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
|
||||
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b h1:FfH+VrHHk6Lxt9HdVS0PXzSXFyS2NbZKXv33FYPol0A=
|
||||
github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b/go.mod h1:AC62GU6hc0BrNm+9RK9VSiwa/EUe1bkIeFORAMcHvJU=
|
||||
github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU=
|
||||
github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkoukk/tiktoken-go v0.1.1-0.20230418101013-cae809389480 h1:IFhPCcB0/HtnEN+ZoUGDT55YgFCymbFJ15kXqs3nv5w=
|
||||
github.com/pkoukk/tiktoken-go v0.1.1-0.20230418101013-cae809389480/go.mod h1:BijIqAP84FMYC4XbdJgjyMpiSjusU8x0Y0W9K2t0QtU=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
@@ -103,10 +117,15 @@ github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFd
|
||||
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
|
||||
github.com/ugorji/go/codec v1.2.9 h1:rmenucSohSTiyL09Y+l2OCk+FrMxGMzho2+tjr5ticU=
|
||||
github.com/ugorji/go/codec v1.2.9/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
|
||||
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/dig v1.16.1 h1:+alNIBsl0qfY0j6epRubp/9obgtrObRAc5aD+6jbWY8=
|
||||
go.uber.org/dig v1.16.1/go.mod h1:557JTAUZT5bUK0SvCwikmLPPtdQhfvLYtO5tJgQSbnk=
|
||||
go.uber.org/fx v1.19.3 h1:YqMRE4+2IepTYCMOvXqQpRa+QAVdiSTnsHU4XNWBceA=
|
||||
@@ -121,30 +140,34 @@ golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUu
|
||||
golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc=
|
||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
|
||||
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
|
||||
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
|
||||
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/ini.v1 v1.66.2 h1:XfR1dOYubytKy4Shzc2LHrrGhU0lDCfDGG1yLPmpgsI=
|
||||
gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.4.7 h1:rY46lkCspzGHn7+IYsNpSfEv9tA+SU4SkkB+GFX125Y=
|
||||
@@ -36,7 +36,7 @@ func (h *ManagerHandler) Login(c *gin.Context) {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
return
|
||||
}
|
||||
manager := h.App.AppConfig.Manager
|
||||
manager := h.App.Config.Manager
|
||||
if data.Username == manager.Username && data.Password == manager.Password {
|
||||
err := utils.SetLoginAdmin(c, manager)
|
||||
if err != nil {
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"bytes"
|
||||
"chatplus/core"
|
||||
"chatplus/core/types"
|
||||
"chatplus/service/function"
|
||||
"chatplus/store/model"
|
||||
"chatplus/store/vo"
|
||||
"chatplus/utils"
|
||||
@@ -29,11 +30,12 @@ const ErrorMsg = "抱歉,AI 助手开小差了,请稍后再试。"
|
||||
|
||||
type ChatHandler struct {
|
||||
BaseHandler
|
||||
db *gorm.DB
|
||||
db *gorm.DB
|
||||
funcZaoBao *function.FuncZaoBao
|
||||
}
|
||||
|
||||
func NewChatHandler(app *core.AppServer, db *gorm.DB) *ChatHandler {
|
||||
handler := ChatHandler{db: db}
|
||||
func NewChatHandler(app *core.AppServer, db *gorm.DB, zaoBao *function.FuncZaoBao) *ChatHandler {
|
||||
handler := ChatHandler{db: db, funcZaoBao: zaoBao}
|
||||
handler.App = app
|
||||
return &handler
|
||||
}
|
||||
@@ -192,11 +194,14 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session types.ChatSession
|
||||
Content: prompt,
|
||||
})
|
||||
var apiKey string
|
||||
response, err := h.doRequest(ctx, userVo, &apiKey, req)
|
||||
response, err := h.fakeRequest(ctx, userVo, &apiKey, req)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "context canceled") {
|
||||
logger.Info("用户取消了请求:", prompt)
|
||||
return nil
|
||||
} else if strings.Contains(err.Error(), "no available key") {
|
||||
replyMessage(ws, "抱歉😔😔😔,系统已经没有可用的 API KEY🔑,您可以导入自己的 API KEY🔑 继续使用!🙏🙏🙏")
|
||||
return nil
|
||||
} else {
|
||||
logger.Error(err)
|
||||
}
|
||||
@@ -208,13 +213,16 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session types.ChatSession
|
||||
defer response.Body.Close()
|
||||
}
|
||||
|
||||
contentType := response.Header.Get("Content-Type")
|
||||
if strings.Contains(contentType, "text/event-stream") {
|
||||
//contentType := response.Header.Get("Content-Type")
|
||||
//if strings.Contains(contentType, "text/event-stream") || true {
|
||||
if true {
|
||||
replyCreatedAt := time.Now()
|
||||
// 循环读取 Chunk 消息
|
||||
var message = types.Message{}
|
||||
var contents = make([]string, 0)
|
||||
var responseBody = types.ApiResponse{}
|
||||
var functionCall = false
|
||||
var functionName string
|
||||
var arguments = make([]string, 0)
|
||||
reader := bufio.NewReader(response.Body)
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
@@ -226,10 +234,11 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session types.ChatSession
|
||||
}
|
||||
break
|
||||
}
|
||||
if !strings.Contains(line, "data:") {
|
||||
if !strings.Contains(line, "data:") || len(line) < 30 {
|
||||
continue
|
||||
}
|
||||
|
||||
var responseBody = types.ApiResponse{}
|
||||
err = json.Unmarshal([]byte(line[6:]), &responseBody)
|
||||
if err != nil || len(responseBody.Choices) == 0 { // 数据解析出错
|
||||
logger.Error(err, line)
|
||||
@@ -238,6 +247,24 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session types.ChatSession
|
||||
break
|
||||
}
|
||||
|
||||
fun := responseBody.Choices[0].Delta.FunctionCall
|
||||
if functionCall && fun.Name == "" {
|
||||
arguments = append(arguments, fun.Arguments)
|
||||
continue
|
||||
}
|
||||
|
||||
if !utils.IsEmptyValue(fun) {
|
||||
functionCall = true
|
||||
functionName = fun.Name
|
||||
replyChunkMessage(ws, types.WsMessage{Type: types.WsStart})
|
||||
replyChunkMessage(ws, types.WsMessage{Type: types.WsMiddle, Content: fmt.Sprintf("正在调用函数 %s 作答 ...\n\n", functionName)})
|
||||
continue
|
||||
}
|
||||
|
||||
if responseBody.Choices[0].FinishReason == "function_call" { // 函数调用完毕
|
||||
break
|
||||
}
|
||||
|
||||
// 初始化 role
|
||||
if responseBody.Choices[0].Delta.Role != "" && message.Role == "" {
|
||||
message.Role = responseBody.Choices[0].Delta.Role
|
||||
@@ -255,6 +282,23 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session types.ChatSession
|
||||
}
|
||||
} // end for
|
||||
|
||||
if functionCall { // 调用函数完成任务
|
||||
// TODO 调用函数完成任务
|
||||
data, err := h.funcZaoBao.Fetch()
|
||||
if err != nil {
|
||||
replyChunkMessage(ws, types.WsMessage{
|
||||
Type: types.WsMiddle,
|
||||
Content: "调用函数出错",
|
||||
})
|
||||
} else {
|
||||
replyChunkMessage(ws, types.WsMessage{
|
||||
Type: types.WsMiddle,
|
||||
Content: data,
|
||||
})
|
||||
}
|
||||
contents = append(contents, data)
|
||||
}
|
||||
|
||||
// 消息发送成功
|
||||
if len(contents) > 0 {
|
||||
// 更新用户的对话次数
|
||||
@@ -269,8 +313,8 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session types.ChatSession
|
||||
message.Content = strings.Join(contents, "")
|
||||
useMsg := types.Message{Role: "user", Content: prompt}
|
||||
|
||||
// 更新上下文消息
|
||||
if userVo.ChatConfig.EnableContext {
|
||||
// 更新上下文消息,如果是调用函数则不需要更新上下文
|
||||
if userVo.ChatConfig.EnableContext && functionCall == false {
|
||||
chatCtx = append(chatCtx, useMsg) // 提问消息
|
||||
chatCtx = append(chatCtx, message) // 回复消息
|
||||
h.App.ChatContexts.Put(session.ChatId, chatCtx)
|
||||
@@ -319,6 +363,10 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session types.ChatSession
|
||||
if res.Error != nil {
|
||||
logger.Error("failed to save reply history message: ", res.Error)
|
||||
}
|
||||
|
||||
// 统计用户 token 数量
|
||||
h.db.Model(&user).UpdateColumn("tokens", gorm.Expr("tokens + ?",
|
||||
historyUserMsg.Tokens+historyReplyMsg.Tokens))
|
||||
}
|
||||
|
||||
// 保存当前会话
|
||||
@@ -390,12 +438,11 @@ func (h *ChatHandler) doRequest(ctx context.Context, user vo.User, apiKey *strin
|
||||
request = request.WithContext(ctx)
|
||||
request.Header.Add("Content-Type", "application/json")
|
||||
|
||||
proxyURL := h.App.AppConfig.ProxyURL
|
||||
proxyURL := h.App.Config.ProxyURL
|
||||
if proxyURL == "" {
|
||||
client = &http.Client{}
|
||||
} else { // 使用代理
|
||||
uri := url.URL{}
|
||||
proxy, _ := uri.Parse(proxyURL)
|
||||
proxy, _ := url.Parse(proxyURL)
|
||||
client = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyURL(proxy),
|
||||
@@ -422,6 +469,13 @@ func (h *ChatHandler) doRequest(ctx context.Context, user vo.User, apiKey *strin
|
||||
return client.Do(request)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) fakeRequest(ctx context.Context, user vo.User, apiKey *string, req types.ApiRequest) (*http.Response, error) {
|
||||
link := "https://img.r9it.com/chatgpt/response"
|
||||
client := &http.Client{}
|
||||
request, _ := http.NewRequest(http.MethodGet, link, nil)
|
||||
return client.Do(request)
|
||||
}
|
||||
|
||||
// 回复客户片段端消息
|
||||
func replyChunkMessage(client types.Client, message types.WsMessage) {
|
||||
msg, err := json.Marshal(message)
|
||||
@@ -47,7 +47,7 @@ func (h *UploadHandler) Upload(c *gin.Context) {
|
||||
// 生成上传文件路径
|
||||
func (h *UploadHandler) genFilePath(filename string) (string, error) {
|
||||
now := time.Now()
|
||||
dir := fmt.Sprintf("%s/upload/%d/%d", h.App.AppConfig.StaticDir, now.Year(), now.Month())
|
||||
dir := fmt.Sprintf("%s/upload/%d/%d", h.App.Config.StaticDir, now.Year(), now.Month())
|
||||
_, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
err = os.MkdirAll(dir, 0755)
|
||||
@@ -63,5 +63,5 @@ func (h *UploadHandler) genFilePath(filename string) (string, error) {
|
||||
func (h *UploadHandler) genFileUrl(filePath string) string {
|
||||
now := time.Now()
|
||||
filename := filepath.Base(filePath)
|
||||
return fmt.Sprintf("%s/upload/%d/%d/%s", h.App.AppConfig.StaticUrl, now.Year(), now.Month(), filename)
|
||||
return fmt.Sprintf("%s/upload/%d/%d/%s", h.App.Config.StaticUrl, now.Year(), now.Month(), filename)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"chatplus/core"
|
||||
"chatplus/core/types"
|
||||
"chatplus/store"
|
||||
"chatplus/store/model"
|
||||
"chatplus/store/vo"
|
||||
"chatplus/utils"
|
||||
@@ -21,10 +22,11 @@ type UserHandler struct {
|
||||
BaseHandler
|
||||
db *gorm.DB
|
||||
searcher *xdb.Searcher
|
||||
levelDB *store.LevelDB
|
||||
}
|
||||
|
||||
func NewUserHandler(app *core.AppServer, db *gorm.DB, searcher *xdb.Searcher) *UserHandler {
|
||||
handler := &UserHandler{db: db, searcher: searcher}
|
||||
func NewUserHandler(app *core.AppServer, db *gorm.DB, searcher *xdb.Searcher, levelDB *store.LevelDB) *UserHandler {
|
||||
handler := &UserHandler{db: db, searcher: searcher, levelDB: levelDB}
|
||||
handler.App = app
|
||||
return handler
|
||||
}
|
||||
@@ -35,6 +37,8 @@ func (h *UserHandler) Register(c *gin.Context) {
|
||||
var data struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Mobile string `json:"mobile"`
|
||||
Code int `json:"code"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
@@ -52,13 +56,30 @@ func (h *UserHandler) Register(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 检查验证码
|
||||
key := CodeStorePrefix + data.Mobile
|
||||
var code int
|
||||
err := h.levelDB.Get(key, &code)
|
||||
if err != nil || code != data.Code {
|
||||
logger.Info(code)
|
||||
resp.ERROR(c, "短信验证码错误")
|
||||
return
|
||||
}
|
||||
|
||||
// check if the username is exists
|
||||
var item model.User
|
||||
tx := h.db.Where("username = ?", data.Username).First(&item)
|
||||
if tx.RowsAffected > 0 {
|
||||
res := h.db.Where("username = ?", data.Username).First(&item)
|
||||
if res.RowsAffected > 0 {
|
||||
resp.ERROR(c, "用户名已存在")
|
||||
return
|
||||
}
|
||||
|
||||
res = h.db.Where("mobile = ?", data.Mobile).First(&item)
|
||||
if res.RowsAffected > 0 {
|
||||
resp.ERROR(c, "该手机号码以及被注册,请更换其他手机号")
|
||||
return
|
||||
}
|
||||
|
||||
// 默认订阅所有角色
|
||||
var chatRoles []model.ChatRole
|
||||
h.db.Find(&chatRoles)
|
||||
@@ -75,6 +96,7 @@ func (h *UserHandler) Register(c *gin.Context) {
|
||||
Avatar: "/images/avatar/user.png",
|
||||
Salt: salt,
|
||||
Status: true,
|
||||
Mobile: data.Mobile,
|
||||
ChatRoles: utils.JsonEncode(roleKeys),
|
||||
ChatConfig: utils.JsonEncode(types.ChatConfig{
|
||||
Temperature: h.App.ChatConfig.Temperature,
|
||||
@@ -89,19 +111,20 @@ func (h *UserHandler) Register(c *gin.Context) {
|
||||
var cfg model.Config
|
||||
h.db.Where("marker = ?", "system").First(&cfg)
|
||||
var config types.SystemConfig
|
||||
err := utils.JsonDecode(cfg.Config, &config)
|
||||
err = utils.JsonDecode(cfg.Config, &config)
|
||||
if err != nil || config.UserInitCalls <= 0 {
|
||||
user.Calls = types.UserInitCalls
|
||||
} else {
|
||||
user.Calls = config.UserInitCalls
|
||||
}
|
||||
res := h.db.Create(&user)
|
||||
res = h.db.Create(&user)
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, "保存数据失败")
|
||||
logger.Error(res.Error)
|
||||
return
|
||||
}
|
||||
|
||||
_ = h.levelDB.Delete(key) // 注册成功,删除短信验证码
|
||||
resp.SUCCESS(c, user)
|
||||
}
|
||||
|
||||
@@ -144,27 +167,6 @@ func (h *UserHandler) Login(c *gin.Context) {
|
||||
// 记录登录信息在服务端
|
||||
h.App.ChatSession.Put(sessionId, types.ChatSession{ClientIP: c.ClientIP(), UserId: user.Id, Username: data.Username, SessionId: sessionId})
|
||||
|
||||
// 加载用户订阅的聊天角色
|
||||
var roleKeys []string
|
||||
err = utils.JsonDecode(user.ChatRoles, &roleKeys)
|
||||
var chatRoles interface{}
|
||||
if err == nil {
|
||||
var roles []model.ChatRole
|
||||
res = h.db.Where("marker IN ?", roleKeys).Find(&roles)
|
||||
if res.Error == err {
|
||||
type Item struct {
|
||||
Name string
|
||||
Key string
|
||||
Icon string
|
||||
}
|
||||
items := make([]Item, 0)
|
||||
for _, r := range roles {
|
||||
items = append(items, Item{Name: r.Name, Key: r.Key, Icon: r.Icon})
|
||||
}
|
||||
chatRoles = items
|
||||
}
|
||||
}
|
||||
|
||||
h.db.Create(&model.UserLoginLog{
|
||||
UserId: user.Id,
|
||||
Username: user.Username,
|
||||
@@ -186,8 +188,7 @@ func (h *UserHandler) Login(c *gin.Context) {
|
||||
"username": user.Username,
|
||||
"tokens": user.Tokens,
|
||||
"calls": user.Calls,
|
||||
"expiredTime": user.ExpiredTime,
|
||||
"chatRoles": chatRoles,
|
||||
"expired_time": user.ExpiredTime,
|
||||
"api_key": chatConfig.ApiKey,
|
||||
"model": chatConfig.Model,
|
||||
"temperature": chatConfig.Temperature,
|
||||
@@ -237,10 +238,11 @@ type userProfile struct {
|
||||
Id uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Nickname string `json:"nickname"`
|
||||
Mobile string `json:"mobile"`
|
||||
Avatar string `json:"avatar"`
|
||||
ChatConfig types.ChatConfig `json:"chat_config"`
|
||||
Calls int `json:"calls"`
|
||||
Tokens int `json:"tokens"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
}
|
||||
|
||||
func (h *UserHandler) Profile(c *gin.Context) {
|
||||
@@ -341,3 +343,47 @@ func (h *UserHandler) Password(c *gin.Context) {
|
||||
|
||||
resp.SUCCESS(c)
|
||||
}
|
||||
|
||||
// BindMobile 绑定手机号
|
||||
func (h *UserHandler) BindMobile(c *gin.Context) {
|
||||
var data struct {
|
||||
Mobile string `json:"mobile"`
|
||||
Code int `json:"code"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
return
|
||||
}
|
||||
|
||||
// 检查手机号是否被其他账号绑定
|
||||
var item model.User
|
||||
res := h.db.Where("mobile = ?", data.Mobile).First(&item)
|
||||
if res.Error == nil {
|
||||
resp.ERROR(c, "该手机号已经被其他账号绑定")
|
||||
return
|
||||
}
|
||||
|
||||
// 检查验证码
|
||||
key := CodeStorePrefix + data.Mobile
|
||||
var code int
|
||||
err := h.levelDB.Get(key, &code)
|
||||
if err != nil || code != data.Code {
|
||||
resp.ERROR(c, "短信验证码错误")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := utils.GetLoginUser(c, h.db)
|
||||
if err != nil {
|
||||
resp.NotAuth(c)
|
||||
return
|
||||
}
|
||||
|
||||
res = h.db.Model(&user).UpdateColumn("mobile", data.Mobile)
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, "更新数据库失败")
|
||||
return
|
||||
}
|
||||
|
||||
_ = h.levelDB.Delete(key) // 删除短信验证码
|
||||
resp.SUCCESS(c)
|
||||
}
|
||||
150
api/handler/verify_handler.go
Normal file
150
api/handler/verify_handler.go
Normal file
@@ -0,0 +1,150 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"chatplus/core"
|
||||
"chatplus/core/types"
|
||||
"chatplus/service"
|
||||
"chatplus/store"
|
||||
"chatplus/utils"
|
||||
"chatplus/utils/resp"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 生成验证的控制器
|
||||
|
||||
type VerifyHandler struct {
|
||||
BaseHandler
|
||||
sms *service.AliYunSmsService
|
||||
db *store.LevelDB
|
||||
}
|
||||
|
||||
const TokenStorePrefix = "/verify/tokens/"
|
||||
const CodeStorePrefix = "/verify/codes/"
|
||||
const MobileStatPrefix = "/verify/stats/"
|
||||
|
||||
func NewVerifyHandler(app *core.AppServer, sms *service.AliYunSmsService, db *store.LevelDB) *VerifyHandler {
|
||||
handler := &VerifyHandler{sms: sms, db: db}
|
||||
handler.App = app
|
||||
return handler
|
||||
}
|
||||
|
||||
type VerifyToken struct {
|
||||
Token string
|
||||
Timestamp int64
|
||||
}
|
||||
|
||||
// CodeStats 验证码发送统计
|
||||
type CodeStats struct {
|
||||
Mobile string
|
||||
Count uint
|
||||
Time int64
|
||||
}
|
||||
|
||||
// Token 生成自验证 token
|
||||
func (h *VerifyHandler) Token(c *gin.Context) {
|
||||
// 如果不是通过浏览器访问,则返回错误的 token
|
||||
if c.GetHeader("Sec-Fetch-Mode") != "cors" {
|
||||
token := fmt.Sprintf("%s:%d", utils.RandString(32), time.Now().Unix())
|
||||
encrypt, err := utils.AesEncrypt(h.App.Config.AesEncryptKey, []byte(token))
|
||||
if err != nil {
|
||||
resp.ERROR(c, "Token 加密出错")
|
||||
return
|
||||
}
|
||||
resp.SUCCESS(c, encrypt)
|
||||
return
|
||||
}
|
||||
|
||||
token := VerifyToken{
|
||||
Token: utils.RandString(32),
|
||||
Timestamp: time.Now().Unix(),
|
||||
}
|
||||
json := utils.JsonEncode(token)
|
||||
encrypt, err := utils.AesEncrypt(h.App.Config.AesEncryptKey, []byte(json))
|
||||
if err != nil {
|
||||
resp.ERROR(c, "Token 加密出错")
|
||||
return
|
||||
}
|
||||
err = h.db.Put(TokenStorePrefix+token.Token, token)
|
||||
if err != nil {
|
||||
resp.ERROR(c, "Token 存储失败")
|
||||
return
|
||||
}
|
||||
|
||||
resp.SUCCESS(c, encrypt)
|
||||
}
|
||||
|
||||
// SendMsg 发送验证码短信
|
||||
func (h *VerifyHandler) SendMsg(c *gin.Context) {
|
||||
var data struct {
|
||||
Mobile string `json:"mobile"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
return
|
||||
}
|
||||
|
||||
decrypt, err := utils.AesDecrypt(h.App.Config.AesEncryptKey, data.Token)
|
||||
if err != nil {
|
||||
resp.ERROR(c, "Token 解密失败")
|
||||
return
|
||||
}
|
||||
|
||||
var token VerifyToken
|
||||
err = utils.JsonDecode(string(decrypt), &token)
|
||||
if err != nil {
|
||||
resp.ERROR(c, "Token 解码失败")
|
||||
return
|
||||
}
|
||||
|
||||
if time.Now().Unix()-token.Timestamp > 30 {
|
||||
resp.ERROR(c, "Token 已过期,请刷新页面重试")
|
||||
return
|
||||
}
|
||||
|
||||
// 验证当前手机号发送次数,24 小时内相同手机号只允许发送 2 次
|
||||
var stat CodeStats
|
||||
err = h.db.Get(MobileStatPrefix+data.Mobile, &stat)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
stat = CodeStats{
|
||||
Mobile: data.Mobile,
|
||||
Count: 0,
|
||||
Time: time.Now().Unix(),
|
||||
}
|
||||
} else if stat.Count == 2 {
|
||||
if time.Now().Unix()-stat.Time > 86400 {
|
||||
stat.Count = 0
|
||||
stat.Time = time.Now().Unix()
|
||||
} else {
|
||||
resp.ERROR(c, "触发流量预警,请 24 小时后再操作!")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
code := utils.RandomNumber(6)
|
||||
err = h.sms.SendVerifyCode(data.Mobile, code)
|
||||
if err != nil {
|
||||
resp.ERROR(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 每个 token 用完一次立即失效
|
||||
_ = h.db.Delete(TokenStorePrefix + token.Token)
|
||||
// 存储验证码,等待后面注册验证
|
||||
err = h.db.Put(CodeStorePrefix+data.Mobile, code)
|
||||
if err != nil {
|
||||
resp.ERROR(c, "验证码保存失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 更新发送次数
|
||||
stat.Count = stat.Count + 1
|
||||
_ = h.db.Put(MobileStatPrefix+data.Mobile, stat)
|
||||
logger.Infof("%+v", stat)
|
||||
|
||||
resp.SUCCESS(c)
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
# chatgpt-plus-java
|
||||
|
||||
chatgpt-plus 后端 API Java 语言实现,待开发。
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"chatplus/handler"
|
||||
"chatplus/handler/admin"
|
||||
logger2 "chatplus/logger"
|
||||
"chatplus/service"
|
||||
"chatplus/service/function"
|
||||
"chatplus/store"
|
||||
"context"
|
||||
"embed"
|
||||
@@ -98,11 +100,18 @@ func main() {
|
||||
return xdb.NewWithBuffer(cBuff)
|
||||
}),
|
||||
|
||||
// 创建函数
|
||||
fx.Provide(func() *function.FuncZaoBao {
|
||||
token := os.Getenv("AL_API_TOKEN")
|
||||
return function.NewZaoBao(token)
|
||||
}),
|
||||
|
||||
// 创建控制器
|
||||
fx.Provide(handler.NewChatRoleHandler),
|
||||
fx.Provide(handler.NewUserHandler),
|
||||
fx.Provide(handler.NewChatHandler),
|
||||
fx.Provide(handler.NewUploadHandler),
|
||||
fx.Provide(handler.NewVerifyHandler),
|
||||
|
||||
fx.Provide(admin.NewConfigHandler),
|
||||
fx.Provide(admin.NewAdminHandler),
|
||||
@@ -110,6 +119,9 @@ func main() {
|
||||
fx.Provide(admin.NewUserHandler),
|
||||
fx.Provide(admin.NewChatRoleHandler),
|
||||
|
||||
// 创建服务
|
||||
fx.Provide(service.NewAliYunSmsService),
|
||||
|
||||
// 注册路由
|
||||
fx.Invoke(func(s *core.AppServer, h *handler.ChatRoleHandler) {
|
||||
group := s.Engine.Group("/api/role/")
|
||||
@@ -124,6 +136,7 @@ func main() {
|
||||
group.GET("profile", h.Profile)
|
||||
group.POST("profile/update", h.ProfileUpdate)
|
||||
group.POST("password", h.Password)
|
||||
group.POST("bind/mobile", h.BindMobile)
|
||||
}),
|
||||
fx.Invoke(func(s *core.AppServer, h *handler.ChatHandler) {
|
||||
group := s.Engine.Group("/api/chat/")
|
||||
@@ -139,6 +152,11 @@ func main() {
|
||||
fx.Invoke(func(s *core.AppServer, h *handler.UploadHandler) {
|
||||
s.Engine.POST("/api/upload", h.Upload)
|
||||
}),
|
||||
fx.Invoke(func(s *core.AppServer, h *handler.VerifyHandler) {
|
||||
group := s.Engine.Group("/api/verify/")
|
||||
group.GET("token", h.Token)
|
||||
group.POST("sms", h.SendMsg)
|
||||
}),
|
||||
|
||||
// 管理后台控制器
|
||||
fx.Invoke(func(s *core.AppServer, h *admin.ConfigHandler) {
|
||||
@@ -1,5 +0,0 @@
|
||||
# chatgpt-plus-php
|
||||
|
||||
chatgpt-plus 后端 API PHP 语言实现,待开发。
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
# chatgpt-plus-python
|
||||
|
||||
chatgpt-plus 后端 API Python 语言实现,待开发。
|
||||
|
||||
|
||||
54
api/service/aliyun_sms_service.go
Normal file
54
api/service/aliyun_sms_service.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"chatplus/core/types"
|
||||
"chatplus/store"
|
||||
"fmt"
|
||||
"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
|
||||
)
|
||||
|
||||
type AliYunSmsService struct {
|
||||
config *types.AppConfig
|
||||
db *store.LevelDB
|
||||
client *dysmsapi.Client
|
||||
}
|
||||
|
||||
func NewAliYunSmsService(config *types.AppConfig, db *store.LevelDB) (*AliYunSmsService, error) {
|
||||
// 创建阿里云短信客户端
|
||||
client, err := dysmsapi.NewClientWithAccessKey(
|
||||
"cn-hangzhou",
|
||||
config.SmsConfig.AccessKey,
|
||||
config.SmsConfig.AccessSecret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create client: %v", err)
|
||||
}
|
||||
|
||||
return &AliYunSmsService{
|
||||
config: config,
|
||||
db: db,
|
||||
client: client,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AliYunSmsService) SendVerifyCode(mobile string, code int) error {
|
||||
// 创建短信请求并设置参数
|
||||
request := dysmsapi.CreateSendSmsRequest()
|
||||
request.Scheme = "https"
|
||||
request.Domain = s.config.SmsConfig.Domain
|
||||
request.PhoneNumbers = mobile
|
||||
request.SignName = "飞行的蜗牛"
|
||||
request.TemplateCode = "SMS_281460317"
|
||||
request.TemplateParam = fmt.Sprintf("{\"code\":\"%d\"}", code) // 短信模板中的参数
|
||||
|
||||
// 发送短信
|
||||
response, err := s.client.SendSms(request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to send SMS:%v", err)
|
||||
}
|
||||
|
||||
if response.Code != "OK" {
|
||||
return fmt.Errorf("failed to send SMS:%v", response.Message)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
51
api/service/function/zao_bao.go
Normal file
51
api/service/function/zao_bao.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package function
|
||||
|
||||
import (
|
||||
"chatplus/utils"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 每日早报函数实现
|
||||
|
||||
type FuncZaoBao struct {
|
||||
apiURL string
|
||||
token string
|
||||
}
|
||||
|
||||
func NewZaoBao(token string) *FuncZaoBao {
|
||||
return &FuncZaoBao{apiURL: "https://v2.alapi.cn/api/zaobao", token: token}
|
||||
}
|
||||
|
||||
type resVo struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data struct {
|
||||
Date string `json:"date"`
|
||||
News []string `json:"news"`
|
||||
WeiYu string `json:"weiyu"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (f *FuncZaoBao) Fetch() (string, error) {
|
||||
|
||||
url := fmt.Sprintf("%s?format=json&token=%s", f.apiURL, f.token)
|
||||
bytes, err := utils.HttpGet(url, "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var res resVo
|
||||
err = utils.JsonDecode(string(bytes), &res)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if res.Code != 200 {
|
||||
return "", fmt.Errorf("call api fail: %s", res.Msg)
|
||||
}
|
||||
builder := make([]string, 0)
|
||||
builder = append(builder, fmt.Sprintf("**%s 早报:**", res.Data.Date))
|
||||
builder = append(builder, res.Data.News...)
|
||||
builder = append(builder, fmt.Sprintf("%s", res.Data.WeiYu))
|
||||
return strings.Join(builder, "\n\n"), nil
|
||||
}
|
||||
5
api/service/sms_service.go
Normal file
5
api/service/sms_service.go
Normal file
@@ -0,0 +1,5 @@
|
||||
package service
|
||||
|
||||
type SmsService interface {
|
||||
SendVerifyCode(mobile string, code int) error
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package store
|
||||
import (
|
||||
"chatplus/store/vo"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
"github.com/syndtr/goleveldb/leveldb/util"
|
||||
)
|
||||
@@ -30,13 +29,13 @@ func (db *LevelDB) Put(key string, value interface{}) error {
|
||||
return db.driver.Put([]byte(key), bytes, nil)
|
||||
}
|
||||
|
||||
func (db *LevelDB) Get(key string) ([]byte, error) {
|
||||
func (db *LevelDB) Get(key string, value interface{}) error {
|
||||
bytes, err := db.driver.Get([]byte(key), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
return bytes, nil
|
||||
return json.Unmarshal(bytes, &value)
|
||||
}
|
||||
|
||||
func (db *LevelDB) Search(prefix string) []string {
|
||||
@@ -3,6 +3,7 @@ package model
|
||||
type User struct {
|
||||
BaseModel
|
||||
Username string `gorm:"index:username,unique"`
|
||||
Mobile string
|
||||
Password string
|
||||
Nickname string
|
||||
Avatar string
|
||||
@@ -5,6 +5,7 @@ import "chatplus/core/types"
|
||||
type User struct {
|
||||
BaseVo
|
||||
Username string `json:"username"`
|
||||
Mobile string `json:"mobile"`
|
||||
Nickname string `json:"nickname"`
|
||||
Avatar string `json:"avatar"`
|
||||
Salt string `json:"salt"` // 密码盐
|
||||
@@ -1,27 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"chatplus/core/types"
|
||||
"chatplus/store/model"
|
||||
"chatplus/store/vo"
|
||||
"chatplus/utils"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/lionsoul2014/ip2region/binding/golang/xdb"
|
||||
"github.com/pkoukk/tiktoken-go"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
lMap := types.NewLMap[string, types.ChatSession]()
|
||||
lMap.Put("name", types.ChatSession{SessionId: utils.RandString(32)})
|
||||
|
||||
item := lMap.Get("abc")
|
||||
fmt.Println(item)
|
||||
}
|
||||
|
||||
// Http client 取消操作
|
||||
@@ -143,3 +141,62 @@ func calTokens() {
|
||||
fmt.Println(len(token))
|
||||
|
||||
}
|
||||
|
||||
func testAesEncrypt() {
|
||||
// 加密
|
||||
text := []byte("this is a secret text")
|
||||
key := utils.RandString(24)
|
||||
encrypt, err := utils.AesEncrypt(key, text)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println("加密密文:", encrypt)
|
||||
// 解密
|
||||
decrypt, err := utils.AesDecrypt(key, encrypt)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println("解密明文:", string(decrypt))
|
||||
}
|
||||
|
||||
func extractFunction() error {
|
||||
open, err := os.Open("res/data.txt")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reader := bufio.NewReader(open)
|
||||
var contents = make([]string, 0)
|
||||
var functionCall = false
|
||||
var functionName string
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if !strings.Contains(line, "data:") {
|
||||
continue
|
||||
}
|
||||
|
||||
var responseBody = types.ApiResponse{}
|
||||
err = json.Unmarshal([]byte(line[6:]), &responseBody)
|
||||
if err != nil || len(responseBody.Choices) == 0 { // 数据解析出错
|
||||
break
|
||||
}
|
||||
|
||||
function := responseBody.Choices[0].Delta.FunctionCall
|
||||
if functionCall && function.Name == "" {
|
||||
contents = append(contents, function.Arguments)
|
||||
continue
|
||||
}
|
||||
|
||||
if !utils.IsEmptyValue(function) {
|
||||
functionCall = true
|
||||
functionName = function.Name
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("函数名称: ", functionName)
|
||||
fmt.Println(strings.Join(contents, ""))
|
||||
return err
|
||||
}
|
||||
@@ -87,3 +87,25 @@ func Ip2Region(searcher *xdb.Searcher, ip string) string {
|
||||
}
|
||||
return fmt.Sprintf("%s-%s-%s", arr[0], arr[2], arr[3])
|
||||
}
|
||||
|
||||
func IsEmptyValue(obj interface{}) bool {
|
||||
v := reflect.ValueOf(obj)
|
||||
switch v.Kind() {
|
||||
case reflect.Ptr, reflect.Interface:
|
||||
return v.IsNil()
|
||||
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
|
||||
return v.Len() == 0
|
||||
case reflect.Bool:
|
||||
return !v.Bool()
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return v.Int() == 0
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
return v.Uint() == 0
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return v.Float() == 0
|
||||
case reflect.Complex64, reflect.Complex128:
|
||||
return v.Complex() == 0
|
||||
default:
|
||||
return reflect.DeepEqual(obj, reflect.Zero(reflect.TypeOf(obj)).Interface())
|
||||
}
|
||||
}
|
||||
70
api/utils/crypto.go
Normal file
70
api/utils/crypto.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// AesEncrypt 加密
|
||||
func AesEncrypt(keyStr string, data []byte) (string, error) {
|
||||
//创建加密实例
|
||||
key := []byte(keyStr)
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
blockSize := block.BlockSize()
|
||||
encryptBytes := pkcs7Padding(data, blockSize)
|
||||
result := make([]byte, len(encryptBytes))
|
||||
//使用cbc加密模式
|
||||
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
|
||||
//执行加密
|
||||
blockMode.CryptBlocks(result, encryptBytes)
|
||||
return base64.StdEncoding.EncodeToString(result), nil
|
||||
}
|
||||
|
||||
// AesDecrypt 解密
|
||||
func AesDecrypt(keyStr string, dataStr string) ([]byte, error) {
|
||||
//创建实例
|
||||
key := []byte(keyStr)
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data, err := base64.StdEncoding.DecodeString(dataStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
blockSize := block.BlockSize()
|
||||
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
|
||||
result := make([]byte, len(data))
|
||||
//执行解密
|
||||
blockMode.CryptBlocks(result, data)
|
||||
//去除填充
|
||||
result, err = pkcs7UnPadding(result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func pkcs7Padding(data []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(data)%blockSize
|
||||
padText := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(data, padText...)
|
||||
}
|
||||
|
||||
func pkcs7UnPadding(data []byte) ([]byte, error) {
|
||||
length := len(data)
|
||||
if length == 0 {
|
||||
return nil, errors.New("empty encrypt data")
|
||||
}
|
||||
unPadding := int(data[length-1])
|
||||
return data[:(length - unPadding)], nil
|
||||
}
|
||||
68
api/utils/http.go
Normal file
68
api/utils/http.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func HttpGet(uri string, proxy string) ([]byte, error) {
|
||||
var client *http.Client
|
||||
if proxy == "" {
|
||||
client = &http.Client{}
|
||||
} else {
|
||||
proxy, _ := url.Parse(proxy)
|
||||
client = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyURL(proxy),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", uri, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func HttpPost(uri string, params map[string]interface{}, proxy string) ([]byte, error) {
|
||||
data, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var client *http.Client
|
||||
if proxy == "" {
|
||||
client = &http.Client{}
|
||||
} else {
|
||||
proxy, _ := url.Parse(proxy)
|
||||
client = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyURL(proxy),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", uri, bytes.NewBuffer(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
@@ -22,17 +22,21 @@ func RandString(length int) string {
|
||||
}
|
||||
|
||||
func RandomNumber(bit int) int {
|
||||
min := intPow(10, bit-1)
|
||||
max := intPow(10, bit) - 1
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
min := 1 // min value
|
||||
max := 1 //max value
|
||||
for i := 0; i < bit; i++ {
|
||||
min = min * 10
|
||||
max = max * 10
|
||||
}
|
||||
max = max * 10
|
||||
return rand.Intn(max-min+1) + min
|
||||
}
|
||||
|
||||
func intPow(x, y int) int {
|
||||
result := 1
|
||||
for i := 0; i < y; i++ {
|
||||
result *= x
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ContainsStr(slice []string, item string) bool {
|
||||
for _, e := range slice {
|
||||
if e == item {
|
||||
1
database/sms.sql
Normal file
1
database/sms.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE `chatgpt_users` ADD `mobile` CHAR(11) NOT NULL COMMENT '手机号码' AFTER `username`;
|
||||
@@ -20,7 +20,7 @@ docker build -t chatgpt-plus-go:$version -f dockerfile-api-go ../
|
||||
# build docker image for chatgpt-plus-vue
|
||||
docker rmi -f registry.cn-hangzhou.aliyuncs.com/geekmaster/chatgpt-plus-vue:$version
|
||||
docker rmi -f chatgpt-plus-vue:$version
|
||||
docker build -t chatgpt-plus-vue:$version -f dockerfile-vue ../
|
||||
docker build --platform linux/amd64 -t chatgpt-plus-vue:$version -f dockerfile-vue ../
|
||||
|
||||
# add tag for aliyum docker registry
|
||||
goImageId=`docker images |grep chatgpt-plus-go |grep $version |awk '{print $3}'`
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Listen = "0.0.0.0:5678"
|
||||
ProxyURL = "http://172.22.11.200:7777"
|
||||
MysqlDns = "root:12345678@tcp(172.28.173.76:3307)/chatgpt_plus?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
MysqlDns = "root:12345678@tcp(172.28.173.76:3307)/chatgpt_plus?charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local"
|
||||
StaticDir = "./static"
|
||||
StaticUrl = "http://localhost:8080/static"
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ version: '3'
|
||||
services:
|
||||
# 后端 API 程序
|
||||
chatgpt-plus-go:
|
||||
image: registry.cn-hangzhou.aliyuncs.com/geekmaster/chatgpt-plus-go:v3.0.2
|
||||
image: registry.cn-hangzhou.aliyuncs.com/geekmaster/chatgpt-plus-go:v3.0.4
|
||||
# image: chatgpt-plus-go:v3.0.2
|
||||
container_name: chatgpt-plus-go
|
||||
restart: always
|
||||
@@ -17,7 +17,7 @@ services:
|
||||
|
||||
# 前端应用
|
||||
chatgpt-vue:
|
||||
image: registry.cn-hangzhou.aliyuncs.com/geekmaster/chatgpt-plus-vue:v3.0.2
|
||||
image: registry.cn-hangzhou.aliyuncs.com/geekmaster/chatgpt-plus-vue:v3.0.4
|
||||
# image: chatgpt-plus-vue:v3.0.2
|
||||
container_name: chatgpt-plus-vue
|
||||
restart: always
|
||||
|
||||
@@ -8,8 +8,5 @@ COPY ./api/go/bin/chatgpt-v3-amd64-linux /var/www/app
|
||||
|
||||
EXPOSE 5678
|
||||
|
||||
RUN apt-get -qq update \
|
||||
&& apt-get -qq install -y --no-install-recommends ca-certificates curl
|
||||
|
||||
# 容器启动时执行的命令
|
||||
CMD ["./chatgpt-v3-amd64-linux"]
|
||||
|
||||
92
web/src/components/BindMobile.vue
Normal file
92
web/src/components/BindMobile.vue
Normal file
@@ -0,0 +1,92 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
v-model="showDialog"
|
||||
:close-on-click-modal="false"
|
||||
:show-close="mobile !== ''"
|
||||
:before-close="close"
|
||||
:title="title"
|
||||
>
|
||||
<div class="form" id="bind-mobile-form">
|
||||
<el-alert v-if="mobile !== ''" type="info" show-icon :closable="false" style="margin-bottom: 20px;">
|
||||
<p>当前用户已绑定手机号:{{ mobile }}, 绑定其他手机号之后自动解绑该手机号。</p>
|
||||
</el-alert>
|
||||
|
||||
<el-form :model="form" label-width="120px">
|
||||
<el-form-item label="手机号码">
|
||||
<el-input v-model="form.mobile"/>
|
||||
</el-form-item>
|
||||
<el-form-item label="手机验证码">
|
||||
<el-row :gutter="10">
|
||||
<el-col :span="12">
|
||||
<el-input v-model.number="form.code" maxlength="6"/>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<send-msg size="" :mobile="form.mobile"/>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<span class="dialog-footer">
|
||||
<el-button type="primary" @click="save">
|
||||
提交绑定
|
||||
</el-button>
|
||||
</span>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import {computed, ref} from "vue";
|
||||
import SendMsg from "@/components/SendMsg.vue";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {httpPost} from "@/utils/http";
|
||||
import {validateMobile} from "@/utils/validate";
|
||||
|
||||
const props = defineProps({
|
||||
show: Boolean,
|
||||
mobile: String
|
||||
});
|
||||
|
||||
const showDialog = computed(() => {
|
||||
return props.show
|
||||
})
|
||||
|
||||
const title = ref('绑定手机号')
|
||||
const form = ref({
|
||||
mobile: '',
|
||||
code: ''
|
||||
})
|
||||
|
||||
const emits = defineEmits(['hide']);
|
||||
|
||||
const save = () => {
|
||||
if (!validateMobile(form.value.mobile)) {
|
||||
return ElMessage.error({message: "请输入正确的手机号码", appendTo: "#bind-mobile-form"});
|
||||
}
|
||||
if (form.value.code === '') {
|
||||
return ElMessage.error({message: "请输入短信验证码", appendTo: "#bind-mobile-form"});
|
||||
}
|
||||
|
||||
httpPost('/api/user/bind/mobile', form.value).then(() => {
|
||||
ElMessage.success({
|
||||
message: '绑定成功',
|
||||
appendTo: '#bind-mobile-form',
|
||||
duration: 1000,
|
||||
onClose: () => emits('hide', false)
|
||||
})
|
||||
}).catch(e => {
|
||||
ElMessage.error({message: "绑定失败:" + e.message, appendTo: "#bind-mobile-form"});
|
||||
})
|
||||
}
|
||||
|
||||
const close = function () {
|
||||
emits('hide', false);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
@@ -3,7 +3,7 @@
|
||||
v-model="showDialog"
|
||||
:close-on-click-modal="false"
|
||||
:before-close="close"
|
||||
:top="top"
|
||||
:top="50+'px'"
|
||||
title="用户设置"
|
||||
>
|
||||
<div class="user-info" id="user-info">
|
||||
@@ -28,6 +28,10 @@
|
||||
<el-input v-model="form.username" readonly disabled/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="绑定手机号">
|
||||
<el-input v-model="form.mobile" readonly disabled/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="聊天上下文">
|
||||
<el-switch v-model="form.chat_config.enable_context"/>
|
||||
</el-form-item>
|
||||
@@ -53,7 +57,7 @@
|
||||
<el-form-item label="剩余调用次数">
|
||||
<el-tag>{{ form['calls'] }}</el-tag>
|
||||
</el-form-item>
|
||||
<el-form-item label="剩余 Tokens">
|
||||
<el-form-item label="消耗 Tokens">
|
||||
<el-tag type="info">{{ form['tokens'] }}</el-tag>
|
||||
</el-form-item>
|
||||
<el-form-item label="API KEY">
|
||||
@@ -96,24 +100,18 @@ const form = ref({
|
||||
username: '',
|
||||
nickname: '',
|
||||
avatar: '',
|
||||
mobile: '',
|
||||
calls: 0,
|
||||
tokens: 0,
|
||||
chat_configs: {}
|
||||
})
|
||||
const top = computed(() => {
|
||||
if (window.innerHeight < 1024) {
|
||||
return '5vh';
|
||||
} else {
|
||||
return '15vh';
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
// 获取最新用户信息
|
||||
httpGet('/api/user/profile').then(res => {
|
||||
form.value = res.data
|
||||
}).catch(() => {
|
||||
ElMessage.error({message: '获取用户信息失败', appendTo: '#user-info'})
|
||||
ElMessage.error("获取用户信息失败")
|
||||
});
|
||||
})
|
||||
|
||||
@@ -128,10 +126,10 @@ const afterRead = (file) => {
|
||||
// 执行上传操作
|
||||
httpPost('/api/upload', formData).then((res) => {
|
||||
form.value.avatar = res.data
|
||||
ElMessage.success({message: '上传成功', appendTo: '#user-info', duration: 1000})
|
||||
ElMessage.success('上传成功')
|
||||
}).catch((e) => {
|
||||
console.log(e.message)
|
||||
ElMessage.error({message: '上传失败', appendTo: '#user-info'})
|
||||
ElMessage.error('上传失败')
|
||||
})
|
||||
},
|
||||
error(err) {
|
||||
@@ -146,16 +144,12 @@ const save = function () {
|
||||
httpPost('/api/user/profile/update', form.value).then(() => {
|
||||
ElMessage.success({
|
||||
message: '更新成功',
|
||||
appendTo: '#user-info',
|
||||
onClose: () => emits('hide', false)
|
||||
})
|
||||
// 更新用户数据
|
||||
emits('update-user', {nickname: form.value['nickname'], avatar: form.value['avatar']});
|
||||
}).catch(() => {
|
||||
ElMessage.error({
|
||||
message: '更新失败',
|
||||
appendTo: document.getElementById('user-info')
|
||||
})
|
||||
}).catch((e) => {
|
||||
ElMessage.error('更新失败:' + e.message)
|
||||
})
|
||||
}
|
||||
const close = function () {
|
||||
|
||||
@@ -55,6 +55,7 @@ const save = function () {
|
||||
ElMessage.success({
|
||||
message: '更新成功',
|
||||
appendTo: '#password-form',
|
||||
duration: 1000,
|
||||
onClose: () => emits('logout', false)
|
||||
})
|
||||
}).catch((e) => {
|
||||
|
||||
59
web/src/components/SendMsg.vue
Normal file
59
web/src/components/SendMsg.vue
Normal file
@@ -0,0 +1,59 @@
|
||||
<template>
|
||||
<el-button type="primary" :disabled="!canSend" :size="props.size" @click="sendMsg" plain>{{
|
||||
btnText
|
||||
}}
|
||||
</el-button>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// 发送短信验证码组件
|
||||
import {ref} from "vue";
|
||||
import {validateMobile} from "@/utils/validate";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {httpGet, httpPost} from "@/utils/http";
|
||||
|
||||
const props = defineProps({
|
||||
mobile: String,
|
||||
size: String,
|
||||
});
|
||||
const btnText = ref('发送验证码')
|
||||
const canSend = ref(true)
|
||||
|
||||
const sendMsg = () => {
|
||||
if (!canSend.value) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!validateMobile(props.mobile)) {
|
||||
return ElMessage.error("请输入合法的手机号")
|
||||
}
|
||||
canSend.value = false
|
||||
httpGet('/api/verify/token').then(res => {
|
||||
httpPost('/api/verify/sms', {token: res.data, mobile: props.mobile}).then(() => {
|
||||
ElMessage.success('短信发送成功')
|
||||
let time = 120
|
||||
btnText.value = time
|
||||
const handler = setInterval(() => {
|
||||
time = time - 1
|
||||
if (time <= 0) {
|
||||
clearInterval(handler)
|
||||
btnText.value = '重新发送'
|
||||
canSend.value = true
|
||||
} else {
|
||||
btnText.value = time
|
||||
}
|
||||
}, 1000)
|
||||
}).catch(e => {
|
||||
canSend.value = true
|
||||
ElMessage.error('短信发送失败:' + e.message)
|
||||
})
|
||||
}).catch(e => {
|
||||
console.log('failed to fetch token: ' + e.message)
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
76
web/src/components/mobile/BindMobile.vue
Normal file
76
web/src/components/mobile/BindMobile.vue
Normal file
@@ -0,0 +1,76 @@
|
||||
<template>
|
||||
<van-dialog v-model:show="showDialog"
|
||||
:title="title"
|
||||
:show-cancel-button="mobile !== ''"
|
||||
@confirm="save"
|
||||
@cancel="close">
|
||||
<van-cell-group inset>
|
||||
<van-field
|
||||
v-model="form.mobile"
|
||||
label="手机号"
|
||||
placeholder="请输入手机号"
|
||||
/>
|
||||
<van-field
|
||||
v-model.number="form.code"
|
||||
center
|
||||
clearable
|
||||
label="短信验证码"
|
||||
placeholder="请输入短信验证码"
|
||||
>
|
||||
<template #button>
|
||||
<!-- <van-button size="small" type="primary">发送验证码</van-button>-->
|
||||
<send-msg size="small" :mobile="form.mobile"/>
|
||||
</template>
|
||||
</van-field>
|
||||
</van-cell-group>
|
||||
</van-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import {computed, ref} from "vue";
|
||||
import SendMsg from "@/components/mobile/SendMsg.vue";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {httpPost} from "@/utils/http";
|
||||
import {validateMobile} from "@/utils/validate";
|
||||
import {showNotify} from "vant";
|
||||
|
||||
const props = defineProps({
|
||||
show: Boolean,
|
||||
mobile: String
|
||||
});
|
||||
|
||||
const showDialog = computed(() => {
|
||||
return props.show
|
||||
})
|
||||
|
||||
const title = ref('绑定手机号')
|
||||
const form = ref({
|
||||
mobile: '',
|
||||
code: ''
|
||||
})
|
||||
|
||||
const emits = defineEmits(['hide']);
|
||||
|
||||
const save = () => {
|
||||
if (!validateMobile(form.value.mobile)) {
|
||||
return showNotify({type: 'danger', message: '请输入正确的手机号码'});
|
||||
}
|
||||
if (form.value.code === '') {
|
||||
return showNotify({type: "danger", message: '请输入短信验证码'})
|
||||
}
|
||||
|
||||
httpPost('/api/user/bind/mobile', form.value).then(() => {
|
||||
showNotify({type: 'success', message: '绑定成功', duration: 1000, onClose: emits('hide', false)});
|
||||
}).catch(e => {
|
||||
showNotify({type: 'danger', message: '绑定失败:' + e.message, duration: 2000});
|
||||
})
|
||||
}
|
||||
|
||||
const close = function () {
|
||||
emits('hide', false);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
62
web/src/components/mobile/SendMsg.vue
Normal file
62
web/src/components/mobile/SendMsg.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<template>
|
||||
<van-button size="small"
|
||||
type="primary"
|
||||
:disabled="!canSend"
|
||||
:size="props.size"
|
||||
@click="sendMsg">{{ btnText }}
|
||||
</van-button>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// 发送短信验证码组件
|
||||
import {ref} from "vue";
|
||||
import {validateMobile} from "@/utils/validate";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {httpGet, httpPost} from "@/utils/http";
|
||||
import {showNotify} from "vant";
|
||||
|
||||
const props = defineProps({
|
||||
mobile: String,
|
||||
size: String,
|
||||
});
|
||||
const btnText = ref('发送验证码')
|
||||
const canSend = ref(true)
|
||||
|
||||
const sendMsg = () => {
|
||||
if (!canSend.value) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!validateMobile(props.mobile)) {
|
||||
return showNotify({type: 'danger', message: '请输入合法的手机号'})
|
||||
}
|
||||
canSend.value = false
|
||||
httpGet('/api/verify/token').then(res => {
|
||||
httpPost('/api/verify/sms', {token: res.data, mobile: props.mobile}).then(() => {
|
||||
showNotify({type: 'success', message: '短信发送成功'})
|
||||
let time = 120
|
||||
btnText.value = time
|
||||
const handler = setInterval(() => {
|
||||
time = time - 1
|
||||
if (time <= 0) {
|
||||
clearInterval(handler)
|
||||
btnText.value = '重新发送'
|
||||
canSend.value = true
|
||||
} else {
|
||||
btnText.value = time
|
||||
}
|
||||
}, 1000)
|
||||
}).catch(e => {
|
||||
canSend.value = true
|
||||
showNotify({type: 'danger', message: '短信发送失败:' + e.message})
|
||||
})
|
||||
}).catch(e => {
|
||||
console.log('failed to fetch token: ' + e.message)
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
11
web/src/utils/validate.js
Normal file
11
web/src/utils/validate.js
Normal file
@@ -0,0 +1,11 @@
|
||||
// 正则校验工具函数
|
||||
|
||||
export function validateEmail(email) {
|
||||
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return regex.test(email);
|
||||
}
|
||||
|
||||
export function validateMobile(mobile) {
|
||||
const regex = /^1[345789]\d{9}$/;
|
||||
return regex.test(mobile);
|
||||
}
|
||||
@@ -60,6 +60,13 @@
|
||||
<span>修改密码</span>
|
||||
</el-dropdown-item>
|
||||
|
||||
<el-dropdown-item @click="showBindMobileDialog = true">
|
||||
<el-icon>
|
||||
<Iphone/>
|
||||
</el-icon>
|
||||
<span>绑定手机号</span>
|
||||
</el-dropdown-item>
|
||||
|
||||
<el-dropdown-item @click="clearAllChats">
|
||||
<el-icon>
|
||||
<Delete/>
|
||||
@@ -187,6 +194,9 @@
|
||||
@update-user="updateUser"/>
|
||||
<password-dialog v-if="isLogin" :show="showPasswordDialog" @hide="showPasswordDialog = false"
|
||||
@logout="logout"/>
|
||||
|
||||
<bind-mobile v-if="isLogin" :show="showBindMobileDialog" :mobile="loginUser.mobile"
|
||||
@hide="showBindMobileDialog = false"/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -200,7 +210,7 @@ import {
|
||||
Check,
|
||||
Close,
|
||||
Delete,
|
||||
Edit,
|
||||
Edit, Iphone,
|
||||
Plus,
|
||||
Promotion,
|
||||
RefreshRight,
|
||||
@@ -219,6 +229,7 @@ import Clipboard from "clipboard";
|
||||
import ConfigDialog from "@/components/ConfigDialog.vue";
|
||||
import PasswordDialog from "@/components/PasswordDialog.vue";
|
||||
import {checkSession} from "@/action/session";
|
||||
import BindMobile from "@/components/BindMobile.vue";
|
||||
|
||||
const title = ref('ChatGPT-智能助手');
|
||||
const logo = 'images/logo.png';
|
||||
@@ -239,6 +250,7 @@ const newChatItem = ref(null);
|
||||
const router = useRouter();
|
||||
const showConfigDialog = ref(false);
|
||||
const showPasswordDialog = ref(false);
|
||||
const showBindMobileDialog = ref(false);
|
||||
const isLogin = ref(false)
|
||||
|
||||
if (isMobile()) {
|
||||
@@ -250,6 +262,9 @@ onMounted(() => {
|
||||
checkSession().then((user) => {
|
||||
loginUser.value = user
|
||||
isLogin.value = true
|
||||
if (user.mobile === '') {
|
||||
showBindMobileDialog.value = true
|
||||
}
|
||||
// 加载角色列表
|
||||
httpGet(`/api/role/list?user_id=${user.id}`).then((res) => {
|
||||
roles.value = res.data;
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
|
||||
<div class="header">{{ title }}</div>
|
||||
<div class="content">
|
||||
<el-form :model="formData" label-width="120px" ref="formRef" :rules="rules">
|
||||
<el-form :model="formData" label-width="120px" ref="formRef">
|
||||
<div class="block">
|
||||
<el-input placeholder="手机号/邮箱(4-30位)"
|
||||
<el-input placeholder="请输入用户名(4-30位)"
|
||||
size="large" maxlength="30"
|
||||
v-model="formData.username"
|
||||
autocomplete="off">
|
||||
@@ -48,6 +48,39 @@
|
||||
</el-input>
|
||||
</div>
|
||||
|
||||
<div class="block">
|
||||
<el-input placeholder="手机号码"
|
||||
size="large" maxlength="11"
|
||||
v-model="formData.mobile"
|
||||
autocomplete="off">
|
||||
<template #prefix>
|
||||
<el-icon>
|
||||
<Iphone/>
|
||||
</el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
</div>
|
||||
|
||||
<div class="block">
|
||||
<el-row :gutter="10">
|
||||
<el-col :span="12">
|
||||
<el-input placeholder="手机验证码"
|
||||
size="large" maxlength="30"
|
||||
v-model.number="formData.code"
|
||||
autocomplete="off">
|
||||
<template #prefix>
|
||||
<el-icon>
|
||||
<Checked/>
|
||||
</el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<send-msg size="large" :mobile="formData.mobile"/>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
|
||||
<el-row class="btn-row">
|
||||
<el-button class="login-btn" size="large" type="primary" @click="register">注册</el-button>
|
||||
</el-row>
|
||||
@@ -70,17 +103,20 @@
|
||||
<script setup>
|
||||
|
||||
import {ref} from "vue";
|
||||
import {Lock, UserFilled} from "@element-plus/icons-vue";
|
||||
import {Checked, Iphone, Lock, UserFilled} from "@element-plus/icons-vue";
|
||||
import {httpPost} from "@/utils/http";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {useRouter} from "vue-router";
|
||||
import FooterBar from "@/components/FooterBar.vue";
|
||||
import SendMsg from "@/components/SendMsg.vue";
|
||||
|
||||
const router = useRouter();
|
||||
const title = ref('ChatGPT-PLUS 用户注册');
|
||||
const formData = ref({
|
||||
username: '',
|
||||
password: '',
|
||||
mobile: '',
|
||||
code: '',
|
||||
repass: '',
|
||||
})
|
||||
const formRef = ref(null)
|
||||
@@ -89,9 +125,6 @@ const register = function () {
|
||||
if (formData.value.username.length < 4) {
|
||||
return ElMessage.error('用户名的长度为4-30个字符');
|
||||
}
|
||||
if (!validateEmail(formData.value.username) && !validateMobile(formData.value.username)) {
|
||||
return ElMessage.error('用户名不合法,请输入手机号码或者邮箱地址');
|
||||
}
|
||||
if (formData.value.password.length < 8) {
|
||||
return ElMessage.error('密码的长度为8-16个字符');
|
||||
}
|
||||
@@ -106,15 +139,6 @@ const register = function () {
|
||||
})
|
||||
}
|
||||
|
||||
const validateEmail = function (email) {
|
||||
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return regex.test(email);
|
||||
}
|
||||
const validateMobile = function (mobile) {
|
||||
const regex = /^1[345789]\d{9}$/;
|
||||
return regex.test(mobile);
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style lang="stylus" scoped>
|
||||
|
||||
@@ -1,165 +1,14 @@
|
||||
<template>
|
||||
<div class="role-list">
|
||||
|
||||
|
||||
<el-form :model="form1" label-width="120px" ref="formRef" :rules="rules">
|
||||
<el-form-item label="角色名称:" prop="name">
|
||||
<el-input
|
||||
v-model="form1.name"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="角色标志:" prop="key">
|
||||
<el-input
|
||||
v-model="form1.key"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="角色图标:" prop="icon">
|
||||
<el-input
|
||||
v-model="form1.icon"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="打招呼信息:" prop="hello_msg">
|
||||
<el-input
|
||||
v-model="form1.hello_msg"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="上下文信息:" prop="context">
|
||||
<template #default>
|
||||
<el-table :data="form1.context" :border="childBorder" size="small">
|
||||
<el-table-column label="对话角色" width="120">
|
||||
<template #default="scope">
|
||||
<el-input
|
||||
v-model="scope.row.role"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="对话内容">
|
||||
<template #header>
|
||||
<div class="context-msg-key">
|
||||
<span>对话内容</span>
|
||||
<span class="fr">
|
||||
<el-button type="primary" @click="addContext" size="small">
|
||||
<el-icon>
|
||||
<Plus/>
|
||||
</el-icon>
|
||||
增加一行
|
||||
</el-button>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #default="scope">
|
||||
<div class="context-msg-content">
|
||||
<el-input
|
||||
v-model="scope.row.content"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<span><el-icon @click="removeContext(scope.$index)"><RemoveFilled/></el-icon></span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</template>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="启用状态">
|
||||
<el-switch v-model="form1.enable"/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<span class="dialog-footer">
|
||||
<el-button @click="showDialog = false">取消</el-button>
|
||||
<el-button type="primary" @click="doUpdate">保存</el-button>
|
||||
</span>
|
||||
</div>
|
||||
<div>{{ title }}</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
|
||||
import {Plus, RemoveFilled} from "@element-plus/icons-vue";
|
||||
import {reactive, ref} from "vue";
|
||||
import {httpPost} from "@/utils/http";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {ref} from "vue";
|
||||
|
||||
const showDialog = ref(false)
|
||||
const childBorder = ref(true)
|
||||
const form1 = ref({context: []})
|
||||
// const form2 = ref({context: []})
|
||||
const formRef = ref(null)
|
||||
|
||||
const rules = reactive({
|
||||
name: [{required: true, message: '请输入用户名', trigger: 'change',}],
|
||||
key: [{required: true, message: '请输入角色标识', trigger: 'change',}],
|
||||
icon: [{required: true, message: '请输入角色图标', trigger: 'change',}],
|
||||
hello_msg: [{required: true, message: '请输入打招呼信息', trigger: 'change',}]
|
||||
})
|
||||
|
||||
|
||||
// 编辑
|
||||
const doUpdate = function () {
|
||||
formRef.value.validate((valid) => {
|
||||
if (valid) {
|
||||
showDialog.value = false
|
||||
httpPost('/api/admin/chat-roles/set', form1.value).then(() => {
|
||||
ElMessage.success('更新角色成功')
|
||||
// 更新当前数据行
|
||||
}).catch((e) => {
|
||||
ElMessage.error('更新角色失败,' + e.message)
|
||||
})
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const addContext = function () {
|
||||
form1.value.context.push({role: '', content: ''})
|
||||
}
|
||||
|
||||
const removeContext = function (index) {
|
||||
form1.value.context.splice(index, 1);
|
||||
}
|
||||
const title = ref('Test Page')
|
||||
|
||||
</script>
|
||||
|
||||
<style lang="stylus" scoped>
|
||||
.role-list {
|
||||
.opt-box {
|
||||
padding-bottom: 10px;
|
||||
|
||||
.el-icon {
|
||||
margin-right 5px;
|
||||
}
|
||||
}
|
||||
|
||||
.context-msg-key {
|
||||
.fr {
|
||||
float right
|
||||
|
||||
.el-icon {
|
||||
margin-right 5px
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.context-msg-content {
|
||||
display flex
|
||||
|
||||
.el-icon {
|
||||
font-size: 20px;
|
||||
margin-top 5px;
|
||||
margin-left 5px;
|
||||
cursor pointer
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -63,6 +63,9 @@
|
||||
</template>
|
||||
</van-picker>
|
||||
</van-popup>
|
||||
|
||||
<bind-mobile v-if="isLogin" :show="showBindMobileDialog" :mobile="loginUser.mobile"
|
||||
@hide="showBindMobileDialog = false"/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -74,6 +77,7 @@ import {checkSession} from "@/action/session";
|
||||
import router from "@/router";
|
||||
import {setChatConfig} from "@/store/chat";
|
||||
import {removeArrayItem} from "@/utils/libs";
|
||||
import BindMobile from "@/components/mobile/BindMobile.vue";
|
||||
|
||||
const title = ref("会话列表")
|
||||
const chatName = ref("")
|
||||
@@ -88,10 +92,14 @@ const roles = ref([])
|
||||
const models = ref([])
|
||||
const showPicker = ref(false)
|
||||
const columns = ref([roles.value, models.value])
|
||||
const showBindMobileDialog = ref(false)
|
||||
|
||||
checkSession().then((user) => {
|
||||
loginUser.value = user
|
||||
isLogin.value = true
|
||||
if (user.mobile === '') {
|
||||
showBindMobileDialog.value = true
|
||||
}
|
||||
// 加载角色列表
|
||||
httpGet(`/api/role/list?user_id=${user.id}`).then((res) => {
|
||||
if (res.data) {
|
||||
|
||||
@@ -283,7 +283,7 @@ const sendMessage = () => {
|
||||
return
|
||||
}
|
||||
|
||||
if (prompt.value.trim().length === 0 || canSend.value === false) {
|
||||
if (prompt.value.trim().length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,14 @@
|
||||
disabled
|
||||
placeholder="用户名"
|
||||
/>
|
||||
<van-field
|
||||
v-model="form.mobile"
|
||||
name="手机号"
|
||||
label="手机号"
|
||||
readonly
|
||||
disabled
|
||||
placeholder="手机号"
|
||||
/>
|
||||
<van-field
|
||||
v-model="form.nickname"
|
||||
name="昵称"
|
||||
@@ -35,7 +43,7 @@
|
||||
</template>
|
||||
</van-field>
|
||||
|
||||
<van-field label="剩余 Tokens">
|
||||
<van-field label="消耗 Tokens">
|
||||
<template #input>
|
||||
<van-tag type="primary">{{ form.tokens }}</van-tag>
|
||||
</template>
|
||||
@@ -61,6 +69,7 @@ const title = ref('用户设置')
|
||||
const form = ref({
|
||||
username: '',
|
||||
nickname: '',
|
||||
mobile: '',
|
||||
avatar: '',
|
||||
calls: 0,
|
||||
tokens: 0
|
||||
|
||||
@@ -45,7 +45,6 @@
|
||||
name="API KEY"
|
||||
label="API KEY"
|
||||
placeholder="配置自己的 api key"
|
||||
:rules="[{ required: true, message: '请填写 API KEY' }]"
|
||||
/>
|
||||
</van-cell-group>
|
||||
<div style="margin: 16px;">
|
||||
@@ -126,4 +125,4 @@ const save = () => {
|
||||
padding-top 60px
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user