/
chats.go
114 lines (102 loc) · 2.62 KB
/
chats.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package bot
import (
"errors"
"fmt"
"github.com/TiunovNN/go-tg-wol/pkg/users"
"github.com/TiunovNN/go-tg-wol/pkg/wol"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
type userState int
const (
newUser userState = iota
registeredUser
)
type ChatEntity struct {
id int64
user *users.User
state userState
userStorage *users.UserStorage
}
type ChatStorage struct {
storage map[int64]*ChatEntity
userStorage *users.UserStorage
}
var (
ErrWrongOperation = errors.New("wrong operation")
)
func NewChatStorage(userStorage *users.UserStorage) *ChatStorage {
return &ChatStorage{
make(map[int64]*ChatEntity, 1),
userStorage,
}
}
func (s *ChatStorage) GetChat(chatId int64) *ChatEntity {
entity, ok := s.storage[chatId]
if ok {
return entity
}
entity = &ChatEntity{
chatId,
nil,
newUser,
s.userStorage,
}
s.storage[chatId] = entity
return entity
}
func (e *ChatEntity) ProcessMessage(command *tgbotapi.Message) (*tgbotapi.MessageConfig, error) {
switch e.state {
case newUser:
if command.Contact != nil && command.Contact.UserID == command.From.ID {
message, err := e.Register(command.Contact.PhoneNumber)
return message, err
} else {
message := tgbotapi.NewMessage(e.id, "Please, introduce yourself!")
message.ReplyMarkup = makeRegisterMenu()
return &message, nil
}
case registeredUser:
if command.Text == "Enable computer" {
return e.SendWakeOnLan()
} else if command.Text == "Sign out" {
e.user = nil
e.state = newUser
message := tgbotapi.NewMessage(e.id, "Please, introduce yourself!")
message.ReplyMarkup = makeRegisterMenu()
return &message, nil
} else {
message := tgbotapi.NewMessage(e.id, "Please, choose one of the commands!")
message.ReplyMarkup = makeMenu()
return &message, nil
}
}
return nil, nil
}
func (e *ChatEntity) Register(phoneNumber string) (*tgbotapi.MessageConfig, error) {
if e.state != newUser {
return nil, ErrWrongOperation
}
if phoneNumber[0] != '+' {
phoneNumber = "+" + phoneNumber
}
user, err := e.userStorage.GetUser(phoneNumber)
if err != nil {
return nil, err
}
e.user = user
e.state = registeredUser
text := fmt.Sprintf("Welcome %s!", e.user.Name)
message := tgbotapi.NewMessage(e.id, text)
message.ReplyMarkup = makeMenu()
return &message, nil
}
func (e *ChatEntity) SendWakeOnLan() (*tgbotapi.MessageConfig, error) {
if e.state != registeredUser {
return nil, ErrWrongOperation
}
wol.Send(e.user.MacAddress)
text := fmt.Sprintf("Sending wake on lan to %s!", e.user.MacAddress)
message := tgbotapi.NewMessage(e.id, text)
message.ReplyMarkup = makeMenu()
return &message, nil
}