diff --git a/.gitignore b/.gitignore index b23330f..b868d05 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,5 @@ # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 .glide/ -settings_custom.json \ No newline at end of file +settings_custom.json +history.json \ No newline at end of file diff --git a/alfred.go b/alfred.go index 75bcf9c..cbe1889 100644 --- a/alfred.go +++ b/alfred.go @@ -2,7 +2,7 @@ * @Author: Bartuccio Antoine * @Date: 2018-07-23 15:24:22 * @Last Modified by: klmp200 -* @Last Modified time: 2018-07-24 12:35:08 +* @Last Modified time: 2018-07-24 12:44:38 */ package main @@ -30,7 +30,8 @@ func main() { } log.Println("Initialize history") - shared.InitHistory(int(settings.Settings["history size"].(float64))) + shared.InitHistory(int(settings.Settings["history size"].(float64)), + settings.Settings["history file"].(string)) log.Println("Bot initialisation") b, err := tb.NewBot(tb.Settings{ diff --git a/settings.json b/settings.json index f6f81c4..587f67d 100644 --- a/settings.json +++ b/settings.json @@ -1,4 +1,5 @@ { "token": "INSERT TOKEN HERE", - "history size": 10 + "history size": 10, + "history file": "history.json" } \ No newline at end of file diff --git a/shared/history.go b/shared/history.go index acf329b..406392b 100644 --- a/shared/history.go +++ b/shared/history.go @@ -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) }