implement persistence
This commit is contained in:
@ -3,9 +3,15 @@ package glist
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var DataPath string
|
||||
|
||||
type Entry struct {
|
||||
Text string `json:"text"`
|
||||
Checked bool `json:"checked"`
|
||||
@ -27,6 +33,42 @@ func NewGList(chatID int, items ...string) *GList {
|
||||
return &g
|
||||
}
|
||||
|
||||
var reqs chan *GList
|
||||
|
||||
func DoPersist() {
|
||||
reqs = make(chan *GList, 50)
|
||||
go func() {
|
||||
for range time.Tick(5 * time.Second) {
|
||||
lists := map[*GList]struct{}{}
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case g := <-reqs:
|
||||
lists[g] = struct{}{}
|
||||
default:
|
||||
break loop
|
||||
}
|
||||
}
|
||||
for g := range lists {
|
||||
g.persist()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (g *GList) persist() {
|
||||
g.Mutex.Lock()
|
||||
defer g.Mutex.Unlock()
|
||||
data, err := json.Marshal(g)
|
||||
if err != nil {
|
||||
log.Panicln("failed to marshal")
|
||||
}
|
||||
filename := path.Join(DataPath, fmt.Sprintf("chkchat%d", g.ChatID))
|
||||
if err := os.WriteFile(filename, data, 0644); err != nil {
|
||||
log.Panicln("failed to write to file")
|
||||
}
|
||||
}
|
||||
|
||||
func (g *GList) Add(text string) error {
|
||||
for _, item := range g.Items {
|
||||
if item.Text == text {
|
||||
@ -34,6 +76,7 @@ func (g *GList) Add(text string) error {
|
||||
}
|
||||
}
|
||||
g.Items = append(g.Items, Entry{text, false})
|
||||
reqs <- g
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -41,6 +84,7 @@ func (g *GList) Toggle(text string) error {
|
||||
for i, item := range g.Items {
|
||||
if item.Text == text {
|
||||
g.Items[i].Checked = !g.Items[i].Checked
|
||||
reqs <- g
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@ -55,6 +99,7 @@ func (g *GList) ClearChecked() {
|
||||
}
|
||||
}
|
||||
g.Items = remaining
|
||||
reqs <- g
|
||||
}
|
||||
|
||||
type button struct {
|
||||
|
Reference in New Issue
Block a user