-
Notifications
You must be signed in to change notification settings - Fork 15
/
session_repository.go
81 lines (66 loc) · 2.38 KB
/
session_repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package margelet
import (
"encoding/json"
"fmt"
"gopkg.in/redis.v3"
"gopkg.in/telegram-bot-api.v4"
"strings"
)
// SessionRepository - public interface for session repository
type SessionRepository interface {
Create(chatID int64, userID int, command string)
Add(chatID int64, userID int, message *tgbotapi.Message)
Remove(chatID int64, userID int)
Command(chatID int64, userID int) string
Dialog(chatID int64, userID int) (messages []tgbotapi.Message)
}
type sessionRepository struct {
key string
redis *redis.Client
}
func newSessionRepository(prefix string, redis *redis.Client) *sessionRepository {
key := strings.Join([]string{prefix, "margelet_sessions"}, "-")
return &sessionRepository{key, redis}
}
// Create - creates new session for chatID, userID and command
func (session *sessionRepository) Create(chatID int64, userID int, command string) {
key := session.keyFor(chatID, userID)
session.redis.Set(key, command, 0)
}
// Add - adds user's answer to existing session
func (session *sessionRepository) Add(chatID int64, userID int, message *tgbotapi.Message) {
key := session.dialogKeyFor(chatID, userID)
json, _ := json.Marshal(message)
session.redis.RPush(key, string(json))
}
// Remove - removes session
func (session *sessionRepository) Remove(chatID int64, userID int) {
key := session.keyFor(chatID, userID)
session.redis.Del(key)
key = session.dialogKeyFor(chatID, userID)
session.redis.Del(key)
}
// Command - returns command for active session for chatID and userID, if exists
// otherwise returns empty string
func (session *sessionRepository) Command(chatID int64, userID int) string {
key := session.keyFor(chatID, userID)
value, _ := session.redis.Get(key).Result()
return value
}
// Dialog returns all user's answers history for chatID and userID
func (session *sessionRepository) Dialog(chatID int64, userID int) (messages []tgbotapi.Message) {
key := session.dialogKeyFor(chatID, userID)
values := session.redis.LRange(key, 0, -1).Val()
for _, value := range values {
msg := tgbotapi.Message{}
json.Unmarshal([]byte(value), &msg)
messages = append(messages, msg)
}
return
}
func (session *sessionRepository) keyFor(chatID int64, userID int) string {
return fmt.Sprintf("%s_%d_%d", session.key, chatID, userID)
}
func (session *sessionRepository) dialogKeyFor(chatID int64, userID int) string {
return fmt.Sprintf("%s_dialog", session.keyFor(chatID, userID))
}