-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.go
More file actions
816 lines (707 loc) · 21.2 KB
/
app.go
File metadata and controls
816 lines (707 loc) · 21.2 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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
goruntime "runtime"
"strings"
"skillui/internal/platform"
"time"
"skillui/internal/config"
"skillui/internal/logging"
"skillui/internal/process"
"skillui/internal/service"
"skillui/internal/store"
"github.com/google/uuid"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
const (
AppName = "skillui"
AppDisplayName = "SkillUI"
// DefaultSlogan is the application slogan used in UI and metadata
DefaultSlogan = "Skills Manager"
)
// App struct
type App struct {
ctx context.Context
pm *process.Manager
store *store.Store
config config.AppConfig
logHub *logging.StreamHub
loggers map[string]*ProcessLogger
autoStartMgr *service.AutoStartManager
systemLogger *logging.RollingStore
dataDir string
}
// getAppDataDir returns the platform-appropriate app data directory.
// On macOS, uses ~/Library/Application Support/SkillUI to comply with
// App Sandbox guidelines (user files should not live in the hidden container).
// On other platforms, falls back to ~/.skillui.
func getAppDataDir() string {
if goruntime.GOOS == "darwin" {
if configDir, err := os.UserConfigDir(); err == nil {
return filepath.Join(configDir, "SkillUI")
}
}
homeDir, _ := os.UserHomeDir()
return filepath.Join(homeDir, ".skillui")
}
// ProcessLogger holds the logger for a specific process
type ProcessLogger struct {
store *logging.RollingStore
hub *logging.StreamHub
}
// NewApp creates a new App application struct
func NewApp() *App {
dataDir := getAppDataDir()
// Migrate old ~/.skillui data to new location on macOS (one-time migration)
if goruntime.GOOS == "darwin" {
homeDir, _ := os.UserHomeDir()
oldDir := filepath.Join(homeDir, ".skillui")
if _, err := os.Stat(oldDir); err == nil {
if _, err2 := os.Stat(dataDir); os.IsNotExist(err2) {
os.Rename(oldDir, dataDir)
}
}
}
return &App{
pm: process.NewManager(),
store: store.NewStore(dataDir),
logHub: logging.NewStreamHub(100),
loggers: make(map[string]*ProcessLogger),
autoStartMgr: service.NewAutoStartManager(AppName, AppDisplayName),
dataDir: dataDir,
}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
// Load configuration
cfg, err := a.store.Load()
if err != nil {
cfg = config.DefaultConfig()
// Initialize system logger first before logging errors
systemLogDir := filepath.Join(a.dataDir, "system_logs")
os.MkdirAll(systemLogDir, 0755)
a.systemLogger = logging.NewRollingStore(systemLogDir, 1000, 10)
a.LogSystemError("startup", fmt.Sprintf("Failed to load config, using default: %v", err))
}
a.config = cfg
// Initialize log directory
if a.config.LogDir == "" {
a.config.LogDir = "logs"
}
logDir := filepath.Join(a.dataDir, a.config.LogDir)
os.MkdirAll(logDir, 0755)
// Initialize system logger
systemLogDir := filepath.Join(a.dataDir, "system_logs")
os.MkdirAll(systemLogDir, 0755)
a.systemLogger = logging.NewRollingStore(systemLogDir, 1000, 10)
// Set up log callback for process manager
a.pm.SetLogCallback(func(processID, stream, line string) {
logger, ok := a.loggers[processID]
if !ok {
return
}
entry := logging.Entry{
Timestamp: time.Now(),
Stream: stream,
Line: line,
}
// Store in memory hub
logger.hub.Push(entry)
// Store in rolling file
logger.store.Append(entry)
})
// Register saved processes
for _, def := range a.config.Processes {
a.pm.Register(def)
// Create logger for this process
processLogDir := filepath.Join(logDir, def.ID)
a.loggers[def.ID] = &ProcessLogger{
store: logging.NewRollingStore(processLogDir, a.config.MaxLogLines, a.config.MaxLogFiles),
hub: logging.NewStreamHub(100),
}
// Auto-start processes if configured
if def.AutoStart {
go a.pm.Start(ctx, def.ID)
}
}
// Log successful startup
a.LogSystemError("startup", fmt.Sprintf("Application started successfully, version: %s, platform: %s", appConfig.Version, a.autoStartMgr.GetPlatform()))
}
// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
return fmt.Sprintf("Hello %s, It's show time!", name)
}
// AddProcess registers a new process
func (a *App) AddProcess(def process.Definition) error {
// Generate ID if not provided
if def.ID == "" {
def.ID = fmt.Sprintf("proc-%d", len(a.config.Processes)+1)
}
// Set default restart policy if not provided
if def.RestartPolicy == "" {
def.RestartPolicy = process.RestartOnFailure
}
// Register with process manager
a.pm.Register(def)
// Create logger for this process
logDir := filepath.Join(a.dataDir, a.config.LogDir, def.ID)
a.loggers[def.ID] = &ProcessLogger{
store: logging.NewRollingStore(logDir, a.config.MaxLogLines, a.config.MaxLogFiles),
hub: logging.NewStreamHub(100),
}
// Add to config and save
a.config.Processes = append(a.config.Processes, def)
err := a.store.Save(a.config)
if err != nil {
a.LogSystemError("AddProcess", fmt.Sprintf("Failed to save config after adding process %s: %v", def.Name, err))
}
return err
}
// RemoveProcess removes a process by ID
func (a *App) RemoveProcess(id string) error {
// Stop the process first
err := a.pm.Stop(id)
if err != nil {
a.LogSystemError("RemoveProcess", fmt.Sprintf("Failed to stop process %s: %v", id, err))
}
// Unregister from process manager
a.pm.Unregister(id)
// Remove from config
newProcesses := make([]process.Definition, 0)
for _, p := range a.config.Processes {
if p.ID != id {
newProcesses = append(newProcesses, p)
}
}
a.config.Processes = newProcesses
// Remove logger
delete(a.loggers, id)
err = a.store.Save(a.config)
if err != nil {
a.LogSystemError("RemoveProcess", fmt.Sprintf("Failed to save config after removing process %s: %v", id, err))
}
return err
}
// UpdateProcess updates a process configuration
func (a *App) UpdateProcess(id string, def process.Definition) error {
// Stop the process first
err := a.pm.Stop(id)
if err != nil {
a.LogSystemError("UpdateProcess", fmt.Sprintf("Failed to stop process %s: %v", id, err))
}
// Update in config
for i, p := range a.config.Processes {
if p.ID == id {
def.ID = id // Preserve the ID
a.config.Processes[i] = def
break
}
}
// Re-register with process manager
a.pm.Register(def)
// Save config
err = a.store.Save(a.config)
if err != nil {
a.LogSystemError("UpdateProcess", fmt.Sprintf("Failed to save config after updating process %s: %v", id, err))
}
return err
}
// StartProcess starts a process by ID
func (a *App) StartProcess(id string) error {
err := a.pm.Start(a.ctx, id)
if err != nil {
a.LogSystemError("StartProcess", fmt.Sprintf("Failed to start process %s: %v", id, err))
}
return err
}
// StopProcess stops a process by ID
func (a *App) StopProcess(id string) error {
err := a.pm.Stop(id)
if err != nil {
a.LogSystemError("StopProcess", fmt.Sprintf("Failed to stop process %s: %v", id, err))
}
return err
}
// RestartProcess restarts a process by ID
func (a *App) RestartProcess(id string) error {
if err := a.pm.Stop(id); err != nil {
a.LogSystemError("RestartProcess", fmt.Sprintf("Failed to stop process %s during restart: %v", id, err))
return err
}
err := a.pm.Start(a.ctx, id)
if err != nil {
a.LogSystemError("RestartProcess", fmt.Sprintf("Failed to start process %s during restart: %v", id, err))
}
return err
}
// ListProcesses returns all processes with their status
func (a *App) ListProcesses() []process.Snapshot {
return a.pm.List()
}
// GetProcessLogs returns logs for a specific process
func (a *App) GetProcessLogs(id string) []logging.Entry {
logger, ok := a.loggers[id]
if !ok {
return []logging.Entry{}
}
return logger.hub.Snapshot()
}
// GetConfig returns the current configuration
func (a *App) GetConfig() config.AppConfig {
return a.config
}
// UpdateConfig updates the configuration
func (a *App) UpdateConfig(cfg config.AppConfig) error {
oldLocale := a.config.Locale
a.config = cfg
// Update tray language if locale changed
if oldLocale != cfg.Locale {
UpdateTrayLanguage()
}
return a.store.Save(a.config)
}
// SelectDirectory opens a directory selection dialog
func (a *App) SelectDirectory() (string, error) {
dir, err := runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Working Directory",
})
if err != nil {
return "", err
}
return dir, nil
}
// SelectFile opens a file selection dialog for selecting executable/command
func (a *App) SelectFile() (string, error) {
file, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Command/Executable",
Filters: []runtime.FileFilter{
{DisplayName: "All Files", Pattern: "*.*"},
},
})
if err != nil {
return "", err
}
return file, nil
}
// SelectZipFile opens a file selection dialog for selecting a zip archive
func (a *App) SelectZipFile() (string, error) {
file, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select ZIP File",
Filters: []runtime.FileFilter{
{DisplayName: "ZIP Files (*.zip)", Pattern: "*.zip"},
{DisplayName: "All Files", Pattern: "*.*"},
},
})
if err != nil {
return "", err
}
return file, nil
}
// GetAutoStartEnabled returns whether auto-start is enabled
func (a *App) GetAutoStartEnabled() (bool, error) {
return a.autoStartMgr.IsEnabled()
}
// SetAutoStartEnabled enables or disables auto-start
func (a *App) SetAutoStartEnabled(enabled bool) error {
if enabled {
return a.autoStartMgr.Enable()
}
return a.autoStartMgr.Disable()
}
// GetPlatform returns the current operating system
func (a *App) GetPlatform() string {
return a.autoStartMgr.GetPlatform()
}
// GetAppName returns the application display name
func (a *App) GetAppName() string {
return AppDisplayName
}
// GetAppVersion returns the current app version
func (a *App) GetAppVersion() string {
return appConfig.Version
}
// GetSystemVersion returns detailed system version information
func (a *App) GetSystemVersion() map[string]string {
info := make(map[string]string)
info["os"] = goruntime.GOOS
info["arch"] = goruntime.GOARCH
info["platform"] = a.autoStartMgr.GetPlatform()
// Get OS version based on platform
var cmd *exec.Cmd
switch goruntime.GOOS {
case "darwin":
cmd = exec.Command("sw_vers", "-productVersion")
case "linux":
cmd = exec.Command("lsb_release", "-ds")
// Fallback to /etc/os-release if lsb_release not available
if _, err := exec.LookPath("lsb_release"); err != nil {
cmd = exec.Command("sh", "-c", "cat /etc/os-release | grep PRETTY_NAME | cut -d'=' -f2 | tr -d '\"'")
}
case "windows":
cmd = exec.Command("cmd", "/c", "ver")
}
if cmd != nil {
if output, err := cmd.Output(); err == nil {
info["osVersion"] = strings.TrimSpace(string(output))
} else {
info["osVersion"] = "unknown"
}
}
// Get hostname
if hostname, err := os.Hostname(); err == nil {
info["hostname"] = hostname
}
info["goVersion"] = goruntime.Version()
info["numCPU"] = fmt.Sprintf("%d", goruntime.NumCPU())
return info
}
// LogSystemError logs system errors to the system log file
func (a *App) LogSystemError(component, message string) {
if a.systemLogger == nil {
return
}
entry := logging.Entry{
Timestamp: time.Now(),
Stream: component,
Line: message,
}
a.systemLogger.Append(entry)
}
// GetSystemLogs returns system logs from the last 24 hours
func (a *App) GetSystemLogs() (string, error) {
var logs strings.Builder
// Collect application system logs
systemLogDir := filepath.Join(a.dataDir, "system_logs")
logs.WriteString("=== Application System Logs ===\n")
if entries, err := os.ReadDir(systemLogDir); err == nil {
now := time.Now()
yesterday := now.Add(-24 * time.Hour)
totalSize := 0
maxSize := 500 * 1024 // Limit to 500KB of logs
for _, entry := range entries {
if entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
// Only include logs from last 24 hours
if info.ModTime().After(yesterday) {
filePath := filepath.Join(systemLogDir, entry.Name())
content, err := os.ReadFile(filePath)
if err == nil {
if totalSize+len(content) > maxSize {
logs.WriteString(fmt.Sprintf("\n... (remaining logs truncated, limit %dKB reached)\n", maxSize/1024))
break
}
logs.WriteString(fmt.Sprintf("\n--- %s ---\n", entry.Name()))
logs.Write(content)
logs.WriteString("\n")
totalSize += len(content)
}
}
}
if totalSize == 0 {
logs.WriteString("No system logs found in the last 24 hours\n")
}
} else {
logs.WriteString(fmt.Sprintf("Unable to read system logs directory: %v\n", err))
}
return logs.String(), nil
}
// GetAppConfig returns application configuration
func (a *App) GetAppConfig() map[string]interface{} {
return map[string]interface{}{
"name": appConfig.Name,
"title": appConfig.Title,
"slogan": appConfig.Slogan,
"version": appConfig.Version,
"website": appConfig.Website,
"websiteGithub": appConfig.WebsiteGithub,
"websiteGitee": appConfig.WebsiteGitee,
"apiBaseUrl": appConfig.ApiBaseUrl,
"analyticsUrl": appConfig.AnalyticsUrl,
"versionCheckUrl": appConfig.VersionCheckUrl,
"feedbackUrl": appConfig.FeedbackUrl,
"guideUrl": appConfig.GuideUrl,
"helpUrl": appConfig.HelpUrl,
}
}
// GetProcess returns a single process by ID
func (a *App) GetProcess(id string) (process.Snapshot, error) {
return a.pm.Get(id)
}
// AnalyticsEvent represents an analytics event to be sent
type AnalyticsEvent struct {
Name string `json:"name"`
Data map[string]interface{} `json:"data,omitempty"`
}
// AnalyticsPayload is the request body format for analytics
type AnalyticsPayload struct {
Data []AnalyticsEvent `json:"data"`
}
const baseURL = "https://skillui.com"
// AppConfig holds application-wide configuration
var appConfig = struct {
Name string
Title string
Slogan string
Version string
Website string
WebsiteGithub string
WebsiteGitee string
ApiBaseUrl string
AnalyticsUrl string
VersionCheckUrl string
FeedbackUrl string
GuideUrl string
HelpUrl string
}{
Name: "SkillUI",
Title: "SkillUI",
Slogan: DefaultSlogan,
Version: "v0.2.4",
Website: baseURL,
WebsiteGithub: "https://github.com/modstart-lib/skillui",
WebsiteGitee: "https://gitee.com/modstart-lib/skillui",
ApiBaseUrl: baseURL + "/api",
AnalyticsUrl: baseURL + "/app_manager/collect",
VersionCheckUrl: baseURL + "/app_manager/updater",
FeedbackUrl: baseURL + "/feedback_ticket",
GuideUrl: baseURL + "/app_manager/guide",
HelpUrl: baseURL + "/app_manager/help",
}
// getDeviceUUID returns a persistent UUID for this device
func (a *App) getDeviceUUID() string {
// Try to load existing UUID from config
if a.config.DeviceUUID != "" {
return a.config.DeviceUUID
}
// Generate new UUID
newUUID := uuid.New().String()
a.config.DeviceUUID = newUUID
// Save to config
a.store.Save(a.config)
return newUUID
}
// getPlatform returns the current platform name
func getPlatform() string {
switch goruntime.GOOS {
case "darwin":
return "mac"
case "windows":
return "win"
case "linux":
return "linux"
default:
return goruntime.GOOS
}
}
// getPlatformArch returns the current platform architecture
func getPlatformArch() string {
switch goruntime.GOARCH {
case "amd64":
return "x64"
case "arm64":
return "arm64"
case "386":
return "x86"
default:
return goruntime.GOARCH
}
}
// getPlatformVersion returns the OS version
func getPlatformVersion() string {
switch goruntime.GOOS {
case "darwin":
// macOS: use sw_vers command
out, err := exec.Command("sw_vers", "-productVersion").Output()
if err == nil {
return strings.TrimSpace(string(out))
}
case "windows":
// Windows: use cmd /c ver
out, err := exec.Command("cmd", "/c", "ver").Output()
if err == nil {
// Parse "Microsoft Windows [Version 10.0.19041.1234]"
s := string(out)
if start := strings.Index(s, "[Version "); start != -1 {
s = s[start+9:]
if end := strings.Index(s, "]"); end != -1 {
return strings.TrimSpace(s[:end])
}
}
}
case "linux":
// Linux: try /etc/os-release
data, err := os.ReadFile("/etc/os-release")
if err == nil {
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, "VERSION_ID=") {
v := strings.TrimPrefix(line, "VERSION_ID=")
return strings.Trim(v, "\"")
}
}
}
}
return "0"
}
// SendAnalytics sends analytics events to the collection endpoint
func (a *App) SendAnalytics(events []AnalyticsEvent) {
go func() {
client := &http.Client{Timeout: 10 * time.Second}
// Build User-Agent: AppOpen/{AppName}/{Version} Platform/{PlatformName}/{PlatformArch}/{PlatformVersion}/{UUID}
userAgent := fmt.Sprintf("AppOpen/%s/%s Platform/%s/%s/%s/%s",
appConfig.Name,
appConfig.Version,
getPlatform(),
getPlatformArch(),
getPlatformVersion(),
a.getDeviceUUID(),
)
// Build form data
formData := map[string]interface{}{
"uuid": a.getDeviceUUID(),
"version": appConfig.Version,
"data": events,
"platform": map[string]string{
"name": getPlatform(),
"arch": getPlatformArch(),
"version": getPlatformVersion(),
},
}
jsonData, err := json.Marshal(formData)
if err != nil {
fmt.Printf("[Analytics] Failed to marshal payload: %v\n", err)
return
}
req, err := http.NewRequest("POST", appConfig.AnalyticsUrl, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("[Analytics] Failed to create request: %v\n", err)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
if err != nil {
fmt.Printf("[Analytics] Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
}()
}
// SaveLogsToFile opens a save dialog and saves logs to the selected file
func (a *App) SaveLogsToFile(processName string, content string) error {
filePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Save Logs",
DefaultFilename: fmt.Sprintf("%s-logs.txt", processName),
Filters: []runtime.FileFilter{
{DisplayName: "Text Files", Pattern: "*.txt"},
{DisplayName: "All Files", Pattern: "*.*"},
},
})
if err != nil {
return err
}
if filePath == "" {
return nil // User cancelled
}
return os.WriteFile(filePath, []byte(content), 0644)
}
// ShowWindow shows the main window (used by system tray)
func (a *App) ShowWindow() {
runtime.WindowShow(a.ctx)
runtime.WindowUnminimise(a.ctx)
runtime.WindowSetAlwaysOnTop(a.ctx, true)
runtime.WindowSetAlwaysOnTop(a.ctx, false)
}
// HideWindow hides the main window and Dock icon
func (a *App) HideWindow() {
runtime.WindowHide(a.ctx)
// Hide Dock icon on macOS
platform.HideDockIcon()
}
// QuitApp quits the application
func (a *App) QuitApp() {
runtime.Quit(a.ctx)
}
// VersionInfo represents version information from the server
type VersionInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Time string `json:"time"`
Url string `json:"url,omitempty"`
}
// versionCheckResponse is the API response format
type versionCheckResponse struct {
Code int `json:"code"`
Data VersionInfo `json:"data"`
}
// CheckVersion checks for new version from the server
func (a *App) CheckVersion() (VersionInfo, error) {
client := &http.Client{Timeout: 10 * time.Second}
// Build User-Agent: AppOpen/{AppName}/{Version} Platform/{PlatformName}/{PlatformArch}/{PlatformVersion}/{UUID}
userAgent := fmt.Sprintf("AppOpen/%s/%s Platform/%s/%s/%s/%s",
appConfig.Name,
appConfig.Version,
getPlatform(),
getPlatformArch(),
getPlatformVersion(),
a.getDeviceUUID(),
)
// Build form data
formData := map[string]interface{}{
"uuid": a.getDeviceUUID(),
"version": appConfig.Version,
"platform": map[string]string{
"name": getPlatform(),
"arch": getPlatformArch(),
"version": getPlatformVersion(),
},
}
jsonData, err := json.Marshal(formData)
if err != nil {
return VersionInfo{}, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequest("POST", appConfig.VersionCheckUrl, bytes.NewBuffer(jsonData))
if err != nil {
return VersionInfo{}, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
if err != nil {
return VersionInfo{}, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return VersionInfo{}, fmt.Errorf("HTTP error: status %d", resp.StatusCode)
}
var result versionCheckResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return VersionInfo{}, fmt.Errorf("failed to decode response: %w", err)
}
if result.Code != 0 {
return VersionInfo{}, fmt.Errorf("API error: code %d", result.Code)
}
return result.Data, nil
}
// shutdown is called when the app is closing
func (a *App) shutdown(ctx context.Context) {
// Log shutdown
a.LogSystemError("shutdown", "Application is shutting down")
// Stop all running processes gracefully
a.pm.StopAll()
// Final log
a.LogSystemError("shutdown", "Application shutdown complete")
}