-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathapp_system.go
More file actions
1189 lines (1068 loc) · 30 KB
/
app_system.go
File metadata and controls
1189 lines (1068 loc) · 30 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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"github.com/projectdiscovery/gologger/levels"
"io"
"net/http"
"os"
"path/filepath"
"red-cloud/i18n"
redc "red-cloud/mod"
"red-cloud/mod/gologger"
goruntime "runtime"
"strings"
"time"
)
func (a *App) GetConfig() ConfigInfo {
logPath := ""
if a.logMgr != nil {
logPath = a.logMgr.BaseDir
}
// Try to load proxy settings from GUI settings first, fallback to env vars
httpProxy := os.Getenv("HTTP_PROXY")
httpsProxy := os.Getenv("HTTPS_PROXY")
socks5Proxy := os.Getenv("ALL_PROXY")
noProxy := os.Getenv("NO_PROXY")
// Load from GUI settings if available
if settings, err := redc.LoadGUISettings(); err == nil && settings != nil {
if settings.HttpProxy != "" {
httpProxy = settings.HttpProxy
}
if settings.HttpsProxy != "" {
httpsProxy = settings.HttpsProxy
}
if settings.Socks5Proxy != "" {
socks5Proxy = settings.Socks5Proxy
}
if settings.NoProxy != "" {
noProxy = settings.NoProxy
}
}
return ConfigInfo{
RedcPath: redc.RedcPath,
ProjectPath: redc.ProjectPath,
LogPath: logPath,
HttpProxy: httpProxy,
HttpsProxy: httpsProxy,
Socks5Proxy: socks5Proxy,
NoProxy: noProxy,
DebugEnabled: redc.Debug,
}
}
func (a *App) GetVersion() string {
return redc.Version
}
func (a *App) CheckForUpdates() (VersionCheckResult, error) {
result := VersionCheckResult{
CurrentVersion: redc.Version,
DownloadURL: "https://github.com/wgpsec/redc/releases",
}
resp, err := redc.NewProxyHTTPClient(30 * time.Second).Get("https://api.github.com/repos/wgpsec/redc/releases/latest")
if err != nil {
result.Error = i18n.T("github_connect_failed")
return result, nil
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
result.Error = i18n.T("github_version_failed")
return result, nil
}
var data map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
result.Error = i18n.T("github_parse_failed")
return result, nil
}
tagName, ok := data["tag_name"].(string)
if !ok {
result.Error = i18n.T("github_latest_failed")
return result, nil
}
result.LatestVersion = tagName
currentVer := strings.TrimPrefix(redc.Version, "v")
latestVer := strings.TrimPrefix(tagName, "v")
result.HasUpdate = compareVersions(currentVer, latestVer) < 0
return result, nil
}
func compareVersions(current, latest string) int {
currentParts := strings.Split(current, ".")
latestParts := strings.Split(latest, ".")
for i := 0; i < len(currentParts) || i < len(latestParts); i++ {
var cur, lat int
if i < len(currentParts) {
fmt.Sscanf(currentParts[i], "%d", &cur)
}
if i < len(latestParts) {
fmt.Sscanf(latestParts[i], "%d", &lat)
}
if cur < lat {
return -1
}
if cur > lat {
return 1
}
}
return 0
}
// CheckAllUpdates checks for updates of redc itself, templates, and plugins in one call
func (a *App) CheckAllUpdates() (UpdateCheckResult, error) {
result := UpdateCheckResult{}
// 1. Check redc version
redcResult, _ := a.CheckForUpdates()
result.Redc = redcResult
// 2. Check template updates (local vs remote registry)
result.Templates = a.checkTemplateUpdates()
// 3. List installed plugins (version info)
result.Plugins = a.checkPluginVersions()
return result, nil
}
func (a *App) checkTemplateUpdates() []TemplateUpdateInfo {
// Get local templates
localTemplates, err := a.ListTemplates()
if err != nil {
return nil
}
localMap := make(map[string]string)
for _, t := range localTemplates {
localMap[t.Name] = t.Version
}
// Fetch remote registry index
registryURL := "https://redc.wgpsec.org"
client := redc.NewProxyHTTPClient(15 * time.Second)
resp, err := client.Get(fmt.Sprintf("%s/index.json?t=%d", registryURL, time.Now().Unix()))
if err != nil {
gologger.Warning().Msgf("checkTemplateUpdates: failed to fetch registry: %v", err)
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil
}
var idx remoteIndexResponse
if err := json.NewDecoder(resp.Body).Decode(&idx); err != nil {
return nil
}
var updates []TemplateUpdateInfo
for name, remote := range idx.Templates {
localVer, installed := localMap[name]
if !installed {
continue
}
latest := strings.TrimPrefix(remote.Latest, "v")
local := strings.TrimPrefix(localVer, "v")
hasUpdate := local != "" && latest != "" && compareVersions(local, latest) < 0
updates = append(updates, TemplateUpdateInfo{
Name: name,
LocalVersion: localVer,
LatestVersion: remote.Latest,
HasUpdate: hasUpdate,
})
}
return updates
}
func (a *App) checkPluginVersions() []PluginUpdateInfo {
plugins, err := a.ListPlugins()
if err != nil {
return nil
}
var result []PluginUpdateInfo
for _, p := range plugins {
result = append(result, PluginUpdateInfo{
Name: p.Name,
Version: p.Version,
})
}
return result
}
func (a *App) SaveProxyConfig(httpProxy, httpsProxy, socks5Proxy, noProxy string) error {
// Set environment variables for current process
if httpProxy != "" {
os.Setenv("HTTP_PROXY", httpProxy)
os.Setenv("http_proxy", httpProxy)
} else {
os.Unsetenv("HTTP_PROXY")
os.Unsetenv("http_proxy")
}
if httpsProxy != "" {
os.Setenv("HTTPS_PROXY", httpsProxy)
os.Setenv("https_proxy", httpsProxy)
} else {
os.Unsetenv("HTTPS_PROXY")
os.Unsetenv("https_proxy")
}
if socks5Proxy != "" {
os.Setenv("ALL_PROXY", socks5Proxy)
os.Setenv("all_proxy", socks5Proxy)
} else {
os.Unsetenv("ALL_PROXY")
os.Unsetenv("all_proxy")
}
if noProxy != "" {
os.Setenv("NO_PROXY", noProxy)
os.Setenv("no_proxy", noProxy)
} else {
os.Unsetenv("NO_PROXY")
os.Unsetenv("no_proxy")
}
// Persist to GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
return fmt.Errorf(i18n.Tf("app_gui_load_failed", err))
}
settings.HttpProxy = httpProxy
settings.HttpsProxy = httpsProxy
settings.Socks5Proxy = socks5Proxy
settings.NoProxy = noProxy
if err := redc.SaveGUISettings(settings); err != nil {
return fmt.Errorf(i18n.Tf("app_gui_save_failed", err))
}
a.emitLog(i18n.Tf("app_proxy_updated", httpProxy, httpsProxy, socks5Proxy, noProxy))
return nil
}
func defaultTerraformConfigPath() (string, bool, error) {
if envPath := strings.TrimSpace(os.Getenv("TF_CLI_CONFIG_FILE")); envPath != "" {
return envPath, true, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", false, err
}
if goruntime.GOOS == "windows" {
appData := os.Getenv("APPDATA")
if appData == "" {
appData = filepath.Join(home, "AppData", "Roaming")
}
return filepath.Join(appData, "terraform.rc"), false, nil
}
return filepath.Join(home, ".terraformrc"), false, nil
}
func parseTerraformMirrorProviders(content string) []string {
providers := []string{}
if strings.Contains(content, "registry.terraform.io/aliyun/alicloud") || strings.Contains(content, "registry.terraform.io/hashicorp/alicloud") {
providers = append(providers, "aliyun")
}
if strings.Contains(content, "registry.terraform.io/tencentcloudstack/") {
providers = append(providers, "tencent")
}
if strings.Contains(content, "registry.terraform.io/volcengine/") {
providers = append(providers, "volc")
}
return providers
}
func terraformMirrorConfigContent(enabled bool, providers []string) string {
var builder strings.Builder
builder.WriteString("# Generated by redc-gui\n")
builder.WriteString("plugin_cache_dir = \"$HOME/.terraform.d/plugin-cache\"\n")
builder.WriteString("disable_checkpoint = true\n")
// 始终优先使用本地缓存,即使网络不可达也能使用已缓存的 provider
builder.WriteString("plugin_cache_may_break_dependency_lock_file = true\n\n")
if !enabled || len(providers) == 0 {
return builder.String()
}
providerSet := make(map[string]bool)
for _, p := range providers {
providerSet[p] = true
}
builder.WriteString("provider_installation {\n")
excludes := []string{}
if providerSet["aliyun"] {
builder.WriteString(" network_mirror {\n")
builder.WriteString(" url = \"https://mirrors.aliyun.com/terraform/\"\n")
builder.WriteString(" include = [\n")
builder.WriteString(" \"registry.terraform.io/aliyun/alicloud\",\n")
builder.WriteString(" \"registry.terraform.io/hashicorp/alicloud\"\n")
builder.WriteString(" ]\n")
builder.WriteString(" }\n")
excludes = append(excludes, "registry.terraform.io/aliyun/alicloud", "registry.terraform.io/hashicorp/alicloud")
}
if providerSet["tencent"] {
builder.WriteString(" network_mirror {\n")
builder.WriteString(" url = \"https://mirrors.tencent.com/terraform/\"\n")
builder.WriteString(" include = [\n")
builder.WriteString(" \"registry.terraform.io/tencentcloudstack/*\"\n")
builder.WriteString(" ]\n")
builder.WriteString(" }\n")
excludes = append(excludes, "registry.terraform.io/tencentcloudstack/*")
}
if providerSet["volc"] {
builder.WriteString(" network_mirror {\n")
builder.WriteString(" url = \"https://mirrors.volces.com/terraform/\"\n")
builder.WriteString(" include = [\n")
builder.WriteString(" \"registry.terraform.io/volcengine/*\"\n")
builder.WriteString(" ]\n")
builder.WriteString(" }\n")
excludes = append(excludes, "registry.terraform.io/volcengine/*")
}
if len(excludes) > 0 {
builder.WriteString(" direct {\n")
builder.WriteString(" exclude = [\n")
for i, item := range excludes {
if i < len(excludes)-1 {
builder.WriteString(fmt.Sprintf(" \"%s\",\n", item))
} else {
builder.WriteString(fmt.Sprintf(" \"%s\"\n", item))
}
}
builder.WriteString(" ]\n")
builder.WriteString(" }\n")
}
builder.WriteString("}\n")
return builder.String()
}
func (a *App) GetTerraformMirrorConfig() (TerraformMirrorConfig, error) {
configPath, fromEnv, err := defaultTerraformConfigPath()
if err != nil {
return TerraformMirrorConfig{}, err
}
result := TerraformMirrorConfig{
Enabled: false,
ConfigPath: configPath,
Managed: false,
FromEnv: fromEnv,
Providers: []string{},
}
content, err := os.ReadFile(configPath)
if err != nil {
if os.IsNotExist(err) {
return result, nil
}
return result, err
}
text := string(content)
result.Managed = strings.Contains(text, "redc-gui")
result.Providers = parseTerraformMirrorProviders(text)
result.Enabled = len(result.Providers) > 0
return result, nil
}
func (a *App) SaveTerraformMirrorConfig(enabled bool, providers []string, configPath string, setEnv bool) error {
path := strings.TrimSpace(configPath)
if path == "" {
p, _, err := defaultTerraformConfigPath()
if err != nil {
return err
}
path = p
}
if setEnv {
os.Setenv("TF_CLI_CONFIG_FILE", path)
}
content := terraformMirrorConfigContent(enabled, providers)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
return err
}
if enabled {
a.emitLog(i18n.Tf("app_tf_mirror_written", path))
} else {
a.emitLog(i18n.Tf("app_tf_mirror_closed", path))
}
return nil
}
func (a *App) TestTerraformEndpoints() ([]EndpointCheck, error) {
endpoints := []struct {
Name string
URL string
}{
{Name: "Terraform Registry", URL: "https://registry.terraform.io/.well-known/terraform.json"},
{Name: "Alibaba Cloud Mirror", URL: "https://mirrors.aliyun.com/terraform/"},
{Name: "Tencent Cloud Mirror", URL: "https://mirrors.tencent.com/terraform/"},
{Name: "Volcengine Mirror", URL: "https://mirrors.volces.com/terraform/"},
}
client := redc.NewProxyHTTPClient(6 * time.Second)
results := make([]EndpointCheck, 0, len(endpoints))
for _, ep := range endpoints {
start := time.Now()
status := 0
ok := false
errMsg := ""
req, err := http.NewRequest("GET", ep.URL, nil)
if err != nil {
errMsg = err.Error()
} else {
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36")
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Pragma", "no-cache")
resp, err := client.Do(req)
if err != nil {
errMsg = err.Error()
} else {
status = resp.StatusCode
if resp.Body != nil {
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
ok = status >= 200 && status < 400
if status == 403 {
ok = false
if errMsg == "" {
errMsg = "403 Forbidden"
}
}
}
}
results = append(results, EndpointCheck{
Name: ep.Name,
URL: ep.URL,
OK: ok,
Status: status,
Error: errMsg,
LatencyMs: time.Since(start).Milliseconds(),
CheckedAt: time.Now().Format(time.RFC3339),
})
}
return results, nil
}
func (a *App) SetDebugLogging(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
redc.Debug = enabled
if enabled {
gologger.DefaultLogger.SetMaxLevel(levels.LevelDebug)
a.emitLog(i18n.T("app_debug_on"))
} else {
gologger.DefaultLogger.SetMaxLevel(levels.LevelInfo)
a.emitLog(i18n.T("app_debug_off"))
}
// Save to GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.DebugEnabled = enabled
return redc.SaveGUISettings(settings)
}
func (a *App) SetNotificationEnabled(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.notificationMgr != nil {
a.notificationMgr.SetEnabled(enabled)
if enabled {
a.emitLog(i18n.T("app_notify_on"))
} else {
a.emitLog(i18n.T("app_notify_off"))
}
}
// Save to GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.NotificationEnabled = enabled
return redc.SaveGUISettings(settings)
}
func (a *App) GetNotificationEnabled() bool {
a.mu.Lock()
defer a.mu.Unlock()
// Load from GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
if a.notificationMgr != nil {
return a.notificationMgr.IsEnabled()
}
return false
}
if settings.NotificationEnabled {
return true
}
// Fallback to notification manager
if a.notificationMgr != nil {
return a.notificationMgr.IsEnabled()
}
return false
}
func (a *App) SetDisableRightClick(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
a.disableRightClick = enabled
// Save to GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.DisableRightClick = enabled
return redc.SaveGUISettings(settings)
}
func (a *App) GetDisableRightClick() bool {
a.mu.Lock()
defer a.mu.Unlock()
// Load from GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
return true // Default to disabled
}
return settings.DisableRightClick
}
func (a *App) SetSpotMonitorEnabled(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
// Save to GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.SpotMonitorEnabled = enabled
if err := redc.SaveGUISettings(settings); err != nil {
return err
}
// Start or stop the monitor
if enabled {
if a.spotMonitor != nil {
// Already running, no-op
return nil
}
a.spotMonitor = NewSpotMonitor(a, 120*time.Second)
a.spotMonitor.Start()
a.emitLog(i18n.T("app_spot_monitor_start_success"))
} else {
if a.spotMonitor != nil {
a.spotMonitor.Stop()
a.spotMonitor = nil
}
a.emitLog(i18n.T("app_spot_monitor_stopped"))
}
return nil
}
func (a *App) GetSpotMonitorEnabled() bool {
a.mu.Lock()
defer a.mu.Unlock()
settings, err := redc.LoadGUISettings()
if err != nil {
return false
}
return settings.SpotMonitorEnabled
}
func (a *App) SetSpotAutoRecoverEnabled(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.SpotAutoRecoverEnabled = enabled
return redc.SaveGUISettings(settings)
}
func (a *App) GetSpotAutoRecoverEnabled() bool {
a.mu.Lock()
defer a.mu.Unlock()
settings, err := redc.LoadGUISettings()
if err != nil {
return false
}
return settings.SpotAutoRecoverEnabled
}
func (a *App) SetLanguage(lang string) error {
a.mu.Lock()
defer a.mu.Unlock()
// Sync with backend i18n module
i18n.SetLang(lang)
// Save to GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.Language = lang
return redc.SaveGUISettings(settings)
}
func (a *App) GetLanguage() string {
a.mu.Lock()
defer a.mu.Unlock()
// Load from GUI settings
settings, err := redc.LoadGUISettings()
if err != nil {
lang := detectSystemLanguage()
i18n.SetLang(lang)
return lang
}
if settings.Language == "" {
lang := detectSystemLanguage()
i18n.SetLang(lang)
return lang
}
i18n.SetLang(settings.Language)
return settings.Language
}
func (a *App) SetShowWelcomeDialog(shown bool) error {
a.mu.Lock()
defer a.mu.Unlock()
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
if shown {
settings.WelcomeDialogShown = "true"
} else {
settings.WelcomeDialogShown = "hidden"
}
return redc.SaveGUISettings(settings)
}
func (a *App) GetShowWelcomeDialog() bool {
a.mu.Lock()
defer a.mu.Unlock()
// If WelcomeDialogShown is empty or "hidden", don't show
// Only show if it's the first time (empty string)
settings, err := redc.LoadGUISettings()
if err != nil {
return true // First time, show
}
// Show only if it's empty (first time)
return settings.WelcomeDialogShown == ""
}
// OnboardingStatus represents the new user onboarding progress
type OnboardingStatus struct {
CredentialsConfigured bool `json:"credentialsConfigured"`
TemplatesInstalled bool `json:"templatesInstalled"`
ScenesCreated bool `json:"scenesCreated"`
Dismissed bool `json:"dismissed"`
}
func (a *App) GetOnboardingStatus() OnboardingStatus {
a.mu.Lock()
defer a.mu.Unlock()
status := OnboardingStatus{}
// Check dismissed
settings, err := redc.LoadGUISettings()
if err == nil {
status.Dismissed = settings.OnboardingDismissed
}
// If dismissed, skip expensive checks
if status.Dismissed {
return status
}
// Check credentials: any provider has access key configured
if a.project != nil {
conf, _, err := redc.ReadConfig("")
if err == nil && conf != nil {
p := conf.Providers
status.CredentialsConfigured = p.Alicloud.AccessKey != "" ||
p.Aws.AccessKey != "" ||
p.Volcengine.AccessKey != "" ||
p.Tencentcloud.SecretId != "" ||
p.Huaweicloud.AccessKey != "" ||
p.UCloud.PublicKey != "" ||
p.Vultr.ApiKey != "" ||
p.Google.Credentials != "" ||
p.Azure.SubscriptionId != ""
}
}
// Check templates installed
templates, err := redc.ListLocalTemplates()
if err == nil {
status.TemplatesInstalled = len(templates) > 0
}
// Check scenes created
if a.project != nil {
cases, err := redc.LoadProjectCases(a.project.ProjectName)
if err == nil {
status.ScenesCreated = len(cases) > 0
}
}
return status
}
func (a *App) SetOnboardingDismissed() error {
a.mu.Lock()
defer a.mu.Unlock()
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.OnboardingDismissed = true
return redc.SaveGUISettings(settings)
}
// GetWebhookConfig returns the current webhook configuration
func (a *App) GetWebhookConfig() WebhookConfig {
if a.notificationMgr != nil && a.notificationMgr.webhookMgr != nil {
return a.notificationMgr.webhookMgr.GetConfig()
}
return WebhookConfig{}
}
// SetWebhookConfig saves webhook configuration to GUI settings and updates the in-memory manager
func (a *App) SetWebhookConfig(cfg WebhookConfig) error {
a.mu.Lock()
defer a.mu.Unlock()
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.WebhookEnabled = cfg.Enabled
settings.WebhookSlack = cfg.Slack
settings.WebhookDingtalk = cfg.Dingtalk
settings.WebhookDingtalkSecret = cfg.DingtalkSecret
settings.WebhookFeishu = cfg.Feishu
settings.WebhookFeishuSecret = cfg.FeishuSecret
settings.WebhookDiscord = cfg.Discord
settings.WebhookWecom = cfg.Wecom
if err := redc.SaveGUISettings(settings); err != nil {
return err
}
// Update in-memory webhook manager
if a.notificationMgr != nil && a.notificationMgr.webhookMgr != nil {
a.notificationMgr.webhookMgr.SetConfig(cfg)
}
return nil
}
// TestWebhook sends a test message to the specified platform
func (a *App) TestWebhook(platform, webhookURL, secret string) error {
if a.notificationMgr == nil || a.notificationMgr.webhookMgr == nil {
return fmt.Errorf("webhook manager not initialized")
}
return a.notificationMgr.webhookMgr.TestWebhook(platform, webhookURL, secret)
}
func detectSystemLanguage() string {
// Try to get system locale
lang := getSystemLocale()
// If locale starts with "zh", use Chinese, otherwise English
if len(lang) >= 2 && lang[:2] == "zh" {
return "zh"
}
return "en"
}
func getSystemLocale() string {
// Try to detect OS and get locale
// For macOS: check LC_ALL, LC_MESSAGES, LANG environment variables
// For Windows: use standard library
// For Linux: check environment variables
// Check common environment variables for locale
locales := []string{"LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"}
for _, env := range locales {
if val := os.Getenv(env); val != "" {
// Parse locale like "en_US.UTF-8" or "zh_CN.UTF-8"
parts := strings.Split(val, ".")
if len(parts) > 0 {
lang := strings.ToLower(parts[0])
return lang
}
}
}
// Try runtime.GOOS specific methods
switch goruntime.GOOS {
case "darwin":
// On macOS, try to get user default language using syscall
return getMacOSLanguage()
case "windows":
// On Windows, try to get console code page
return getWindowsLanguage()
}
return "en"
}
func getMacOSLanguage() string {
// Try using environment variable that macOS sets
if lang := os.Getenv("LANG"); lang != "" {
return strings.ToLower(strings.Split(lang, "_")[0])
}
return "en"
}
func getWindowsLanguage() string {
// On Windows, try to detect language from environment variables
// Check common Windows language settings
if lang := os.Getenv("LANG"); lang != "" {
return strings.ToLower(strings.Split(lang, "_")[0])
}
// Check LC_ALL, LC_MESSAGES
for _, env := range []string{"LC_ALL", "LC_MESSAGES"} {
if val := os.Getenv(env); val != "" {
parts := strings.Split(val, ".")
if len(parts) > 0 {
return strings.ToLower(parts[0])
}
}
}
return "en"
}
func maskValue(value string) string {
if value == "" {
return ""
}
if len(value) <= 4 {
return "****"
}
return "****" + value[len(value)-4:]
}
// SetCaseTags sets tags for a specific case or deployment
func (a *App) SetCaseTags(id string, tags []string) error {
settings, err := redc.LoadGUISettings()
if err != nil {
settings = &redc.GUISettings{}
}
if settings.CaseTags == nil {
settings.CaseTags = make(map[string][]string)
}
if len(tags) == 0 {
delete(settings.CaseTags, id)
} else {
settings.CaseTags[id] = tags
}
return redc.SaveGUISettings(settings)
}
// GetAllCaseTags returns the full tag map {id: [tags]}
func (a *App) GetAllCaseTags() map[string][]string {
settings, err := redc.LoadGUISettings()
if err != nil || settings == nil || settings.CaseTags == nil {
return map[string][]string{}
}
return settings.CaseTags
}
// GetAllTagNames returns all unique tag names across all cases
func (a *App) GetAllTagNames() []string {
settings, err := redc.LoadGUISettings()
if err != nil || settings == nil || settings.CaseTags == nil {
return []string{}
}
seen := make(map[string]bool)
var tags []string
for _, ts := range settings.CaseTags {
for _, t := range ts {
if !seen[t] {
seen[t] = true
tags = append(tags, t)
}
}
}
return tags
}
// DeleteTagByName removes a tag from all cases/deployments that use it
func (a *App) DeleteTagByName(tagName string) error {
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
if settings.CaseTags == nil {
return nil
}
for id, tags := range settings.CaseTags {
filtered := make([]string, 0, len(tags))
for _, t := range tags {
if t != tagName {
filtered = append(filtered, t)
}
}
if len(filtered) == 0 {
delete(settings.CaseTags, id)
} else {
settings.CaseTags[id] = filtered
}
}
return redc.SaveGUISettings(settings)
}
// GetHTTPServerConfig returns current HTTP server config
func (a *App) GetHTTPServerConfig() map[string]interface{} {
settings, _ := redc.LoadGUISettings()
if settings == nil {
return map[string]interface{}{
"enabled": false,
"port": 8899,
"host": "127.0.0.1",
"token": "",
}
}
port := settings.HTTPServerPort
if port == 0 {
port = 8899
}
host := settings.HTTPServerHost
if host == "" {
host = "127.0.0.1"
}
return map[string]interface{}{
"enabled": settings.HTTPServerEnabled,
"port": port,
"host": host,
"token": settings.HTTPServerToken,
}
}
// SetHTTPServerConfig saves HTTP server config
func (a *App) SetHTTPServerConfig(enabled bool, port int, host string, token string) error {
settings, err := redc.LoadGUISettings()
if err != nil {
return err
}
settings.HTTPServerEnabled = enabled
settings.HTTPServerPort = port
settings.HTTPServerHost = host
settings.HTTPServerToken = token
return redc.SaveGUISettings(settings)
}
// StartHTTPServer starts the embedded HTTP server
func (a *App) StartHTTPServer(port int, host string, token string) error {
if a.httpSrv != nil {
return fmt.Errorf("HTTP Server is already running")