-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstorage.go
85 lines (73 loc) · 1.66 KB
/
storage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
type AppStorage struct {
sync.Mutex
KnownAccounts []Account `json:"known_accounts"`
LastUpdateCheckAt time.Time `json:"last_update_check_at"`
KnownLatestVersion string `json:"known_latest_version"`
}
type Account struct {
Id string `json:"id"`
Nickname string `json:"nickname"`
}
var (
_storageFile string
_storage AppStorage
)
func storageInit() {
_storageFile = filepath.Join(_internalDir, "storage.json")
_storage.Load()
}
func (s *AppStorage) Load() {
s.Lock()
defer s.Unlock()
encoded, err := os.ReadFile(_storageFile)
if err != nil {
log.Errorf("error loading storage.json: %s", err)
return
}
if err := json.Unmarshal(encoded, &s); err != nil {
log.Errorf("error parsing storage.json: %s", err)
return
}
}
func (s *AppStorage) Persist() {
s.Lock()
defer s.Unlock()
encoded, err := json.Marshal(s)
if err != nil {
log.Errorf("error serializing app storage: %s", err)
return
}
if err := os.WriteFile(_storageFile, encoded, 0644); err != nil {
log.Errorf("error writing app storage: %s", err)
}
}
func (s *AppStorage) AddKnownAccount(account Account) {
s.Lock()
accounts := []Account{account}
seen := map[string]struct{}{account.Id: {}}
for _, a := range s.KnownAccounts {
if _, exists := seen[a.Id]; !exists {
accounts = append(accounts, a)
seen[a.Id] = struct{}{}
}
}
s.KnownAccounts = accounts
s.Unlock()
go s.Persist()
}
func (s *AppStorage) SetUpdateCheck(latestVersion string) {
s.Lock()
s.LastUpdateCheckAt = time.Now()
s.KnownLatestVersion = latestVersion
s.Unlock()
go s.Persist()
}