Persistant history across reboots

This commit is contained in:
klmp200 2018-07-24 12:57:31 +02:00
parent 7336770332
commit 85b52e23e5
No known key found for this signature in database
GPG key ID: E7245548C53F904B
4 changed files with 41 additions and 6 deletions

View file

@ -2,12 +2,14 @@
* @Author: Bartuccio Antoine
* @Date: 2018-07-24 01:27:11
* @Last Modified by: klmp200
* @Last Modified time: 2018-07-24 11:51:52
* @Last Modified time: 2018-07-24 12:54:21
*/
package shared
import (
"encoding/json"
"io/ioutil"
"sync"
)
@ -17,15 +19,24 @@ type history struct {
data map[int64][]string
}
type historyFile struct {
mutex sync.Mutex
path string
}
var History history
var hf historyFile
// Init a chat history of a given size
func InitHistory(size int) {
func InitHistory(size int, history_file_path string) {
hf = historyFile{}
hf.path = history_file_path
History = history{}
History.mutex.Lock()
defer History.mutex.Unlock()
History.size = size
History.data = make(map[int64][]string)
hf.read()
}
// Get the number of messages saved in the history
@ -89,4 +100,25 @@ func (h history) append(chatID int64, m string) {
array[i] = val
}
array[h.size-1] = m
go hf.write()
}
func (h historyFile) read() {
h.mutex.Lock()
defer h.mutex.Unlock()
data, err := ioutil.ReadFile(h.path)
if err != nil {
// File doesn't exist, skip import
return
}
json.Unmarshal(data, &History.data)
}
func (h historyFile) write() {
h.mutex.Lock()
defer h.mutex.Unlock()
History.mutex.Lock()
defer History.mutex.Unlock()
data, _ := json.Marshal(History.data)
ioutil.WriteFile(h.path, data, 0770)
}