Skip to content

Commit

Permalink
支持websocket sign地址,优化登录流程
Browse files Browse the repository at this point in the history
  • Loading branch information
zhaodice committed Jan 1, 2025
1 parent 65fa79c commit f8ac980
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 19 deletions.
8 changes: 8 additions & 0 deletions cmd/gocq/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ func LoginInteract() {
if !global.PathExists("device.json") {
log.Warn("虚拟设备信息不存在, 将自动生成随机设备.")
device = client.GenRandomDevice()

_ = os.WriteFile("device.json", device.ToJson(), 0o644)
log.Info("已生成设备信息并保存到 device.json 文件.")
} else {
Expand Down Expand Up @@ -220,6 +221,13 @@ func LoginInteract() {
time.Sleep(time.Second * 5)
}
log.Info("开始尝试登录并同步消息...")
if base.Account.Password == "" && device.Protocol != client.AndroidWatch {
log.Warn("你用了空密码,因此你只能选手表协议!已自动把你变成手表...")
device.Protocol = client.AndroidWatch
} else if base.Account.Password != "" && device.Protocol == client.AndroidWatch {
log.Warn("你用了密码,但是手表协议不支持密码登录,已自动吞噬你的密码...")
base.Account.Password = ""
}
log.Infof("使用协议: %s", device.Protocol.Version())
cli = newClient()
cli.UseDevice(device)
Expand Down
67 changes: 59 additions & 8 deletions cmd/gocq/qsign.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import (
"github.com/ProtocolScience/AstralGocq/server"
"github.com/RomiChan/websocket"
"github.com/google/uuid"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -121,17 +123,66 @@ func (m *SignServerManager) asyncCheckServers(servers []config.SignServer) *conf
}

func isServerAvailable(signServer string) bool {
resp, err := download.Request{
Method: http.MethodGet,
URL: signServer,
}.WithTimeout(3 * time.Second).Bytes()
if err == nil && gjson.GetBytes(resp, "code").Int() == 0 {
return true
}
log.Warnf("Server %v may be unavailable, error: %v", signServer, err)
parsedURL, err := url.Parse(signServer)
if err != nil {
log.Warnf("Invalid URL: %v, error: %v", signServer, err)
return false
}
switch parsedURL.Scheme {
case "http", "https":
return isHTTPAvailable(signServer)
case "ws", "wss":
return isWebSocketAvailable(signServer)
default:
log.Error("Unsupported protocol: %v", parsedURL.Scheme)

Check failure on line 137 in cmd/gocq/qsign.go

View workflow job for this annotation

GitHub Actions / lint

printf: github.com/sirupsen/logrus.Error call has possible Printf formatting directive %v (govet)
return false
}
}

func isHTTPAvailable(url string) bool {
httpClient := http.Client{
Timeout: 3 * time.Second,
}

resp, err := httpClient.Get(url)

Check failure on line 147 in cmd/gocq/qsign.go

View workflow job for this annotation

GitHub Actions / lint

response body must be closed (bodyclose)
if err != nil {
log.Warnf("HTTP check failed for %v, error: %v", url, err)
return false
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)

if resp.StatusCode == http.StatusOK {
// Assuming response body contains JSON with a "code" field
bodyBytes, err := io.ReadAll(resp.Body)
if err == nil && gjson.GetBytes(bodyBytes, "code").Int() == 0 {
return true
}
}

return false
}

func isWebSocketAvailable(url string) bool {
dialer := websocket.Dialer{
HandshakeTimeout: 3 * time.Second,
}

conn, _, err := dialer.Dial(url, nil)

Check failure on line 172 in cmd/gocq/qsign.go

View workflow job for this annotation

GitHub Actions / lint

response body must be closed (bodyclose)
if err != nil {
log.Warnf("WebSocket check failed for %v, error: %v", url, err)
return false
}
defer func(conn *websocket.Conn) {
_ = conn.Close()
}(conn)

// Optionally, you can send a ping or some message to verify further

return true
}

// SignClient handles requests to the sign server.
type SignClient struct {
client *client.QQClient
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.20
require (
github.com/FloatTech/sqlite v1.6.3
github.com/Microsoft/go-winio v0.6.2-0.20230724192519-b29bbd58a65a
github.com/ProtocolScience/AstralGo v0.0.0-20241231203200-eb101c2df8fa
github.com/ProtocolScience/AstralGo v0.0.0-20250101143547-c6b94f5d2867
github.com/RomiChan/syncx v0.0.0-20221202055724-5f842c53020e
github.com/RomiChan/websocket v1.4.3-0.20220227141055-9b2c6168c9c5
github.com/fumiama/go-base16384 v1.7.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ github.com/ProtocolScience/AstralGo v0.0.0-20241231010307-01edf5253812 h1:WhmN0P
github.com/ProtocolScience/AstralGo v0.0.0-20241231010307-01edf5253812/go.mod h1:Wg8s7tsAsz9aTzQAcElBf9toTy1vU14AB9xmOiTQv7s=
github.com/ProtocolScience/AstralGo v0.0.0-20241231203200-eb101c2df8fa h1:HTn/KWTz92AGJjlFtICWA5X6QWQ+xt2cGT9ZoaR0exI=
github.com/ProtocolScience/AstralGo v0.0.0-20241231203200-eb101c2df8fa/go.mod h1:Wg8s7tsAsz9aTzQAcElBf9toTy1vU14AB9xmOiTQv7s=
github.com/ProtocolScience/AstralGo v0.0.0-20250101143547-c6b94f5d2867 h1:tepmYaqiLfHMW6H3Q6JVQ9+TDG6ydf8DtEKS+HzN2lk=
github.com/ProtocolScience/AstralGo v0.0.0-20250101143547-c6b94f5d2867/go.mod h1:Wg8s7tsAsz9aTzQAcElBf9toTy1vU14AB9xmOiTQv7s=
github.com/RomiChan/protobuf v0.1.1-0.20230204044148-2ed269a2e54d h1:/Xuj3fIiMY2ls1TwvPKmaqQrtJsPY+c9s+0lOScVHd8=
github.com/RomiChan/protobuf v0.1.1-0.20230204044148-2ed269a2e54d/go.mod h1:2Ie+hdBFQpQFDHfeklgxoFmQRCE7O+KwFpISeXq7OwA=
github.com/RomiChan/syncx v0.0.0-20221202055724-5f842c53020e h1:wR3MXQ3VbUlPKOOUwLOYgh/QaJThBTYtsl673O3lqSA=
Expand Down
65 changes: 56 additions & 9 deletions modules/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"os"
"regexp"
"strconv"
"strings"

log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -91,18 +92,23 @@ type Server struct {

// Parse 从默认配置文件路径中获取
func Parse(path string) *Config {
_, err := os.Stat(path)
if err != nil {
generateConfig()
fmt.Println("配置文件已生成,按Enter继续,或者Ctrl+C退出程序来手动修改配置文件")
_, _ = bufio.NewReader(os.Stdin).ReadString('\n')
}
file, err := os.ReadFile(path)
config := &Config{}
if err == nil {
err = yaml.NewDecoder(strings.NewReader(expand(string(file), os.Getenv))).Decode(config)
if err != nil {
log.Fatal("配置文件不合法!", err)
if err == nil {
return config
}
} else {
generateConfig()
os.Exit(0)
}
return config
fmt.Println("配置文件不合法!", err)
os.Exit(1)
return nil
}

var serverconfs []*Server
Expand Down Expand Up @@ -140,9 +146,50 @@ func generateConfig() {
sb.WriteString(serverconfs[r].Default)
}
}
_ = os.WriteFile("config.yml", []byte(sb.String()), 0o644)
fmt.Println("默认配置文件已生成,请修改 config.yml 后重新启动!")
_, _ = input.ReadString('\n')

// Parse the YAML configuration
var config map[string]interface{}
err = yaml.Unmarshal([]byte(sb.String()), &config)
if err != nil {
log.Fatal("无法解析配置: ", err)
}
// Access nested map for account
if account, ok := config["account"].(map[string]interface{}); ok {
// Capture QQ account information
fmt.Print("请输入您的QQ账号: ")
uinStr, err := input.ReadString('\n')
if err != nil {
log.Fatal("输入不合法: ", err)
}
uinStr = strings.TrimSpace(uinStr)
uin, err := strconv.ParseInt(uinStr, 10, 64)
if err != nil {
log.Fatal("QQ账号必须是数字: ", err)
}
account["uin"] = uin

fmt.Print("请输入您的密码(可空): ")
password, err := input.ReadString('\n')
if err != nil {
log.Fatal("输入不合法: ", err)
}

account["password"] = strings.TrimSpace(password)

// Serialize the updated configuration back to YAML
updatedConfig, err := yaml.Marshal(&config)
if err != nil {
log.Fatal("无法序列化配置: ", err)
}

// Write the updated configuration to a file
err = os.WriteFile("config.yml", updatedConfig, 0o644)
if err != nil {
log.Fatal("无法写入配置文件: ", err)
}
} else {
log.Fatal("无法解析配置: ", err)
}
}

// expand 使用正则进行环境变量展开
Expand Down
5 changes: 4 additions & 1 deletion modules/config/default_config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ account: # 账号相关
# ...
#
# 服务器可使用docker在本地搭建或者使用他人开放的服务
sign-servers:
sign-servers:
- url: 'ws://183.131.51.152:7860/ws' # 备用
key: 'selfshare'
authorization: '-'
- url: 'https://qsign.trpgbot.com' # 主签名服务器地址, 必填
key: 'selfshare' # 签名服务器所需要的apikey, 如果签名服务器的版本在1.1.0及以下则此项无效
authorization: '-' # authorization 内容, 依服务端设置,如 'Bearer xxxx'
Expand Down

0 comments on commit f8ac980

Please sign in to comment.