๐Ÿ“ฆ alexandear / final-surge-bot

๐Ÿ“„ bot.go ยท 230 lines
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230package bot

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"time"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)

const (
	CommandStart = "start"

	KeyboardButtonTask = "/task"

	Emails = 100
)

var ErrNotFound = errors.New("not found")

type UserToken struct {
	UserKey string
	Token   string
}

type Workout struct {
	Date        time.Time
	Description string
}

type Sender interface {
	Send(msg tgbotapi.Chattable) (tgbotapi.Message, error)
}

type Storage interface {
	UserToken(ctx context.Context, userName string) (UserToken, error)
	UpdateUserToken(ctx context.Context, userName string, userToken UserToken) error
}

type FinalSurge interface {
	Login(ctx context.Context, email, password string) (UserToken, error)
	Workouts(ctx context.Context, userToken UserToken, startDate, endDate time.Time) ([]Workout, error)
}

type Clock interface {
	Now() time.Time
}

//go:generate mockgen -source=$GOFILE -package mock -destination mock/interfaces_mock.go
type Bot struct {
	bot   Sender
	db    Storage
	fs    FinalSurge
	clock Clock

	keyboard tgbotapi.ReplyKeyboardMarkup

	userEmails map[string]string
}

func NewBot(bot Sender, db Storage, fs FinalSurge, clock Clock) *Bot {
	return &Bot{
		bot:   bot,
		db:    db,
		fs:    fs,
		clock: clock,

		keyboard: tgbotapi.NewReplyKeyboard(tgbotapi.NewKeyboardButtonRow(
			tgbotapi.NewKeyboardButton(KeyboardButtonTask),
		)),

		userEmails: make(map[string]string, Emails),
	}
}

func (b *Bot) ProcessUpdate(ctx context.Context, update tgbotapi.Update) error {
	if update.Message == nil {
		return nil
	}

	msg, err := b.message(ctx, update.Message)
	if err != nil {
		return fmt.Errorf("get message: %w", err)
	}

	if msg == nil {
		return nil
	}

	if _, err := b.bot.Send(*msg); err != nil {
		return fmt.Errorf("send reply msg to chat %d: %w", msg.ChatID, err)
	}

	return nil
}

func (b *Bot) Keyboard() tgbotapi.ReplyKeyboardMarkup {
	return b.keyboard
}

func (b *Bot) message(ctx context.Context, message *tgbotapi.Message) (*tgbotapi.MessageConfig, error) {
	userName := message.From.UserName
	chatID := message.Chat.ID
	text := message.Text

	if message.IsCommand() && message.Command() == CommandStart {
		b.userEmails[userName] = ""

		msg := tgbotapi.NewMessage(chatID, "Enter FinalSurge email:")

		return &msg, nil
	}

	if text == KeyboardButtonTask {
		return b.buttonTask(ctx, userName, chatID)
	}

	email, ok := b.userEmails[userName]
	if !ok {
		return b.newChooseOptionMsg(chatID), nil
	}

	switch {
	case email == "":
		b.userEmails[userName] = text

		msg := tgbotapi.NewMessage(chatID, "Enter FinalSurge password:")

		return &msg, nil
	case email != "":
		userToken, err := b.fs.Login(ctx, email, text)
		if err != nil {
			return nil, fmt.Errorf("login: %w", err)
		}

		if err := b.db.UpdateUserToken(ctx, userName, userToken); err != nil {
			return nil, fmt.Errorf("update user token: %w", err)
		}

		b.userEmails[userName] = ""

		return b.newChooseOptionMsg(chatID), nil
	}

	return nil, nil
}

func (b *Bot) buttonTask(ctx context.Context, userName string, chatID int64) (*tgbotapi.MessageConfig, error) {
	userToken, err := b.db.UserToken(ctx, userName)
	if errors.Is(err, ErrNotFound) {
		msg := tgbotapi.NewMessage(chatID, "Please authorize first by entering /start")

		return &msg, nil
	}

	if err != nil {
		return nil, fmt.Errorf("get usertoken: %w", err)
	}

	today := NewDate(b.clock.Now())
	tomorrow := today.AddDate(0, 0, 1)

	workouts, err := b.fs.Workouts(context.Background(), userToken, today, tomorrow)
	if err != nil {
		return nil, fmt.Errorf("get workouts: %w", err)
	}

	task := MessageTask(workouts, today, tomorrow)

	msg := tgbotapi.NewMessage(chatID, task)

	return &msg, nil
}

func MessageTask(workouts []Workout, today, tomorrow time.Time) string {
	todayDescriptions := make([]string, 0, len(workouts))
	tomorrowDescriptions := make([]string, 0, len(workouts))

	for _, w := range workouts {
		switch {
		case w.Date.Equal(today):
			todayDescriptions = append(todayDescriptions, w.Description)
		case w.Date.Equal(tomorrow):
			tomorrowDescriptions = append(tomorrowDescriptions, w.Description)
		default:
		}
	}

	task := strings.Builder{}
	task.WriteString("Tasks:")
	task.WriteByte('\n')

	writeDescriptions := func(day string, date time.Time, descriptions []string) {
		task.WriteString(day)
		task.WriteByte(' ')
		task.WriteString(date.Format("02.01"))
		task.WriteByte(':')
		task.WriteByte('\n')

		if len(descriptions) != 0 {
			for _, d := range descriptions {
				task.WriteString(d)
				task.WriteByte('\n')
			}
		} else {
			task.WriteString("not set")
			task.WriteByte('\n')
		}
	}

	writeDescriptions("Today", today, todayDescriptions)
	task.WriteByte('\n')
	writeDescriptions("Tomorrow", tomorrow, tomorrowDescriptions)

	return task.String()
}

func (b *Bot) newChooseOptionMsg(chatID int64) *tgbotapi.MessageConfig {
	msg := tgbotapi.NewMessage(chatID, "Choose option:")
	msg.ReplyMarkup = b.keyboard

	return &msg
}

func NewDate(t time.Time) time.Time {
	return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
}