Skip to content

Commit

Permalink
Test4 (#31)
Browse files Browse the repository at this point in the history
* Compiled main.go and pushed changes

* test

* 适配了频道私聊,用bolt数据库取代ini

* 适配了nonebot2

* add license

* add a lot

* trss support

* add action

* add action

* add action

* fixbug

* add wss

* bugfix

* fix action

* fix action again

* fa

* fix

* add a lot

* add ws server token

* bugifx

* fixat

* bugfix

* bugfix

* test

* test2

* add url service

* add url service

* bugfix

* fix

* fix

* fix

* bug fix

* fix

* test

* add webui
  • Loading branch information
Hoshinonyaruko authored Nov 2, 2023
1 parent 6efe96d commit f0ae49a
Show file tree
Hide file tree
Showing 142 changed files with 19,760 additions and 164 deletions.
122 changes: 85 additions & 37 deletions botgo/token/authtoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ func (atoken *AuthTokenInfo) StartRefreshAccessToken(ctx context.Context, tokenU
// 首先,立即获取一次AccessToken
tokenInfo, err := queryAccessToken(ctx, tokenURL, appID, clientSecrent)
if err != nil {
return err
log.Errorf("无法获取AccessToken: %v", err)
//return err
}
atoken.setAuthToken(tokenInfo)
log.Info("获取到的token是: %s\n", tokenInfo.Token) // 输出获取到的token
Expand All @@ -69,9 +70,9 @@ func (atoken *AuthTokenInfo) StartRefreshAccessToken(ctx context.Context, tokenU
atoken.once.Do(func() {
go func() { // 启动一个新的goroutine
for {
// 如果tokenTTL为0或负数,将其设置为1
// 如果tokenTTL为0或负数,将其设置为15
if tokenTTL <= 0 {
tokenTTL = 1
tokenTTL = 15
}
select {
case <-time.NewTimer(time.Duration(tokenTTL) * time.Second).C: // 当token过期时
Expand All @@ -89,6 +90,7 @@ func (atoken *AuthTokenInfo) StartRefreshAccessToken(ctx context.Context, tokenU
tokenTTL = tokenInfo.ExpiresIn
} else {
log.Errorf("queryAccessToken err:%v", err)
log.Errorf("请在config.yml或网页控制台的默认机器人中设置正确的appid和密钥信息")
}
}
}()
Expand Down Expand Up @@ -130,61 +132,107 @@ type queryTokenRsp struct {
ExpiresIn string `json:"expires_in"`
}

func queryAccessToken(ctx context.Context, tokenURL, appID, clientSecrent string) (AccessTokenInfo, error) {
method := "POST"
// func queryAccessToken(ctx context.Context, tokenURL, appID, clientSecrent string) (AccessTokenInfo, error) {
// method := "POST"

defer func() {
if err := recover(); err != nil {
log.Errorf("queryAccessToken err:%v", err)
}
}()
// defer func() {
// if err := recover(); err != nil {
// log.Errorf("queryAccessToken err:%v", err)
// }
// }()
// if tokenURL == "" {
// tokenURL = getAccessTokenURL
// }

// queryReq := queryTokenReq{
// AppID: appID,
// ClientSecret: clientSecrent,
// }
// data, err := json.Marshal(queryReq)
// if err != nil {
// return AccessTokenInfo{}, err
// }
// payload := bytes.NewReader(data)
// log.Infof("reqdata:%v", string(data))
// client := &http.Client{
// Timeout: 10 * time.Second,
// }
// log.Infof("tokenURL:%v", tokenURL)
// req, err := http.NewRequest(method, tokenURL, payload)
// if err != nil {
// log.Errorf("NewRequest err:%v", err)
// return AccessTokenInfo{}, err
// }
// req.Header.Add("Content-Type", "application/json")
// res, err := client.Do(req)
// if err != nil {
// log.Errorf("http do err:%v", err)
// return AccessTokenInfo{}, err
// }
// defer res.Body.Close()

// body, err := ioutil.ReadAll(res.Body)
// if err != nil {
// log.Errorf("ReadAll do err:%v", err)
// return AccessTokenInfo{}, err
// }
// log.Infof("accesstoken:%v", string(body))
// queryRsp := queryTokenRsp{}
// if err = json.Unmarshal(body, &queryRsp); err != nil {
// log.Errorf("Unmarshal err:%v", err)
// return AccessTokenInfo{}, err
// }

// rdata := AccessTokenInfo{
// Token: queryRsp.AccessToken,
// UpTime: time.Now(),
// }
// rdata.ExpiresIn, _ = strconv.ParseInt(queryRsp.ExpiresIn, 10, 64)
// return rdata, err
// }

// queryAccessToken retrieves a new AccessToken.
func queryAccessToken(ctx context.Context, tokenURL, appID, clientSecret string) (AccessTokenInfo, error) {
if tokenURL == "" {
tokenURL = getAccessTokenURL
tokenURL = getAccessTokenURL // Assumes getAccessTokenURL is declared elsewhere
}

queryReq := queryTokenReq{
reqBody := queryTokenReq{
AppID: appID,
ClientSecret: clientSecrent,
ClientSecret: clientSecret,
}
data, err := json.Marshal(queryReq)
reqData, err := json.Marshal(reqBody)
if err != nil {
return AccessTokenInfo{}, err
}
payload := bytes.NewReader(data)
log.Infof("reqdata:%v", string(data))
client := &http.Client{
Timeout: 10 * time.Second,
}
log.Infof("tokenURL:%v", tokenURL)
req, err := http.NewRequest(method, tokenURL, payload)

req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, bytes.NewReader(reqData))
if err != nil {
log.Errorf("NewRequest err:%v", err)
return AccessTokenInfo{}, err
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)

resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Errorf("http do err:%v", err)
return AccessTokenInfo{}, err
}
defer res.Body.Close()
defer resp.Body.Close()

body, err := ioutil.ReadAll(res.Body)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("ReadAll do err:%v", err)
return AccessTokenInfo{}, err
}
log.Infof("accesstoken:%v", string(body))
queryRsp := queryTokenRsp{}
if err = json.Unmarshal(body, &queryRsp); err != nil {
log.Errorf("Unmarshal err:%v", err)

var respData queryTokenRsp
if err := json.Unmarshal(body, &respData); err != nil {
return AccessTokenInfo{}, err
}

rdata := AccessTokenInfo{
Token: queryRsp.AccessToken,
UpTime: time.Now(),
}
rdata.ExpiresIn, _ = strconv.ParseInt(queryRsp.ExpiresIn, 10, 64)
return rdata, err
expiresIn, _ := strconv.ParseInt(respData.ExpiresIn, 10, 64) // Ignoring error can be dangerous, handle it as needed

return AccessTokenInfo{
Token: respData.AccessToken,
ExpiresIn: expiresIn,
UpTime: time.Now(),
}, nil
}
3 changes: 2 additions & 1 deletion botgo/token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ func UserToken(appID uint64, clientSecret string) *Token {

func (t *Token) InitToken(ctx context.Context) (err error) {
if err = t.authToken.StartRefreshAccessToken(ctx, t.tokenURL, fmt.Sprint(t.appID), t.clientSecret); err != nil {
return err
log.Errorf("无法获取AccessToken: %v", err)
//return err
}
return nil
}
Expand Down
137 changes: 135 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
// config/config.go

package config

import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"sync"

"github.com/hoshinonyaruko/gensokyo/mylog"
"github.com/hoshinonyaruko/gensokyo/sys"
"github.com/hoshinonyaruko/gensokyo/template"
"gopkg.in/yaml.v3"
)

Expand Down Expand Up @@ -41,6 +44,8 @@ type Settings struct {
Crt string `yaml:"crt"`
Key string `yaml:"key"`
DeveloperLog bool `yaml:"developer_log"`
Username string `yaml:"server_user_name"`
Password string `yaml:"server_user_password"`
}

// LoadConfig 从文件中加载配置并初始化单例配置
Expand All @@ -65,6 +70,79 @@ func LoadConfig(path string) (*Config, error) {
return conf, nil
}

// UpdateConfig 将配置写入文件
func UpdateConfig(conf *Config, path string) error {
data, err := yaml.Marshal(conf)
if err != nil {
return err
}
return os.WriteFile(path, data, 0644)
}

// WriteYAMLToFile 将YAML格式的字符串写入到指定的文件路径
func WriteYAMLToFile(yamlContent string) error {
// 获取当前执行的可执行文件的路径
exePath, err := os.Executable()
if err != nil {
log.Println("Error getting executable path:", err)
return err
}

// 获取可执行文件所在的目录
exeDir := filepath.Dir(exePath)

// 构建config.yml的完整路径
configPath := filepath.Join(exeDir, "config.yml")

// 写入文件
os.WriteFile(configPath, []byte(yamlContent), 0644)

sys.RestartApplication()
return nil
}

// DeleteConfig 删除配置文件并创建一个新的配置文件模板
func DeleteConfig() error {
// 获取当前执行的可执行文件的路径
exePath, err := os.Executable()
if err != nil {
mylog.Println("Error getting executable path:", err)
return err
}

// 获取可执行文件所在的目录
exeDir := filepath.Dir(exePath)

// 构建config.yml的完整路径
configPath := filepath.Join(exeDir, "config.yml")

// 删除配置文件
if err := os.Remove(configPath); err != nil {
mylog.Println("Error removing config file:", err)
return err
}

// 获取内网IP地址
ip, err := sys.GetLocalIP()
if err != nil {
mylog.Println("Error retrieving the local IP address:", err)
return err
}

// 将 <YOUR_SERVER_DIR> 替换成实际的内网IP地址
configData := strings.Replace(template.ConfigTemplate, "<YOUR_SERVER_DIR>", ip, -1)

// 创建一个新的配置文件模板 写到配置
if err := os.WriteFile(configPath, []byte(configData), 0644); err != nil {
mylog.Println("Error writing config.yml:", err)
return err
}

sys.RestartApplication()

return nil
}

// 获取ws地址数组
func GetWsAddress() []string {
mu.Lock()
Expand Down Expand Up @@ -234,3 +312,58 @@ func GetDeveloperLog() bool {
}
return instance.Settings.DeveloperLog
}

// ComposeWebUIURL 组合webui的完整访问地址
func ComposeWebUIURL() string {
serverDir := GetServer_dir()
port := GetPortValue()

// 判断端口是不是443,如果是,则使用https协议
protocol := "http"
if port == "443" {
protocol = "https"
}

// 组合出完整的URL
return fmt.Sprintf("%s://%s:%s/webui", protocol, serverDir, port)
}

// ComposeWebUIURL 组合webui的完整访问地址
func ComposeWebUIURLv2() string {
ip, _ := sys.GetPublicIP()

port := GetPortValue()

// 判断端口是不是443,如果是,则使用https协议
protocol := "http"
if port == "443" {
protocol = "https"
}

// 组合出完整的URL
return fmt.Sprintf("%s://%s:%s/webui", protocol, ip, port)
}

// GetServerUserName 获取服务器用户名
func GetServerUserName() string {
mu.Lock()
defer mu.Unlock()

if instance == nil {
mylog.Println("Warning: instance is nil when trying to get server user name.")
return ""
}
return instance.Settings.Username
}

// GetServerUserPassword 获取服务器用户密码
func GetServerUserPassword() string {
mu.Lock()
defer mu.Unlock()

if instance == nil {
mylog.Println("Warning: instance is nil when trying to get server user password.")
return ""
}
return instance.Settings.Password
}
9 changes: 9 additions & 0 deletions frontend/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
9 changes: 9 additions & 0 deletions frontend/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/dist
/src-bex/www
/src-capacitor
/src-cordova
/.quasar
/node_modules
.eslintrc.js
babel.config.js
/src-ssr
Loading

0 comments on commit f0ae49a

Please sign in to comment.