Compare commits

...

11 Commits

Author SHA1 Message Date
Antoine Bartuccio 35eab30bcd Migrate to gomodules
continuous-integration/drone/push Build is passing Details
2020-11-11 15:32:38 +01:00
Antoine Bartuccio 7b26cc3640 Merge pull request 'spongify_answer' (#19) from spongify_answer into master
continuous-integration/drone/push Build is failing Details
Reviewed-on: #19
2020-11-09 18:29:45 +00:00
madahin 7b4f2d3b25 Use camelCase instead of snake_case
Because this shity language can't deal with snake_case and
the snake_case evangile is a traitor to it's cause.
2020-11-09 19:24:22 +01:00
madahin 30397b9207 Fix formating with `go fmt` 2020-11-09 19:14:21 +01:00
madahin e786b77f62 Fix identation 2020-11-09 19:12:14 +01:00
madahin 9df38b5a88 Calling the /sponge command as a reply will now spongify the quoted message 2020-11-09 18:40:30 +01:00
Antoine Bartuccio 3d3133eaff
Fix CI
continuous-integration/drone/push Build is passing Details
2019-07-23 22:19:18 +02:00
Antoine Bartuccio c001bca84a
Fix dockerfile for CI
continuous-integration/drone/push Build is failing Details
2019-07-23 22:15:42 +02:00
Antoine Bartuccio 05203f3392
Better, faster and safer file management
the build was successful Details
continuous-integration/drone/push Build is failing Details
2019-01-05 17:48:09 +01:00
Antoine Bartuccio f722e70052 Fix Arioch
the build was successful Details
2019-01-04 11:45:28 +01:00
Antoine Bartuccio daa77fcfc4 Merge branch 'normalization' of ALFRED/ALFRED into master
the build was successful Details
2019-01-04 10:33:23 +00:00
10 changed files with 239 additions and 119 deletions

View File

@ -1,36 +1,40 @@
pipeline: kind: pipeline
build: type: docker
image: golang:1.11 name: default
group: build
commands: steps:
- export GOPATH=/drone - name: build
- go get -v -d ./... image: golang:1.14
- go build . commands:
test: - go build
image: golang:1.11
group: test - name: publish
secrets: [ test_api_token ] image: plugins/docker
environment: [ test_api_token ] settings:
commands: repo: klmp200/alfred
- export GOPATH=/drone username:
- go get -v -d ./... from_secret: docker_username
- go test ./... password:
publish: from_secret: docker_password
image: plugins/docker when:
repo: klmp200/alfred branch: master
secrets: [ docker_username, docker_password ] event: push
when:
branch: master - name: deploy
event: push image: appleboy/drone-ssh
deploy: environment:
image: appleboy/drone-ssh SSH_PASSWORD:
host: from_secret: ssh_password
- ollivander.diagon-alley settings:
username: dronedeploy host:
secrets: [ ssh_password ] from_secret: ssh_host
envs: [ ssh_password ] username:
script: from_secret: ssh_username
- echo $SSH_PASSWORD | sudo -S systemctl restart alfred-bot password:
when: from_secret: ssh_password
branch: master envs: [ SSH_PASSWORD ]
event: push script:
- echo $SSH_PASSWORD | sudo -S systemctl restart alfred-bot
when:
branch: master
event: push

View File

@ -1,30 +1,16 @@
FROM golang:1.11 AS builder FROM golang:1.14 AS builder
RUN mkdir /build
# Download and install the latest release of dep WORKDIR /build
# ADD https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64 /usr/bin/dep
# RUN chmod +x /usr/bin/dep
# Copy the code from the host and compile it # Copy the code from the host and compile it
RUN mkdir -p src/git.klmp200.net/ALFRED/ALFRED COPY . .
COPY . src/git.klmp200.net/ALFRED/ALFRED
WORKDIR "src/git.klmp200.net/ALFRED/ALFRED"
RUN go get -v -d ./...
RUN mkdir res RUN mkdir res
COPY settings.json res COPY settings.json res
COPY quotes.json res COPY quotes.json res
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix nocgo -o /app . RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix nocgo -o /app .
FROM scratch
# We use Alpine for it's ca-certificates needed by http lib # We need ca-certifactes for http calls
FROM alpine:3.4 COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
RUN apk add --no-cache ca-certificates apache2-utils
COPY --from=builder /app ./ COPY --from=builder /app ./
COPY --from=builder /go/src/git.klmp200.net/ALFRED/ALFRED/res ./ COPY --from=builder /build/res ./
ENTRYPOINT ["./app"] ENTRYPOINT ["./app"]

View File

@ -2,7 +2,7 @@
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-23 15:24:22 * @Date: 2018-07-23 15:24:22
* @Last Modified by: Bartuccio Antoine * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2019-01-04 10:52:37 * @Last Modified time: 2019-01-05 17:47:10
*/ */
package main package main
@ -19,6 +19,7 @@ import (
) )
func main() { func main() {
registeredCommands := map[string]func(*tb.Message){ registeredCommands := map[string]func(*tb.Message){
tb.OnText: commands.OnText, tb.OnText: commands.OnText,
"/registerprivate": commands.RegisterPrivate, "/registerprivate": commands.RegisterPrivate,

View File

@ -15,15 +15,25 @@ import (
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )
func Sponge(m *tb.Message) { func spongify(inputMessage string) string {
message := "" spongifiedMessage := ""
for i, char := range shared.History.LastMessage(m.Chat.ID) { for i, char := range inputMessage {
if i%2 == 0 { if i%2 == 0 {
message += strings.ToLower(string(char)) spongifiedMessage += strings.ToLower(string(char))
} else { } else {
message += strings.ToUpper(string(char)) spongifiedMessage += strings.ToUpper(string(char))
} }
} }
shared.Bot.Send(m.Chat, message) return spongifiedMessage
} }
func Sponge(m *tb.Message) {
message := ""
if m.IsReply() {
message = spongify(m.ReplyTo.Text)
} else {
message = spongify(shared.History.LastMessage(m.Chat.ID))
}
shared.Bot.Send(m.Chat, message)
}

View File

@ -2,7 +2,7 @@
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-25 18:51:38 * @Date: 2018-07-25 18:51:38
* @Last Modified by: Bartuccio Antoine * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2019-01-04 10:47:25 * @Last Modified time: 2019-01-04 11:44:47
*/ */
package commands package commands
@ -93,19 +93,21 @@ func TwitterSJW(m *tb.Message) {
testOrInitTwitter() testOrInitTwitter()
lastUse, exists := shared.ChatData.Get(m.Chat.ID, "last chaos use") lastUse, exists := shared.ChatData.Get(m.Chat.ID, "last chaos use")
if exists { if exists {
var date *time.Time date := time.Now()
if lastUseConverted, isString := lastUse.(string); isString { switch serializedDate := lastUse.(type) {
parsedDate, err := time.Parse(time.RFC3339, lastUseConverted) case string:
parsedDate, err := time.Parse(time.RFC3339, serializedDate)
if err == nil { if err == nil {
date = &parsedDate date = parsedDate
} }
case time.Time:
date = serializedDate
default:
shared.Bot.Send(m.Chat, "Arioch ne répondra pas à votre appel.")
return
} }
if lastUseConverted, isDate := lastUse.(time.Time); isDate { if time.Now().Before(date.Add(time.Hour * 24)) {
date = &lastUseConverted
}
if date != nil || time.Now().Before(date.Add(time.Hour*24)) {
shared.Bot.Send(m.Chat, "Arioch ne répondra pas à votre appel.") shared.Bot.Send(m.Chat, "Arioch ne répondra pas à votre appel.")
return return
} }

11
go.mod Normal file
View File

@ -0,0 +1,11 @@
module git.klmp200.net/klmp200/abitbol
go 1.15
require (
git.klmp200.net/ALFRED/ALFRED v0.0.0-20201109182945-7b26cc3640f2
github.com/PuerkitoBio/goquery v1.6.0 // indirect
github.com/dghubble/go-twitter v0.0.0-20201011215211-4b180d0cc78d // indirect
github.com/dghubble/oauth1 v0.6.0 // indirect
gopkg.in/tucnak/telebot.v2 v2.3.5
)

33
go.sum Normal file
View File

@ -0,0 +1,33 @@
git.klmp200.net/ALFRED/ALFRED v0.0.0-20201109182945-7b26cc3640f2 h1:aFcX//JwBBVDBRxycyzBC+mJ+cuTQKrM6wIeVmdEHLM=
git.klmp200.net/ALFRED/ALFRED v0.0.0-20201109182945-7b26cc3640f2/go.mod h1:j6PTiwlXECBIqwIm/4zbrXrwfXoWYD+EY7BPZWYTKrs=
github.com/PuerkitoBio/goquery v1.6.0 h1:j7taAbelrdcsOlGeMenZxc2AWXD5fieT1/znArdnx94=
github.com/PuerkitoBio/goquery v1.6.0/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
github.com/andybalholm/cascadia v1.1.0 h1:BuuO6sSfQNFRu1LppgbD25Hr2vLYW25JvxHs5zzsLTo=
github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
github.com/cenkalti/backoff v2.1.1+incompatible h1:tKJnvO2kl0zmb/jA5UKAt4VoEVw1qxKWjE/Bpp46npY=
github.com/cenkalti/backoff v2.1.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dghubble/go-twitter v0.0.0-20201011215211-4b180d0cc78d h1:sBKr0A8iQ1qAOozedZ8Aox+Jpv+TeP1Qv7dcQyW8V+M=
github.com/dghubble/go-twitter v0.0.0-20201011215211-4b180d0cc78d/go.mod h1:xfg4uS5LEzOj8PgZV7SQYRHbG7jPUnelEiaAVJxmhJE=
github.com/dghubble/oauth1 v0.6.0 h1:m1yC01Ohc/eF38jwZ8JUjL1a+XHHXtGQgK+MxQbmSx0=
github.com/dghubble/oauth1 v0.6.0/go.mod h1:8pFdfPkv/jr8mkChVbNVuJ0suiHe278BtWI4Tk1ujxk=
github.com/dghubble/sling v1.3.0 h1:pZHjCJq4zJvc6qVQ5wN1jo5oNZlNE0+8T/h0XeXBUKU=
github.com/dghubble/sling v1.3.0/go.mod h1:XXShWaBWKzNLhu2OxikSNFrlsvowtz4kyRuXUG7oQKY=
github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/tucnak/telebot.v2 v2.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
gopkg.in/tucnak/telebot.v2 v2.3.5/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@ -2,13 +2,14 @@
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-27 15:37:59 * @Date: 2018-07-27 15:37:59
* @Last Modified by: Bartuccio Antoine * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2019-01-04 10:49:45 * @Last Modified time: 2019-01-05 17:46:26
*/ */
package shared package shared
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io/ioutil" "io/ioutil"
"sync" "sync"
) )
@ -25,23 +26,28 @@ type chatDataFile struct {
} }
// ChatData manage access to stored data about a chat // ChatData manage access to stored data about a chat
var ChatData chatData var ChatData *chatData
var cdf chatDataFile var cdf chatDataFile
// InitChatData is meant to store infos about a chat. // InitChatData is meant to store infos about a chat.
func InitChatData(path string) { func InitChatData(chatDataFilePath string) {
cdf = chatDataFile{path: path}
ChatData = chatData{data: make(map[int64]map[string]interface{})} cdf = chatDataFile{path: chatDataFilePath}
ChatData = &chatData{data: make(map[int64]map[string]interface{})}
ChatData.mutex.Lock() ChatData.mutex.Lock()
defer ChatData.mutex.Unlock() defer ChatData.mutex.Unlock()
cdf.read() cdf.read()
} }
// Set stores data about a chat // Set stores data about a chat
func (c chatData) Set(chat int64, key string, data interface{}) { func (c *chatData) Set(chat int64, key string, data interface{}) {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() defer c.mutex.Unlock()
if _, exists := c.data[chat]; !exists { if _, exists := c.data[chat]; !exists {
c.data[chat] = make(map[string]interface{}) c.data[chat] = make(map[string]interface{})
} }
@ -50,9 +56,11 @@ func (c chatData) Set(chat int64, key string, data interface{}) {
} }
// Get retrieves data about a chat // Get retrieves data about a chat
func (c chatData) Get(chat int64, key string) (interface{}, bool) { func (c *chatData) Get(chat int64, key string) (interface{}, bool) {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() defer c.mutex.Unlock()
m, exists := c.data[chat] m, exists := c.data[chat]
if !exists { if !exists {
return nil, false return nil, false
@ -64,22 +72,35 @@ func (c chatData) Get(chat int64, key string) (interface{}, bool) {
return data, true return data, true
} }
func (c chatDataFile) read() { func (c *chatDataFile) read() {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() defer c.mutex.Unlock()
data, err := ioutil.ReadFile(c.path) data, err := ioutil.ReadFile(c.path)
if err != nil { if err != nil {
// File doesn't exist, skip import // File doesn't exist, skip import
return return
} }
json.Unmarshal(data, &ChatData.data) 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() { func (c *chatDataFile) write() {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() defer c.mutex.Unlock()
ChatData.mutex.Lock() ChatData.mutex.Lock()
defer ChatData.mutex.Unlock() defer ChatData.mutex.Unlock()
data, _ := json.Marshal(ChatData.data)
ioutil.WriteFile(c.path, data, 0770) 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)
}
} }

View File

@ -2,13 +2,14 @@
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 01:27:11 * @Date: 2018-07-24 01:27:11
* @Last Modified by: Bartuccio Antoine * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2019-01-04 10:51:32 * @Last Modified time: 2019-01-05 17:45:18
*/ */
package shared package shared
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io/ioutil" "io/ioutil"
"sync" "sync"
) )
@ -25,32 +26,39 @@ type historyFile struct {
} }
// History manages acces to chat history // History manages acces to chat history
var History history var History *history
var hf historyFile var hf historyFile
// InitHistory init a chit history of a given size // InitHistory init a chit history of a given size
func InitHistory(size int, history_file_path string) { func InitHistory(size int, historyFilePath string) {
hf = historyFile{} hf = historyFile{}
hf.path = history_file_path hf.path = historyFilePath
History = history{} History = &history{}
History.mutex.Lock() History.mutex.Lock()
defer History.mutex.Unlock() defer History.mutex.Unlock()
History.size = size History.size = size
History.data = make(map[int64][]string) History.data = make(map[int64][]string)
hf.read() hf.read()
} }
// Size get the number of messages saved in the history // Size get the number of messages saved in the history
func (h history) Size() int { func (h *history) Size() int {
h.mutex.Lock() h.mutex.Lock()
defer h.mutex.Unlock() defer h.mutex.Unlock()
return h.size return h.size
} }
// Message get a selected message in a chat history // Message get a selected message in a chat history
func (h history) Message(chatID int64, n int) string { func (h *history) Message(chatID int64, n int) string {
h.mutex.Lock() h.mutex.Lock()
defer h.mutex.Unlock() defer h.mutex.Unlock()
array, exists := h.data[chatID] array, exists := h.data[chatID]
if exists && n >= 0 && n < len(array) { if exists && n >= 0 && n < len(array) {
return array[n] return array[n]
@ -59,9 +67,11 @@ func (h history) Message(chatID int64, n int) string {
} }
// AddMessage append a message to a given chat // AddMessage append a message to a given chat
func (h history) AddMessage(chatID int64, m string) { func (h *history) AddMessage(chatID int64, m string) {
h.mutex.Lock() h.mutex.Lock()
defer h.mutex.Unlock() defer h.mutex.Unlock()
if _, exists := h.data[chatID]; !exists { if _, exists := h.data[chatID]; !exists {
h.data[chatID] = make([]string, h.size, h.size) h.data[chatID] = make([]string, h.size, h.size)
} }
@ -69,9 +79,11 @@ func (h history) AddMessage(chatID int64, m string) {
} }
// LastMessage get the last message of a given chat // LastMessage get the last message of a given chat
func (h history) LastMessage(chatID int64) string { func (h *history) LastMessage(chatID int64) string {
h.mutex.Lock() h.mutex.Lock()
defer h.mutex.Unlock() defer h.mutex.Unlock()
if _, exists := h.data[chatID]; exists { if _, exists := h.data[chatID]; exists {
return h.data[chatID][h.size-1] return h.data[chatID][h.size-1]
} }
@ -79,9 +91,11 @@ func (h history) LastMessage(chatID int64) string {
} }
// ChatHistory get a copy of a given chat history // ChatHistory get a copy of a given chat history
func (h history) ChatHistory(chatID int64) []string { func (h *history) ChatHistory(chatID int64) []string {
h.mutex.Lock() h.mutex.Lock()
defer h.mutex.Unlock() defer h.mutex.Unlock()
array, exists := h.data[chatID] array, exists := h.data[chatID]
if exists { if exists {
c := make([]string, h.size, h.size) c := make([]string, h.size, h.size)
@ -93,7 +107,8 @@ func (h history) ChatHistory(chatID int64) []string {
// Add a message at the end of a chat and move everithyng up // Add a message at the end of a chat and move everithyng up
// Assert that the slice exists and mutex already locked // Assert that the slice exists and mutex already locked
func (h history) append(chatID int64, m string) { func (h *history) append(chatID int64, m string) {
c := make([]string, h.size-1, h.size-1) c := make([]string, h.size-1, h.size-1)
array, _ := h.data[chatID] array, _ := h.data[chatID]
copy(c, array[1:]) copy(c, array[1:])
@ -104,22 +119,35 @@ func (h history) append(chatID int64, m string) {
go hf.write() go hf.write()
} }
func (h historyFile) read() { func (h *historyFile) read() {
h.mutex.Lock() h.mutex.Lock()
defer h.mutex.Unlock() defer h.mutex.Unlock()
data, err := ioutil.ReadFile(h.path) data, err := ioutil.ReadFile(h.path)
if err != nil { if err != nil {
// File doesn't exist, skip import // File doesn't exist, skip import
return return
} }
json.Unmarshal(data, &History.data) if err := json.Unmarshal(data, &History.data); err != nil {
fmt.Printf("Error while unmarshaling user history with path %s, error : %v\n", h.path, err)
}
} }
func (h historyFile) write() { func (h *historyFile) write() {
h.mutex.Lock() h.mutex.Lock()
defer h.mutex.Unlock() defer h.mutex.Unlock()
History.mutex.Lock() History.mutex.Lock()
defer History.mutex.Unlock() defer History.mutex.Unlock()
data, _ := json.Marshal(History.data)
ioutil.WriteFile(h.path, data, 0770) data, err := json.Marshal(History.data)
if err != nil {
fmt.Printf("Error while marshaling history file with path %s, error : %v\n", h.path, err)
return
}
if err := ioutil.WriteFile(h.path, data, 0770); err != nil {
fmt.Printf("Error writing history file with path %s, error %v\n", h.path, err)
}
} }

View File

@ -2,7 +2,7 @@
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 14:41:03 * @Date: 2018-07-24 14:41:03
* @Last Modified by: Bartuccio Antoine * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2019-01-04 10:52:13 * @Last Modified time: 2019-01-05 17:45:59
*/ */
package shared package shared
@ -27,24 +27,29 @@ type usersFile struct {
} }
// Users shared user for commands // Users shared user for commands
var Users users var Users *users
var uf usersFile var uf usersFile
// InitUsers inits the User info storage // InitUsers inits the User info storage
func InitUsers(users_file_path string) { func InitUsers(usersFilePath string) {
uf = usersFile{} uf = usersFile{}
uf.path = users_file_path uf.path = usersFilePath
Users = users{} Users = &users{}
Users.mutex.Lock() Users.mutex.Lock()
defer Users.mutex.Unlock() defer Users.mutex.Unlock()
Users.data = make(map[string]map[string]string) Users.data = make(map[string]map[string]string)
uf.read() uf.read()
} }
// Get an info about a given user // Get an info about a given user
func (u users) Get(username string, key string) (string, bool) { func (u *users) Get(username string, key string) (string, bool) {
u.mutex.Lock() u.mutex.Lock()
defer u.mutex.Unlock() defer u.mutex.Unlock()
user, exists := u.data[username] user, exists := u.data[username]
if !exists { if !exists {
return "", false return "", false
@ -56,9 +61,11 @@ func (u users) Get(username string, key string) (string, bool) {
} }
// Set add an info about a given user // Set add an info about a given user
func (u users) Set(username string, key, data string) { func (u *users) Set(username string, key, data string) {
u.mutex.Lock() u.mutex.Lock()
defer u.mutex.Unlock() defer u.mutex.Unlock()
if _, exists := u.data[username]; !exists { if _, exists := u.data[username]; !exists {
u.data[username] = make(map[string]string) u.data[username] = make(map[string]string)
} }
@ -67,9 +74,11 @@ func (u users) Set(username string, key, data string) {
} }
// GetUsernames get all usernames stored in settings // GetUsernames get all usernames stored in settings
func (u users) GetUsernames() []string { func (u *users) GetUsernames() []string {
u.mutex.Lock() u.mutex.Lock()
defer u.mutex.Unlock() defer u.mutex.Unlock()
var usernames []string var usernames []string
for username := range u.data { for username := range u.data {
usernames = append(usernames, username) usernames = append(usernames, username)
@ -78,7 +87,8 @@ func (u users) GetUsernames() []string {
} }
// GetUserChat retrieve the chat of the user if registered // GetUserChat retrieve the chat of the user if registered
func (u users) GetUserChat(username string) (*tb.Chat, error) { func (u *users) GetUserChat(username string) (*tb.Chat, error) {
serializedChat, exists := u.Get(username, "private_chat") serializedChat, exists := u.Get(username, "private_chat")
if !exists { if !exists {
return nil, fmt.Errorf("No private chat registered for %s", username) return nil, fmt.Errorf("No private chat registered for %s", username)
@ -93,7 +103,8 @@ func (u users) GetUserChat(username string) (*tb.Chat, error) {
} }
// SetUserChat register a private chat for an user // SetUserChat register a private chat for an user
func (u users) SetUserChat(username string, chat *tb.Chat) { func (u *users) SetUserChat(username string, chat *tb.Chat) {
serializedChat, err := json.Marshal(chat) serializedChat, err := json.Marshal(chat)
if err != nil { if err != nil {
return return
@ -102,22 +113,35 @@ func (u users) SetUserChat(username string, chat *tb.Chat) {
u.Set(username, "private_chat", string(serializedChat)) u.Set(username, "private_chat", string(serializedChat))
} }
func (u usersFile) read() { func (u *usersFile) read() {
u.mutex.Lock() u.mutex.Lock()
defer u.mutex.Unlock() defer u.mutex.Unlock()
data, err := ioutil.ReadFile(u.path) data, err := ioutil.ReadFile(u.path)
if err != nil { if err != nil {
// File doesn't exist, skip import // File doesn't exist, skip import
return return
} }
json.Unmarshal(data, &Users.data) 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() { func (u *usersFile) write() {
u.mutex.Lock() u.mutex.Lock()
defer u.mutex.Unlock() defer u.mutex.Unlock()
Users.mutex.Lock() Users.mutex.Lock()
defer Users.mutex.Unlock() defer Users.mutex.Unlock()
data, _ := json.Marshal(Users.data)
ioutil.WriteFile(u.path, data, 0770) 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)
}
} }