-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
116 lines (99 loc) · 2.26 KB
/
cache.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
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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"sync"
"time"
)
type Cache struct {
Member []ChatMember
DeleteList []WelcomeMessage `json:"DeleteList,omitempty"`
LastChanged int64 `json:"last_changed"`
}
type ChatMember struct {
Id int64 `json:"id"`
WelcomeShowed bool `json:"welcome"`
Rank int `json:"rank"`
MessageCount int `json:"count"`
}
var (
cache Cache
dataMutex sync.RWMutex
)
func loadCache() error {
dataMutex.Lock()
defer dataMutex.Unlock()
file, err := os.ReadFile("cache.json")
if err != nil {
if os.IsNotExist(err) {
log.Println("No cache file.")
// Create empty data if file doesn't exist
cache = Cache{}
return nil
}
return fmt.Errorf("error reading cache.json: %v", err)
}
err = json.Unmarshal(file, &cache)
if err != nil {
return fmt.Errorf("error unmarshalling cache.json: %v", err)
}
return nil
}
func saveCache() error {
dataMutex.Lock()
defer dataMutex.Unlock()
file, err := json.MarshalIndent(cache, "", " ")
if err != nil {
return fmt.Errorf("error marshalling data: %v", err)
}
err = os.WriteFile("cache.json", file, 0644)
if err != nil {
return fmt.Errorf("error saving data to cache.json: %v", err)
}
return nil
}
func importCache() (bool, error) {
err := loadCache()
if err != nil {
fmt.Println("Error loading data:", err)
}
fmt.Println("Last changed:", cache.LastChanged)
cache.LastChanged = time.Now().Unix()
return true, nil
}
func syncData() {
for {
// Update last_changed regardless of import status
cache.LastChanged = time.Now().Unix()
if err := saveCache(); err != nil {
fmt.Println("Error saving data:", err)
}
time.Sleep(1 * time.Minute)
}
}
func getMember(memberId int64) (member *ChatMember) {
for _, member := range cache.Member {
if member.Id == memberId {
current := member
return ¤t
}
}
return nil
}
func clearCachedUser(userid int64) {
for id, member := range cache.Member {
if member.Id == userid {
cache.Member = append(cache.Member[:id], cache.Member[id+1:]...)
break
}
}
}
func clearDeleteListByUser(userid int64) {
for id, message := range cache.DeleteList {
if message.UserID == userid {
cache.DeleteList = append(cache.DeleteList[:id], cache.DeleteList[id+1:]...)
}
}
}