-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.go
More file actions
1472 lines (1251 loc) · 40.1 KB
/
app.go
File metadata and controls
1472 lines (1251 loc) · 40.1 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 provides the Wails binding layer that connects the frontend to all backend modules.
package main
import (
"archive/zip"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"surfmanager/internal/apps"
"surfmanager/internal/backup"
"surfmanager/internal/config"
"surfmanager/internal/process"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// Note represents a user note with metadata.
type Note struct {
ID string `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// logLine writes to console, emits to frontend, and appends to log file
func (a *App) logLine(msg string) {
fmt.Println(msg)
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "log", msg)
}
if a.logFilePath == "" {
return
}
a.logMutex.Lock()
defer a.logMutex.Unlock()
f, err := os.OpenFile(a.logFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return
}
defer f.Close()
timestamp := time.Now().Format(time.RFC3339)
fmt.Fprintf(f, "%s %s\n", timestamp, msg)
}
// GetLogs returns the current activity log content
func (a *App) GetLogs() (string, error) {
if a.logFilePath == "" {
return "", fmt.Errorf("log file not initialized")
}
data, err := os.ReadFile(a.logFilePath)
if err != nil {
return "", err
}
return string(data), nil
}
// LogMessage allows frontend to append a log line
func (a *App) LogMessage(message string) {
if message == "" {
return
}
a.logLine(message)
}
// App struct holds all backend managers and provides Wails-bound methods.
type App struct {
ctx context.Context
config *config.Manager
process *process.Killer
backup *backup.Manager
apps *apps.ConfigLoader
logFilePath string
logMutex sync.Mutex
}
// NewApp creates a new App application struct.
func NewApp() *App {
return &App{}
}
// startup is called when the app starts. Initializes all managers.
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
a.config = config.GetManager()
if err := a.config.EnsureSurfManagerDirs(); err != nil {
fmt.Printf("Warning: Failed to create SurfManager directories: %v\n", err)
}
// Prepare log file under Documents/SurfManager/logs/app.log
logsDir := filepath.Join(a.config.GetDocumentsDir(), "SurfManager", "logs")
os.MkdirAll(logsDir, 0755)
a.logFilePath = filepath.Join(logsDir, "app.log")
// Touch file
if f, fileErr := os.OpenFile(a.logFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); fileErr == nil {
f.Close()
}
a.process = process.NewKiller(func(msg string) {
a.logLine(msg)
})
a.backup = backup.NewManager(a.config.GetDocumentsDir())
var loaderErr error
a.apps, loaderErr = apps.NewConfigLoader()
if loaderErr != nil {
fmt.Printf("Warning: Failed to initialize apps loader: %v\n", loaderErr)
} else {
if err := a.apps.LoadAllConfigs(); err != nil {
fmt.Printf("Warning: Failed to load app configs: %v\n", err)
}
}
}
// ============================================================================
// Platform Info
// ============================================================================
// GetPlatformInfo returns platform information
func (a *App) GetPlatformInfo() map[string]string {
return a.config.GetPlatformInfo()
}
// GetCurrentUser returns the current username
func (a *App) GetCurrentUser() string {
return a.config.GetCurrentUser()
}
// ============================================================================
// App Configuration Methods
// ============================================================================
// GetApps returns all configured applications
func (a *App) GetApps() []apps.AppConfig {
if a.apps == nil {
return []apps.AppConfig{}
}
return a.apps.GetAllApps()
}
// GetActiveApps returns only active applications
func (a *App) GetActiveApps() []apps.AppConfig {
if a.apps == nil {
return []apps.AppConfig{}
}
return a.apps.GetActiveApps()
}
// GetApp returns a specific app configuration
func (a *App) GetApp(appKey string) *apps.AppConfig {
if a.apps == nil {
return nil
}
return a.apps.GetApp(appKey)
}
// SaveApp saves an app configuration
func (a *App) SaveApp(config apps.AppConfig) error {
if a.apps == nil {
return fmt.Errorf("apps loader not initialized")
}
return a.apps.SaveConfig(config)
}
// DeleteApp removes an app configuration
func (a *App) DeleteApp(appKey string) error {
if a.apps == nil {
return fmt.Errorf("apps loader not initialized")
}
return a.apps.DeleteConfig(appKey)
}
// ToggleApp toggles the active state of an app
func (a *App) ToggleApp(appKey string) error {
if a.apps == nil {
return fmt.Errorf("apps loader not initialized")
}
return a.apps.ToggleActive(appKey)
}
// ReloadApps reloads all app configurations from disk
func (a *App) ReloadApps() error {
if a.apps == nil {
return fmt.Errorf("apps loader not initialized")
}
return a.apps.Reload()
}
// CheckAppInstalled checks if an app is installed by verifying exe paths
func (a *App) CheckAppInstalled(appKey string) bool {
cfg := a.GetApp(appKey)
if cfg == nil {
return false
}
for _, exePath := range cfg.Paths.ExePaths {
if _, err := os.Stat(exePath); err == nil {
return true
}
}
return false
}
// GetAppDataPath returns the first existing data path for an app
func (a *App) GetAppDataPath(appKey string) string {
cfg := a.GetApp(appKey)
if cfg == nil {
return ""
}
for _, dataPath := range cfg.Paths.DataPaths {
if _, err := os.Stat(dataPath); err == nil {
return dataPath
}
}
return ""
}
// ============================================================================
// Reset Data Methods
// ============================================================================
// ResetApp resets an application's data with optional auto-backup
func (a *App) ResetApp(appKey string, autoBackup bool, skipClose bool) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
dataPath := a.GetAppDataPath(appKey)
if dataPath == "" {
return fmt.Errorf("no data folder found for %s", cfg.DisplayName)
}
processNames := a.collectProcessNames(cfg)
// Smart close the app (unless skipClose is true)
if !skipClose && len(processNames) > 0 {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 5,
"message": fmt.Sprintf("Closing %s...", cfg.DisplayName),
})
if err := a.process.SmartClose(cfg.DisplayName, processNames); err != nil {
return fmt.Errorf("failed to close %s: %w", cfg.DisplayName, err)
}
}
// Create auto-backup if enabled (includes addon folders)
if autoBackup {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 20,
"message": "Creating auto-backup...",
})
if err := a.backup.CreateAutoBackup(appKey, dataPath, func(p backup.BackupProgress) {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 20 + p.Percent/5,
"message": p.Message,
})
}); err != nil {
wailsRuntime.EventsEmit(a.ctx, "log", fmt.Sprintf("[AutoBackup] Failed: %v", err))
}
}
// Only delete data folder if there are backup items configured
// (meaning user wants to manage this folder)
shouldResetDataFolder := len(cfg.BackupItems) > 0
if shouldResetDataFolder {
// Delete data folder
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 50,
"message": fmt.Sprintf("Deleting %s data...", cfg.DisplayName),
})
if err := os.RemoveAll(dataPath); err != nil {
return fmt.Errorf("failed to delete data: %w", err)
}
// Recreate empty folder
if err := os.MkdirAll(dataPath, 0755); err != nil {
return fmt.Errorf("failed to recreate folder: %w", err)
}
} else {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 50,
"message": "Skipping data folder (no backup items configured)...",
})
}
// Delete addon folders if configured
if len(cfg.AddonPaths) > 0 {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 80,
"message": "Deleting additional folders...",
})
for _, addonPath := range cfg.AddonPaths {
if _, err := os.Stat(addonPath); err == nil {
if err := os.RemoveAll(addonPath); err != nil {
wailsRuntime.EventsEmit(a.ctx, "log", fmt.Sprintf("[Reset] Failed to delete addon folder %s: %v", addonPath, err))
}
}
}
}
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 100,
"message": "Reset complete!",
})
return nil
}
// ResetAccountOnly removes only known account-related files.
// This operation always requires the target app to be closed first.
func (a *App) ResetAccountOnly(appKey string) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
dataPath := a.GetAppDataPath(appKey)
if dataPath == "" {
return fmt.Errorf("no data folder found for %s", cfg.DisplayName)
}
// Validate and clean the data path
dataPath = filepath.Clean(dataPath)
absDataPath, err := filepath.Abs(dataPath)
if err != nil {
return fmt.Errorf("invalid data path: %w", err)
}
processNames := a.collectProcessNames(cfg)
// Remove account-only always requires app to be closed
if len(processNames) > 0 {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 10,
"message": fmt.Sprintf("Closing %s...", cfg.DisplayName),
})
if err := a.process.SmartClose(cfg.DisplayName, processNames); err != nil {
return fmt.Errorf("failed to close %s: %w", cfg.DisplayName, err)
}
}
accountOnlyPaths := []string{
"User/globalStorage/state.vscdb",
"User/globalStorage/state.vscdb.backup",
"User/globalStorage/storage.json",
}
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 30,
"message": "Removing account files...",
})
deletedCount := 0
for i, relPath := range accountOnlyPaths {
cleanRelPath := filepath.Clean(filepath.FromSlash(relPath))
targetPath := filepath.Clean(filepath.Join(absDataPath, cleanRelPath))
// Ensure resolved path stays inside app data directory
if targetPath != absDataPath && !strings.HasPrefix(targetPath, absDataPath+string(os.PathSeparator)) {
wailsRuntime.EventsEmit(a.ctx, "log", fmt.Sprintf("[RemoveAccountOnly] Skipped unsafe path: %s", relPath))
continue
}
if _, statErr := os.Stat(targetPath); statErr == nil {
if rmErr := os.RemoveAll(targetPath); rmErr != nil {
wailsRuntime.EventsEmit(a.ctx, "log", fmt.Sprintf("[RemoveAccountOnly] Failed to delete %s: %v", relPath, rmErr))
} else {
deletedCount++
}
}
progress := 30 + int(float64(i+1)/float64(len(accountOnlyPaths))*70)
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": progress,
"message": fmt.Sprintf("Processed: %s", relPath),
})
}
if deletedCount == 0 {
wailsRuntime.EventsEmit(a.ctx, "log", "[RemoveAccountOnly] No known account files found to delete")
}
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 100,
"message": fmt.Sprintf("Remove account complete! Deleted %d file(s)", deletedCount),
})
return nil
}
// GenerateNewID generates new machine IDs for an app
func (a *App) GenerateNewID(appKey string) (int, error) {
cfg := a.GetApp(appKey)
if cfg == nil {
return 0, fmt.Errorf("app not found: %s", appKey)
}
dataPath := a.GetAppDataPath(appKey)
if dataPath == "" {
return 0, fmt.Errorf("no data folder found for %s", cfg.DisplayName)
}
// Validate and clean the data path
dataPath = filepath.Clean(dataPath)
absDataPath, err := filepath.Abs(dataPath)
if err != nil {
return 0, fmt.Errorf("invalid data path: %w", err)
}
newMachineID := generateUUID()
newSessionID := generateUUID()
updatedCount := 0
err = filepath.Walk(absDataPath, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() || !strings.HasSuffix(info.Name(), ".json") {
return nil
}
// Validate that the path is within the expected data directory
cleanPath := filepath.Clean(path)
if !strings.HasPrefix(cleanPath, absDataPath) {
return nil // Skip files outside the data directory
}
data, err := os.ReadFile(path)
if err != nil {
return nil
}
// Validate JSON size to prevent potential DoS attacks
const maxJSONSize = 10 * 1024 * 1024 // 10MB limit
if len(data) > maxJSONSize {
return nil
}
var jsonData map[string]interface{}
if err := json.Unmarshal(data, &jsonData); err != nil {
return nil
}
modified := false
if _, ok := jsonData["machineId"]; ok {
jsonData["machineId"] = newMachineID
modified = true
updatedCount++
}
if _, ok := jsonData["telemetry.machineId"]; ok {
jsonData["telemetry.machineId"] = newMachineID
modified = true
updatedCount++
}
if _, ok := jsonData["sessionId"]; ok {
jsonData["sessionId"] = newSessionID
modified = true
updatedCount++
}
// Force add to storage.json
if info.Name() == "storage.json" {
if _, ok := jsonData["machineId"]; !ok {
jsonData["machineId"] = newMachineID
jsonData["telemetry.machineId"] = newMachineID
modified = true
updatedCount += 2
}
}
if modified {
newData, err := json.MarshalIndent(jsonData, "", " ")
if err == nil {
if writeErr := os.WriteFile(path, newData, 0644); writeErr != nil {
fmt.Printf("Warning: Failed to write %s: %v\n", path, writeErr)
}
}
}
return nil
})
return updatedCount, err
}
// LaunchApp launches an application
func (a *App) LaunchApp(appKey string) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
for _, exePath := range cfg.Paths.ExePaths {
if _, err := os.Stat(exePath); err == nil {
cmd := exec.Command(exePath)
return cmd.Start()
}
}
return fmt.Errorf("executable not found for %s", cfg.DisplayName)
}
// OpenFolder opens a folder in the file explorer
func (a *App) OpenFolder(path string) error {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
// Convert forward slashes to backslashes for Windows Explorer
path = strings.ReplaceAll(path, "/", "\\")
cmd = exec.Command("explorer", path)
case "darwin":
cmd = exec.Command("open", path)
default:
cmd = exec.Command("xdg-open", path)
}
return cmd.Start()
}
// OpenURL opens a URL in the user's default browser (not WebView)
func (a *App) OpenURL(url string) error {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
case "darwin":
cmd = exec.Command("open", url)
default:
cmd = exec.Command("xdg-open", url)
}
return cmd.Start()
}
// OpenAppFolder opens the app's data folder
func (a *App) OpenAppFolder(appKey string) error {
dataPath := a.GetAppDataPath(appKey)
if dataPath == "" {
return fmt.Errorf("no data folder found")
}
return a.OpenFolder(dataPath)
}
// KillApp kills all processes for an app
func (a *App) KillApp(appKey string) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
processNames := a.collectProcessNames(cfg)
if len(processNames) == 0 {
return nil
}
return a.process.SmartClose(cfg.DisplayName, processNames)
}
// ResetAddonData resets only the addon folders for an app
func (a *App) ResetAddonData(appKey string, skipClose bool) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
if len(cfg.AddonPaths) == 0 {
return fmt.Errorf("no addon folders configured for %s", cfg.DisplayName)
}
processNames := a.collectProcessNames(cfg)
// Smart close the app (unless skipClose is true)
if !skipClose && len(processNames) > 0 {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 10,
"message": fmt.Sprintf("Closing %s...", cfg.DisplayName),
})
if err := a.process.SmartClose(cfg.DisplayName, processNames); err != nil {
return fmt.Errorf("failed to close %s: %w", cfg.DisplayName, err)
}
}
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 30,
"message": "Deleting addon folders...",
})
deletedCount := 0
for i, addonPath := range cfg.AddonPaths {
if _, err := os.Stat(addonPath); err == nil {
if err := os.RemoveAll(addonPath); err != nil {
wailsRuntime.EventsEmit(a.ctx, "log", fmt.Sprintf("[ResetAddon] Failed to delete %s: %v", addonPath, err))
} else {
deletedCount++
}
}
// Progress update
progress := 30 + int(float64(i+1)/float64(len(cfg.AddonPaths))*60)
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": progress,
"message": fmt.Sprintf("Deleted: %s", filepath.Base(addonPath)),
})
}
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 100,
"message": fmt.Sprintf("Reset complete! Deleted %d addon folder(s)", deletedCount),
})
return nil
}
func (a *App) collectProcessNames(cfg *apps.AppConfig) []string {
var processNames []string
for _, exePath := range cfg.Paths.ExePaths {
processNames = append(processNames, filepath.Base(exePath))
}
if len(cfg.Paths.ProcessNames) > 0 {
processNames = append(processNames, cfg.Paths.ProcessNames...)
}
return processNames
}
// IsAppRunning checks if an app is currently running
func (a *App) IsAppRunning(appKey string) bool {
cfg := a.GetApp(appKey)
if cfg == nil {
return false
}
processNames := a.collectProcessNames(cfg)
if len(processNames) == 0 {
return false
}
return a.process.IsRunning(processNames)
}
// ============================================================================
// Session/Backup Methods
// ============================================================================
// CalculateBackupSize calculates the total size of a backup before creation
func (a *App) CalculateBackupSize(appKey string, includeData bool) (map[string]interface{}, error) {
cfg := a.GetApp(appKey)
if cfg == nil {
return nil, fmt.Errorf("app not found: %s", appKey)
}
var dataSize int64
var addonSize int64
// Calculate data folder size if includeData is true
if includeData && len(cfg.BackupItems) > 0 {
dataPath := a.GetAppDataPath(appKey)
if dataPath != "" {
// Calculate size for each backup item
for _, item := range cfg.BackupItems {
itemPath := filepath.Join(dataPath, item.Path)
// Check if path exists
info, err := os.Stat(itemPath)
if err != nil {
// Skip if optional or doesn't exist
if item.Optional || os.IsNotExist(err) {
continue
}
// For non-optional items, log but continue
fmt.Printf("Warning: Failed to stat %s: %v\n", itemPath, err)
continue
}
// Calculate size (file or directory)
if info.IsDir() {
size, err := a.calculatePathSize(itemPath)
if err == nil {
dataSize += size
}
} else {
dataSize += info.Size()
}
}
}
}
// Calculate addon folders size
for _, addonPath := range cfg.AddonPaths {
// Check if addon path exists
if _, err := os.Stat(addonPath); err != nil {
// Skip if doesn't exist
continue
}
size, err := a.calculatePathSize(addonPath)
if err == nil {
addonSize += size
}
}
totalSize := dataSize + addonSize
// Build result map
result := map[string]interface{}{
"total_size": totalSize,
"data_size": dataSize,
"addon_size": addonSize,
"total_size_formatted": backup.FormatSize(totalSize),
"data_size_formatted": backup.FormatSize(dataSize),
"addon_size_formatted": backup.FormatSize(addonSize),
}
return result, nil
}
// calculatePathSize calculates the total size of a file or directory
func (a *App) calculatePathSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return nil // Skip errors
}
if !info.IsDir() {
size += info.Size()
}
return nil
})
return size, err
}
// GetSessions returns all sessions for an app
func (a *App) GetSessions(appKey string, includeAuto bool) ([]backup.Session, error) {
return a.backup.GetSessions(appKey, includeAuto)
}
// GetAllSessions returns sessions for all apps
func (a *App) GetAllSessions(includeAuto bool) ([]backup.Session, error) {
var allSessions []backup.Session
apps := a.GetActiveApps()
for _, app := range apps {
sessions, err := a.backup.GetSessions(app.AppName, includeAuto)
if err != nil {
continue
}
allSessions = append(allSessions, sessions...)
}
return allSessions, nil
}
// CreateBackup creates a new backup session
func (a *App) CreateBackup(appKey, sessionName string, addonOnly bool) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
dataPath := a.GetAppDataPath(appKey)
if dataPath == "" {
return fmt.Errorf("no data folder found for %s", cfg.DisplayName)
}
// Check for duplicate
if a.backup.SessionExists(appKey, sessionName) {
return fmt.Errorf("session '%s' already exists", sessionName)
}
// Check if app is running
isRunning := a.IsAppRunning(appKey)
// If app is running and we need a full backup, return error
if isRunning && !addonOnly {
return fmt.Errorf("app must be closed for full backup. Please close %s first or choose addon-only backup", cfg.DisplayName)
}
// Smart close the app first (unless addonOnly)
processNames := a.collectProcessNames(cfg)
if !addonOnly && len(processNames) > 0 {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 5,
"message": fmt.Sprintf("Closing %s...", cfg.DisplayName),
})
a.process.SmartClose(cfg.DisplayName, processNames)
}
// Convert backup items (skip if addonOnly)
var backupItems []backup.BackupItem
if !addonOnly {
for _, item := range cfg.BackupItems {
backupItems = append(backupItems, backup.BackupItem{
Path: item.Path,
Optional: item.Optional,
})
}
}
// Create backup
return a.backup.CreateBackup(appKey, sessionName, dataPath, backupItems, cfg.AddonPaths, addonOnly, func(p backup.BackupProgress) {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": p.Percent,
"message": p.Message,
})
})
}
func (a *App) ReplaceSessionData(appKey, sessionName string, addonOnly bool) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
dataPath := a.GetAppDataPath(appKey)
if dataPath == "" {
return fmt.Errorf("no data folder found for %s", cfg.DisplayName)
}
// Check session exists
if !a.backup.SessionExists(appKey, sessionName) {
return fmt.Errorf("session '%s' not found", sessionName)
}
// Check if app is running for full replace
isRunning := a.IsAppRunning(appKey)
if isRunning && !addonOnly {
return fmt.Errorf("app must be closed for full replace. Please close %s first or choose addon-only replace", cfg.DisplayName)
}
// Smart close the app first (unless addonOnly)
processNames := a.collectProcessNames(cfg)
if !addonOnly && len(processNames) > 0 {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 5,
"message": fmt.Sprintf("Closing %s...", cfg.DisplayName),
})
a.process.SmartClose(cfg.DisplayName, processNames)
}
// Convert backup items (skip if addonOnly)
var backupItems []backup.BackupItem
if !addonOnly {
for _, item := range cfg.BackupItems {
backupItems = append(backupItems, backup.BackupItem{
Path: item.Path,
Optional: item.Optional,
})
}
}
// Replace session contents
return a.backup.ReplaceSession(appKey, sessionName, dataPath, backupItems, cfg.AddonPaths, addonOnly, func(p backup.BackupProgress) {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": p.Percent,
"message": p.Message,
})
})
}
// RestoreBackup restores a backup session
func (a *App) RestoreBackup(appKey, sessionName string, skipClose bool) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
dataPath := a.GetAppDataPath(appKey)
if dataPath == "" {
// Use first data path as target
if len(cfg.Paths.DataPaths) > 0 {
dataPath = cfg.Paths.DataPaths[0]
} else {
return fmt.Errorf("no data path configured for %s", cfg.DisplayName)
}
}
// Smart close the app first (unless skipClose is true)
processNames := a.collectProcessNames(cfg)
if !skipClose && len(processNames) > 0 {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 5,
"message": fmt.Sprintf("Closing %s...", cfg.DisplayName),
})
a.process.SmartClose(cfg.DisplayName, processNames)
}
// Restore backup
err := a.backup.RestoreBackup(appKey, sessionName, dataPath, cfg.AddonPaths, func(p backup.BackupProgress) {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": p.Percent,
"message": p.Message,
})
})
if err == nil {
// Set as active session
a.backup.SetActiveSession(appKey, sessionName)
// Generate new IDs after successful restore
count, _ := a.GenerateNewID(appKey)
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 100,
"message": fmt.Sprintf("Restore complete! Updated %d ID(s)", count),
})
}
return err
}
func (a *App) RestoreAccountOnly(appKey, sessionName string, skipClose bool) error {
cfg := a.GetApp(appKey)
if cfg == nil {
return fmt.Errorf("app not found: %s", appKey)
}
dataPath := a.GetAppDataPath(appKey)
if dataPath == "" {
if len(cfg.Paths.DataPaths) > 0 {
dataPath = cfg.Paths.DataPaths[0]
} else {
return fmt.Errorf("no data path configured for %s", cfg.DisplayName)
}
}
processNames := a.collectProcessNames(cfg)
if !skipClose && len(processNames) > 0 {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 5,
"message": fmt.Sprintf("Closing %s...", cfg.DisplayName),
})
a.process.SmartClose(cfg.DisplayName, processNames)
}
err := a.backup.RestoreAccountOnly(appKey, sessionName, dataPath, func(p backup.BackupProgress) {
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": p.Percent,
"message": p.Message,
})
})
if err == nil {
a.backup.SetActiveSession(appKey, sessionName)
count, _ := a.GenerateNewID(appKey)
wailsRuntime.EventsEmit(a.ctx, "progress", map[string]interface{}{
"percent": 100,
"message": fmt.Sprintf("Account files restored! Updated %d ID(s)", count),
})
}
return err
}
// DeleteSession deletes a backup session
func (a *App) DeleteSession(appKey, sessionName string) error {
return a.backup.DeleteSession(appKey, sessionName)
}
// RenameSession renames a backup session
func (a *App) RenameSession(appKey, oldName, newName string) error {
return a.backup.RenameSession(appKey, oldName, newName)
}
// SetActiveSession sets the active session for an app
func (a *App) SetActiveSession(appKey, sessionName string) error {
return a.backup.SetActiveSession(appKey, sessionName)
}
// GetActiveSession returns the active session for an app
func (a *App) GetActiveSession(appKey string) string {
return a.backup.GetActiveSession(appKey)
}
// OpenSessionFolder opens the session folder in file explorer
func (a *App) OpenSessionFolder(appKey, sessionName string) error {
path := a.backup.GetSessionPath(appKey, sessionName)
return a.OpenFolder(path)
}
// CountAutoBackups returns the count of auto-backups
func (a *App) CountAutoBackups() int {
return a.backup.CountAllAutoBackups()
}
// ClearAllSessions deletes all backup sessions for all apps
func (a *App) ClearAllSessions() (int, error) {
apps := a.GetActiveApps()
deletedCount := 0
for _, app := range apps {