-
Notifications
You must be signed in to change notification settings - Fork 908
/
gateway.go
1466 lines (1180 loc) · 38.7 KB
/
gateway.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
// Discordgo - Discord bindings for Go
// Available at https://github.com/bwmarrin/discordgo
// Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file contains low level functions for interacting with the Discord
// data websocket interface.
package discordgo
import (
"bytes"
"compress/zlib"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/botlabs-gg/yagpdb/v2/lib/gojay"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
var (
ErrAlreadyOpen = errors.New("connection already open")
)
type GatewayIntent int
const (
GatewayIntentGuilds GatewayIntent = 1 << 0
// - GUILD_CREATE
// - GUILD_UPDATE
// - GUILD_DELETE
// - GUILD_ROLE_CREATE
// - GUILD_ROLE_UPDATE
// - GUILD_ROLE_DELETE
// - CHANNEL_CREATE
// - CHANNEL_UPDATE
// - CHANNEL_DELETE
// - CHANNEL_PINS_UPDATE
GatewayIntentGuildMembers GatewayIntent = 1 << 1
// - GUILD_MEMBER_ADD
// - GUILD_MEMBER_UPDATE
// - GUILD_MEMBER_REMOVE
GatewayIntentGuildBans GatewayIntent = 1 << 2
// - GUILD_BAN_ADD
// - GUILD_BAN_REMOVE
GatewayIntentGuildEmojis GatewayIntent = 1 << 3
// - GUILD_EMOJIS_UPDATE
GatewayIntentGuildIntegrations GatewayIntent = 1 << 4
// - GUILD_INTEGRATIONS_UPDATE
GatewayIntentGuildWebhooks GatewayIntent = 1 << 5
// - WEBHOOKS_UPDATE
GatewayIntentGuildInvites GatewayIntent = 1 << 6
// - INVITE_CREATE
// - INVITE_DELETE
GatewayIntentGuildVoiceStates GatewayIntent = 1 << 7
// - VOICE_STATE_UPDATE
GatewayIntentGuildPresences GatewayIntent = 1 << 8
// - PRESENCE_UPDATE
GatewayIntentGuildMessages GatewayIntent = 1 << 9
// - MESSAGE_CREATE
// - MESSAGE_UPDATE
// - MESSAGE_DELETE
// - MESSAGE_DELETE_BULK
GatewayIntentGuildMessageReactions GatewayIntent = 1 << 10
// - MESSAGE_REACTION_ADD
// - MESSAGE_REACTION_REMOVE
// - MESSAGE_REACTION_REMOVE_ALL
// - MESSAGE_REACTION_REMOVE_EMOJI
GatewayIntentGuildMessageTyping GatewayIntent = 1 << 11
// - TYPING_START
GatewayIntentDirectMessages GatewayIntent = 1 << 12
// - CHANNEL_CREATE
// - MESSAGE_CREATE
// - MESSAGE_UPDATE
// - MESSAGE_DELETE
// - CHANNEL_PINS_UPDATE
GatewayIntentDirectMessageReactions GatewayIntent = 1 << 13
// - MESSAGE_REACTION_ADD
// - MESSAGE_REACTION_REMOVE
// - MESSAGE_REACTION_REMOVE_ALL
// - MESSAGE_REACTION_REMOVE_EMOJI
GatewayIntentDirectMessageTyping GatewayIntent = 1 << 14
// - TYPING_START
GatewayIntentMessageContent GatewayIntent = 1 << 15
GatewayIntentGuildScheduledEvents GatewayIntent = 1 << 16
GatewayIntentAutomoderationExecution GatewayIntent = 1 << 21
// - AUTO_MODERATION_ACTION_EXECUTION
GatewayIntentAutomoderationConfiguration GatewayIntent = 1 << 20
// - AUTO_MODERATION_RULE_CREATE
// - AUTO_MODERATION_RULE_UPDATE
// - AUTO_MODERATION_RULE_DELETE
)
// max size of buffers before they're discarded (e.g after a big incmoing event)
const MaxIntermediaryBuffersSize = 10000
// GatewayIdentifyRatelimiter is if you need some custom identify ratelimit logic (if you're running shards across processes for example)
type GatewayIdentifyRatelimiter interface {
RatelimitIdentify(shardID int) // Called whenever an attempted identify is made, can be called from multiple goroutines at the same time
}
// Standard implementation of the GatewayIdentifyRatelimiter
type StdGatewayIdentifyRatleimiter struct {
ch chan bool
once sync.Once
}
func (rl *StdGatewayIdentifyRatleimiter) RatelimitIdentify(shardID int) {
rl.once.Do(func() {
rl.ch = make(chan bool)
go func() {
ticker := time.NewTicker(time.Second * 5)
for {
rl.ch <- true
<-ticker.C
}
}()
})
<-rl.ch
}
// This is used at the package level because it can be used by multiple sessions
// !! Changing this after starting 1 or more gateway sessions will lead to undefined behaviour
var IdentifyRatelimiter GatewayIdentifyRatelimiter = &StdGatewayIdentifyRatleimiter{}
// GatewayOP represents a gateway operation
// see https://discordapp.com/developers/docs/topics/gateway#gateway-opcodespayloads-gateway-opcodes
type GatewayOP int
const (
GatewayOPDispatch GatewayOP = 0 // (Receive)
GatewayOPHeartbeat GatewayOP = 1 // (Send/Receive)
GatewayOPIdentify GatewayOP = 2 // (Send)
GatewayOPStatusUpdate GatewayOP = 3 // (Send)
GatewayOPVoiceStateUpdate GatewayOP = 4 // (Send)
GatewayOPVoiceServerPing GatewayOP = 5 // (Send)
GatewayOPResume GatewayOP = 6 // (Send)
GatewayOPReconnect GatewayOP = 7 // (Receive)
GatewayOPRequestGuildMembers GatewayOP = 8 // (Send)
GatewayOPInvalidSession GatewayOP = 9 // (Receive)
GatewayOPHello GatewayOP = 10 // (Receive)
GatewayOPHeartbeatACK GatewayOP = 11 // (Receive)
)
type GatewayStatus int
const (
GatewayStatusDisconnected GatewayStatus = iota
GatewayStatusConnecting
GatewayStatusIdentifying
GatewayStatusResuming
GatewayStatusReady
)
func (gs GatewayStatus) String() string {
switch gs {
case GatewayStatusDisconnected:
return "Disconnected"
case GatewayStatusConnecting:
return "Connecting"
case GatewayStatusIdentifying:
return "Identifying"
case GatewayStatusResuming:
return "Resuming"
case GatewayStatusReady:
return "Ready"
}
return "??"
}
// GatewayConnectionManager is responsible for managing the gateway connections for a single shard
// We create a new GatewayConnection every time we reconnect to avoid a lot of synchronization needs
// and also to avoid having to manually reset the connection state, all the workers related to the old connection
// should eventually stop, and if they're late they will be working on a closed connection anyways so it dosen't matter
type GatewayConnectionManager struct {
mu sync.RWMutex
openmu sync.Mutex
voiceConnections map[int64]*VoiceConnection
// stores sessions current Discord Gateway
gateway string
shardCount int
shardID int
session *Session
currentConnection *GatewayConnection
status GatewayStatus
sessionID string
sequence int64
resumeGatewayUrl string
idCounter int
errorStopReconnects error // set when an error occurs that should stop reconnects (such as bad token, and other things)
}
func (s *GatewayConnectionManager) SetSessionInfo(sessionID string, sequence int64, resumeGatewayUrl string) {
s.mu.Lock()
s.sessionID = sessionID
s.sequence = sequence
s.resumeGatewayUrl = resumeGatewayUrl
s.mu.Unlock()
}
func (s *GatewayConnectionManager) GetSessionInfo() (sessionID string, sequence int64, resumeGatewayUrl string) {
s.mu.RLock()
sessionID = s.sessionID
sequence = s.sequence
resumeGatewayUrl = s.resumeGatewayUrl
s.mu.RUnlock()
return
}
// Open is a helper for Session.GatewayConnectionManager.Open()
func (s *Session) Open() error {
return s.GatewayManager.Open()
}
var (
ErrBadAuth = errors.New("authentication failed")
ErrInvalidIntent = errors.New("one of the gateway intents passed was invalid")
ErrDisabledIntent = errors.New("an intent you specified has not been enabled or not been whitelisted for")
ErrInvalidShard = errors.New("you specified a invalid sharding setup")
)
func (g *GatewayConnectionManager) Open() error {
g.session.log(LogInformational, " called")
g.openmu.Lock()
defer g.openmu.Unlock()
g.mu.Lock()
if g.errorStopReconnects != nil {
g.mu.Unlock()
return g.errorStopReconnects
}
if g.currentConnection != nil {
cc := g.currentConnection
g.currentConnection = nil
g.mu.Unlock()
cc.Close()
g.mu.Lock()
}
g.idCounter++
if g.gateway == "" {
gatewayAddr, err := g.session.Gateway()
if err != nil {
g.mu.Unlock()
return err
}
g.gateway = gatewayAddr
}
g.initSharding()
newConn := NewGatewayConnection(g, g.idCounter, g.session.Intents)
// Opening may be a long process, with ratelimiting and whatnot
// we wanna be able to query things like status in the meantime
g.mu.Unlock()
err := newConn.open(g.sessionID, g.sequence, g.resumeGatewayUrl)
g.mu.Lock()
g.currentConnection = newConn
g.session.log(LogInformational, "reconnecting voice connections")
for _, vc := range g.voiceConnections {
go func(voiceConn *VoiceConnection, gwc *GatewayConnectionManager) {
gwc.session.log(LogInformational, "reconnecting voice connection: %d", voiceConn.GuildID)
voiceConn.Lock()
voiceConn.gatewayConn = newConn
voiceConn.Unlock()
}(vc, g)
// go vc.reconnect(newConn)
}
g.mu.Unlock()
return err
}
// initSharding sets the sharding details and verifies that they are valid
func (g *GatewayConnectionManager) initSharding() {
g.shardCount = g.session.ShardCount
if g.shardCount < 1 {
g.shardCount = 1
}
g.shardID = g.session.ShardID
if g.shardID >= g.shardCount || g.shardID < 0 {
g.mu.Unlock()
panic("Invalid shardID: ID:" + strconv.Itoa(g.shardID) + " Count:" + strconv.Itoa(g.shardCount))
}
}
// Status returns the status of the current active connection
func (g *GatewayConnectionManager) Status() GatewayStatus {
cc := g.GetCurrentConnection()
if cc == nil {
return GatewayStatusDisconnected
}
return cc.Status()
}
func (g *GatewayConnectionManager) HeartBeatStats() (lastSend time.Time, lastAck time.Time) {
conn := g.GetCurrentConnection()
if conn == nil {
return
}
lastSend, lastAck = conn.heartbeater.Times()
return
}
func (g *GatewayConnectionManager) RequestGuildMembers(guildID int64, query string, limit int) {
conn := g.GetCurrentConnection()
if conn == nil {
return
}
conn.RequestGuildMembers(&RequestGuildMembersData{
GuildID: guildID,
Query: &query,
Limit: limit,
})
}
func (g *GatewayConnectionManager) RequestGuildMemberByID(guildID int64, query int64, limit int) {
conn := g.GetCurrentConnection()
if conn == nil {
return
}
conn.RequestGuildMembers(&RequestGuildMembersData{
GuildID: guildID,
Limit: limit,
UserIDs: []int64{query},
})
}
func (g *GatewayConnectionManager) RequestGuildMembersComplex(d *RequestGuildMembersData) {
conn := g.GetCurrentConnection()
if conn == nil {
return
}
conn.RequestGuildMembers(d)
}
func (g *GatewayConnectionManager) GetCurrentConnection() *GatewayConnection {
g.mu.RLock()
defer g.mu.RUnlock()
return g.currentConnection
}
type voiceChannelJoinData struct {
GuildID *string `json:"guild_id"`
ChannelID *string `json:"channel_id"`
SelfMute bool `json:"self_mute"`
SelfDeaf bool `json:"self_deaf"`
}
// ChannelVoiceJoin joins the session user to a voice channel.
//
// gID : Guild ID of the channel to join.
// cID : Channel ID of the channel to join.
// mute : If true, you will be set to muted upon joining.
// deaf : If true, you will be set to deafened upon joining.
func (g *GatewayConnectionManager) ChannelVoiceJoin(gID, cID int64, mute, deaf bool) (voice *VoiceConnection, err error) {
g.session.log(LogInformational, "called")
debug.PrintStack()
g.mu.Lock()
voice = g.voiceConnections[gID]
if voice == nil {
voice = &VoiceConnection{
gatewayConnManager: g,
gatewayConn: g.currentConnection,
GuildID: gID,
session: g.session,
Connected: make(chan bool),
LogLevel: g.session.LogLevel,
Debug: g.session.Debug,
}
g.voiceConnections[gID] = voice
}
g.mu.Unlock()
voice.Lock()
voice.ChannelID = cID
voice.deaf = deaf
voice.mute = mute
voice.Unlock()
strGID := StrID(gID)
strCID := StrID(cID)
// Send the request to Discord that we want to join the voice channel
op := outgoingEvent{
Operation: GatewayOPVoiceStateUpdate,
Data: voiceChannelJoinData{&strGID, &strCID, mute, deaf},
}
g.mu.Lock()
if g.currentConnection == nil {
g.mu.Unlock()
return nil, errors.New("bot not connected to gateway")
}
cc := g.currentConnection
g.mu.Unlock()
cc.writer.Queue(op)
// doesn't exactly work perfect yet.. TODO
err = voice.waitUntilConnected()
if err != nil {
cc.log(LogWarning, "error waiting for voice to connect, %s", err)
voice.Close()
// force remove it just incase
g.mu.Lock()
if g.voiceConnections[gID] == voice {
delete(g.voiceConnections, gID)
}
g.mu.Unlock()
return
}
return
}
func (g *GatewayConnectionManager) ChannelVoiceLeave(gID int64) {
g.mu.RLock()
cc := g.currentConnection
g.mu.RUnlock()
if cc == nil {
return
}
strGID := strconv.FormatInt(gID, 10)
data := outgoingEvent{
Operation: GatewayOPVoiceStateUpdate,
Data: voiceChannelJoinData{&strGID, nil, true, true},
}
cc.writer.Queue(data)
}
// onVoiceStateUpdate handles Voice State Update events on the data websocket.
func (g *GatewayConnectionManager) onVoiceStateUpdate(st *VoiceStateUpdate) {
// If we don't have a connection for the channel, don't bother
if st.ChannelID == 0 {
return
}
// Check if we have a voice connection to update
g.mu.Lock()
voice, exists := g.voiceConnections[st.GuildID]
if !exists {
g.mu.Unlock()
return
}
// We only care about events that are about us.
if g.session.State.User.ID != st.UserID {
g.mu.Unlock()
return
}
if st.ChannelID == 0 {
g.session.log(LogInformational, "Deleting VoiceConnection %d", st.GuildID)
delete(g.voiceConnections, st.GuildID)
g.mu.Unlock()
return
}
g.mu.Unlock()
// Store the SessionID for later use.
voice.Lock()
voice.UserID = st.UserID
voice.sessionID = st.SessionID
voice.ChannelID = st.ChannelID
voice.Unlock()
}
// onVoiceServerUpdate handles the Voice Server Update data websocket event.
//
// This is also fired if the Guild's voice region changes while connected
// to a voice channel. In that case, need to re-establish connection to
// the new region endpoint.
func (g *GatewayConnectionManager) onVoiceServerUpdate(st *VoiceServerUpdate) {
g.session.log(LogInformational, "called")
g.mu.RLock()
voice, exists := g.voiceConnections[st.GuildID]
g.mu.RUnlock()
// If no VoiceConnection exists, just skip this
if !exists {
return
}
// If currently connected to voice ws/udp, then disconnect.
// Has no effect if not connected.
voice.Close()
// Store values for later use
voice.Lock()
voice.token = st.Token
voice.endpoint = st.Endpoint
voice.GuildID = st.GuildID
voice.Unlock()
// Open a connection to the voice server
err := voice.open()
if err != nil {
g.session.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
}
}
// Close maintains backwards compatibility with old discordgo versions
// It's the same as s.GatewayManager.Close()
func (s *Session) Close() error {
return s.GatewayManager.Close()
}
func (g *GatewayConnectionManager) Close() (err error) {
g.mu.Lock()
if g.currentConnection != nil {
g.mu.Unlock()
err = g.currentConnection.Close()
g.mu.Lock()
g.currentConnection = nil
}
g.mu.Unlock()
return
}
func (g *GatewayConnectionManager) Reconnect(forceIdentify bool) error {
g.mu.RLock()
currentConn := g.currentConnection
g.mu.RUnlock()
if currentConn != nil {
err := currentConn.Reconnect(forceIdentify)
return err
}
return nil
}
type GatewayConnection struct {
mu sync.Mutex
// The parent manager
manager *GatewayConnectionManager
intents []GatewayIntent
opened bool
workersRunning bool
reconnecting bool
status GatewayStatus
// Stores a mapping of guild id's to VoiceConnections
voiceConnections map[string]*VoiceConnection
// The underlying websocket connection.
conn net.Conn
// stores session ID of current Gateway connection
sessionID string
// stores url to resume connection
resumeGatewayUrl string
// This gets closed when the connection closes to signal all workers to stop
stopWorkers chan interface{}
wsReader *wsutil.Reader
// contains the raw message fragments until we have received them all
readMessageBuffer *bytes.Buffer
zlibReader io.Reader
jsonDecoder *gojay.Decoder
teeReader io.Reader
secondPassJsonDecoder *json.Decoder
secondPassGojayDecoder *gojay.Decoder
secondPassBuf *bytes.Buffer
heartbeater *wsHeartBeater
writer *wsWriter
connID int // A increasing id per connection from the connection manager to help identify the origin of logs
decodedBuffer bytes.Buffer
// so we dont need to re-allocate a event on each event
event *Event
}
func NewGatewayConnection(parent *GatewayConnectionManager, id int, intents []GatewayIntent) *GatewayConnection {
gwc := &GatewayConnection{
manager: parent,
stopWorkers: make(chan interface{}),
readMessageBuffer: bytes.NewBuffer(make([]byte, 0, 0xffff)), // initial 65k buffer
connID: id,
status: GatewayStatusConnecting,
event: &Event{},
secondPassBuf: &bytes.Buffer{},
intents: intents,
}
secondPassJson := json.NewDecoder(gwc.secondPassBuf)
gwc.secondPassJsonDecoder = secondPassJson
gwc.secondPassGojayDecoder = gojay.NewDecoder(gwc.secondPassBuf)
return gwc
}
func (g *GatewayConnection) concurrentReconnect(forceReIdentify bool) {
go func() {
err := g.Reconnect(forceReIdentify)
if err != nil {
g.log(LogError, "failed reconnecting to the gateway: %v", err)
}
}()
}
// Reconnect is a helper for Close() and Connect() and will attempt to resume if possible
func (g *GatewayConnection) Reconnect(forceReIdentify bool) error {
g.mu.Lock()
if g.reconnecting {
g.mu.Unlock()
g.log(LogInformational, "attempted to reconnect to the gateway while already reconnecting")
return nil
}
g.log(LogInformational, "reconnecting to the gateway")
debug.PrintStack()
g.reconnecting = true
if forceReIdentify {
g.sessionID = ""
}
g.mu.Unlock()
err := g.Close()
if err != nil {
return err
}
return g.manager.Open()
}
// ReconnectUnlessStopped will not reconnect if close was called earlier
func (g *GatewayConnection) ReconnectUnlessClosed(forceReIdentify bool) error {
select {
case <-g.stopWorkers:
return nil
default:
return g.Reconnect(forceReIdentify)
}
}
// Close closes the gateway connection
func (g *GatewayConnection) Close() error {
g.mu.Lock()
g.status = GatewayStatusDisconnected
sidCop := g.sessionID
seqCop := atomic.LoadInt64(g.heartbeater.sequence)
// If were not actually connected then do nothing
wasRunning := g.workersRunning
g.workersRunning = false
if g.conn == nil {
if wasRunning {
close(g.stopWorkers)
}
g.mu.Unlock()
g.manager.mu.Lock()
g.manager.sessionID = sidCop
g.manager.sequence = seqCop
g.manager.mu.Unlock()
return nil
}
g.log(LogInformational, "closing gateway connection")
// copy these here to later be assigned to the manager for possible resuming
g.mu.Unlock()
if wasRunning {
// Send the close frame
frame := ws.NewCloseFrame(ws.NewCloseFrameBody(
4000, "o7",
))
frame = ws.MaskFrameInPlace(frame)
compiled := ws.MustCompileFrame(frame)
g.writer.QueueClose(compiled)
close(g.stopWorkers)
started := time.Now()
// Wait for discord to close connnection
for {
time.Sleep(time.Millisecond * 100)
g.mu.Lock()
if g.conn == nil {
g.mu.Unlock()
break
}
// Yes, this actually does happen...
if time.Since(started) > time.Second*5 {
g.log(LogWarning, "dead connection")
g.conn.Close()
g.mu.Unlock()
break
}
g.mu.Unlock()
}
g.mu.Lock()
sidCop = g.sessionID
seqCop = atomic.LoadInt64(g.heartbeater.sequence)
g.mu.Unlock()
g.manager.mu.Lock()
g.manager.sessionID = sidCop
g.manager.sequence = seqCop
g.manager.mu.Unlock()
}
return nil
}
func newUpdateStatusData(activityType ActivityType, statusType Status, statusText, streamingUrl string) *UpdateStatusData {
usd := &UpdateStatusData{
AFK: false,
Status: statusType,
}
now := int(time.Now().Unix())
if statusType == StatusIdle {
usd.IdleSince = &now
}
if statusText != "" {
usd.Activity = &Activity{
Name: statusText,
State: statusText,
Type: activityType,
URL: streamingUrl,
}
}
return usd
}
// UpdateStatus is used to update the user's status.
// Set the custom status to statusText.
// Set the online status to statusType.
func (s *Session) UpdateStatus(activityType ActivityType, statusType Status, statusText, streamingUrl string) (err error) {
if streamingUrl != "" {
activityType = ActivityTypeStreaming
}
return s.UpdateStatusComplex(*newUpdateStatusData(activityType, statusType, statusText, streamingUrl))
}
// UpdatePlayingStatus is used to update the user's playing status.
// Set the game being played to status.
// Set the online status to statusType.
func (s *Session) UpdatePlayingStatus(statusText string, statusType Status) (err error) {
return s.UpdateStatusComplex(*newUpdateStatusData(ActivityTypePlaying, statusType, statusText, ""))
}
// UpdateStreamingStatus is used to update the user's streaming status.
// Set the name of the stream to status.
// Set the online status to statusType.
// Set the stream URL to url.
func (s *Session) UpdateStreamingStatus(statusText string, statusType Status, url string) (err error) {
return s.UpdateStatusComplex(*newUpdateStatusData(ActivityTypeStreaming, statusType, statusText, url))
}
// UpdateListeningStatus is used to update the user's listening status
// Set what the user is listening to to status.
// Set the online status to statusType.
func (s *Session) UpdateListeningStatus(statusText string, statusType Status) (err error) {
return s.UpdateStatusComplex(*newUpdateStatusData(ActivityTypeListening, statusType, statusText, ""))
}
// UpdateWatchingStatus is used to update the user's watching status
// Set what the user is watching to status.
// Set the online status to statusType.
func (s *Session) UpdateWatchingStatus(statusText string, statusType Status) (err error) {
return s.UpdateStatusComplex(*newUpdateStatusData(ActivityTypeWatching, statusType, statusText, ""))
}
// UpdateCustomStatus is used to update the user's custom status
// Set the user's custom text to status.
// Set the online status to statusType.
func (s *Session) UpdateCustomStatus(statusText string, statusType Status) (err error) {
return s.UpdateStatusComplex(*newUpdateStatusData(ActivityTypeCustom, statusType, statusText, ""))
}
// UpdateCompetingStatus is used to update the user's competing status
// Set what the user is competing in to status.
// Set the online status to statusType.
func (s *Session) UpdateCompetingStatus(statusText string, statusType Status) (err error) {
return s.UpdateStatusComplex(*newUpdateStatusData(ActivityTypeCompeting, statusType, statusText, ""))
}
func (s *Session) UpdateStatusComplex(usd UpdateStatusData) (err error) {
curConn := s.GatewayManager.GetCurrentConnection()
if curConn == nil {
return errors.New("no gateway connection")
}
curConn.UpdateStatusComplex(usd)
return nil
}
// UpdateStatusComplex allows for sending the raw status update data untouched by discordgo.
func (g *GatewayConnection) UpdateStatusComplex(usd UpdateStatusData) {
g.writer.Queue(outgoingEvent{Operation: GatewayOPStatusUpdate, Data: usd})
}
// Status returns the current status of the connection
func (g *GatewayConnection) Status() (st GatewayStatus) {
g.mu.Lock()
st = g.status
g.mu.Unlock()
return
}
// Connect connects to the discord gateway and starts handling frames
func (g *GatewayConnection) open(sessionID string, sequence int64, resumeGatewayUrl string) error {
g.mu.Lock()
if g.opened {
g.mu.Unlock()
return ErrAlreadyOpen
}
var conn net.Conn
var err error
for {
gatewayUrl := g.manager.gateway
// if this is an intended resume, use the resume gateway url provided by discord
if sessionID != "" && resumeGatewayUrl != "" {
gatewayUrl = resumeGatewayUrl
}
conn, _, _, err = ws.Dial(context.TODO(), gatewayUrl+"?v="+APIVersion+"&encoding=json&compress=zlib-stream")
if err != nil {
if conn != nil {
conn.Close()
}
g.log(LogError, "Failed opening connection to the gateway, retrying in 5 seconds: %v", err)
time.Sleep(time.Second * 5)
continue
}
break
}
g.log(LogInformational, "Connected to the gateway websocket")
go g.manager.session.handleEvent(connectEventType, &Connect{})
g.conn = conn
g.opened = true
g.wsReader = wsutil.NewClientSideReader(conn)
err = g.startWorkers()
if err != nil {
return err
}
g.sessionID = sessionID
g.mu.Unlock()
if sessionID == "" {
return g.identify()
} else {
g.heartbeater.UpdateSequence(sequence)
return g.resume(sessionID, sequence)
}
}
// startWorkers starts the background workers for reading, receiving and heartbeating
func (g *GatewayConnection) startWorkers() error {
// The writer
writerWorker := newWSWriter(g.conn, g.manager.session, g.stopWorkers)
g.writer = writerWorker
go writerWorker.Run()
// The heartbeater, this is started after we receive hello
g.heartbeater = &wsHeartBeater{
stop: g.stopWorkers,
writer: g.writer,
receivedAck: true,
sequence: new(int64),
onNoAck: func() {
if g.conn == nil {
return
}
g.log(LogError, "No heartbeat ack received since sending last heartbeast, reconnecting... ip: %s", g.conn.RemoteAddr().String())
err := g.ReconnectUnlessClosed(false)
if err != nil {
g.log(LogError, "Failed reconnecting to the gateway: %v", err)
}
},
}
// Start the event reader
go g.reader()
g.workersRunning = true
return nil
}
// reader reads incmoing messages from the gateway
func (g *GatewayConnection) reader() {
// The buffer that is used to read into the bytes buffer
// We need to control the amount read so we can't use buffer.ReadFrom directly
// TODO: write it directly into the bytes buffer somehow to avoid a uneeded copy?
intermediateBuffer := make([]byte, 0xffff)
for {
header, err := g.wsReader.NextFrame()
if err != nil {
g.readerError(err, "error reading next gateway message: %v", err)
return
}
for readAmount := int64(0); readAmount < header.Length; {