diff --git a/global/param.go b/global/param.go index 25e138f5..5f01bea7 100644 --- a/global/param.go +++ b/global/param.go @@ -2,6 +2,9 @@ package global import ( "github.com/tidwall/gjson" + "math" + "regexp" + "strconv" "strings" ) @@ -48,3 +51,22 @@ func EnsureBool(p interface{}, defaultVal bool) bool { } return defaultVal } + +// VersionNameCompare 检查版本名是否需要更新, 仅适用于 go-cqhttp 的版本命名规则 +// 例: v0.9.29-fix2 == v0.9.29-fix2 -> false +// v0.9.29-fix1 < v0.9.29-fix2 -> true +// v0.9.29-fix2 > v0.9.29-fix1 -> false +// v0.9.29-fix2 < v0.9.30 -> true +func VersionNameCompare(current, remote string) bool { + sp := regexp.MustCompile(`[0-9]\d*`) + cur := sp.FindAllStringSubmatch(current, -1) + re := sp.FindAllStringSubmatch(remote, -1) + for i := 0; i < int(math.Min(float64(len(cur)), float64(len(re)))); i++ { + curSub, _ := strconv.Atoi(cur[i][0]) + reSub, _ := strconv.Atoi(re[i][0]) + if curSub < reSub { + return true + } + } + return len(cur) < len(re) +} diff --git a/main.go b/main.go index 7601725a..971d001a 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,8 @@ import ( "encoding/json" "fmt" "github.com/Mrs4s/go-cqhttp/server" + "github.com/guonaihong/gout" + "github.com/tidwall/gjson" "io" "io/ioutil" "os" @@ -253,6 +255,7 @@ func main() { } b := server.WebServer.Run(fmt.Sprintf("%s:%d", conf.WebUi.Host, conf.WebUi.WebUiPort), cli) c := server.Console + go checkUpdate() signal.Notify(c, os.Interrupt, os.Kill) <-c b.Release() @@ -282,3 +285,27 @@ func DecryptPwd(ePwd string, key []byte) string { } return string(tea.Decrypt(encrypted)) } + +func checkUpdate() { + log.Infof("正在检查更新.") + if coolq.Version == "unknown" { + log.Warnf("检查更新失败: 使用的 Actions 测试版或自编译版本") + return + } + var res string + if err := gout.GET("https://api.github.com/repos/Mrs4s/go-cqhttp/releases").BindBody(&res).Do(); err != nil { + log.Warnf("检查更新失败: %v", err) + return + } + detail := gjson.Parse(res) + if len(detail.Array()) < 1 { + return + } + info := detail.Array()[0] + if global.VersionNameCompare(coolq.Version, info.Get("tag_name").Str) { + log.Infof("当前有更新的 go-cqhttp 可供更新, 请前往 https://github.com/Mrs4s/go-cqhttp/releases 下载.") + log.Infof("当前版本: %v 最新版本: %v", coolq.Version, info.Get("tag_name").Str) + return + } + log.Infof("检查更新完成. 当前已运行最新版本.") +}