-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommands.go
321 lines (297 loc) · 7.82 KB
/
commands.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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"
)
// Need to implement
// /save custom card for practice
// /modify
type PracticeType int
const (
// answer should match exact word
// FIXME: FIXME: FIXME: FIXME: This doesn't work!!!!!!!!
// cannot save obfuscated - cannot check.
// cannot save clear - cannot extract raw from obfuscated.
// this need fixing - make sure repetition_test passes.
PracticeWordSpelling PracticeType = iota
// answer of the form know/don't know
PracticeKnowledge
)
const UsePractice = PracticeKnowledge
var (
SupportedInputLanguages = map[string]Settings{
"Hungarian": Settings{
InputLanguage: "Hungarian",
InputLanguageISO639_3: "hun",
TranslationLanguages: map[string]bool{
"eng": true,
"rus": true,
"ukr": true,
},
},
"English": Settings{
InputLanguage: "English",
InputLanguageISO639_3: "eng",
TranslationLanguages: map[string]bool{
"rus": true,
"ukr": true,
},
},
"German": Settings{
InputLanguage: "German",
InputLanguageISO639_3: "deu",
TranslationLanguages: map[string]bool{
"eng": true,
"rus": true,
"ukr": true,
},
},
}
TimeZones = func() map[string]bool {
timeZones := make(map[string]bool)
for i := -12; i < 12; i++ {
timeZones[fmt.Sprintf("UTC%+d", i)] = true
}
timeZones["UTC"] = true
return timeZones
}()
)
type CallbackAction int
const (
SaveWordAction CallbackAction = iota
PracticeKnowAction
PracticeDontKnowAction
PracticeDontKnowActionNoPractice
)
// Make sure all fields are Public, otherwise encoding will not work
// TODO: Should include ID to make sure the same action is not performed many
// times? In general should keep track of different IDs to make sure that stuff
// is not processed more than once?
type CallbackInfo struct {
Action CallbackAction
// One of below is set depending on the action.
Word string
Setting string
}
// FIXME: Should return an error?
func CallbackInfoFromString(s string) CallbackInfo {
var c CallbackInfo
if err := json.Unmarshal([]byte(s), &c); err != nil {
panic(err)
}
return c
}
func (c CallbackInfo) String() string {
m, err := json.Marshal(c)
if err != nil {
panic(err)
}
return string(m)
}
type Commander struct {
*Clients
bot *Bot
}
type CommanderOptions struct {
useCache bool
dbPath string
port int
certPath string
keyPath string
ip string
push bool
stages []time.Duration
}
func escapeMarkdown(s string) string {
r := strings.NewReplacer(
"_", "\\_",
"*", "\\*",
"[", "\\[",
"]", "\\]",
"(", "\\(",
")", "\\)",
"~", "\\~",
"`", "\\`",
">", "\\>",
"#", "\\#",
"+", "\\+",
"-", "\\-",
"=", "\\=",
"|", "\\|",
"{", "\\{",
"}", "\\}",
".", "\\.",
"!", "\\!",
)
return r.Replace(s)
}
func NewCommander(tm *Telegram, opts *CommanderOptions) (*Commander, error) {
hc := &http.Client{}
var cache DefCacheInterface
if opts.useCache {
var err error
cache, err = NewDefCache(opts.dbPath)
if err != nil {
return nil, fmt.Errorf("new cache(%q): %w", opts.dbPath, err)
}
} else {
cache = &NoCache{}
}
// TODO: Can use errgroup if there is a need to paralelize. This is the
// slowest step in initialization.
uf, err := NewUsageFetcher(opts.dbPath)
if err != nil {
return nil, fmt.Errorf("creating usage fetcher: %w", err)
}
sc, err := NewSettingsConfig(opts.dbPath)
if err != nil {
return nil, fmt.Errorf("creating settings config: %w", err)
}
d := &Definer{
usage: uf,
cache: cache,
http: hc,
}
r, err := NewRepetition(opts.dbPath, opts.stages)
if err != nil {
return nil, err
}
c := &Clients{
Telegram: tm,
Definer: d,
Repetitions: r,
Settings: sc,
}
// Make sure that telegram client is setup correctly
raw := json.RawMessage{}
if err := tm.Call("getMe", nil, &raw); err != nil {
return nil, err
}
log.Printf("getMe: %s", string(raw))
return &Commander{
Clients: c,
bot: &Bot{
state: &State{c},
command: make(map[int64]Command),
},
}, nil
}
// Update processes the user's update and spit out output.
// Should return an error only on unrecoverable errors due to which we cannot
// continue execution.
// TODO: Use answerCallbackQuery to notify client that callback was processed?
func (c *Commander) Update(u *Update) error {
err := c.bot.Update(u)
if err != nil {
// Not sure what to do otherwise, but crashing isn't nice.
log.Printf("INTENAL ERROR for update %v: %v", u, err)
}
return nil
}
func (c *Commander) PollAndProcess() error {
// TODO: Push instead of Poll
updates, err := c.Telegram.Poll()
if err != nil {
return err
}
log.Printf("updates: %v", updates)
if len(updates) > 0 {
log.Printf("sample message: %v", updates[0].Message)
}
// query:
// for definitions: https://ertelmezo.oszk.hu/kereses.php?kereses=dal
// for wiktionary:
// for translation:
// Don't display more than x for each source.
// After that:
// memoization (ask questions and check prob show definition & then check), storage (start with something simple to use word -> definition).
for _, u := range updates {
if err := c.Update(u); err != nil {
return err
}
}
return nil
}
func (c *Commander) handleUpdate(req *http.Request) error {
if req.Method != "POST" {
return fmt.Errorf("want POST; got %s", req.Method)
}
b := new(bytes.Buffer)
if _, err := b.ReadFrom(req.Body); err != nil {
return fmt.Errorf("reading body of req %v: %v", req, err)
}
var update Update
if err := json.Unmarshal(b.Bytes(), &update); err != nil {
return fmt.Errorf("json.Unmarshal(%q): %w", b.String(), err)
}
return c.Update(&update)
}
func (c *Commander) WebhookCallback(w http.ResponseWriter, req *http.Request) {
if err := c.handleUpdate(req); err != nil {
log.Printf("INTERNAL ERROR[Webhook]: %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
w.WriteHeader(http.StatusOK)
}
func (c *Commander) StartPush(opts *CommanderOptions) error {
addr := fmt.Sprintf("https://%s:%d/%s", opts.ip, opts.port, BotToken)
if err := c.Telegram.SetWebhook(addr, opts.certPath); err != nil {
return err
}
c.Telegram.LogWebhookInfo()
mux := http.NewServeMux()
mux.HandleFunc("/"+BotToken, c.WebhookCallback)
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
}
srv := &http.Server{
Addr: fmt.Sprintf(":%d", opts.port),
Handler: mux,
TLSConfig: cfg,
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
}
log.Printf("Starting serving on %s", addr)
return srv.ListenAndServeTLS(opts.certPath, opts.keyPath)
}
// TODO: Accept time.Ticker channel -> Will give an ability to inline
// PollAndProcess and test Start in addition to the rest.
func (c *Commander) StartPoll() error {
// Reset webhook, otherwise getUpdates would not work!
if err := c.Telegram.SetWebhook("", ""); err != nil {
return err
}
c.Telegram.LogWebhookInfo()
for {
if err := c.PollAndProcess(); err != nil {
return err
}
time.Sleep(time.Second * 3)
}
}