-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.go
2341 lines (2170 loc) · 72.1 KB
/
main.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"crypto/tls"
"database/sql"
"encoding/json"
"errors"
"flag"
"fmt"
"html"
"image"
"io/ioutil"
"math/rand"
"net"
"net/http"
"os"
"os/signal"
"path"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"text/template"
"time"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/bcmk/go-smtpd/smtpd"
"github.com/bcmk/siren/lib"
"github.com/bcmk/siren/payments"
tg "github.com/bcmk/telegram-bot-api"
"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3"
)
var (
checkErr = lib.CheckErr
lerr = lib.Lerr
linf = lib.Linf
ldbg = lib.Ldbg
)
type tplData = map[string]interface{}
type timeDiff struct {
Days int
Hours int
Minutes int
Seconds int
Nanoseconds int
}
type notification struct {
id int
endpoint string
chatID int64
modelID string
status lib.StatusKind
timeDiff *int
imageURL string
social bool
sound bool
priority int
kind packetKind
}
type model struct {
modelID string
status lib.StatusKind
}
type statusChange struct {
modelID string
status lib.StatusKind
timestamp int
}
type statRequest struct {
endpoint string
writer http.ResponseWriter
request *http.Request
done chan bool
}
type ipnRequest struct {
writer http.ResponseWriter
request *http.Request
done chan bool
}
type queryDurationsData struct {
avg float64
count int
}
type user struct {
chatID int64
maxModels int
reports int
blacklist bool
showImages bool
offlineNotifications bool
}
type subscription struct {
chatID int64
modelID string
endpoint string
}
type worker struct {
clients []*lib.Client
bots map[string]*tg.BotAPI
db *sql.DB
cfg *config
httpQueriesDuration time.Duration
updatesDuration time.Duration
cleaningDuration time.Duration
changesInPeriod int
confirmedChangesInPeriod int
ourOnline map[string]bool
specialModels map[string]bool
siteStatuses map[string]statusChange
siteOnline map[string]bool
tr map[string]*lib.Translations
tpl map[string]*template.Template
trAds map[string]map[string]*lib.Translation
tplAds map[string]*template.Template
modelIDPreprocessing func(string) string
checker lib.Checker
unsuccessfulRequests []bool
unsuccessfulRequestsPos int
downloadResults chan bool
downloadErrors []bool
downloadResultsPos int
nextErrorReport time.Time
coinPaymentsAPI *payments.CoinPaymentsAPI
mailTLS *tls.Config
durations map[string]queryDurationsData
images map[string]string
botNames map[string]string
lowPriorityMsg chan outgoingPacket
highPriorityMsg chan outgoingPacket
outgoingMsgResults chan msgSendResult
unconfirmedSubsResults chan lib.StatusResults
onlineModelsChan chan lib.StatusUpdateResults
sendingNotifications chan []notification
sentNotifications chan []notification
mainGID int
ourIDs []int64
modelIDRegexp *regexp.Regexp
}
type incomingPacket struct {
message tg.Update
endpoint string
}
type outgoingPacket struct {
message baseChattable
endpoint string
requested time.Time
kind packetKind
}
type packetKind int
const (
notificationPacket packetKind = 0
replyPacket packetKind = 1
adPacket packetKind = 2
messagePacket packetKind = 3
)
type email struct {
chatID int64
endpoint string
email string
}
type appliedKind int
const (
invalidReferral appliedKind = iota
followerExists
referralApplied
)
const (
messageSent = 200
messageBadRequest = 400
messageBlocked = 403
messageTooManyRequests = 429
messageUnknownError = -1
messageUnknownNetworkError = -2
messageTimeout = -3
messageMigrate = -4
messageChatNotFound = -5
)
type msgSendResult struct {
priority int
timestamp int
result int
endpoint string
chatID int64
delay int
kind packetKind
}
type waitingUser struct {
chatID int64
endpoint string
}
func newWorker(args []string) *worker {
if len(args) != 1 {
panic("usage: siren <config>")
}
cfg := readConfig(args[0])
var err error
var mailTLS *tls.Config
if cfg.Mail != nil && cfg.Mail.Certificate != "" {
mailTLS, err = loadTLS(cfg.Mail.Certificate, cfg.Mail.CertificateKey)
checkErr(err)
}
var clients []*lib.Client
for _, address := range cfg.SourceIPAddresses {
clients = append(clients, lib.HTTPClientWithTimeoutAndAddress(cfg.TimeoutSeconds, address, cfg.EnableCookies))
}
telegramClient := lib.HTTPClientWithTimeoutAndAddress(cfg.TelegramTimeoutSeconds, "", false)
bots := make(map[string]*tg.BotAPI)
for n, p := range cfg.Endpoints {
//noinspection GoNilness
var bot *tg.BotAPI
bot, err = tg.NewBotAPIWithClient(p.BotToken, tg.APIEndpoint, telegramClient.Client)
checkErr(err)
bots[n] = bot
}
db, err := sql.Open("sqlite3", cfg.DBPath)
checkErr(err)
tr, tpl := lib.LoadAllTranslations(trsByEndpoint(cfg))
trAds, tplAds := lib.LoadAllAds(trsAdsByEndpoint(cfg))
for _, t := range tpl {
template.Must(t.New("affiliate_link").Parse(cfg.AffiliateLink))
}
w := &worker{
bots: bots,
db: db,
cfg: cfg,
clients: clients,
tr: tr,
tpl: tpl,
trAds: trAds,
tplAds: tplAds,
unsuccessfulRequests: make([]bool, cfg.errorDenominator),
downloadErrors: make([]bool, cfg.errorDenominator),
downloadResults: make(chan bool),
mailTLS: mailTLS,
durations: map[string]queryDurationsData{},
images: map[string]string{},
botNames: map[string]string{},
lowPriorityMsg: make(chan outgoingPacket, 10000),
highPriorityMsg: make(chan outgoingPacket, 10000),
outgoingMsgResults: make(chan msgSendResult),
unconfirmedSubsResults: make(chan lib.StatusResults),
onlineModelsChan: make(chan lib.StatusUpdateResults),
sendingNotifications: make(chan []notification, 1000),
sentNotifications: make(chan []notification),
mainGID: gid(),
ourIDs: cfg.getOurIDs(),
}
if cp := cfg.CoinPayments; cp != nil {
w.coinPaymentsAPI = payments.NewCoinPaymentsAPI(cp.PublicKey, cp.PrivateKey, "https://"+cp.IPNListenURL, cfg.TimeoutSeconds, cfg.Debug)
}
switch cfg.Website {
case "test":
w.checker = &lib.RandomChecker{}
w.modelIDPreprocessing = lib.CanonicalModelID
w.modelIDRegexp = lib.ModelIDRegexp
case "bongacams":
w.checker = &lib.BongaCamsChecker{}
w.modelIDPreprocessing = lib.CanonicalModelID
w.modelIDRegexp = lib.ModelIDRegexp
case "chaturbate":
w.checker = &lib.ChaturbateChecker{}
w.modelIDPreprocessing = lib.ChaturbateCanonicalModelID
w.modelIDRegexp = lib.ModelIDRegexp
case "stripchat":
w.checker = &lib.StripchatChecker{}
w.modelIDPreprocessing = lib.CanonicalModelID
w.modelIDRegexp = lib.ModelIDRegexp
case "livejasmin":
w.checker = &lib.LiveJasminChecker{}
w.modelIDPreprocessing = lib.CanonicalModelID
w.modelIDRegexp = lib.ModelIDRegexp
case "camsoda":
w.checker = &lib.CamSodaChecker{}
w.modelIDPreprocessing = lib.CanonicalModelID
w.modelIDRegexp = lib.ModelIDRegexp
case "flirt4free":
w.checker = &lib.Flirt4FreeChecker{}
w.modelIDPreprocessing = lib.Flirt4FreeCanonicalModelID
w.modelIDRegexp = lib.ModelIDRegexp
case "streamate":
w.checker = &lib.StreamateChecker{}
w.modelIDPreprocessing = lib.CanonicalModelID
w.modelIDRegexp = lib.ModelIDRegexp
case "twitch":
w.checker = &lib.TwitchChecker{}
w.modelIDPreprocessing = lib.TwitchCanonicalModelID
w.modelIDRegexp = lib.TwitchModelIDRegexp
default:
panic("wrong website")
}
return w
}
func trsByEndpoint(cfg *config) map[string][]string {
result := make(map[string][]string)
for k, v := range cfg.Endpoints {
result[k] = v.Translation
}
return result
}
func trsAdsByEndpoint(cfg *config) map[string][]string {
result := map[string][]string{}
for k, v := range cfg.Endpoints {
result[k] = v.Ads
}
return result
}
func (w *worker) setWebhook() {
for n, p := range w.cfg.Endpoints {
linf("setting webhook for endpoint %s...", n)
if p.WebhookDomain == "" {
continue
}
if p.CertificatePath == "" {
var _, err = w.bots[n].SetWebhook(tg.NewWebhook(path.Join(p.WebhookDomain, p.ListenPath)))
checkErr(err)
} else {
var _, err = w.bots[n].SetWebhook(tg.NewWebhookWithCert(path.Join(p.WebhookDomain, p.ListenPath), p.CertificatePath))
checkErr(err)
}
info, err := w.bots[n].GetWebhookInfo()
checkErr(err)
if info.LastErrorDate != 0 {
linf("last webhook error time: %v", time.Unix(int64(info.LastErrorDate), 0))
}
if info.LastErrorMessage != "" {
linf("last webhook error message: %s", info.LastErrorMessage)
}
linf("OK")
}
}
func (w *worker) removeWebhook() {
for n := range w.cfg.Endpoints {
linf("removing webhook for endpoint %s...", n)
_, err := w.bots[n].RemoveWebhook()
checkErr(err)
linf("OK")
}
}
func (w *worker) initBotNames() {
for n := range w.cfg.Endpoints {
user, err := w.bots[n].GetMe()
checkErr(err)
linf("bot name for endpoint %s: %s", n, user.UserName)
w.botNames[n] = user.UserName
}
}
func (w *worker) setCommands() {
for n := range w.cfg.Endpoints {
text := templateToString(w.tpl[n], w.tr[n].RawCommands.Key, nil)
lines := strings.Split(text, "\n")
var commands []tg.BotCommand
for _, l := range lines {
pair := strings.SplitN(l, "-", 2)
if len(pair) != 2 {
checkErr(fmt.Errorf("unexpected command pair %q", l))
}
pair[0], pair[1] = strings.TrimSpace(pair[0]), strings.TrimSpace(pair[1])
commands = append(commands, tg.BotCommand{Command: pair[0], Description: pair[1]})
if w.cfg.Debug {
ldbg("command %s - %s", pair[0], pair[1])
}
}
linf("setting commands for endpoint %s...", n)
err := w.bots[n].SetMyCommands(commands)
checkErr(err)
linf("OK")
}
}
func (w *worker) sendText(
queue chan outgoingPacket,
endpoint string,
chatID int64,
notify bool,
disablePreview bool,
parse lib.ParseKind,
text string,
kind packetKind,
) {
msg := tg.NewMessage(chatID, text)
msg.DisableNotification = !notify
msg.DisableWebPagePreview = disablePreview
switch parse {
case lib.ParseHTML, lib.ParseMarkdown:
msg.ParseMode = parse.String()
}
w.enqueueMessage(queue, endpoint, &messageConfig{msg}, kind)
}
func (w *worker) sendImage(
queue chan outgoingPacket,
endpoint string,
chatID int64,
notify bool,
parse lib.ParseKind,
text string,
image []byte,
kind packetKind,
) {
fileBytes := tg.FileBytes{Name: "preview", Bytes: image}
msg := tg.NewPhotoUpload(chatID, fileBytes)
msg.Caption = text
msg.DisableNotification = !notify
switch parse {
case lib.ParseHTML, lib.ParseMarkdown:
msg.ParseMode = parse.String()
}
w.enqueueMessage(queue, endpoint, &photoConfig{msg}, kind)
}
func (w *worker) enqueueMessage(queue chan outgoingPacket, endpoint string, msg baseChattable, kind packetKind) {
select {
case queue <- outgoingPacket{endpoint: endpoint, message: msg, requested: time.Now(), kind: kind}:
default:
lerr("the outgoing message queue is full")
}
}
func (w *worker) sender(queue chan outgoingPacket, priority int) {
for packet := range queue {
now := int(time.Now().Unix())
delay := 0
resend:
for {
result := w.sendMessageInternal(packet.endpoint, packet.message)
delay = int(time.Since(packet.requested).Milliseconds())
w.outgoingMsgResults <- msgSendResult{
priority: priority,
timestamp: now,
result: result,
endpoint: packet.endpoint,
chatID: packet.message.baseChat().ChatID,
delay: delay,
kind: packet.kind,
}
switch result {
case messageTimeout:
time.Sleep(1000 * time.Millisecond)
continue resend
case messageUnknownNetworkError:
time.Sleep(1000 * time.Millisecond)
continue resend
case messageTooManyRequests:
time.Sleep(8000 * time.Millisecond)
continue resend
default:
time.Sleep(60 * time.Millisecond)
break resend
}
}
}
}
func (w *worker) sendMessageInternal(endpoint string, msg baseChattable) int {
chatID := msg.baseChat().ChatID
if _, err := w.bots[endpoint].Send(msg); err != nil {
switch err := err.(type) {
case tg.Error:
switch err.Code {
case messageBlocked:
if w.cfg.Debug {
ldbg("cannot send a message, bot blocked")
}
return messageBlocked
case messageTooManyRequests:
if w.cfg.Debug {
ldbg("cannot send a message, too many requests")
}
return messageTooManyRequests
case messageBadRequest:
if err.ResponseParameters.MigrateToChatID != 0 {
if w.cfg.Debug {
ldbg("cannot send a message, group migration")
}
return messageMigrate
}
if err.Message == "Bad Request: chat not found" {
if w.cfg.Debug {
ldbg("cannot send a message, chat not found")
}
return messageChatNotFound
}
lerr("cannot send a message, bad request, code: %d, error: %v", err.Code, err)
return err.Code
default:
lerr("cannot send a message, unknown code: %d, error: %v", err.Code, err)
return err.Code
}
case net.Error:
if err.Timeout() {
if w.cfg.Debug {
ldbg("cannot send a message, timeout")
}
return messageTimeout
}
lerr("cannot send a message, unknown network error")
return messageUnknownNetworkError
default:
lerr("unexpected error type while sending a message to %d, %v", chatID, err)
return messageUnknownError
}
}
return messageSent
}
func templateToString(t *template.Template, key string, data map[string]interface{}) string {
buf := &bytes.Buffer{}
err := t.ExecuteTemplate(buf, key, data)
checkErr(err)
return buf.String()
}
func (w *worker) sendTr(
queue chan outgoingPacket,
endpoint string,
chatID int64,
notify bool,
translation *lib.Translation,
data map[string]interface{},
kind packetKind,
) {
tpl := w.tpl[endpoint]
text := templateToString(tpl, translation.Key, data)
w.sendText(queue, endpoint, chatID, notify, translation.DisablePreview, translation.Parse, text, kind)
}
func (w *worker) sendAdsTr(
queue chan outgoingPacket,
endpoint string,
chatID int64,
notify bool,
translation *lib.Translation,
data map[string]interface{},
) {
tpl := w.tplAds[endpoint]
text := templateToString(tpl, translation.Key, data)
w.sendText(queue, endpoint, chatID, notify, translation.DisablePreview, translation.Parse, text, adPacket)
}
func (w *worker) sendTrImage(
queue chan outgoingPacket,
endpoint string,
chatID int64,
notify bool,
translation *lib.Translation,
data map[string]interface{},
image []byte,
kind packetKind,
) {
tpl := w.tpl[endpoint]
text := templateToString(tpl, translation.Key, data)
w.sendImage(queue, endpoint, chatID, notify, translation.Parse, text, image, kind)
}
func (w *worker) createDatabase(done chan bool) {
linf("creating database if needed...")
for _, prelude := range w.cfg.SQLPrelude {
w.mustExec(prelude)
}
w.mustExec(`create table if not exists schema_version (version integer);`)
w.applyMigrations()
done <- true
}
func (w *worker) initCache() {
start := time.Now()
w.siteStatuses = w.queryLastStatusChanges()
w.siteOnline = w.getLastOnlineModels()
w.ourOnline, w.specialModels = w.queryConfirmedModels()
elapsed := time.Since(start)
linf("cache initialized in %d ms", elapsed.Milliseconds())
}
func (w *worker) getLastOnlineModels() map[string]bool {
res := map[string]bool{}
for k, v := range w.siteStatuses {
if v.status == lib.StatusOnline {
res[k] = true
}
}
return res
}
func (w *worker) confirmationSeconds(status lib.StatusKind) int {
switch status {
case lib.StatusOnline:
return w.cfg.StatusConfirmationSeconds.Online
case lib.StatusOffline:
return w.cfg.StatusConfirmationSeconds.Offline
case lib.StatusDenied:
return w.cfg.StatusConfirmationSeconds.Denied
case lib.StatusNotFound:
return w.cfg.StatusConfirmationSeconds.NotFound
default:
return 0
}
}
func (w *worker) updateStatus(insertStatusChangeStmt, updateLastStatusChangeStmt *sql.Stmt, next statusChange) {
prev := w.siteStatuses[next.modelID]
if next.status != prev.status {
w.mustExecPrepared(insertStatusChange, insertStatusChangeStmt, next.modelID, next.status, next.timestamp)
w.mustExecPrepared(updateLastStatusChange, updateLastStatusChangeStmt, next.modelID, next.status, next.timestamp)
w.siteStatuses[next.modelID] = next
if next.status == lib.StatusOnline {
w.siteOnline[next.modelID] = true
} else {
delete(w.siteOnline, next.modelID)
}
}
}
func (w *worker) confirmStatus(updateModelStatusStmt *sql.Stmt, now int) []string {
all := lib.HashDiffAll(w.ourOnline, w.siteOnline)
var confirmations []string
for _, modelID := range all {
statusChange := w.siteStatuses[modelID]
confirmationSeconds := w.confirmationSeconds(statusChange.status)
durationConfirmed := confirmationSeconds == 0 || statusChange.timestamp == 0 || (now-statusChange.timestamp >= confirmationSeconds)
if durationConfirmed {
if statusChange.status == lib.StatusOnline {
w.ourOnline[modelID] = true
} else {
delete(w.ourOnline, modelID)
}
w.mustExecPrepared(updateModelStatus, updateModelStatusStmt, modelID, statusChange.status)
confirmations = append(confirmations, modelID)
}
}
return confirmations
}
func (w *worker) notifyOfAddResults(queue chan outgoingPacket, notifications []notification, social bool) {
for _, n := range notifications {
data := tplData{"model": n.modelID}
if n.status&(lib.StatusOnline|lib.StatusOffline|lib.StatusDenied) != 0 {
w.sendTr(queue, n.endpoint, n.chatID, false, w.tr[n.endpoint].ModelAdded, data, replyPacket)
} else {
w.sendTr(queue, n.endpoint, n.chatID, false, w.tr[n.endpoint].AddError, data, replyPacket)
}
}
}
func (w *worker) downloadImages(notifications []notification) map[string][]byte {
images := map[string][]byte{}
for _, n := range notifications {
if n.imageURL != "" {
images[n.imageURL] = nil
}
}
for url := range images {
images[url] = w.downloadImage(url)
}
return images
}
func (w *worker) notifyOfStatuses(highPriorityQueue chan outgoingPacket, lowPriorityQueue chan outgoingPacket, notifications []notification) {
images := w.downloadImages(notifications)
for _, n := range notifications {
queue := lowPriorityQueue
if n.priority > 0 {
queue = highPriorityQueue
}
w.notifyOfStatus(queue, n, images[n.imageURL], n.social)
}
}
func (w *worker) trAdsSlice(endpoint string) []*lib.Translation {
var res []*lib.Translation
for _, v := range w.trAds[endpoint] {
res = append(res, v)
}
sort.Slice(res, func(i, j int) bool { return res[i].Key < res[j].Key })
return res
}
func (w *worker) ad(queue chan outgoingPacket, endpoint string, chatID int64) {
trAds := w.trAdsSlice(endpoint)
if len(trAds) == 0 {
return
}
adNum := rand.Intn(len(trAds))
w.sendAdsTr(queue, endpoint, chatID, false, trAds[adNum], nil)
}
func (w *worker) notifyOfStatus(queue chan outgoingPacket, n notification, image []byte, social bool) {
if w.cfg.Debug {
ldbg("notifying of status of the model %s", n.modelID)
}
var timeDiff *timeDiff
if n.timeDiff != nil {
temp := calcTimeDiff(*n.timeDiff)
timeDiff = &temp
}
data := tplData{"model": n.modelID, "time_diff": timeDiff}
switch n.status {
case lib.StatusOnline:
if image == nil {
w.sendTr(queue, n.endpoint, n.chatID, true, w.tr[n.endpoint].Online, data, n.kind)
} else {
w.sendTrImage(queue, n.endpoint, n.chatID, true, w.tr[n.endpoint].Online, data, image, n.kind)
}
case lib.StatusOffline:
w.sendTr(queue, n.endpoint, n.chatID, false, w.tr[n.endpoint].Offline, data, n.kind)
case lib.StatusDenied:
w.sendTr(queue, n.endpoint, n.chatID, false, w.tr[n.endpoint].Denied, data, n.kind)
}
if social && rand.Intn(10) == 0 {
w.ad(queue, n.endpoint, n.chatID)
}
}
func (w *worker) mustUser(chatID int64) (user user) {
user, found := w.user(chatID)
if !found {
checkErr(fmt.Errorf("user not found: %d", chatID))
}
return
}
func (w *worker) showWeek(endpoint string, chatID int64, modelID string) {
if modelID != "" {
w.showWeekForModel(endpoint, chatID, modelID)
return
}
models := w.modelsForChat(endpoint, chatID)
for _, m := range models {
w.showWeekForModel(endpoint, chatID, m)
}
if len(models) == 0 {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].ZeroSubscriptions, nil, replyPacket)
}
}
func (w *worker) showWeekForModel(endpoint string, chatID int64, modelID string) {
modelID = w.modelIDPreprocessing(modelID)
if !w.modelIDRegexp.MatchString(modelID) {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].InvalidSymbols, tplData{"model": modelID}, replyPacket)
return
}
hours, start := w.week(modelID)
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].Week, tplData{
"hours": hours,
"weekday": int(start.UTC().Weekday()),
"model": modelID,
}, replyPacket)
}
func (w *worker) addModel(endpoint string, chatID int64, modelID string, now int) bool {
if modelID == "" {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].SyntaxAdd, nil, replyPacket)
return false
}
modelID = w.modelIDPreprocessing(modelID)
if !w.modelIDRegexp.MatchString(modelID) {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].InvalidSymbols, tplData{"model": modelID}, replyPacket)
return false
}
if w.subscriptionExists(endpoint, chatID, modelID) {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].AlreadyAdded, tplData{"model": modelID}, replyPacket)
return false
}
subscriptionsNumber := w.subscriptionsNumber(endpoint, chatID)
user := w.mustUser(chatID)
if subscriptionsNumber >= user.maxModels {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].NotEnoughSubscriptions, nil, replyPacket)
w.subscriptionUsage(endpoint, chatID, true)
return false
}
var confirmedStatus lib.StatusKind
if w.ourOnline[modelID] {
confirmedStatus = lib.StatusOnline
} else if _, ok := w.siteStatuses[modelID]; ok {
confirmedStatus = lib.StatusOffline
} else if w.maybeModel(modelID) != nil {
confirmedStatus = lib.StatusOffline
} else {
w.mustExec("insert into signals (chat_id, model_id, endpoint, confirmed) values (?,?,?,?)", chatID, modelID, endpoint, false)
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].CheckingModel, nil, replyPacket)
return false
}
w.mustExec("insert into signals (chat_id, model_id, endpoint, confirmed) values (?,?,?,?)", chatID, modelID, endpoint, true)
w.mustExec("insert or ignore into models (model_id, status) values (?,?)", modelID, confirmedStatus)
subscriptionsNumber++
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].ModelAdded, tplData{"model": modelID}, replyPacket)
nots := []notification{{
endpoint: endpoint,
chatID: chatID,
modelID: modelID,
status: confirmedStatus,
timeDiff: w.modelDuration(modelID, now),
social: false,
priority: 1,
kind: replyPacket}}
if subscriptionsNumber >= user.maxModels-w.cfg.HeavyUserRemainder {
w.subscriptionUsage(endpoint, chatID, true)
}
w.storeNotifications(nots)
return true
}
func (w *worker) subscriptionUsage(endpoint string, chatID int64, ad bool) {
subscriptionsNumber := w.subscriptionsNumber(endpoint, chatID)
user := w.mustUser(chatID)
tr := w.tr[endpoint].SubscriptionUsage
if ad {
tr = w.tr[endpoint].SubscriptionUsageAd
}
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, tr,
tplData{
"subscriptions_used": subscriptionsNumber,
"total_subscriptions": user.maxModels,
},
replyPacket)
}
func (w *worker) wantMore(endpoint string, chatID int64) {
w.showReferral(endpoint, chatID)
if w.cfg.CoinPayments == nil || w.cfg.Mail == nil {
return
}
tpl := w.tpl[endpoint]
text := templateToString(tpl, w.tr[endpoint].BuyAd.Key, tplData{
"price": w.cfg.CoinPayments.subscriptionPacketPrice,
"number_of_subscriptions": w.cfg.CoinPayments.subscriptionPacketModelNumber,
})
buttonText := templateToString(tpl, w.tr[endpoint].BuyButton.Key, tplData{
"number_of_subscriptions": w.cfg.CoinPayments.subscriptionPacketModelNumber,
})
buttons := [][]tg.InlineKeyboardButton{{tg.NewInlineKeyboardButtonData(buttonText, "buy")}}
keyboard := tg.NewInlineKeyboardMarkup(buttons...)
msg := tg.NewMessage(chatID, text)
msg.ReplyMarkup = keyboard
w.enqueueMessage(w.highPriorityMsg, endpoint, &messageConfig{msg}, replyPacket)
}
func (w *worker) settings(endpoint string, chatID int64) {
subscriptionsNumber := w.subscriptionsNumber(endpoint, chatID)
user := w.mustUser(chatID)
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].Settings, tplData{
"subscriptions_used": subscriptionsNumber,
"total_subscriptions": user.maxModels,
"show_images": user.showImages,
"offline_notifications_supported": w.cfg.OfflineNotifications,
"offline_notifications": user.offlineNotifications,
}, replyPacket)
}
func (w *worker) enableImages(endpoint string, chatID int64, showImages bool) {
w.mustExec("update users set show_images=? where chat_id=?", showImages, chatID)
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].OK, nil, replyPacket)
}
func (w *worker) enableOfflineNotifications(endpoint string, chatID int64, offlineNotifications bool) {
w.mustExec("update users set offline_notifications=? where chat_id=?", offlineNotifications, chatID)
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].OK, nil, replyPacket)
}
func (w *worker) removeModel(endpoint string, chatID int64, modelID string) {
if modelID == "" {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].SyntaxRemove, nil, replyPacket)
return
}
modelID = w.modelIDPreprocessing(modelID)
if !w.modelIDRegexp.MatchString(modelID) {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].InvalidSymbols, tplData{"model": modelID}, replyPacket)
return
}
if !w.subscriptionExists(endpoint, chatID, modelID) {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].ModelNotInList, tplData{"model": modelID}, replyPacket)
return
}
w.mustExec("delete from signals where chat_id=? and model_id=? and endpoint=?", chatID, modelID, endpoint)
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].ModelRemoved, tplData{"model": modelID}, replyPacket)
}
func (w *worker) sureRemoveAll(endpoint string, chatID int64) {
w.mustExec("delete from signals where chat_id=? and endpoint=?", chatID, endpoint)
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].AllModelsRemoved, nil, replyPacket)
}
func (w *worker) buy(endpoint string, chatID int64) {
var buttons [][]tg.InlineKeyboardButton
for _, c := range w.cfg.CoinPayments.Currencies {
buttons = append(buttons, []tg.InlineKeyboardButton{tg.NewInlineKeyboardButtonData(c, "buy_with "+c)})
}
user := w.mustUser(chatID)
keyboard := tg.NewInlineKeyboardMarkup(buttons...)
tpl := w.tpl[endpoint]
text := templateToString(tpl, w.tr[endpoint].SelectCurrency.Key, tplData{
"dollars": w.cfg.CoinPayments.subscriptionPacketPrice,
"number_of_subscriptions": w.cfg.CoinPayments.subscriptionPacketModelNumber,
"total_subscriptions": user.maxModels + w.cfg.CoinPayments.subscriptionPacketModelNumber,
})
msg := tg.NewMessage(chatID, text)
msg.ReplyMarkup = keyboard
w.enqueueMessage(w.highPriorityMsg, endpoint, &messageConfig{msg}, replyPacket)
}
func (w *worker) buyWith(endpoint string, chatID int64, currency string) {
found := false
for _, c := range w.cfg.CoinPayments.Currencies {
if currency == c {
found = true
break
}
}
if !found {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].UnknownCurrency, nil, replyPacket)
return
}
email := w.email(endpoint, chatID)
localID := uuid.New()
transaction, err := w.coinPaymentsAPI.CreateTransaction(w.cfg.CoinPayments.subscriptionPacketPrice, currency, email, localID.String())
if err != nil {
w.sendTr(w.highPriorityMsg, endpoint, chatID, false, w.tr[endpoint].TryToBuyLater, nil, replyPacket)
lerr("create transaction failed, %v", err)
return
}
kind := "coinpayments"
timestamp := int(time.Now().Unix())
w.mustExec(`
insert into transactions (
status,
kind,
local_id,
chat_id,
remote_id,
timeout,
amount,
address,
dest_tag,
status_url,
checkout_url,
timestamp,
model_number,
currency,
endpoint)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
payments.StatusCreated,
kind,
localID,
chatID,
transaction.TXNID,
transaction.Timeout,
transaction.Amount,
transaction.Address,
transaction.DestTag,
transaction.StatusURL,