-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
1643 lines (1540 loc) · 44.9 KB
/
group.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 chadango
import (
"context"
"fmt"
"math/rand"
"strconv"
"strings"
"time"
"github.com/rs/zerolog/log"
)
// Group represents a chat group with various properties and state.
type Group struct {
App *Application // Reference to the application.
Name string // The name of the group.
AnonName string // The anonymous user name format.
NameColor string // The color for displaying name in the message.
TextColor string // The color for displaying text in the message.
TextFont string // The font style for displaying text in the message.
TextSize int // The font size for displaying text in the message.
WsUrl string // The WebSocket URL for connecting to the group.
ws *WebSocket // The WebSocket connection to the group.
Connected bool // Indicates if the group is currently connected.
events chan string // Channel for propagating events back to the listener.
takeOver chan context.Context // Channel for taking over the WebSocket connection.
backoff *Backoff // Cancelable backoff for reconnection.
context context.Context // Context for running the group operations.
cancelCtx context.CancelFunc // Function for stopping group operations.
Version [2]int // The version of the group.
Owner string // The owner of the group.
SessionID string // The session ID for the group.
LoggedIn bool // Indicates if the user is logged in to the group.
LoginName string // The login name of the user.
LoginTime time.Time // The time when the user logged in.
TimeDiff time.Duration // The time difference between the server and client.
LoginIp string // The IP address of the user.
Moderators SyncMap[string, int64] // Map of moderators and their access levels.
Flag int64 // The flag value for the group.
Channel int64 // The channel flag of the group.
Restrict time.Time // The time when the group is restricted from the flood ban and auto moderation.
RateLimit time.Duration // The rate limit duration for sending messages.
RateLimited time.Time // The time when the group is rate-limited.
MaxMessageLength int // The maximum allowed length of a message.
PremiumExpireAt time.Time // The time when the premium membership expires.
Messages OrderedSyncMap[string, *Message] // Ordered map of messages history in the group.
TempMessages SyncMap[string, *Message] // Map of temporary messages in the group.
TempMessageIds SyncMap[string, string] // Map of temporary message IDs in the group.
Participants SyncMap[string, *Participant] // Map of participants in the group. Invoke `g.GetParticipantsStart` to initiate the participant feeds.
ParticipantCount int64 // The total count of participants in the group.
UserCount int // The count of registered users in the group.
AnonCount int // The count of anonymous users in the group.
}
func (g *Group) initFields() {
g.Moderators = NewSyncMap[string, int64]()
g.Messages = NewOrderedSyncMap[string, *Message]()
g.TempMessages = NewSyncMap[string, *Message]()
g.TempMessageIds = NewSyncMap[string, string]()
g.Participants = NewSyncMap[string, *Participant]()
}
// Connect establishes a connection to the server.
// It returns an error if the connection cannot be established.
func (g *Group) Connect(ctx context.Context) (err error) {
if g.Connected {
return ErrAlreadyConnected
}
g.context, g.cancelCtx = context.WithCancel(ctx)
err = g.connect()
if err != nil {
g.cancelCtx()
}
g.Connected = true
return
}
func (g *Group) connect() (err error) {
log.Debug().Str("Name", g.Name).Msg("Connecting")
defer func() {
if err != nil {
g.ws.Close()
log.Debug().Str("Name", g.Name).Msg("Connect failed")
}
}()
g.ws = &WebSocket{
OnError: g.wsOnError,
}
if err = g.ws.Connect(g.WsUrl); err != nil {
return
}
// Initializing channels.
g.events = make(chan string, EVENT_BUFFER_SIZE)
g.takeOver = make(chan context.Context)
var frame string
// This may not be necessary, but oh well, let's just do it anyway.
if err = g.Send("v", "\x00"); err != nil {
return
}
if frame, err = g.ws.Recv(); err != nil {
return
}
if !strings.HasPrefix(frame, "v") {
return ErrInvalidResponse
}
g.events <- frame
// Attempting to login to the group chat.
if g.LoggedIn {
err = g.Send("bauth", g.Name, g.App.Config.SessionID, g.App.Config.Username, g.App.Config.Password, "\x00")
} else {
err = g.Send("bauth", g.Name, g.App.Config.SessionID, g.App.Config.Username, "", "\x00")
}
if err != nil {
return
}
if frame, err = g.ws.Recv(); err != nil {
return
}
if head, _, ok := strings.Cut(frame, ":"); ok && head != "ok" {
return ErrLoginFailed
}
g.events <- frame
g.ws.Sustain(g.context)
go g.listen()
log.Debug().Str("Name", g.Name).Msg("Connected")
return
}
// listen listens for incoming messages and events on the WebSocket connection.
func (g *Group) listen() {
var frame string
var release context.Context
for {
select {
case <-g.context.Done():
return
case frame = <-g.events:
if frame == EndFrame {
return
}
go g.wsOnFrame(frame)
case frame = <-g.ws.Events:
if frame == EndFrame {
return
}
go g.wsOnFrame(frame)
case release = <-g.takeOver:
inner:
for {
select {
case <-g.context.Done():
return
case <-release.Done():
break inner
case frame = <-g.events:
if frame == EndFrame {
return
}
go g.wsOnFrame(frame)
}
}
}
}
}
// Disconnect gracefully closes the connection to the server.
func (g *Group) Disconnect() {
if g.backoff != nil {
g.backoff.Cancel()
}
if !g.Connected {
return
}
g.Connected = false
g.cancelCtx()
g.ws.Close()
}
// Reconnect attempts to reconnect to the server.
func (g *Group) Reconnect() (err error) {
g.ws.Close()
g.backoff = &Backoff{
Duration: BASE_BACKOFF_DUR,
MaxDuration: MAX_BACKOFF_DUR,
}
defer func() {
g.backoff = nil
}()
for retries := 0; retries < MAX_RETRIES && !g.backoff.Sleep(g.context); retries++ {
if err = g.connect(); err == nil {
return
}
}
// Either canceled or reached the maximum retries.
return ErrRetryEnds
}
// Send will join the `args` with a ":" separator and then send it to the server asynchronously.
func (g *Group) Send(args ...string) error {
if !g.ws.Connected {
return ErrNotConnected
}
length := len(args)
if length == 0 {
return ErrNoArgument
}
// The terminator should be appended without a separator.
// Valid terminator: \r\n, \x00
terminator := args[length-1]
args = args[:length-1]
command := strings.Join(args, ":")
return g.ws.Send(command + terminator)
}
// SyncSend will send the `args` and wait until receiving the correct reply or until timeout.
// First, a `g.takeOver` request will be made and it will wait until the listener goroutine catches it.
// Then, the `args` will be sent to the server.
// Each time a frame is received, the `callback` function is invoked and passed the frame.
// The `callback` should return `true` if a correct frame is acquired, and `false` otherwise.
func (g *Group) SyncSendWithTimeout(callback func(string) bool, timeout time.Duration, args ...string) (err error) {
ctx, cancel := context.WithTimeout(g.context, timeout)
defer cancel()
// Make a takeover request to allow the listener to relinquish the connection.
select {
case <-ctx.Done():
return ErrTimeout
case g.takeOver <- ctx:
}
if err = g.Send(args...); err != nil {
return
}
var frame string
for {
select {
case <-ctx.Done():
return ErrTimeout
case frame = <-g.ws.Events:
if frame == EndFrame {
g.events <- frame
return ErrConnectionClosed
}
if strings.HasPrefix(frame, "climited") {
// This response is received when messages are being sent too quickly.
// I believe this applies globally to any type of command sent to the server,
// not limited to sending messages alone.
// If it turns out to be correct, move this `climited` check to the `SyncSend` method.
// climited:1485666967794:bm:e8n2:0:<n000/><f x9000="1">n
return ErrCLimited
}
if callback(frame) {
return
}
}
}
}
// SyncSend will send the `args` and wait until receiving the correct reply or until timeout (default to 5 seconds).
// For more information, refer to the documentation of `g.SyncSendWithTimeout`.
func (g *Group) SyncSend(cb func(string) bool, text ...string) error {
return g.SyncSendWithTimeout(cb, SYNC_SEND_TIMEOUT, text...)
}
// SendMessage sends the `text` and returns the sent `*Message`.
// In case of an error, including flood ban, auto moderation, rate limit,
// as well as login, proxy, and verification restrictions, the corresponding error will be returned.
func (g *Group) SendMessage(text string) (msg *Message, err error) {
// The received "b" and "u" frames should be returned to `g.Events`.
var idBuffer = map[string]string{}
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "b":
g.events <- frame
fields := strings.SplitN(data, ":", 5)
if msg == nil && fields[3] == g.SessionID[:8] {
message := ParseGroupMessage(data, g)
if !message.User.IsSelf {
return false
}
msg = message
if newID, ok := idBuffer[message.ID]; ok {
message.ID = newID
return true
}
}
case "u":
g.events <- frame
oldID, newID, _ := strings.Cut(data, ":")
if msg != nil && msg.ID == oldID {
msg.ID = newID
return true
}
idBuffer[oldID] = newID
case "show_fw":
g.eventRestrictUpdate(data)
err = ErrFloodWarning
return true
case "show_tb", "tb":
g.eventRestrictUpdate(data)
err = ErrRestricted
return true
case "show_nlp":
if mask, _ := strconv.Atoi(data); mask&2 == 2 {
err = ErrSpamWarning
} else if mask&8 == 8 {
err = ErrShortWarning
} else {
err = ErrNonSenseWarning
}
return true
case "show_nlp_tb":
// The first data in the fields is unknown, so let's leave it as it is for now.
// show_nlp_tb:3:900
_, min, _ := strings.Cut(data, ":")
g.eventRestrictUpdate(min)
err = ErrRestricted
return true
case "nlptb":
g.eventRestrictUpdate(data)
err = ErrRestricted
return true
case "msglexceeded":
g.MaxMessageLength, _ = strconv.Atoi(data)
err = ErrMessageLength
return true
case "ratelimited":
dur, _ := time.ParseDuration(data + "s")
g.RateLimited = time.Now().Add(dur)
err = ErrRateLimited
return true
case "mustlogin":
err = ErrMustLogin
return true
case "proxybanned":
err = ErrProxyBanned
return true
case "verificationrequired":
err = ErrVerificationRequired
default:
// Send the frame back to the listener.
g.events <- frame
}
return false
}
// I'm not sure what it is for, but it gets sent back to the client when `climited` occurs.
// randomString := GenerateRandomString(4)
randomString := strconv.FormatInt(int64(15e5*rand.Float64()), 36)
// Style thing
if g.LoggedIn {
text = fmt.Sprintf(`<n%s/><f x%02d%s="%s">%s`, g.NameColor, g.TextSize, g.TextColor, g.TextFont, text)
} else {
// It would look nicer if it were wrapped in a separate method.
if g.AnonName == "" {
g.AnonName = "anon0001"
}
// Same as above, the anonymous seed should not be recalculated for each message sending.
text = fmt.Sprintf(`<n%s/>%s`, CreateAnonSeed(g.AnonName, g.SessionID[:8]), text)
}
// Replacing newlines with the `<br/>` tag.
text = strings.ReplaceAll(text, "\r\n", "<br/>")
text = strings.ReplaceAll(text, "\n", "<br/>")
err = g.SyncSend(cb, "bm", randomString, fmt.Sprintf("%d", g.Channel), text, "\r\n")
return
}
// SendMessage sends the chunked `text` with a size of `chunkSize` and returns the sent `[]*Message`.
// In the event of an error, the already sent messages will be returned along with the error for the unsent message.
func (g *Group) SendMessageChunked(text string, chunkSize int) (msgs []*Message, err error) {
var msg *Message
for _, chunk := range SplitTextIntoChunks(text, chunkSize) {
if msg, err = g.SendMessage(chunk); err != nil {
return
}
msgs = append(msgs, msg)
}
return
}
// IsRestricted checks if the group is restricted.
// The restriction can originate from either a flood ban or a rate limit.
func (g *Group) IsRestricted() bool {
return g.Restrict.After(time.Now()) || g.RateLimited.After(time.Now())
}
// GetParticipantsStart initiates the `participant` event feeds and returns the current participants.
// The `participant` event will be triggered when there is user activity, such as joining, logging out, logging in, or leaving.
func (g *Group) GetParticipantsStart() (p *SyncMap[string, *Participant], err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "gparticipants":
g.Participants.Clear()
anoncount, entries, _ := strings.Cut(data, ":")
g.AnonCount, _ = strconv.Atoi(anoncount)
var fields []string
var user *User
var t time.Time
var ts string
var participant *Participant
for _, entry := range strings.Split(entries, ";") {
fields = strings.SplitN(entry, ":", 6)
if fields[3] != "None" {
user = &User{Name: fields[3]}
} else if fields[4] != "None" {
user = &User{Name: fields[4], IsAnon: true}
} else {
ts = strings.Split(fields[1], ".")[0]
user = &User{Name: GetAnonName(ts[len(ts)-4:], fields[2]), IsAnon: true}
}
user.IsSelf = fields[2] == g.SessionID[:8] && user.Name == g.LoginName
t, _ = ParseTime(fields[1])
participant = &Participant{
ParticipantID: fields[0],
ID: fields[2],
User: user,
Time: t,
}
g.Participants.Set(fields[0], participant)
}
p = &g.Participants
g.UserCount = g.Participants.Len()
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "gparticipants", "\r\n")
return
}
// GetParticipantsStop stops the participant event feeds.
// This will leave g.Participants, g.UserCount, g.AnonCount out of date.
func (g *Group) GetParticipantsStop() error {
return g.Send("gparticipants", "stop", "\r\n")
}
// GetRateLimit retrieves the rate limit settings for the group.
func (g *Group) GetRateLimit() (rate, current time.Duration, err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "getratelimit":
r, c, _ := strings.Cut(data, ":")
rate, _ = time.ParseDuration(r + "s")
g.RateLimit = rate
current, _ := time.ParseDuration(c + "s")
g.RateLimited = time.Now().Add(current)
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "getratelimit", "\r\n")
return
}
// SetRateLimit sets the rate limit interval for the group.
func (g *Group) SetRateLimit(interval time.Duration) (rate time.Duration, err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "ratelimitset":
rate, _ = time.ParseDuration(data + "s")
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "setratelimit", fmt.Sprintf("%.0f", interval.Seconds()), "\r\n")
return
}
// GetAnnouncement retrieves the announcement settings for the group.
func (g *Group) GetAnnouncement() (annc string, enabled bool, interval time.Duration, err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "getannc":
fields := strings.SplitN(data, ":", 6)
annc = fields[4]
enabled = fields[0] != "0"
interval, _ = time.ParseDuration(fields[3] + "s")
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "getannouncement", "\r\n")
return
}
// SetAnnouncement sets the announcement settings for the group.
func (g *Group) SetAnnouncement(annc string, enable bool, interval time.Duration) (err error) {
ena := "0"
if enable {
ena = "1"
}
err = g.Send("updateannouncement", ena, fmt.Sprintf("%.0f", interval.Seconds()), "\r\n")
return
}
// UpdateGroupFlag updates the group's flag by adding and removing specific flags.
func (g *Group) UpdateGroupFlag(addition, removal int64) (err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "groupflagstoggled":
fields := strings.SplitN(data, ":", 3)
/* addition, _ := strconv.ParseInt(fields[0], 10, 64)
removal, _ := strconv.ParseInt(fields[1], 10, 64)
status, _ := strconv.Atoi(fields[2]) */
if fields[2] != "1" {
err = ErrUpdateFailed
}
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "updategroupflags", fmt.Sprintf("%d:%d", addition, removal), "\r\n")
return
}
// GetPremiumInfo retrieves the premium status and expiration time for the group.
// This function would activate server validation for the premium status.
// For example, the message background and media won't activate before this command is sent.
func (g *Group) GetPremiumInfo() (flag int, expire time.Time, err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "premium":
fl, ti, _ := strings.Cut(data, ":")
flag, _ = strconv.Atoi(fl)
expire, _ = ParseTime(ti)
g.PremiumExpireAt = expire
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "getpremium", "\r\n")
return
}
// SetBackground sets the background status of the group.
// If enable is true, it enables the background feature for the group.
// If enable is false, it disables the background feature for the group.
func (g *Group) SetBackground(enable bool) (err error) {
if enable {
if g.PremiumExpireAt.IsZero() {
if _, g.PremiumExpireAt, err = g.GetPremiumInfo(); err != nil {
return
}
}
if g.PremiumExpireAt.Before(time.Now()) {
return ErrPremiumExpired
}
return g.Send("msgbg", "1", "\r\n")
}
return g.Send("msgbg", "0", "\r\n")
}
// SetMedia sets the media status of the group.
// If enable is true, it enables the media feature for the group.
// If enable is false, it disables the media feature for the group.
func (g *Group) SetMedia(enable bool) (err error) {
if enable {
if g.PremiumExpireAt.IsZero() {
if _, g.PremiumExpireAt, err = g.GetPremiumInfo(); err != nil {
return
}
}
if g.PremiumExpireAt.Before(time.Now()) {
return ErrPremiumExpired
}
return g.Send("msgmedia", "1", "\r\n")
}
return g.Send("msgmedia", "0", "\r\n")
}
// GetBanList retrieves a list of blocked users (ban list) for the group.
// The offset can be set to zero time to retrieve the newest result.
// The returned order is from newer to older.
func (g *Group) GetBanList(offset time.Time, ammount int) (banList []Blocked, err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "blocklist":
var fields []string
var t time.Time
var banned Blocked
for _, entry := range strings.Split(data, ";") {
fields = strings.SplitN(entry, ":", 5)
t, _ = ParseTime(fields[3])
banned = Blocked{
IP: fields[1],
ModerationID: fields[0],
Target: fields[2],
Blocker: fields[4],
Time: t,
}
banList = append(banList, banned)
}
return true
default:
g.events <- frame
}
return false
}
offsetS := fmt.Sprintf("%d", offset.Unix())
ammountS := fmt.Sprintf("%d", ammount)
err = g.SyncSend(cb, "blocklist", "block", offsetS, "next", ammountS, "anons", "1", "\r\n")
return
}
// SearchBannedUser searches for a banned user in the group's ban list.
// The query can be either a user name or an IP address.
func (g *Group) SearchBannedUser(query string) (banned Blocked, ok bool) {
query = strings.TrimSpace(query)
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "bansearchresult":
fields := strings.SplitN(data, ":", 6)
// It would be nicer to use a constant rather than a naked string.
t, _ := time.Parse("2006-01-02 15:04:05", fields[5])
banned = Blocked{
IP: fields[2],
ModerationID: fields[3],
Target: fields[1],
Blocker: fields[4],
Time: t,
}
ok = true
return true
case "badbansearchstring":
// Simply return an empty result.
return true
default:
g.events <- frame
}
return false
}
g.SyncSend(cb, "searchban", query, "\r\n")
return
}
// GetUnbanList retrieves a list of unblocked users (unban list) for the group.
// The `offset` is taken from the earliest time in the previous result or zero `time.Time`.
// The `amount` corresponds to the desired number of results.
func (g *Group) GetUnbanList(offset time.Time, ammount int) (unbanList []Unblocked, err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "unblocklist":
var fields []string
var t time.Time
var unbanned Unblocked
for _, entry := range strings.Split(data, ";") {
fields = strings.SplitN(entry, ":", 5)
t, _ = ParseTime(fields[3])
unbanned = Unblocked{
IP: fields[1],
ModerationID: fields[0],
Target: fields[2],
Unblocker: fields[4],
Time: t,
}
unbanList = append(unbanList, unbanned)
}
return true
default:
g.events <- frame
}
return false
}
offsetS := fmt.Sprintf("%d", offset.Unix())
ammountS := fmt.Sprintf("%d", ammount)
err = g.SyncSend(cb, "blocklist", "unblock", offsetS, "next", ammountS, "anons", "1", "\r\n")
return
}
// Login logs in to the group with the provided username and password.
// If the password is an empty string, it will log in as the named anon instead.
func (g *Group) Login(username, password string) (err error) {
cb := func(frame string) bool {
head, _, _ := strings.Cut(frame, ":")
switch head {
case "badalias":
// badalias:8 (reserved for anons)
err = ErrBadAlias
return true
case "aliasok":
g.LoginName = username
return true
case "badlogin":
// badlogin:2 (wrong password)
err = ErrBadLogin
return true
case "pwdok":
g.LoginName = username
g.LoggedIn = true
return true
default:
g.events <- frame
}
return false
}
if password != "" {
err = g.SyncSend(cb, "blogin", username, password, "\r\n")
} else {
err = g.SyncSend(cb, "blogin", username, "\r\n")
}
return
}
// Logout logs out from the group.
func (g *Group) Logout() (err error) {
cb := func(frame string) bool {
head, _, _ := strings.Cut(frame, ":")
switch head {
case "logoutok":
if access, ok := g.Moderators.Get(strings.ToLower(g.LoginName)); ok && access > 0 {
// If the used account was a moderator, reload it.
defer func() {
g.Messages.Clear()
g.TempMessages.Clear()
g.TempMessageIds.Clear()
g.Moderators.Clear()
g.Send("reload_init_batch", "\r\n")
}()
}
seed := fmt.Sprintf("%d", g.LoginTime.Unix())
g.LoginName = GetAnonName(seed[len(seed)-4:], g.SessionID[:8])
g.LoggedIn = false
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "blogout", "\r\n")
return
}
// GetBanWords retrieves the banned word settings for the group.
func (g *Group) GetBanWords() (banWord BanWord, err error) {
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "bw":
partial, exact, _ := strings.Cut(data, ":")
banWord = BanWord{WholeWords: exact, Words: partial}
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "getbannedwords", "\r\n")
return
}
// SetBanWords sets the banned word settings for the group.
func (g *Group) SetBanWords(banWord BanWord) (err error) {
cb := func(frame string) bool {
head, _, _ := strings.Cut(frame, ":")
switch head {
case "ubw":
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "\x00setbannedwords", banWord.Words, banWord.WholeWords, "\r\n")
return
}
// Delete deletes the specified message from the group.
func (g *Group) Delete(message *Message) (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "delete":
g.events <- frame
if data == message.ID {
return true
}
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "delmsg", message.ID, "\r\n")
return
}
// DeleteAll deletes all messages in the group.
func (g *Group) DeleteAll(message *Message) (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "deleteall":
g.events <- frame
for _, messageID := range strings.Split(data, ":") {
if messageID == message.ID {
return true
}
}
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "delallmsg", message.ModerationID, message.UserIP, message.User.Name, "\r\n")
return
}
// ClearAll clears all messages in the group.
func (g *Group) ClearAll() (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "clearall":
g.events <- frame
if data == "error" {
err = ErrClearFailed
}
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "clearall", "\r\n")
return
}
// BanUser bans the user associated with the specified message.
func (g *Group) BanUser(message *Message) (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "blocked":
g.events <- frame
moderationID, _, _ := strings.Cut(data, ":")
if moderationID == message.ModerationID {
return true
}
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "block", message.ModerationID, message.UserIP, message.User.Name, "\r\n")
return
}
// UnbanUser unblocks the specified blocked user.
func (g *Group) UnbanUser(blocked *Blocked) (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "unblocked":
g.events <- frame
moderationID, _, _ := strings.Cut(data, ":")
if moderationID == blocked.ModerationID {
return true
}
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "removeblock", blocked.ModerationID, blocked.IP, "\r\n")
return
}
// UnbanAll unblocks all blocked users.
func (g *Group) UnbanAll() (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, _, _ := strings.Cut(frame, ":")
switch head {
case "allunblocked":
// allunblocked:2 (length of unblocked users)
g.events <- frame
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "unbanall", "\r\n")
return
}
// AddModerator adds a moderator to the group with the specified username and access level.
func (g *Group) AddModerator(username string, access int64) (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "mods":
g.events <- frame
var uname string
for _, entry := range strings.Split(data, ":") {
uname, _, _ = strings.Cut(entry, ",")
if strings.EqualFold(uname, username) {
return true
}
}
err = ErrAddModFailed
return true
case "addmoderr":
err = ErrAddModFailed
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "addmod", username, fmt.Sprintf("%d", access), "\r\n")
return
}
// UpdateModerator updates the access level of the specified moderator.
func (g *Group) UpdateModerator(username string, access int64) (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {
case "mods":
g.events <- frame
var uname, flag string
var flagInt int64
for _, entry := range strings.Split(data, ":") {
uname, flag, _ = strings.Cut(entry, ",")
flagInt, _ = strconv.ParseInt(flag, 10, 64)
if strings.EqualFold(uname, username) && flagInt == access {
return true
}
}
case "updatemoderr":
err = ErrUpdateModFailed
return true
default:
g.events <- frame
}
return false
}
err = g.SyncSend(cb, "addmod", username, fmt.Sprintf("%d", access), "\r\n")
return
}
// RemoveModerator removes the specified moderator from the group.
func (g *Group) RemoveModerator(username string) (err error) {
// The received frame should be returned to `g.Events`.
cb := func(frame string) bool {
head, data, _ := strings.Cut(frame, ":")
switch head {