Added !poker and auth entry point
This commit is contained in:
84
internal/points/points.go
Normal file
84
internal/points/points.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package points
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
dataDir = "internal/storage"
|
||||
pointsFile = "points.json"
|
||||
)
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
pts map[string]int
|
||||
)
|
||||
|
||||
const DefaultPoints = 100000
|
||||
|
||||
// init or load points from disk
|
||||
func LoadPoints() error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
pts = make(map[string]int)
|
||||
path := filepath.Join(dataDir, pointsFile)
|
||||
|
||||
data, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(data, &pts)
|
||||
}
|
||||
|
||||
// save balances to disk
|
||||
func SavePoints() error {
|
||||
mu.Lock()
|
||||
data, err := json.MarshalIndent(pts, "", " ")
|
||||
mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
return ioutil.WriteFile(filepath.Join(dataDir, pointsFile), data, 0644)
|
||||
}
|
||||
|
||||
// return point balance for user, init if needed
|
||||
func GetPoints(user string) int {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
key := strings.ToLower(user)
|
||||
bal, ok := pts[key]
|
||||
if !ok {
|
||||
pts[key] = DefaultPoints
|
||||
bal = DefaultPoints
|
||||
}
|
||||
return bal
|
||||
}
|
||||
|
||||
// add points to user's bal, save & return new bal
|
||||
func AddPoints(user string, delta int) (int error) {
|
||||
mu.Lock()
|
||||
key := strings.ToLower(user)
|
||||
bal, ok := pts[key]
|
||||
if !ok {
|
||||
bal = DefaultPoints
|
||||
}
|
||||
bal += delta
|
||||
pts[key] = bal
|
||||
mu.Unlock()
|
||||
|
||||
if err := SavePoints(); err != nil {
|
||||
return bal, err
|
||||
}
|
||||
return bal, nil
|
||||
}
|
Reference in New Issue
Block a user