-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.go
More file actions
844 lines (730 loc) · 20.5 KB
/
Copy pathapp.go
File metadata and controls
844 lines (730 loc) · 20.5 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
package main
import (
"archive/zip"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
stdruntime "runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
const CurrentVersion = "2.2.2"
const MetadataURL = "https://jnuexam.gubaiovo.com/metadata.json"
type DownloadItem struct {
Name string `json:"name"`
Url string `json:"url"`
Size int64 `json:"size"`
ArchivePath string `json:"archive_path,omitempty"`
}
type PlatformInfo struct {
Url string `json:"url"`
Checksum string `json:"checksum"`
}
type UpdateInfo struct {
Version string `json:"version"`
Force bool `json:"force"`
Desc string `json:"desc"`
Platforms map[string]PlatformInfo `json:"platforms"`
}
type NoticeInfo struct {
Show bool `json:"show"`
Id string `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
}
type AppMetadata struct {
Notice NoticeInfo `json:"notice"`
Update UpdateInfo `json:"update"`
}
type CheckResult struct {
HasUpdate bool `json:"has_update"`
CurrentVer string `json:"current_ver"`
RemoteVer string `json:"remote_ver"`
UpdateDesc string `json:"update_desc"`
IsForce bool `json:"is_force"`
DownloadURL string `json:"download_url"`
Checksum string `json:"checksum"`
Notice NoticeInfo `json:"notice"`
}
type SourceConfig struct {
JsonUrl string `json:"json_url"`
FileKey string `json:"file_key"`
DirUrl string `json:"dir_url,omitempty"`
}
// type FileNode struct {
// Name string `json:"name"`
// Path string `json:"path"`
// Size interface{} `json:"size"`
// Files []*FileNode `json:"files,omitempty"`
// Dirs []*FileNode `json:"dirs,omitempty"`
// CfUrl string `json:"cf_url,omitempty"`
// GithubRawUrl string `json:"github_raw_url,omitempty"`
// }
type DownloadProgress struct {
Filename string `json:"filename"`
Percentage float64 `json:"percentage"`
}
type PreviewLaunchContext struct {
IsPreview bool `json:"is_preview"`
URL string `json:"url"`
Name string `json:"name"`
Ext string `json:"ext"`
}
type App struct {
ctx context.Context
dirCache map[string]interface{}
cacheLock sync.RWMutex
launchContext PreviewLaunchContext
}
func NewApp(args []string) *App {
return &App{
dirCache: make(map[string]interface{}),
launchContext: parseLaunchContext(args),
}
}
func parseLaunchContext(args []string) PreviewLaunchContext {
var launch PreviewLaunchContext
for i := 0; i < len(args); i++ {
switch args[i] {
case "--preview":
launch.IsPreview = true
case "--preview-url":
if i+1 < len(args) {
launch.URL = strings.TrimSpace(args[i+1])
i++
}
case "--preview-name":
if i+1 < len(args) {
launch.Name = strings.TrimSpace(args[i+1])
i++
}
case "--preview-ext":
if i+1 < len(args) {
launch.Ext = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(args[i+1])), ".")
i++
}
}
}
if !launch.IsPreview || launch.URL == "" {
return PreviewLaunchContext{}
}
if launch.Name == "" {
baseURL := launch.URL
if idx := strings.IndexAny(baseURL, "?#"); idx >= 0 {
baseURL = baseURL[:idx]
}
launch.Name = path.Base(baseURL)
if launch.Name == "" || launch.Name == "." || launch.Name == "/" {
launch.Name = "preview"
}
}
if launch.Ext == "" {
launch.Ext = strings.TrimPrefix(strings.ToLower(filepath.Ext(launch.Name)), ".")
}
if launch.Ext != "pdf" && launch.Ext != "txt" {
return PreviewLaunchContext{}
}
return launch
}
func (a *App) IsPreviewMode() bool {
return a.launchContext.IsPreview
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
go a.cleanupOldFile()
}
func (a *App) GetLaunchContext() PreviewLaunchContext {
return a.launchContext
}
func (a *App) cleanupOldFile() {
exePath, err := os.Executable()
if err != nil {
return
}
oldPath := exePath + ".old"
if _, err := os.Stat(oldPath); os.IsNotExist(err) {
return
}
runtime.LogPrintf(a.ctx, "发现旧版本文件: %s,准备清理...", oldPath)
for i := 0; i < 5; i++ {
time.Sleep(1 * time.Second)
err = os.Remove(oldPath)
if err == nil {
runtime.LogPrintf(a.ctx, "成功删除旧版本备份文件 (第 %d 次尝试)", i+1)
return
}
runtime.LogPrintf(a.ctx, "删除失败 (尝试 %d/5): %v", i+1, err)
}
runtime.LogPrintf(a.ctx, "放弃清理:旧文件可能仍被占用")
}
func (a *App) clearDirectoryCache() {
a.cacheLock.Lock()
a.dirCache = make(map[string]interface{})
a.cacheLock.Unlock()
}
func newHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{Timeout: timeout}
}
func ensureHTTPSuccess(resp *http.Response, url string) error {
if resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices {
return nil
}
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
message := strings.TrimSpace(string(snippet))
if message != "" {
return fmt.Errorf("请求失败 [%d %s]: %s", resp.StatusCode, resp.Status, message)
}
return fmt.Errorf("请求失败 [%d %s]: %s", resp.StatusCode, resp.Status, url)
}
func stagedFilePath(targetPath string) string {
name := fmt.Sprintf(".%s.%d.part", filepath.Base(targetPath), time.Now().UnixNano())
return filepath.Join(filepath.Dir(targetPath), name)
}
func replaceFile(targetPath string, stagedPath string) error {
backupPath := fmt.Sprintf("%s.bak.%d", targetPath, time.Now().UnixNano())
targetExists := false
if _, err := os.Stat(targetPath); err == nil {
targetExists = true
if err := os.Rename(targetPath, backupPath); err != nil {
return err
}
} else if !os.IsNotExist(err) {
return err
}
if err := os.Rename(stagedPath, targetPath); err != nil {
if targetExists {
_ = os.Rename(backupPath, targetPath)
}
return err
}
if targetExists {
_ = os.Remove(backupPath)
}
return nil
}
func sanitizeArchivePath(candidate string, fallback string) string {
if strings.TrimSpace(candidate) == "" {
return fallback
}
cleaned := path.Clean(strings.ReplaceAll(candidate, "\\", "/"))
cleaned = strings.TrimPrefix(cleaned, "./")
cleaned = strings.TrimLeft(cleaned, "/")
if cleaned == "." || cleaned == "" || strings.HasPrefix(cleaned, "../") {
return fallback
}
return cleaned
}
func normalizeVersion(version string) string {
version = strings.TrimSpace(version)
version = strings.TrimPrefix(version, "v")
if idx := strings.Index(version, "-"); idx >= 0 {
version = version[:idx]
}
return version
}
func compareVersions(left string, right string) int {
left = normalizeVersion(left)
right = normalizeVersion(right)
leftParts := strings.Split(left, ".")
rightParts := strings.Split(right, ".")
maxLen := len(leftParts)
if len(rightParts) > maxLen {
maxLen = len(rightParts)
}
for i := 0; i < maxLen; i++ {
var leftVal int
var rightVal int
if i < len(leftParts) {
leftVal, _ = strconv.Atoi(leftParts[i])
}
if i < len(rightParts) {
rightVal, _ = strconv.Atoi(rightParts[i])
}
if leftVal > rightVal {
return 1
}
if leftVal < rightVal {
return -1
}
}
return 0
}
func runDetachedWindowsUpdateScript(scriptPath string) error {
cmd := exec.Command("cmd", "/C", "start", "", "/B", scriptPath)
cmd.Dir = filepath.Dir(scriptPath)
return cmd.Start()
}
func (a *App) FetchSourceList(url string) (map[string]SourceConfig, error) {
runtime.LogPrintf(a.ctx, "正在获取源列表: %s", url)
client := newHTTPClient(10 * time.Second)
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if err := ensureHTTPSuccess(resp, url); err != nil {
return nil, err
}
var sources map[string]SourceConfig
if err := json.NewDecoder(resp.Body).Decode(&sources); err != nil {
return nil, err
}
for k, v := range sources {
if v.JsonUrl == "" && v.DirUrl != "" {
v.JsonUrl = v.DirUrl
sources[k] = v
}
}
a.clearDirectoryCache()
return sources, nil
}
func (a *App) FetchDirectory(url string) (interface{}, error) {
a.cacheLock.RLock()
if cached, ok := a.dirCache[url]; ok {
a.cacheLock.RUnlock()
runtime.LogPrintf(a.ctx, "命中缓存: %s", url)
return cached, nil
}
a.cacheLock.RUnlock()
runtime.LogPrintf(a.ctx, "正在获取目录(网络): %s", url)
client := newHTTPClient(15 * time.Second)
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if err := ensureHTTPSuccess(resp, url); err != nil {
return nil, err
}
var root interface{}
if err := json.NewDecoder(resp.Body).Decode(&root); err != nil {
return nil, err
}
a.cacheLock.Lock()
a.dirCache[url] = root
a.cacheLock.Unlock()
return root, nil
}
func (a *App) DownloadFile(url string, savePath string) error {
runtime.LogPrintf(a.ctx, "开始下载: %s -> %s", url, savePath)
if err := os.MkdirAll(filepath.Dir(savePath), 0755); err != nil {
return err
}
tmpPath := stagedFilePath(savePath)
out, err := os.Create(tmpPath)
if err != nil {
return err
}
defer func() {
out.Close()
if _, err := os.Stat(tmpPath); err == nil {
_ = os.Remove(tmpPath)
}
}()
resp, err := newHTTPClient(30 * time.Second).Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if err := ensureHTTPSuccess(resp, url); err != nil {
return err
}
counter := &WriteCounter{
Total: float64(resp.ContentLength),
HasTotal: resp.ContentLength > 0,
Filename: filepath.Base(savePath),
Ctx: a.ctx,
}
if _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil {
return err
}
if err := out.Close(); err != nil {
return err
}
if err := replaceFile(savePath, tmpPath); err != nil {
return err
}
return nil
}
func (a *App) DownloadFilesAsZip(files []DownloadItem, savePath string) error {
runtime.LogPrintf(a.ctx, "开始批量下载打包: %d 个文件 -> %s", len(files), savePath)
if err := os.MkdirAll(filepath.Dir(savePath), 0755); err != nil {
return err
}
tmpPath := stagedFilePath(savePath)
outFile, err := os.Create(tmpPath)
if err != nil {
return err
}
defer func() {
outFile.Close()
if _, err := os.Stat(tmpPath); err == nil {
_ = os.Remove(tmpPath)
}
}()
zipWriter := zip.NewWriter(outFile)
defer func() {
_ = zipWriter.Close()
}()
var totalSize float64
for _, f := range files {
if f.Size > 0 {
totalSize += float64(f.Size)
}
}
var currentDownloaded float64
var completedFiles int
client := newHTTPClient(30 * time.Second)
for _, file := range files {
entryPath := sanitizeArchivePath(file.ArchivePath, file.Name)
writer, err := zipWriter.Create(entryPath)
if err != nil {
return err
}
resp, err := client.Get(file.Url)
if err != nil {
return fmt.Errorf("下载文件 %s 失败: %v", file.Name, err)
}
if err := ensureHTTPSuccess(resp, file.Url); err != nil {
resp.Body.Close()
return fmt.Errorf("下载文件 %s 失败: %w", file.Name, err)
}
buf := make([]byte, 32*1024)
for {
n, readErr := resp.Body.Read(buf)
if n > 0 {
_, writeErr := writer.Write(buf[:n])
if writeErr != nil {
resp.Body.Close()
return writeErr
}
currentDownloaded += float64(n)
if totalSize > 0 {
percent := (currentDownloaded / totalSize) * 100
runtime.EventsEmit(a.ctx, "download_progress", DownloadProgress{
Filename: "打包下载中...",
Percentage: percent,
})
}
}
if readErr == io.EOF {
break
}
if readErr != nil {
resp.Body.Close()
return readErr
}
}
resp.Body.Close()
completedFiles++
if totalSize <= 0 && len(files) > 0 {
percent := (float64(completedFiles) / float64(len(files))) * 100
runtime.EventsEmit(a.ctx, "download_progress", DownloadProgress{
Filename: "打包下载中...",
Percentage: percent,
})
}
}
if err := zipWriter.Close(); err != nil {
return err
}
if err := outFile.Close(); err != nil {
return err
}
if err := replaceFile(savePath, tmpPath); err != nil {
return err
}
return nil
}
func (a *App) SelectSavePath(defaultName string) string {
selection, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "另存为",
DefaultFilename: defaultName,
DefaultDirectory: "",
})
if err != nil {
return ""
}
return selection
}
func (a *App) OpenFileDir(filePath string) error {
runtime.LogPrintf(a.ctx, "尝试打开文件夹: %s", filePath)
dir := filepath.Dir(filePath)
var cmd *exec.Cmd
switch stdruntime.GOOS {
case "windows":
cmd = exec.Command("explorer", "/select,", filePath)
case "darwin":
cmd = exec.Command("open", "-R", filePath)
case "linux":
cmd = exec.Command("xdg-open", dir)
default:
return fmt.Errorf("unsupported platform")
}
return cmd.Start()
}
func (a *App) OpenPreviewWindow(url string, fileName string) error {
url = strings.TrimSpace(url)
fileName = strings.TrimSpace(fileName)
if url == "" {
return fmt.Errorf("预览链接为空")
}
ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(fileName)), ".")
if ext != "pdf" && ext != "txt" {
return fmt.Errorf("当前仅支持预览 PDF 和 TXT 文件")
}
exePath, err := os.Executable()
if err != nil {
return fmt.Errorf("无法获取程序路径: %v", err)
}
cmd := exec.Command(
exePath,
"--preview",
"--preview-url", url,
"--preview-name", fileName,
"--preview-ext", ext,
)
cmd.Dir = filepath.Dir(exePath)
if err := cmd.Start(); err != nil {
return fmt.Errorf("无法打开预览窗口: %v", err)
}
return nil
}
func (a *App) FetchTextPreview(url string) (string, error) {
url = strings.TrimSpace(url)
if url == "" {
return "", fmt.Errorf("预览链接为空")
}
resp, err := newHTTPClient(30 * time.Second).Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if err := ensureHTTPSuccess(resp, url); err != nil {
return "", err
}
const maxPreviewBytes = 2 * 1024 * 1024
data, err := io.ReadAll(io.LimitReader(resp.Body, maxPreviewBytes+1))
if err != nil {
return "", err
}
if len(data) > maxPreviewBytes {
return "", fmt.Errorf("TXT 预览内容过大,请直接下载后查看")
}
return strings.ToValidUTF8(string(data), "\uFFFD"), nil
}
func (a *App) FetchPDFPreview(url string) (string, error) {
url = strings.TrimSpace(url)
if url == "" {
return "", fmt.Errorf("预览链接为空")
}
resp, err := newHTTPClient(2 * time.Minute).Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if err := ensureHTTPSuccess(resp, url); err != nil {
return "", err
}
const maxPreviewBytes = 20 * 1024 * 1024
data, err := io.ReadAll(io.LimitReader(resp.Body, maxPreviewBytes+1))
if err != nil {
return "", err
}
if len(data) > maxPreviewBytes {
return "", fmt.Errorf("PDF 预览文件过大,请直接下载后查看")
}
return base64.StdEncoding.EncodeToString(data), nil
}
type WriteCounter struct {
Total float64
HasTotal bool
Downloaded float64
Filename string
Ctx context.Context
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Downloaded += float64(n)
percent := 0.0
if wc.HasTotal && wc.Total > 0 {
percent = (wc.Downloaded / wc.Total) * 100
}
runtime.EventsEmit(wc.Ctx, "download_progress", DownloadProgress{
Filename: wc.Filename,
Percentage: percent,
})
return n, nil
}
func (a *App) CheckAppUpdate() (*CheckResult, error) {
runtime.LogPrintf(a.ctx, ">>>>> 开始检查更新,URL: %s", MetadataURL)
client := newHTTPClient(5 * time.Second)
resp, err := client.Get(MetadataURL)
if err != nil {
runtime.LogPrintf(a.ctx, ">>>>> 网络请求失败: %v", err)
return nil, err
}
defer resp.Body.Close()
if err := ensureHTTPSuccess(resp, MetadataURL); err != nil {
return nil, err
}
var meta AppMetadata
if err := json.NewDecoder(resp.Body).Decode(&meta); err != nil {
runtime.LogPrintf(a.ctx, ">>>>> JSON 解析失败: %v", err)
return nil, err
}
runtime.LogPrintf(a.ctx, ">>>>> 解析到的远程版本: %s", meta.Update.Version)
platformKey := fmt.Sprintf("%s-%s", stdruntime.GOOS, stdruntime.GOARCH)
runtime.LogPrintf(a.ctx, ">>>>> 当前系统生成的 Key: [%s]", platformKey)
var target PlatformInfo
var ok bool
if meta.Update.Platforms != nil {
target, ok = meta.Update.Platforms[platformKey]
runtime.LogPrintf(a.ctx, ">>>>> Map 匹配结果: %v, 下载地址: %s", ok, target.Url)
} else {
runtime.LogPrintf(a.ctx, ">>>>> 警告: meta.Update.Platforms 为空 (JSON 结构可能不匹配)")
}
hasUpdate := compareVersions(meta.Update.Version, CurrentVersion) > 0 && ok
runtime.LogPrintf(a.ctx, ">>>>> 最终判定 hasUpdate: %v (本地: %s, 远程: %s)", hasUpdate, CurrentVersion, meta.Update.Version)
return &CheckResult{
HasUpdate: hasUpdate,
CurrentVer: CurrentVersion,
RemoteVer: meta.Update.Version,
UpdateDesc: meta.Update.Desc,
IsForce: meta.Update.Force,
DownloadURL: target.Url,
Checksum: target.Checksum,
Notice: meta.Notice,
}, nil
}
func (a *App) PerformSelfUpdate(url string, checksum string) error {
runtime.LogPrintf(a.ctx, "开始自动更新流程...")
if strings.TrimSpace(checksum) == "" {
return fmt.Errorf("更新包缺少校验和,已拒绝执行不安全更新")
}
exePath, err := os.Executable()
if err != nil {
return fmt.Errorf("无法获取程序路径: %v", err)
}
dir := filepath.Dir(exePath)
targetName := "JNU-EXAM-Downloader"
if stdruntime.GOOS == "windows" {
targetName += ".exe"
}
targetPath := filepath.Join(dir, targetName)
tmpPath := filepath.Join(dir, fmt.Sprintf("update-%d.tmp", time.Now().UnixNano()))
runtime.LogPrintf(a.ctx, "正在下载更新: %s", url)
resp, err := newHTTPClient(5 * time.Minute).Get(url)
if err != nil {
return fmt.Errorf("下载失败: %v", err)
}
defer resp.Body.Close()
if err := ensureHTTPSuccess(resp, url); err != nil {
return err
}
out, err := os.Create(tmpPath)
if err != nil {
return fmt.Errorf("无法创建临时文件: %v", err)
}
defer func() {
out.Close()
if _, err := os.Stat(tmpPath); err == nil {
_ = os.Remove(tmpPath)
}
}()
hasher := sha256.New()
contentLen := resp.ContentLength
buf := make([]byte, 32*1024)
var downloaded int64
for {
n, readErr := resp.Body.Read(buf)
if n > 0 {
if _, err := out.Write(buf[:n]); err != nil {
return err
}
if _, err := hasher.Write(buf[:n]); err != nil {
return err
}
downloaded += int64(n)
if contentLen > 0 {
percent := (float64(downloaded) / float64(contentLen)) * 100
runtime.EventsEmit(a.ctx, "update_progress", percent)
}
}
if readErr == io.EOF {
break
}
if readErr != nil {
return readErr
}
}
if err := out.Close(); err != nil {
return err
}
calculatedHash := hex.EncodeToString(hasher.Sum(nil))
if !strings.EqualFold(calculatedHash, checksum) {
return fmt.Errorf("文件校验失败! 期望: %s, 实际: %s", checksum, calculatedHash)
}
oldPath := exePath + ".old"
_ = os.Remove(oldPath)
if stdruntime.GOOS == "windows" {
scriptPath := filepath.Join(dir, fmt.Sprintf("apply-update-%d.cmd", time.Now().UnixNano()))
scriptContent := strings.Join([]string{
"@echo off",
"setlocal",
fmt.Sprintf(":waitloop"),
fmt.Sprintf(`tasklist /FI "PID eq %d" | find "%d" >nul`, os.Getpid(), os.Getpid()),
"if not errorlevel 1 (",
" timeout /t 1 /nobreak >nul",
" goto waitloop",
")",
fmt.Sprintf(`if exist "%s" del /f /q "%s"`, oldPath, oldPath),
fmt.Sprintf(`if exist "%s" move /Y "%s" "%s" >nul`, targetPath, targetPath, oldPath),
fmt.Sprintf(`move /Y "%s" "%s" >nul`, tmpPath, targetPath),
fmt.Sprintf(`if errorlevel 1 exit /b 1`),
fmt.Sprintf(`start "" "%s"`, targetPath),
fmt.Sprintf(`del /f /q "%s"`, scriptPath),
}, "\r\n")
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0644); err != nil {
return fmt.Errorf("无法创建更新脚本: %v", err)
}
if err := runDetachedWindowsUpdateScript(scriptPath); err != nil {
return fmt.Errorf("无法启动更新脚本: %v", err)
}
os.Exit(0)
return nil
}
if err := os.Rename(exePath, oldPath); err != nil {
return fmt.Errorf("无法重命名当前程序: %v", err)
}
if err := os.Rename(tmpPath, targetPath); err != nil {
_ = os.Rename(oldPath, exePath)
return fmt.Errorf("无法应用新文件: %v", err)
}
if err := os.Chmod(targetPath, 0755); err != nil {
_ = os.Rename(targetPath, tmpPath)
_ = os.Rename(oldPath, exePath)
return fmt.Errorf("无法设置执行权限: %v", err)
}
runtime.LogPrintf(a.ctx, "更新完成,准备重启: %s", targetPath)
cmd := exec.Command(targetPath)
if err := cmd.Start(); err != nil {
_ = os.Remove(targetPath)
_ = os.Rename(oldPath, exePath)
return fmt.Errorf("无法启动新版本: %v", err)
}
os.Exit(0)
return nil
}