2020-04-25 02:36:33 +00:00
|
|
|
//
|
|
|
|
// For the brave souls who get this far: You are the chosen ones,
|
|
|
|
// the valiant knights of programming who toil away, without rest,
|
|
|
|
// fixing our most awful code. To you, true saviors, kings of men,
|
|
|
|
// I say this: never gonna give you up, never gonna let you down,
|
|
|
|
// never gonna run around and desert you. Never gonna make you cry,
|
|
|
|
// never gonna say goodbye. Never gonna tell a lie and hurt you.
|
|
|
|
//
|
|
|
|
|
|
|
|
package voicegateway
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2020-07-29 20:10:48 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2020-10-28 22:39:59 +00:00
|
|
|
"github.com/diamondburned/arikawa/v2/discord"
|
|
|
|
"github.com/diamondburned/arikawa/v2/internal/moreatomic"
|
|
|
|
"github.com/diamondburned/arikawa/v2/utils/json"
|
|
|
|
"github.com/diamondburned/arikawa/v2/utils/wsutil"
|
2020-04-25 02:36:33 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// Version represents the current version of the Discord Gateway Gateway this package uses.
|
|
|
|
Version = "4"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrNoSessionID = errors.New("no sessionID was received")
|
|
|
|
ErrNoEndpoint = errors.New("no endpoint was received")
|
|
|
|
)
|
|
|
|
|
2020-11-15 19:45:47 +00:00
|
|
|
type Event = interface{}
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
// State contains state information of a voice gateway.
|
|
|
|
type State struct {
|
2020-07-21 20:27:59 +00:00
|
|
|
GuildID discord.GuildID
|
|
|
|
ChannelID discord.ChannelID
|
|
|
|
UserID discord.UserID
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
SessionID string
|
|
|
|
Token string
|
|
|
|
Endpoint string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Gateway represents a Discord Gateway Gateway connection.
|
|
|
|
type Gateway struct {
|
|
|
|
state State // constant
|
|
|
|
|
|
|
|
mutex sync.RWMutex
|
|
|
|
ready ReadyEvent
|
|
|
|
|
2020-10-22 17:47:27 +00:00
|
|
|
WS *wsutil.Websocket
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
Timeout time.Duration
|
|
|
|
reconnect moreatomic.Bool
|
|
|
|
|
2020-08-20 04:32:25 +00:00
|
|
|
EventLoop wsutil.PacemakerLoop
|
2020-11-15 19:45:47 +00:00
|
|
|
Events chan Event
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
// ErrorLog will be called when an error occurs (defaults to log.Println)
|
|
|
|
ErrorLog func(err error)
|
|
|
|
// AfterClose is called after each close. Error can be non-nil, as this is
|
|
|
|
// called even when the Gateway is gracefully closed. It's used mainly for
|
|
|
|
// reconnections or any type of connection interruptions. (defaults to noop)
|
|
|
|
AfterClose func(err error)
|
|
|
|
|
|
|
|
// Filled by methods, internal use
|
|
|
|
waitGroup *sync.WaitGroup
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(state State) *Gateway {
|
2020-11-03 17:16:42 +00:00
|
|
|
// https://discord.com/developers/docs/topics/voice-connections#establishing-a-voice-websocket-connection
|
2020-10-29 18:32:30 +00:00
|
|
|
var endpoint = "wss://" + strings.TrimSuffix(state.Endpoint, ":80") + "/?v=" + Version
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
return &Gateway{
|
|
|
|
state: state,
|
2020-10-29 18:32:30 +00:00
|
|
|
WS: wsutil.New(endpoint),
|
2020-04-25 02:36:33 +00:00
|
|
|
Timeout: wsutil.WSTimeout,
|
2020-11-15 19:45:47 +00:00
|
|
|
Events: make(chan Event, wsutil.WSBuffer),
|
2020-04-25 02:36:33 +00:00
|
|
|
ErrorLog: wsutil.WSError,
|
|
|
|
AfterClose: func(error) {},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: get rid of
|
|
|
|
func (c *Gateway) Ready() ReadyEvent {
|
|
|
|
c.mutex.RLock()
|
|
|
|
defer c.mutex.RUnlock()
|
|
|
|
|
|
|
|
return c.ready
|
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// OpenCtx shouldn't be used, but JoinServer instead.
|
|
|
|
func (c *Gateway) OpenCtx(ctx context.Context) error {
|
|
|
|
if c.state.Endpoint == "" {
|
|
|
|
return errors.New("missing endpoint in state")
|
|
|
|
}
|
|
|
|
|
2020-11-03 17:16:42 +00:00
|
|
|
// https://discord.com/developers/docs/topics/voice-connections#establishing-a-voice-websocket-connection
|
2020-04-25 02:36:33 +00:00
|
|
|
var endpoint = "wss://" + strings.TrimSuffix(c.state.Endpoint, ":80") + "/?v=" + Version
|
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Connecting to voice endpoint (endpoint=" + endpoint + ")")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
// Create a new context with a timeout for the connection.
|
2020-07-11 19:50:32 +00:00
|
|
|
ctx, cancel := context.WithTimeout(ctx, c.Timeout)
|
2020-04-25 02:36:33 +00:00
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
// Connect to the Gateway Gateway.
|
2020-10-22 17:47:27 +00:00
|
|
|
if err := c.WS.Dial(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to connect to voice gateway")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Trying to start...")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
// Try to start or resume the connection.
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := c.start(ctx); err != nil {
|
2020-04-25 02:36:33 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start .
|
2020-07-11 19:50:32 +00:00
|
|
|
func (c *Gateway) start(ctx context.Context) error {
|
|
|
|
if err := c.__start(ctx); err != nil {
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Start failed: ", err)
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
// Close can be called with the mutex still acquired here, as the
|
|
|
|
// pacemaker hasn't started yet.
|
|
|
|
if err := c.Close(); err != nil {
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Failed to close after start fail: ", err)
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// this function blocks until READY.
|
2020-07-11 19:50:32 +00:00
|
|
|
func (c *Gateway) __start(ctx context.Context) error {
|
2020-04-25 02:36:33 +00:00
|
|
|
// Make a new WaitGroup for use in background loops:
|
|
|
|
c.waitGroup = new(sync.WaitGroup)
|
|
|
|
|
2020-10-22 17:47:27 +00:00
|
|
|
ch := c.WS.Listen()
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
// Wait for hello.
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Waiting for Hello..")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
var hello *HelloEvent
|
2020-07-11 19:50:32 +00:00
|
|
|
// Wait for the Hello event; return if it times out.
|
|
|
|
select {
|
|
|
|
case e, ok := <-ch:
|
|
|
|
if !ok {
|
|
|
|
return errors.New("unexpected ws close while waiting for Hello")
|
|
|
|
}
|
|
|
|
if _, err := wsutil.AssertEvent(e, HelloOP, &hello); err != nil {
|
|
|
|
return errors.Wrap(err, "error at Hello")
|
|
|
|
}
|
|
|
|
case <-ctx.Done():
|
|
|
|
return errors.Wrap(ctx.Err(), "failed to wait for Hello event")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Received Hello")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2020-11-03 17:16:42 +00:00
|
|
|
// https://discord.com/developers/docs/topics/voice-connections#establishing-a-voice-websocket-connection
|
2020-04-25 02:36:33 +00:00
|
|
|
// Turns out Hello is sent right away on connection start.
|
|
|
|
if !c.reconnect.Get() {
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := c.IdentifyCtx(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to identify")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
} else {
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := c.ResumeCtx(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to resume")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// This bool is because we should only try and Resume once.
|
|
|
|
c.reconnect.Set(false)
|
|
|
|
|
|
|
|
// Wait for either Ready or Resumed.
|
2020-07-11 19:50:32 +00:00
|
|
|
err := wsutil.WaitForEvent(ctx, c, ch, func(op *wsutil.OP) bool {
|
2020-04-25 02:36:33 +00:00
|
|
|
return op.Code == ReadyOP || op.Code == ResumedOP
|
|
|
|
})
|
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to wait for Ready or Resumed")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start the event handler, which also handles the pacemaker death signal.
|
|
|
|
c.waitGroup.Add(1)
|
|
|
|
|
2020-08-20 03:48:55 +00:00
|
|
|
c.EventLoop.RunAsync(hello.HeartbeatInterval.Duration(), ch, c, func(err error) {
|
2020-04-25 07:13:07 +00:00
|
|
|
c.waitGroup.Done() // mark so Close() can exit.
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Event loop stopped.")
|
2020-04-25 07:13:07 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
c.ErrorLog(err)
|
2020-07-15 23:39:40 +00:00
|
|
|
|
|
|
|
if err := c.Reconnect(); err != nil {
|
|
|
|
c.ErrorLog(errors.Wrap(err, "failed to reconnect voice"))
|
|
|
|
}
|
|
|
|
|
2020-04-25 07:13:07 +00:00
|
|
|
// Reconnect should spawn another eventLoop in its Start function.
|
|
|
|
}
|
|
|
|
})
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Started successfully.")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
// Close closes the underlying Websocket connection.
|
|
|
|
func (g *Gateway) Close() error {
|
|
|
|
wsutil.WSDebug("VoiceGateway: Trying to close. Pacemaker check skipped.")
|
2020-10-22 17:47:27 +00:00
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Closing the Websocket...")
|
|
|
|
err := g.WS.Close()
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
if errors.Is(err, wsutil.ErrWebsocketClosed) {
|
|
|
|
wsutil.WSDebug("VoiceGateway: Websocket already closed.")
|
|
|
|
return nil
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Websocket closed; error:", err)
|
2020-10-22 17:47:27 +00:00
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Waiting for the Pacemaker loop to exit.")
|
|
|
|
g.waitGroup.Wait()
|
|
|
|
wsutil.WSDebug("VoiceGateway: Pacemaker loop exited.")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
g.AfterClose(err)
|
|
|
|
wsutil.WSDebug("VoiceGateway: AfterClose callback finished.")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-07-15 23:39:40 +00:00
|
|
|
func (c *Gateway) Reconnect() error {
|
|
|
|
return c.ReconnectCtx(context.Background())
|
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
func (c *Gateway) ReconnectCtx(ctx context.Context) error {
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Reconnecting...")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2020-07-15 23:39:40 +00:00
|
|
|
// TODO: implement a reconnect loop
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
// Guarantee the gateway is already closed. Ignore its error, as we're
|
|
|
|
// redialing anyway.
|
|
|
|
c.Close()
|
|
|
|
|
|
|
|
c.reconnect.Set(true)
|
|
|
|
|
|
|
|
// Condition: err == ErrInvalidSession:
|
|
|
|
// If the connection is rate limited (documented behavior):
|
2020-11-03 17:16:42 +00:00
|
|
|
// https://discord.com/developers/docs/topics/gateway#rate-limiting
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := c.OpenCtx(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to reopen gateway")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("VoiceGateway: Reconnected successfully.")
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
func (c *Gateway) SessionDescriptionCtx(
|
|
|
|
ctx context.Context, sp SelectProtocol) (*SessionDescriptionEvent, error) {
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
// Add the handler first.
|
|
|
|
ch, cancel := c.EventLoop.Extras.Add(func(op *wsutil.OP) bool {
|
|
|
|
return op.Code == SessionDescriptionOP
|
|
|
|
})
|
|
|
|
defer cancel()
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := c.SelectProtocolCtx(ctx, sp); err != nil {
|
2020-04-25 02:36:33 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var sesdesc *SessionDescriptionEvent
|
|
|
|
|
|
|
|
// Wait for SessionDescriptionOP packet.
|
2020-07-11 19:50:32 +00:00
|
|
|
select {
|
|
|
|
case e, ok := <-ch:
|
|
|
|
if !ok {
|
|
|
|
return nil, errors.New("unexpected close waiting for session description")
|
|
|
|
}
|
|
|
|
if err := e.UnmarshalData(&sesdesc); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to unmarshal session description")
|
|
|
|
}
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, errors.Wrap(ctx.Err(), "failed to wait for session description")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return sesdesc, nil
|
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// Send sends a payload to the Gateway with the default timeout.
|
2020-04-25 02:36:33 +00:00
|
|
|
func (c *Gateway) Send(code OPCode, v interface{}) error {
|
2020-07-11 19:50:32 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), c.Timeout)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
return c.SendCtx(ctx, code, v)
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
func (c *Gateway) SendCtx(ctx context.Context, code OPCode, v interface{}) error {
|
2020-04-25 02:36:33 +00:00
|
|
|
var op = wsutil.OP{
|
|
|
|
Code: code,
|
|
|
|
}
|
|
|
|
|
|
|
|
if v != nil {
|
|
|
|
b, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to encode v")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
op.Data = b
|
|
|
|
}
|
|
|
|
|
|
|
|
b, err := json.Marshal(op)
|
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to encode payload")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// WS should already be thread-safe.
|
2020-10-22 17:47:27 +00:00
|
|
|
return c.WS.SendCtx(ctx, b)
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|