-
Notifications
You must be signed in to change notification settings - Fork 42
/
main.go
359 lines (335 loc) · 8.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package main
import (
"bufio"
"crypto/md5"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"reflect"
"runtime"
"strconv"
"strings"
"time"
"github.com/XiaoMengXinX/Music163bot-Go/v2/bot"
"github.com/XiaoMengXinX/Music163bot-Go/v2/symbols"
"github.com/sirupsen/logrus"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
"github.com/traefik/yaegi/stdlib/syscall"
"github.com/traefik/yaegi/stdlib/unsafe"
)
var config map[string]string
var (
_ConfigPath *string
_NoUpdate *bool
_NoMD5Check *bool
_SrcPath *string
_BotEntry *string
)
var (
runtimeVer = fmt.Sprintf(runtime.Version()) // 编译环境
_VersionName = "" // 程序版本
_VersionCodeStr = ""
_VersionCode = 0
commitSHA = "" // 编译哈希
buildTime = "" // 编译日期
buildArch = fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH) // 运行环境
repoPath = "" // 项目地址
rawRepoPath = ""
)
type metadata struct {
Version string `json:"version"`
VersionCode int `json:"version_code"`
Files []struct {
File string `json:"file"`
Md5 string `json:"md5"`
} `json:"files"`
}
// LogFormatter 自定义 log 格式
type LogFormatter struct{}
// Format 自定义 log 格式
func (s *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
timestamp := time.Now().Local().Format("2006/01/02 15:04:05")
var msg string
msg = fmt.Sprintf("%s [%s] %s (%s:%d)\n", timestamp, strings.ToUpper(entry.Level.String()), entry.Message, path.Base(entry.Caller.File), entry.Caller.Line)
return []byte(msg), nil
}
func init() {
_VersionCode, _ = strconv.Atoi(_VersionCodeStr)
logrus.SetFormatter(&logrus.TextFormatter{
DisableColors: false,
FullTimestamp: true,
DisableLevelTruncation: true,
PadLevelText: true,
})
logrus.SetFormatter(new(LogFormatter))
logrus.SetReportCaller(true)
dirExists("./log")
timeStamp := time.Now().Local().Format("2006-01-02")
logFile := fmt.Sprintf("./log/%v.log", timeStamp)
file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
logrus.Errorln(err)
}
output := io.MultiWriter(os.Stdout, file)
logrus.SetOutput(output)
if config["LogLevel"] != "" {
level, err := logrus.ParseLevel(config["LogLevel"])
if err != nil {
logrus.Errorln(err)
} else {
logrus.SetLevel(level)
}
}
f := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
_ConfigPath = f.String("c", "config.ini", "配置文件")
_NoUpdate = f.Bool("no-update", false, "关闭更新检测")
_NoMD5Check = f.Bool("no-md5-check", false, "关闭 md5 效验")
_SrcPath = f.String("path", "./src", "自定义更新下载/加载路径")
_BotEntry = f.String("bot-entry", "bot.Start", "自定义动态加载入口")
_ = f.Parse(os.Args[1:])
logrus.Printf("Music163bot-Go %s(%d)", _VersionName, _VersionCode)
conf, err := readConfig(*_ConfigPath)
if err != nil {
logrus.Errorln("读取配置文件失败,请检查配置文件")
logrus.Fatal(err)
}
config = conf
initConfig(config)
}
func main() {
var meta metadata
var actionCode = -1 // actionCode: 0 exit, 1 error exit, 2 reload src, 3 update src
for true {
err := func() (err error) {
data, err := getLocalVersion()
if err != nil {
return err
}
meta = data
if !*_NoMD5Check && data.VersionCode != 0 {
logrus.Println("正在校验文件MD5")
err := checkMD5(data)
if err != nil {
return err
}
logrus.Println("MD5校验成功")
}
return err
}()
if func() bool {
if err == nil {
if (!*_NoMD5Check && len(meta.Files) == 0) || (*_NoUpdate && len(meta.Files) == 0) {
return true
}
v, err := loadDyn(meta)
if err == nil {
start, ok := v.Interface().(func(map[string]string) int)
if ok {
config["VersionName"] = meta.Version
config["VersionCode"] = fmt.Sprintf("%d", meta.VersionCode)
if *_NoUpdate && *_NoMD5Check {
logrus.Printf("加载自定义源码中")
} else {
logrus.Printf("加载版本 %s(%d) 中", meta.Version, meta.VersionCode)
}
actionCode = start(config)
} else {
return true
}
} else {
logrus.Errorln(err)
return true
}
} else {
logrus.Errorln(err)
return true
}
return false
}() {
logrus.Printf("加载内置版本 %s(%d) 中", _VersionName, _VersionCode)
actionCode = bot.Start(config)
}
switch actionCode {
case 0:
os.Exit(0)
case 1:
logrus.Fatal("Unexpected error")
case 2:
time.Sleep(2 * time.Second)
conf, err := readConfig(*_ConfigPath)
if err != nil {
logrus.Errorln(err)
logrus.Fatal("读取配置文件失败,请检查配置文件")
} else {
config = conf
initConfig(config)
}
continue
case 3:
time.Sleep(2 * time.Second)
continue
}
}
}
func loadDyn(meta metadata) (res reflect.Value, err error) {
defer func() {
e := recover()
if e != nil {
err = fmt.Errorf("%v", e)
}
}()
i := interp.New(interp.Options{})
_ = i.Use(unsafe.Symbols)
_ = i.Use(stdlib.Symbols)
_ = i.Use(syscall.Symbols)
_ = i.Use(symbols.Symbols)
if *_NoUpdate && *_NoMD5Check {
files, err := ioutil.ReadDir(*_SrcPath)
if err != nil {
return reflect.Value{}, err
}
for _, f := range files {
if strings.Contains(f.Name(), ".go") {
_, err := i.EvalPath(fmt.Sprintf("%s/%s", *_SrcPath, f.Name()))
if err != nil {
return reflect.Value{}, err
}
}
}
} else {
for _, f := range meta.Files {
if strings.Contains(path.Base(f.File), ".go") {
_, err := i.EvalPath(fmt.Sprintf("%s/%s", *_SrcPath, path.Base(f.File)))
if err != nil {
return reflect.Value{}, err
}
}
}
}
res, err = i.Eval(*_BotEntry)
if err != nil {
return reflect.Value{}, err
}
return res, err
}
func getLocalVersion() (meta metadata, err error) {
if fileExists(fmt.Sprintf("%s/version.json", *_SrcPath)) {
content, err := ioutil.ReadFile(fmt.Sprintf("%s/version.json", *_SrcPath))
if err != nil {
return meta, err
}
err = json.Unmarshal(content, &meta)
return meta, err
}
return meta, err
}
func checkMD5(data metadata) (err error) {
for _, f := range data.Files {
file, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", *_SrcPath, path.Base(f.File)))
if err != nil {
return err
}
md5Data := md5.Sum(file)
if hex.EncodeToString(md5Data[:]) != f.Md5 {
return fmt.Errorf("文件: %s/%s MD5效验失败 ", *_SrcPath, path.Base(f.File))
}
}
return err
}
func readConfig(path string) (config map[string]string, err error) {
config = make(map[string]string)
f, err := os.Open(path)
if err != nil {
return config, err
}
defer func(f *os.File) {
e := f.Close()
if e != nil {
err = e
}
}(f)
r := bufio.NewReader(f)
for {
b, _, err := r.ReadLine()
if err != nil {
if err == io.EOF {
break
}
return config, err
}
s := strings.TrimSpace(string(b))
index := strings.Index(s, "=")
if index < 0 {
continue
}
key := strings.TrimSpace(s[:index])
if len(key) == 0 {
continue
}
value := strings.TrimSpace(s[index+1:])
if len(value) == 0 {
continue
}
config[key] = value
}
return config, err
}
func fileExists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
func dirExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
err := os.Mkdir(path, os.ModePerm)
if err != nil {
logrus.Errorf("mkdir %v failed: %v\n", path, err)
}
return false
}
logrus.Errorf("Error: %v\n", err)
return false
}
func initConfig(config map[string]string) {
config["BinVersionName"] = _VersionName
config["BinVersionCode"] = fmt.Sprintf("%d", _VersionCode)
config["runtimeVer"] = runtimeVer
config["buildTime"] = buildTime
config["commitSHA"] = commitSHA
config["buildArch"] = buildArch
config["repoPath"] = repoPath
config["rawRepoPath"] = rawRepoPath
if *_NoUpdate {
config["AutoUpdate"] = "false"
} else if config["AutoUpdate"] == "false" {
*_NoUpdate = true
}
if *_NoMD5Check {
config["CheckMD5"] = "false"
} else if config["CheckMD5"] == "false" {
*_NoMD5Check = true
}
if config["SrcPath"] != "" {
*_SrcPath = config["SrcPath"]
} else {
config["SrcPath"] = *_SrcPath
}
if config["BotEntry"] != "" {
*_BotEntry = config["BotEntry"]
}
}