-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
388 lines (342 loc) · 7.94 KB
/
user.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"math/rand"
"mime/multipart"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/pkg/errors"
"github.com/sethvargo/go-retry"
tele "gopkg.in/telebot.v3"
)
type User struct {
T *tele.User `json:"tele"`
ID int `json:"id"`
Active int `json:"active"`
Deleted int `json:"deleted"`
Karma int `json:"karma"`
Login string `json:"login"`
City string `json:"city"`
Gender string `json:"gender"`
Csrf string `json:"csrf_token"`
Subsite string `json:"subsite"`
Keywords []string `json:"keys"`
Jar []*http.Cookie `json:"jar"`
}
type Message struct {
User User `json:"user"`
ID int `json:"id"`
Body string `json:"body"`
Created int64 `json:"created"`
}
func (m Message) String() string {
return ø("%d <%s> %s", m.ID, m.User.Login, m.Body)
}
func (u *User) logged() bool {
return u.Csrf != ""
}
func (u *User) outbound() *http.Client {
var lepraURL, _ = url.Parse("https://leprosorium.ru")
client := &http.Client{}
client.Jar, _ = cookiejar.New(nil)
client.Jar.SetCookies(lepraURL, u.Jar)
return client
}
func (u *User) api(path string, subsite string) string {
if subsite != "" {
subsite += "."
}
return "https://" + subsite + "leprosorium.ru" + path
}
func (u *User) login(password string) error {
path := u.api("/ajax/auth/login/", "")
form := map[string]string{
"username": u.Login,
"password": password,
"g-recaptcha-response": "",
}
pf := url.Values{}
for k, v := range form {
pf.Add(k, v)
}
resp, err := (&http.Client{}).PostForm(path, pf)
if err != nil {
return err
}
defer resp.Body.Close()
csrf := &struct {
Status string `json:"status"`
Token string `json:"csrf_token"`
}{}
err = json.NewDecoder(resp.Body).Decode(csrf)
if err != nil {
return errors.Wrap(err, "csrf could not be decoded")
}
if csrf.Status != "OK" {
return errors.New("NOT OK")
}
u.Csrf = csrf.Token
u.Jar = resp.Cookies()
return nil
}
func (u *User) broadcast(message string) error {
h, rate := H(message, u.Login), 1
if v, err := rates.Get(h); err != expired {
rate += v.(int)
}
rates.SetWithExpire(h, rate, rateWindow)
if rate > 3 {
return ErrOutboundSpam
}
if rate > 2 && u.T != nil {
bot.Send(u.T, ratelimitCue)
}
path := u.api("/ajax/chat/add/", u.Subsite)
form := map[string]string{
"last": strconv.Itoa(this.Lm[u.Subsite]),
"csrf_token": u.Csrf,
"body": message,
}
pf := url.Values{}
for k, v := range form {
pf.Add(k, v)
}
client := u.outbound()
resp, err := client.PostForm(path, pf)
if err != nil {
// best intentions
go func() {
bo := backoff(100*time.Millisecond, time.Minute)
retry.Do(nil, bo, func(_ context.Context) error {
resp, err := client.PostForm(path, pf)
if err != nil {
return retry.RetryableError(err)
}
return resp.Body.Close()
})
}()
return err
}
return resp.Body.Close()
}
func (u *User) personal(text string) bool {
for _, keyword := range append(u.Keywords, u.Login) {
if strings.Index(text, keyword) >= 0 {
return true
}
}
return false
}
func (u *User) primo(subsite string) error {
if !listening[subsite] && !u.subsiteExists(subsite) {
return ErrNotFound
}
err := u.poll(subsite)
if err != nil {
return err
}
go func() {
for range time.NewTicker(polly).C {
err = u.poll(subsite)
if err != nil && err != io.EOF {
listening[subsite] = false
pollq <- subsite
break
}
}
}()
listening[subsite] = true
return nil
}
func (u *User) poll(subsite string) error {
defer save()
path := u.api("/ajax/chat/load/", subsite)
form := map[string]string{
"last_message_id": strconv.Itoa(this.Lm[subsite]),
"csrf_token": u.Csrf,
}
pf := url.Values{}
for k, v := range form {
pf.Add(k, v)
}
resp, err := u.outbound().PostForm(path, pf)
if err != nil {
return err
}
defer resp.Body.Close()
var schema struct {
Messages []Message `json:"messages"`
Err []struct {
Code string `json:"code"`
} `json:"errors,omitempty"`
}
err = json.NewDecoder(resp.Body).Decode(&schema)
if err != nil {
return errors.Wrap(err, "updates could not be decoded")
}
if schema.Err != nil {
code := schema.Err[0].Code
if code == "not_authorized" {
return ErrForbidden
}
return errors.New("exotic api error: " + code)
}
for _, msg := range schema.Messages {
// let's push things forward
this.Lm[subsite] = msg.ID
var (
sender = msg.User.Login
body = msg.Body
)
body = strings.ReplaceAll(body, "\n", " ")
body = strings.ReplaceAll(body, "\u00a0", " ")
body = linkrx.ReplaceAllString(body, "$1")
body = strings.TrimSpace(body)
if utf8.RuneCountInString(body) == 0 {
continue
}
msg.Body = body
h, rate := H(sender, body), 1
if v, err := rates.Get(h); err != expired {
rate += v.(int)
}
rates.SetWithExpire(h, rate, rateWindow)
if rate > 3 {
continue
}
// and now the entities
var noshow, nopreview bool
for _, url := range urlrx.FindAllString(body, -1) {
h, rate := H(url), 1
if v, err := rates.Get(url); err != expired {
rate += v.(int)
}
rates.SetWithExpire(h, rate, rateWindow)
if rate > 1 {
nopreview = true
}
if rate > 3 {
noshow = true
break
}
}
if subsite == "" {
logiq <- msg
rand.Seed(time.Now().Unix())
for _, model := range this.Models {
// don't engage with itself
if model.User.Login == sender {
continue
}
// only 20% of messages re-engage other models
if ismodel(sender) && rand.Float32() > 0.2 {
continue
}
// final filter: 5% engagement for nonpersonal
if !model.personal(body) || rand.Float32() > 0.05 {
continue
}
model.feed(sender, body)
}
}
if noshow {
continue
}
for id, u := range this.Users {
if u.Login == sender || u.Subsite != subsite {
continue
}
h := H(u.Login, sender)
if _, err = rates.Get(h); err != expired {
continue
}
personal := u.personal(body)
opts := &tele.SendOptions{
DisableWebPagePreview: nopreview,
DisableNotification: !personal,
}
body := ø(cue, sender, body)
msg, err := bot.Send(u.T, body, opts)
if err != nil {
if err == tele.ErrBlockedByUser {
delete(this.Users, id)
continue
}
// retry
msg, err = bot.Send(u.T, body, opts)
if err != nil {
continue
}
}
if personal {
bot.Pin(msg)
}
}
}
return nil
}
func (u *User) upload(c tele.Context, f string, r io.Reader) (string, error) {
const path = "https://idiod.video/api/upload.php"
var b bytes.Buffer
w := multipart.NewWriter(&b)
fw, _ := w.CreateFormFile("file", f)
if _, err := io.Copy(fw, r); err != nil {
return "", c.Reply(ø(errorCue, err))
}
w.Close()
req, err := http.NewRequest("POST", path, &b)
if err != nil {
return "", c.Reply(ø(errorCue, err))
}
req.Header.Set("Content-Type", w.FormDataContentType())
resp, err := u.outbound().Do(req)
if err != nil {
// retry
<-time.After(15 * time.Second)
resp, err = u.outbound().Do(req)
if err != nil {
return "", c.Reply(ø(errorCue, err))
}
}
defer resp.Body.Close()
var payload struct {
Status string `json:"status"`
Hash string `json:"hash"`
URL string `json:"url"`
Filetype string `json:"filetype"`
DeleteCode string `json:"delete_code"`
DeleteURL string `json:"delete_url"`
}
err = json.NewDecoder(resp.Body).Decode(&payload)
if err != nil {
return "", c.Reply(ø(errorCue, err))
}
if payload.Status != "ok" {
return "", c.Reply(ø(errorCue, payload))
}
return "https://idiod.video/" + payload.URL, nil
}
func (u *User) subsiteExists(subsite string) bool {
if subsite == "" {
return true
}
path := "https://" + subsite + ".leprosorium.ru"
client := u.outbound()
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
resp, err := client.Get(path)
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode == 200
}