/* * @Author: Bartuccio Antoine * @Date: 2018-07-27 15:37:59 * @Last Modified by: Bartuccio Antoine * @Last Modified time: 2019-01-05 17:46:26 */ package shared import ( "encoding/json" "fmt" "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(chatDataFilePath string) { cdf = chatDataFile{path: chatDataFilePath} 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 } if err := json.Unmarshal(data, &ChatData.data); err != nil { fmt.Printf("Error while unmarshaling chat data with path %s, error : %v\n", c.path, err) } } func (c *chatDataFile) write() { c.mutex.Lock() defer c.mutex.Unlock() ChatData.mutex.Lock() defer ChatData.mutex.Unlock() data, err := json.Marshal(ChatData.data) if err != nil { fmt.Printf("Error while marshaling chat data file with path %s, error : %v\n", c.path, err) return } if err := ioutil.WriteFile(c.path, data, 0770); err != nil { fmt.Printf("Error writing chat data file with path %s, error %v\n", c.path, err) } }