Skip to content

Commit

Permalink
refactor: 重构了下载逻辑
Browse files Browse the repository at this point in the history
feat: 目前可以显示下载进度了
  • Loading branch information
hamster1963 committed Jul 28, 2023
1 parent 7aff9c2 commit 7caf6bb
Show file tree
Hide file tree
Showing 5 changed files with 199 additions and 61 deletions.
14 changes: 5 additions & 9 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ module speed-cron-updater

go 1.20

require (
github.com/gogf/gf/v2 v2.4.4
github.com/schollz/progressbar/v3 v3.13.1
)
require github.com/gogf/gf/v2 v2.5.1

require (
github.com/BurntSushi/toml v1.1.0 // indirect
github.com/clbanning/mxj/v2 v2.5.5 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-logr/logr v1.2.3 // indirect
Expand All @@ -20,15 +18,13 @@ require (
github.com/mattn/go-colorable v0.1.9 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
go.opentelemetry.io/otel v1.7.0 // indirect
go.opentelemetry.io/otel/sdk v1.7.0 // indirect
go.opentelemetry.io/otel/trace v1.7.0 // indirect
golang.org/x/net v0.0.0-20211123202848-9e5a29745d54 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/term v0.6.0 // indirect
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
golang.org/x/text v0.8.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
23 changes: 8 additions & 15 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@ github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/gogf/gf/v2 v2.4.4 h1:+s7PKxd4LJKjJn5ODZvYcbXMM5e+88Ww1W3GdOarLE8=
github.com/gogf/gf/v2 v2.4.4/go.mod h1:tsbmtwcAl2chcYoq/fP9W2FZf06aw4i89X34nbSHo9Y=
github.com/gogf/gf/v2 v2.5.1 h1:mkmqWrKTsuLRnv4OL1CS9voPMqfSx/DSY7JJnd/HnfA=
github.com/gogf/gf/v2 v2.5.1/go.mod h1:9XLWIkCQmaWIugHag4AEOtex0LlVeUHsUxqjAC8f6ew=
github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0=
github.com/grokify/html-strip-tags-go v0.0.1/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78=
github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=
github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo=
github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mattn/go-colorable v0.1.9 h1:sqDoxXbdeALODt0DAeJCVp38ps9ZogZEAXjus69YV3U=
Expand All @@ -34,18 +33,13 @@ github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/schollz/progressbar/v3 v3.13.1 h1:o8rySDYiQ59Mwzy2FELeHY5ZARXZTVJC7iHD6PEFUiE=
github.com/schollz/progressbar/v3 v3.13.1/go.mod h1:xvrbki8kfT1fzWzBT/UZd9L6GA+jdL7HAgq2RFnO6fQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
Expand All @@ -62,8 +56,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211123202848-9e5a29745d54 h1:CIhTfGs+z2NBqcn+cfZ2Tnyg+fd6rP41sC8ykB86JzQ=
golang.org/x/net v0.0.0-20211123202848-9e5a29745d54/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand All @@ -80,12 +74,11 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 h1:GLw7MR8AfAG2GmGcmVgObFOHXYypgGjnGno25RDwn3Y=
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2/go.mod h1:EFNZuWvGYxIRUEX+K8UmCFwYmZjqcrnq15ZuVldZkZ0=
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
Expand All @@ -96,5 +89,5 @@ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8T
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
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=
56 changes: 19 additions & 37 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package main

import (
"context"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/gclient"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/glog"
"os/exec"
"speed-cron-updater/utils"
"time"
)

Expand All @@ -32,8 +30,8 @@ func main() {
glog.Info(ctx, "speed_cron版本为:", string(versionOut))
}
// 与服务器版本比较
githubVersion := getLatestVersion()
if githubVersion == "" {
githubVersion, _, downloadStatus := utils.GetLatestVersionInfo()
if githubVersion == "" || !downloadStatus {
glog.Warning(ctx, "获取github最新版本失败,无法比较版本")
time.Sleep(5 * time.Second)
return
Expand All @@ -56,62 +54,46 @@ func main() {
stopOut, err := stopCmd.Output()
if err != nil {
glog.Warning(ctx, "关闭speed_cron失败,原因:", err.Error())
time.Sleep(5 * time.Second)
return
}
glog.Debug(ctx, "关闭speed_cron结果:", string(stopOut))

// 下载最新版本
exeUrl := "https://gh.xinyu.today/https://github.com/hamster1963/Speed-Cron/releases/latest/download/speed_cron_windows_amd64.exe"
exe, err := g.Client().Get(ctx, exeUrl)
err = gfile.PutBytes("client/core_bin/speed_cron.exe", exe.ReadAll())
if err != nil {
_, exeUrl, downloadStatus := utils.GetLatestVersionInfo()
if !downloadStatus {
glog.Warning(ctx, "下载最新版本: 获取github最新版本失败,无法下载")
time.Sleep(5 * time.Second)
return
}
exeUrl = "https://gh.xinyu.today/" + exeUrl
if err := utils.HTTPDownloadFileWithPercent(exeUrl, "client/core_bin/speed_cron.exe"); err != nil {
glog.Warning(ctx, "下载speed_cron失败,原因:", err.Error())
time.Sleep(5 * time.Second)
return
}

glog.Info(ctx, "下载speed_cron成功...")

// 检测版本
versionCmd := exec.Command("client/core_bin/speed_cron.exe", "version")
versionOut, err := versionCmd.Output()
if err != nil {
glog.Warning(ctx, "检测speed_cron版本失败,原因:", err.Error())
time.Sleep(5 * time.Second)
return
}
glog.Info(ctx, "当前speed_cron版本为:", string(versionOut))
glog.Info(ctx, "最新获取到本地speed_cron版本为:", string(versionOut))

startCmd := exec.Command("client/speed_cron_process.exe", "start")
startOut, err := startCmd.Output()
if err != nil {
glog.Warning(ctx, "启动speed_cron失败,原因:", err.Error())
time.Sleep(5 * time.Second)
return
}
glog.Debug(ctx, "启动speed_cron结果:", string(startOut))
glog.Info(ctx, "更新完成...程序会在5s后自动关闭...")
time.Sleep(5 * time.Second)
}

}

// getLatestVersion 获取github最新版本
func getLatestVersion() (version string) {
url := "http://120.24.211.49:10441/GetLatestVersion"
response, err := g.Client().Get(context.TODO(), url)
if err != nil {
glog.Warning(context.TODO(), "请求github最新版本失败,原因:", err.Error())
return ""
}
defer func(response *gclient.Response) {
err := response.Close()
if err != nil {
glog.Warning(context.TODO(), "关闭response失败,原因:", err.Error())
}
}(response)
githubResJson, err := gjson.DecodeToJson(response.ReadAllString())
if err != nil {
glog.Warning(context.TODO(), "解析response失败,原因:", err.Error())
return ""
}
if len(githubResJson.Get("data.github_res.asserts").Array()) == 0 {
glog.Warning(context.TODO(), "解析response失败,原因:", "github_res.asserts为空")
return ""
}
return githubResJson.Get("data.github_res.tag_name").String()
}
115 changes: 115 additions & 0 deletions utils/download.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package utils

import (
"context"
"fmt"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/os/glog"
"io"
"net/http"
"os"
"strconv"
"time"
)

// HTTPDownloadFileWithPercent downloads target url file to local path with percent process printing.
func HTTPDownloadFileWithPercent(url string, localSaveFilePath string) error {
start := time.Now()
out, err := os.Create(localSaveFilePath)
if err != nil {
return gerror.Wrapf(err, `download "%s" to "%s" failed`, url, localSaveFilePath)
}
defer func(out *os.File) {
err := out.Close()
if err != nil {
glog.Warning(context.Background(), err)
}
}(out)

headResp, err := http.Head(url)
if err != nil {
return gerror.Wrapf(err, `download "%s" to "%s" failed`, url, localSaveFilePath)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
glog.Warning(context.Background(), err)
}
}(headResp.Body)

size, err := strconv.Atoi(headResp.Header.Get("Content-Length"))
if err != nil {
return gerror.Wrap(err, "retrieve Content-Length failed")
}
doneCh := make(chan int64)

go doPrintDownloadPercent(doneCh, localSaveFilePath, int64(size))

resp, err := http.Get(url)
if err != nil {
return gerror.Wrapf(err, `download "%s" to "%s" failed`, url, localSaveFilePath)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
glog.Warning(context.Background(), err)
}
}(resp.Body)

wroteBytesCount, err := io.Copy(out, resp.Body)
if err != nil {
return gerror.Wrapf(err, `download "%s" to "%s" failed`, url, localSaveFilePath)
}

doneCh <- wroteBytesCount
elapsed := time.Since(start)
if elapsed > time.Minute {
glog.Printf(context.Background(), `download completed in %.0fm`, float64(elapsed)/float64(time.Minute))
} else {
glog.Printf(context.Background(), `download completed in %.0fs`, elapsed.Seconds())
}

return nil
}

func doPrintDownloadPercent(doneCh chan int64, localSaveFilePath string, total int64) {
var (
stop = false
lastPercentFmt string
)
for {
select {
case <-doneCh:
stop = true

default:
file, err := os.Open(localSaveFilePath)
if err != nil {
glog.Fatal(context.Background(), err)
time.Sleep(5 * time.Second)
}
fi, err := file.Stat()
if err != nil {
glog.Fatal(context.Background(), err)
time.Sleep(5 * time.Second)
}
size := fi.Size()
if size == 0 {
size = 1
}
var (
percent = float64(size) / float64(total) * 100
percentFmt = fmt.Sprintf(`%.0f`, percent) + "%"
)
if lastPercentFmt != percentFmt {
lastPercentFmt = percentFmt
glog.Debug(context.Background(), "下载最新二进制文件进度: "+percentFmt)
}
}

if stop {
break
}
time.Sleep(200 * time.Millisecond)
}
}
52 changes: 52 additions & 0 deletions utils/github.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package utils

import (
"context"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/gclient"
"github.com/gogf/gf/v2/os/glog"
)

// GetLatestVersionInfo 获取github最新版本
func GetLatestVersionInfo() (version string, downloadUrl string, downloadStatus bool) {
backendURL := "http://120.24.211.49:10441/GetLatestVersion"
response, err := g.Client().Get(context.TODO(), backendURL)
if err != nil {
glog.Warning(context.TODO(), "请求github最新版本失败,原因:", err.Error())
return "", "", false
}
defer func(response *gclient.Response) {
err := response.Close()
if err != nil {
glog.Warning(context.TODO(), "关闭response失败,原因:", err.Error())
}
}(response)
githubResJson, err := gjson.DecodeToJson(response.ReadAllString())
if err != nil {
glog.Warning(context.TODO(), "解析response失败,原因:", err.Error())
return "", "", false
}

// 判断GitHub Release可更新二进制文件是否存在
if len(githubResJson.Get("data.github_res.assets").Array()) == 0 {
glog.Warning(context.TODO(), "解析response失败,原因:", "github_res.assets为空")
return "", "", false
}
version = githubResJson.Get("data.github_res.tag_name").String()

// 获取下载文件名是否正确
downloadFileName := githubResJson.Get("data.github_res.assets.0.name").String()
if downloadFileName != "speed_cron_windows_amd64.exe" {
glog.Warning(context.TODO(), "解析response失败,原因:", "downloadFileName不正确")
return "", "", false
}

// 获取下载地址
downloadUrl = githubResJson.Get("data.github_res.assets.0.browser_download_url").String()
if version == "" || downloadUrl == "" {
glog.Warning(context.TODO(), "解析response失败,原因:", "version或downloadUrl为空")
return "", "", false
}
return version, downloadUrl, true
}

0 comments on commit 7caf6bb

Please sign in to comment.