ALFRED/shared/users.go

148 lines
2.9 KiB
Go

/*
* @Author: Bartuccio Antoine
* @Date: 2018-07-24 14:41:03
* @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2019-01-05 17:45:59
*/
package shared
import (
"encoding/json"
"fmt"
"io/ioutil"
"sync"
tb "gopkg.in/tucnak/telebot.v2"
)
type users struct {
mutex sync.Mutex
data map[string]map[string]string
}
type usersFile struct {
mutex sync.Mutex
path string
}
// Users shared user for commands
var Users *users
var uf usersFile
// InitUsers inits the User info storage
func InitUsers(usersFilePath string) {
uf = usersFile{}
uf.path = usersFilePath
Users = &users{}
Users.mutex.Lock()
defer Users.mutex.Unlock()
Users.data = make(map[string]map[string]string)
uf.read()
}
// Get an info about a given user
func (u *users) Get(username string, key string) (string, bool) {
u.mutex.Lock()
defer u.mutex.Unlock()
user, exists := u.data[username]
if !exists {
return "", false
}
if _, exists = user[key]; !exists {
return "", false
}
return user[key], true
}
// Set add an info about a given user
func (u *users) Set(username string, key, data string) {
u.mutex.Lock()
defer u.mutex.Unlock()
if _, exists := u.data[username]; !exists {
u.data[username] = make(map[string]string)
}
u.data[username][key] = data
go uf.write()
}
// GetUsernames get all usernames stored in settings
func (u *users) GetUsernames() []string {
u.mutex.Lock()
defer u.mutex.Unlock()
var usernames []string
for username := range u.data {
usernames = append(usernames, username)
}
return usernames
}
// GetUserChat retrieve the chat of the user if registered
func (u *users) GetUserChat(username string) (*tb.Chat, error) {
serializedChat, exists := u.Get(username, "private_chat")
if !exists {
return nil, fmt.Errorf("No private chat registered for %s", username)
}
chat := &tb.Chat{}
if json.Unmarshal([]byte(serializedChat), chat) != nil {
return nil, fmt.Errorf("Error while parsing chat for %s", username)
}
return chat, nil
}
// SetUserChat register a private chat for an user
func (u *users) SetUserChat(username string, chat *tb.Chat) {
serializedChat, err := json.Marshal(chat)
if err != nil {
return
}
u.Set(username, "private_chat", string(serializedChat))
}
func (u *usersFile) read() {
u.mutex.Lock()
defer u.mutex.Unlock()
data, err := ioutil.ReadFile(u.path)
if err != nil {
// File doesn't exist, skip import
return
}
if err := json.Unmarshal(data, &Users.data); err != nil {
fmt.Printf("Error while unmarshaling user file with path %s, error : %v\n", u.path, err)
}
}
func (u *usersFile) write() {
u.mutex.Lock()
defer u.mutex.Unlock()
Users.mutex.Lock()
defer Users.mutex.Unlock()
data, err := json.Marshal(Users.data)
if err != nil {
fmt.Printf("Error while marshaling user file with path %s, error : %v\n", u.path, err)
return
}
if err := ioutil.WriteFile(u.path, data, 0770); err != nil {
fmt.Printf("Error writing user file with path %s, error : %v\n", u.path, err)
}
}