~badt/glavar

glavar/user.go -rw-r--r-- 7.6 KiB
6a19d38eIan P Badtrousers fthinoporo: multicore batching 5 months ago
                                                                                
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
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/bluele/gcache"
	"github.com/pkg/errors"
	"github.com/sethvargo/go-retry"
	tele "gopkg.in/tucnak/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 {
	Body    string `json:"body"`
	Created int    `json:"created"`
	ID      int    `json:"id"`
	User    User   `json:"user"`
}

func (m Message) String() string {
	return fmt.Sprintf("[%d@%s>%s]%d", m.ID, m.User.Login, m.Body)
}

func (u *User) logged() bool {
	return u.Csrf != ""
}

var lepra, _ = url.Parse("https://leprosorium.ru")

func (u *User) outbound() *http.Client {
	client := &http.Client{}
	client.Jar, _ = cookiejar.New(nil)
	client.Jar.SetCookies(lepra, 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 {
	key := u.Login + "\n\n" + message
	value, err := rates.Get(key)
	if err == gcache.KeyNotFoundError {
		value = 0
		rates.SetWithExpire(key, 0, rateWindow)
	}
	rate := value.(int) + 1
	rates.Set(key, rate)
	if rate > 5 {
		_, err := bot.Send(u.T, ratelimitCue)
		return err
	}

	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() {
			c := context.Background()
			fib, _ := retry.NewFibonacci(100 * time.Millisecond)
			dt := retry.WithMaxDuration(1*time.Minute, fib)

			retry.Do(c, dt, func(c context.Context) error {
				resp, err := client.PostForm(path, pf)
				if err != nil {
					return retry.RetryableError(err)
				}
				return resp.Body.Close()
			})
		}()
		return err
	}
	resp.Body.Close()
	return nil
}

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(u *User, subsite string) {
		for range time.NewTicker(5 * time.Second).C {
			err = u.poll(subsite)
			if err != nil && err != io.EOF {
				listening[subsite] = false
				pollq <- subsite
				break
			}
		}
	}(u, subsite)
	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 {
		this.LM[subsite] = msg.ID
		body := strings.TrimSpace(msg.Body)
		if len(body) == 0 {
			continue
		}
		body = strings.ReplaceAll(body, "\n", " ")

		author := msg.User.Login

		// the message itself
		key := author + "\n" + body
		value, err := rates.Get(key)
		if err == gcache.KeyNotFoundError {
			value = 0
		}
		rate := value.(int) + 1
		rates.SetWithExpire(key, rate, rateWindow)
		if rate > 3 {
			continue
		}

		// and now its entities
		var noshow, nopreview bool
		urls := regularURL.FindAllString(body, -1)
		for _, url := range urls {
			value, err := rates.Get(url)
			if err == gcache.KeyNotFoundError {
				value = 0
			}
			rate := value.(int) + 1
			rates.SetWithExpire(url, rate, rateWindow)
			if rate > 3 {
				nopreview = true
			}
			if rate > 5 {
				noshow = true
				break
			}
		}
		if noshow {
			continue
		}

		for id, u := range this.Cunts {
			if u.Login == author || u.Subsite != subsite {
				continue
			}
			_, err = black.Get(u.Login + "~" + author)
			if err != gcache.KeyNotFoundError {
				continue
			}

			personal := u.personal(body)

			opts := &tele.SendOptions{
				DisableWebPagePreview: nopreview,
				DisableNotification:   !personal,
			}

			body := ø(cue, author, body)
			msg, err := bot.Send(u.T, body, opts)
			if err != nil {
				if err == tele.ErrBlockedByUser {
					delete(this.Cunts, 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
}