14 Commits

Author SHA1 Message Date
30397b9207 Fix formating with go fmt 2020-11-09 19:14:21 +01:00
e786b77f62 Fix identation 2020-11-09 19:12:14 +01:00
9df38b5a88 Calling the /sponge command as a reply will now spongify the quoted message 2020-11-09 18:40:30 +01:00
3d3133eaff Fix CI
All checks were successful
continuous-integration/drone/push Build is passing
2019-07-23 22:19:18 +02:00
c001bca84a Fix dockerfile for CI
Some checks failed
continuous-integration/drone/push Build is failing
2019-07-23 22:15:42 +02:00
05203f3392 Better, faster and safer file management
Some checks failed
continuous-integration/drone/push Build is failing
the build was successful
2019-01-05 17:48:09 +01:00
f722e70052 Fix Arioch
All checks were successful
the build was successful
2019-01-04 11:45:28 +01:00
daa77fcfc4 Merge branch 'normalization' of ALFRED/ALFRED into master
All checks were successful
the build was successful
2019-01-04 10:33:23 +00:00
cc31b9d00a Fix CI for go 1.11
All checks were successful
the build was successful
2019-01-04 11:31:37 +01:00
ed824600e9 Upgrade to go 1.11
Some checks failed
the build failed
2019-01-04 11:09:20 +01:00
541ab556d7 Remove relative path and follow gometalinter guide lines
Some checks failed
the build failed
2019-01-04 10:55:51 +01:00
94313b4819 Fix register_private.go permission error
All checks were successful
the build was successful
2019-01-03 22:03:03 +01:00
21ae38639d Merge branch 'bro-features' of ALFRED/ALFRED into master
All checks were successful
the build was successful
2019-01-02 23:03:55 +00:00
4ecc1e2072 Merge branch 'bro-features' of ALFRED/ALFRED into master
All checks were successful
the build was successful
2019-01-02 13:41:05 +00:00
19 changed files with 250 additions and 131 deletions

View File

@ -1,13 +1,13 @@
pipeline: pipeline:
build: build:
image: golang image: golang:1.11
group: build group: build
commands: commands:
- go get -v -d ./... - go get -v -d ./...
- go build . - go build .
test: test:
image: golang image: golang:1.11
group: build group: test
secrets: [ test_api_token ] secrets: [ test_api_token ]
environment: [ test_api_token ] environment: [ test_api_token ]
commands: commands:

View File

@ -1,16 +1,17 @@
FROM golang:1.10 AS builder FROM golang:1.11 AS builder
# Download and install the latest release of dep # Download and install the latest release of dep
# ADD https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64 /usr/bin/dep # ADD https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64 /usr/bin/dep
# RUN chmod +x /usr/bin/dep # RUN chmod +x /usr/bin/dep
WORKDIR /go/src/git.klmp200.net/ALFRED/ALFRED
# Copy the code from the host and compile it # Copy the code from the host and compile it
COPY . ./ COPY . .
RUN go get -v -d ./... 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
@ -20,7 +21,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix nocgo -o /app .
FROM alpine:3.4 FROM alpine:3.4
RUN apk add --no-cache ca-certificates apache2-utils RUN apk add --no-cache ca-certificates apache2-utils
COPY --from=builder /app ./ COPY --from=builder /app ./
COPY --from=builder /go/res ./ COPY --from=builder /go/src/git.klmp200.net/ALFRED/ALFRED/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-02 22:58:03 * @Last Modified time: 2019-01-05 17:47:10
*/ */
package main package main
@ -11,13 +11,15 @@ import (
"log" "log"
"time" "time"
"./commands" "git.klmp200.net/ALFRED/ALFRED/commands"
"./settings" "git.klmp200.net/ALFRED/ALFRED/settings"
"./shared" "git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )
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

@ -1,19 +1,22 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-27 19:53:09 * @Date: 2018-07-27 19:53:09
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-28 13:17:05 * @Last Modified time: 2019-01-04 10:36:16
*/ */
package commands package commands
import ( import (
"../shared" "net/http"
"git.klmp200.net/ALFRED/ALFRED/shared"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
"net/http"
) )
// AperoTime checks if it's time to drink on an external website
func AperoTime(m *tb.Message) { func AperoTime(m *tb.Message) {
response, err := http.Get("http://estcequecestbientotlapero.fr") response, err := http.Get("http://estcequecestbientotlapero.fr")
if err != nil { if err != nil {
@ -27,13 +30,4 @@ func AperoTime(m *tb.Message) {
return return
} }
shared.Bot.Send(m.Chat, doc.Find("h2").First().Text()) shared.Bot.Send(m.Chat, doc.Find("h2").First().Text())
// doc.Find("h2").Each(func(i int, s *goquery.Selection) {
// log.Println(s.Text())
// })
// node, err := html.Parse(response.Body)
// if err != nil {
// shared.Bot.Send(m.Chat, "La réponse qui m'a été fournit est incohérente.")
// return
// }
// log.Println(node.NextSibling)
} }

View File

@ -1,20 +1,23 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 20:50:04 * @Date: 2018-07-24 20:50:04
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-24 21:00:59 * @Last Modified time: 2019-01-04 10:37:39
*/ */
package commands package commands
import ( import (
"../shared"
tb "gopkg.in/tucnak/telebot.v2"
"math/rand" "math/rand"
"strconv" "strconv"
"strings" "strings"
"git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2"
) )
// Dice rolls a dice
func Dice(m *tb.Message) { func Dice(m *tb.Message) {
split := strings.Split(m.Text, " ") split := strings.Split(m.Text, " ")
if len(split) < 2 { if len(split) < 2 {

View File

@ -1,17 +1,18 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 12:11:26 * @Date: 2018-07-24 12:11:26
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-24 12:12:58 * @Last Modified time: 2019-01-04 10:38:07
*/ */
package commands package commands
import ( import (
"../shared" "git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )
// Framapad send a link to the ALFRED framapad
func Framapad(m *tb.Message) { func Framapad(m *tb.Message) {
shared.Bot.Send(m.Chat, "Venez participer à mon développement en posant vos idées ici : https://mensuel.framapad.org/p/ALFRED2LERETOUR.") shared.Bot.Send(m.Chat, "Venez participer à mon développement en posant vos idées ici : https://mensuel.framapad.org/p/ALFRED2LERETOUR.")
} }

View File

@ -1,18 +1,21 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 14:55:33 * @Date: 2018-07-24 14:55:33
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-25 01:29:53 * @Last Modified time: 2019-01-04 10:38:32
*/ */
package commands package commands
import ( import (
"../shared"
tb "gopkg.in/tucnak/telebot.v2"
"strings" "strings"
"git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2"
) )
// SetGender register your gender on ALFRED
func SetGender(m *tb.Message) { func SetGender(m *tb.Message) {
if m.Sender.Username == "" { if m.Sender.Username == "" {
shared.Bot.Send(m.Chat, "Il faut avoir enregistré un username pour pouvoir utiliser cette fonction") shared.Bot.Send(m.Chat, "Il faut avoir enregistré un username pour pouvoir utiliser cette fonction")

View File

@ -1,17 +1,19 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 12:07:34 * @Date: 2018-07-24 12:07:34
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-24 12:08:49 * @Last Modified time: 2019-01-04 10:39:07
*/ */
package commands package commands
import ( import (
"../shared" "git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )
// Git sends a link to the git repo
func Git(m *tb.Message) { func Git(m *tb.Message) {
shared.Bot.Send(m.Chat, "Mon code source est accessible librement à l'adresse https://git.klmp200.net/ALFRED/ALFRED. Venez contribuer :)") shared.Bot.Send(m.Chat, "Mon code source est accessible librement à l'adresse https://git.klmp200.net/ALFRED/ALFRED. Venez contribuer :)")
} }

View File

@ -1,17 +1,19 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 12:05:45 * @Date: 2018-07-24 12:05:45
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-24 12:06:39 * @Last Modified time: 2019-01-04 10:39:24
*/ */
package commands package commands
import ( import (
"../shared" "git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )
// Hello makes ALFRED say hello
func Hello(m *tb.Message) { func Hello(m *tb.Message) {
shared.Bot.Send(m.Chat, "Bonjour "+m.Sender.Username) shared.Bot.Send(m.Chat, "Bonjour "+m.Sender.Username)
} }

View File

@ -1,17 +1,19 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 12:09:37 * @Date: 2018-07-24 12:09:37
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-24 12:10:26 * @Last Modified time: 2019-01-04 10:39:50
*/ */
package commands package commands
import ( import (
"../shared" "git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )
// OnText saves chat history
func OnText(m *tb.Message) { func OnText(m *tb.Message) {
shared.History.AddMessage(m.Chat.ID, m.Text) shared.History.AddMessage(m.Chat.ID, m.Text)
} }

View File

@ -1,8 +1,8 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-11-14 00:15:43 * @Date: 2018-11-14 00:15:43
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-11-14 00:31:48 * @Last Modified time: 2019-01-04 10:40:01
*/ */
package commands package commands
@ -13,7 +13,7 @@ import (
"math/rand" "math/rand"
"sync" "sync"
"../shared" "git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )

View File

@ -2,13 +2,14 @@
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2019-01-02 22:46:05 * @Date: 2019-01-02 22:46:05
* @Last Modified by: Bartuccio Antoine * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2019-01-03 00:02:48 * @Last Modified time: 2019-01-04 10:40:28
*/ */
package commands package commands
import ( import (
"../shared" "git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )
@ -17,10 +18,12 @@ func RegisterPrivate(m *tb.Message) {
if m.Chat.Type != tb.ChatPrivate { if m.Chat.Type != tb.ChatPrivate {
shared.Bot.Send(m.Chat, "Cette commande n'est disponible qu'en messages privés") shared.Bot.Send(m.Chat, "Cette commande n'est disponible qu'en messages privés")
return
} }
if m.Sender.Username == "" { if m.Sender.Username == "" {
shared.Bot.Send(m.Chat, "Vous devez avoir enregistré un username") shared.Bot.Send(m.Chat, "Vous devez avoir enregistré un username")
return
} }
shared.Users.SetUserChat(m.Sender.Username, m.Chat) shared.Users.SetUserChat(m.Sender.Username, m.Chat)
@ -32,10 +35,12 @@ func UnRegisterPrivate(m *tb.Message) {
if m.Chat.Type != tb.ChatPrivate { if m.Chat.Type != tb.ChatPrivate {
shared.Bot.Send(m.Chat, "Cette commande n'est disponible qu'en messages privés") shared.Bot.Send(m.Chat, "Cette commande n'est disponible qu'en messages privés")
return
} }
if m.Sender.Username == "" { if m.Sender.Username == "" {
shared.Bot.Send(m.Chat, "Vous devez avoir enregistré un username") shared.Bot.Send(m.Chat, "Vous devez avoir enregistré un username")
return
} }
shared.Users.SetUserChat(m.Sender.Username, nil) shared.Users.SetUserChat(m.Sender.Username, nil)

View File

@ -1,27 +1,38 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 11:52:11 * @Date: 2018-07-24 11:52:11
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-24 11:58:42 * @Last Modified time: 2019-01-04 10:40:38
*/ */
package commands package commands
import ( import (
"../shared"
tb "gopkg.in/tucnak/telebot.v2"
"strings" "strings"
"git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2"
) )
func Spongify(input_message string) string {
spongified_message := ""
for i, char := range input_message {
if i%2 == 0 {
spongified_message += strings.ToLower(string(char))
} else {
spongified_message += strings.ToUpper(string(char))
}
}
return spongified_message
}
func Sponge(m *tb.Message) { func Sponge(m *tb.Message) {
message := "" message := ""
for i, char := range shared.History.LastMessage(m.Chat.ID) { if m.IsReply() {
if i%2 == 0 { message = Spongify(m.ReplyTo.Text)
message += strings.ToLower(string(char)) } else {
} else { message = Spongify(shared.History.LastMessage(m.Chat.ID))
message += strings.ToUpper(string(char))
}
} }
shared.Bot.Send(m.Chat, message) shared.Bot.Send(m.Chat, message)
} }

View File

@ -15,7 +15,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"../shared" "git.klmp200.net/ALFRED/ALFRED/shared"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )

View File

@ -1,21 +1,23 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-25 18:51:38 * @Date: 2018-07-25 18:51:38
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-27 16:49:59 * @Last Modified time: 2019-01-04 11:44:47
*/ */
package commands package commands
import ( import (
"../settings"
"../shared"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
tb "gopkg.in/tucnak/telebot.v2"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"git.klmp200.net/ALFRED/ALFRED/settings"
"git.klmp200.net/ALFRED/ALFRED/shared"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
tb "gopkg.in/tucnak/telebot.v2"
) )
var client *twitter.Client var client *twitter.Client
@ -44,6 +46,7 @@ func twitterCommunicationError(m *tb.Message) {
shared.Bot.Send(m.Chat, "Désolé, les serveurs de twitter sont injoignables.") shared.Bot.Send(m.Chat, "Désolé, les serveurs de twitter sont injoignables.")
} }
// LastTrumpTweet sends the last tweet of Donald Trump
func LastTrumpTweet(m *tb.Message) { func LastTrumpTweet(m *tb.Message) {
testOrInitTwitter() testOrInitTwitter()
user, _, err := client.Users.Show(&twitter.UserShowParams{ScreenName: "realDonaldTrump"}) user, _, err := client.Users.Show(&twitter.UserShowParams{ScreenName: "realDonaldTrump"})
@ -70,6 +73,7 @@ func LastTrumpTweet(m *tb.Message) {
shared.Bot.Send(m.Chat, strings.Join(response, " ")) shared.Bot.Send(m.Chat, strings.Join(response, " "))
} }
// TwitterTrends sends the french twitter trends
func TwitterTrends(m *tb.Message) { func TwitterTrends(m *tb.Message) {
testOrInitTwitter() testOrInitTwitter()
trends, _, err := client.Trends.Place(int64(615702), nil) trends, _, err := client.Trends.Place(int64(615702), nil)
@ -84,16 +88,25 @@ func TwitterTrends(m *tb.Message) {
shared.Bot.Send(m.Chat, message) shared.Bot.Send(m.Chat, message)
} }
// TwitterSJW sends lasts messages with #SJW
func TwitterSJW(m *tb.Message) { func TwitterSJW(m *tb.Message) {
testOrInitTwitter() testOrInitTwitter()
last_use, 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 _, is_string := last_use.(string); is_string { switch serializedDate := lastUse.(type) {
date, _ = time.Parse(time.RFC3339, last_use.(string)) case string:
} else { parsedDate, err := time.Parse(time.RFC3339, serializedDate)
date = last_use.(time.Time) if err == nil {
date = parsedDate
}
case time.Time:
date = serializedDate
default:
shared.Bot.Send(m.Chat, "Arioch ne répondra pas à votre appel.")
return
} }
if time.Now().Before(date.Add(time.Hour * 24)) { if 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

View File

@ -1,8 +1,8 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 11:56:47 * @Date: 2018-07-24 11:56:47
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-24 11:58:34 * @Last Modified time: 2019-01-04 10:48:26
*/ */
package shared package shared
@ -11,4 +11,5 @@ import (
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
) )
// Bot contains telebot instance
var Bot *tb.Bot var Bot *tb.Bot

View File

@ -1,14 +1,15 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-27 15:37:59 * @Date: 2018-07-27 15:37:59
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-27 16:06:51 * @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"
) )
@ -24,22 +25,29 @@ type chatDataFile struct {
path string path string
} }
var ChatData chatData // ChatData manage access to stored data about a chat
var ChatData *chatData
var cdf chatDataFile var cdf chatDataFile
// Init chat data 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()
} }
func (c chatData) Set(chat int64, key string, data interface{}) { // Set stores data about a chat
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{})
} }
@ -47,9 +55,12 @@ func (c chatData) Set(chat int64, key string, data interface{}) {
go cdf.write() go cdf.write()
} }
func (c chatData) Get(chat int64, key string) (interface{}, bool) { // Get retrieves data about a chat
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
@ -61,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

@ -1,14 +1,15 @@
/* /*
* @Author: Bartuccio Antoine * @Author: Bartuccio Antoine
* @Date: 2018-07-24 01:27:11 * @Date: 2018-07-24 01:27:11
* @Last Modified by: klmp200 * @Last Modified by: Bartuccio Antoine
* @Last Modified time: 2018-07-24 12:54:21 * @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"
) )
@ -24,32 +25,40 @@ type historyFile struct {
path string path string
} }
var History history // History manages acces to chat history
var History *history
var hf historyFile var hf historyFile
// Init a chat 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()
} }
// 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
} }
// 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]
@ -57,30 +66,36 @@ func (h history) Message(chatID int64, n int) string {
return "" return ""
} }
// 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)
} }
h.append(chatID, m) h.append(chatID, m)
} }
// 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]
} }
return "" return ""
} }
// 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)
@ -92,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:])
@ -103,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-02 22:37:58 * @Last Modified time: 2019-01-05 17:45:59
*/ */
package shared package shared
@ -27,23 +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
func InitUsers(users_file_path string) { // InitUsers inits the User info storage
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
@ -54,10 +60,12 @@ func (u users) Get(username string, key string) (string, bool) {
return user[key], true return user[key], true
} }
// 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)
} }
@ -65,19 +73,22 @@ func (u users) Set(username string, key, data string) {
go uf.write() go uf.write()
} }
// GetUsernames 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)
} }
return usernames return usernames
} }
// 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)
@ -92,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
@ -101,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)
}
} }