ALFRED/shared/chat.go

86 lines
1.7 KiB
Go

/*
* @Author: Bartuccio Antoine
* @Date: 2018-07-27 15:37:59
* @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2019-01-04 10:49:45
*/
package shared
import (
"encoding/json"
"io/ioutil"
"sync"
)
// General purpose chat info storage
type chatData struct {
mutex sync.Mutex
data map[int64]map[string]interface{}
}
type chatDataFile struct {
mutex sync.Mutex
path string
}
// ChatData manage access to stored data about a chat
var ChatData chatData
var cdf chatDataFile
// InitChatData is meant to store infos about a chat.
func InitChatData(path string) {
cdf = chatDataFile{path: path}
ChatData = chatData{data: make(map[int64]map[string]interface{})}
ChatData.mutex.Lock()
defer ChatData.mutex.Unlock()
cdf.read()
}
// Set stores data about a chat
func (c chatData) Set(chat int64, key string, data interface{}) {
c.mutex.Lock()
defer c.mutex.Unlock()
if _, exists := c.data[chat]; !exists {
c.data[chat] = make(map[string]interface{})
}
c.data[chat][key] = data
go cdf.write()
}
// Get retrieves data about a chat
func (c chatData) Get(chat int64, key string) (interface{}, bool) {
c.mutex.Lock()
defer c.mutex.Unlock()
m, exists := c.data[chat]
if !exists {
return nil, false
}
data, ok := m[key]
if !ok {
return nil, false
}
return data, true
}
func (c chatDataFile) read() {
c.mutex.Lock()
defer c.mutex.Unlock()
data, err := ioutil.ReadFile(c.path)
if err != nil {
// File doesn't exist, skip import
return
}
json.Unmarshal(data, &ChatData.data)
}
func (c chatDataFile) write() {
c.mutex.Lock()
defer c.mutex.Unlock()
ChatData.mutex.Lock()
defer ChatData.mutex.Unlock()
data, _ := json.Marshal(ChatData.data)
ioutil.WriteFile(c.path, data, 0770)
}