2020-04-25 02:36:33 +00:00
|
|
|
package voice
|
|
|
|
|
|
|
|
import (
|
2020-07-11 19:50:32 +00:00
|
|
|
"context"
|
2020-04-25 02:36:33 +00:00
|
|
|
"sync"
|
2020-07-11 19:50:32 +00:00
|
|
|
"time"
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2021-06-02 02:53:19 +00:00
|
|
|
"github.com/diamondburned/arikawa/v3/state"
|
|
|
|
"github.com/diamondburned/arikawa/v3/utils/handler"
|
2020-11-17 20:09:15 +00:00
|
|
|
|
2020-07-29 20:10:48 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2021-06-02 02:53:19 +00:00
|
|
|
"github.com/diamondburned/arikawa/v3/discord"
|
|
|
|
"github.com/diamondburned/arikawa/v3/gateway"
|
|
|
|
"github.com/diamondburned/arikawa/v3/internal/handleloop"
|
|
|
|
"github.com/diamondburned/arikawa/v3/internal/moreatomic"
|
|
|
|
"github.com/diamondburned/arikawa/v3/session"
|
|
|
|
"github.com/diamondburned/arikawa/v3/utils/wsutil"
|
|
|
|
"github.com/diamondburned/arikawa/v3/voice/udp"
|
|
|
|
"github.com/diamondburned/arikawa/v3/voice/voicegateway"
|
2020-04-25 02:36:33 +00:00
|
|
|
)
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// Protocol is the encryption protocol that this library uses.
|
2020-04-25 02:36:33 +00:00
|
|
|
const Protocol = "xsalsa20_poly1305"
|
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
// ErrAlreadyConnecting is returned when the session is already connecting.
|
|
|
|
var ErrAlreadyConnecting = errors.New("already connecting")
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// ErrCannotSend is an error when audio is sent to a closed channel.
|
|
|
|
var ErrCannotSend = errors.New("cannot send audio to closed channel")
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// WSTimeout is the duration to wait for a gateway operation including Session
|
|
|
|
// to complete before erroring out. This only applies to functions that don't
|
|
|
|
// take in a context already.
|
|
|
|
var WSTimeout = 10 * time.Second
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// Session is a single voice session that wraps around the voice gateway and UDP
|
|
|
|
// connection.
|
2020-04-25 02:36:33 +00:00
|
|
|
type Session struct {
|
2020-11-15 19:45:47 +00:00
|
|
|
*handler.Handler
|
2020-04-25 02:36:33 +00:00
|
|
|
ErrorLog func(err error)
|
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
session *session.Session
|
2020-12-01 01:49:18 +00:00
|
|
|
cancels []func()
|
2020-11-17 20:09:15 +00:00
|
|
|
looper *handleloop.Loop
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
// joining determines the behavior of incoming event callbacks (Update).
|
|
|
|
// If this is true, incoming events will just send into Updated channels. If
|
|
|
|
// false, events will trigger a reconnection.
|
|
|
|
joining moreatomic.Bool
|
|
|
|
incoming chan struct{} // used only when joining == true
|
|
|
|
|
|
|
|
mut sync.RWMutex
|
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
state voicegateway.State // guarded except UserID
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
// TODO: expose getters mutex-guarded.
|
|
|
|
gateway *voicegateway.Gateway
|
|
|
|
voiceUDP *udp.Connection
|
|
|
|
}
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// NewSession creates a new voice session for the current user.
|
|
|
|
func NewSession(state *state.State) (*Session, error) {
|
|
|
|
u, err := state.Me()
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to get me")
|
|
|
|
}
|
|
|
|
|
|
|
|
return NewSessionCustom(state.Session, u.ID), nil
|
|
|
|
}
|
2020-11-17 20:09:15 +00:00
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// NewSessionCustom creates a new voice session from the given session and user
|
|
|
|
// ID.
|
|
|
|
func NewSessionCustom(ses *session.Session, userID discord.UserID) *Session {
|
|
|
|
handler := handler.New()
|
|
|
|
hlooper := handleloop.NewLoop(handler)
|
|
|
|
session := &Session{
|
2020-11-17 20:09:15 +00:00
|
|
|
Handler: handler,
|
2020-12-01 01:49:18 +00:00
|
|
|
looper: hlooper,
|
2020-04-25 02:36:33 +00:00
|
|
|
session: ses,
|
|
|
|
state: voicegateway.State{
|
|
|
|
UserID: userID,
|
|
|
|
},
|
|
|
|
ErrorLog: func(err error) {},
|
2020-07-11 19:50:32 +00:00
|
|
|
incoming: make(chan struct{}, 2),
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
2020-12-01 01:49:18 +00:00
|
|
|
session.cancels = []func(){
|
|
|
|
ses.AddHandler(session.updateServer),
|
|
|
|
ses.AddHandler(session.updateState),
|
|
|
|
}
|
|
|
|
|
|
|
|
return session
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
func (s *Session) updateServer(ev *gateway.VoiceServerUpdateEvent) {
|
2020-04-25 02:36:33 +00:00
|
|
|
// If this is true, then mutex is acquired already.
|
|
|
|
if s.joining.Get() {
|
2020-11-17 20:09:15 +00:00
|
|
|
if s.state.GuildID != ev.GuildID {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
s.state.Endpoint = ev.Endpoint
|
|
|
|
s.state.Token = ev.Token
|
|
|
|
|
|
|
|
s.incoming <- struct{}{}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
s.mut.Lock()
|
|
|
|
defer s.mut.Unlock()
|
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
if s.state.GuildID != ev.GuildID {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reconnect.
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
s.state.Endpoint = ev.Endpoint
|
|
|
|
s.state.Token = ev.Token
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), WSTimeout)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
if err := s.reconnectCtx(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
s.ErrorLog(errors.Wrap(err, "failed to reconnect after voice server update"))
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
func (s *Session) updateState(ev *gateway.VoiceStateUpdateEvent) {
|
2020-11-17 20:09:15 +00:00
|
|
|
if s.state.UserID != ev.UserID { // constant so no mutex
|
2020-04-25 02:36:33 +00:00
|
|
|
// Not our state.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// If this is true, then mutex is acquired already.
|
|
|
|
if s.joining.Get() {
|
2020-12-01 01:49:18 +00:00
|
|
|
if s.state.GuildID != ev.GuildID {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
s.state.SessionID = ev.SessionID
|
|
|
|
s.state.ChannelID = ev.ChannelID
|
|
|
|
|
|
|
|
s.incoming <- struct{}{}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
func (s *Session) JoinChannel(gID discord.GuildID, cID discord.ChannelID, mute, deaf bool) error {
|
2020-07-11 19:50:32 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), WSTimeout)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
return s.JoinChannelCtx(ctx, gID, cID, mute, deaf)
|
2020-07-11 19:50:32 +00:00
|
|
|
}
|
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
// JoinChannelCtx joins a voice channel. Callers shouldn't use this method
|
2020-12-01 01:49:18 +00:00
|
|
|
// directly, but rather Voice's. This method shouldn't ever be called
|
|
|
|
// concurrently.
|
2020-10-22 17:47:27 +00:00
|
|
|
func (s *Session) JoinChannelCtx(
|
2020-12-01 01:49:18 +00:00
|
|
|
ctx context.Context, gID discord.GuildID, cID discord.ChannelID, mute, deaf bool) error {
|
2020-10-22 17:47:27 +00:00
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
if s.joining.Get() {
|
|
|
|
return ErrAlreadyConnecting
|
|
|
|
}
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
// Acquire the mutex during join, locking during IO as well.
|
|
|
|
s.mut.Lock()
|
|
|
|
defer s.mut.Unlock()
|
|
|
|
|
|
|
|
// Set that we're joining.
|
|
|
|
s.joining.Set(true)
|
|
|
|
defer s.joining.Set(false) // reset when done
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// Ensure gateway and voiceUDP are already closed.
|
2020-04-25 02:36:33 +00:00
|
|
|
s.ensureClosed()
|
|
|
|
|
|
|
|
// Set the state.
|
|
|
|
s.state.ChannelID = cID
|
|
|
|
s.state.GuildID = gID
|
|
|
|
|
|
|
|
// Ensure that if `cID` is zero that it passes null to the update event.
|
2020-07-29 20:58:39 +00:00
|
|
|
channelID := discord.NullChannelID
|
2020-07-29 20:10:17 +00:00
|
|
|
if cID.IsValid() {
|
2020-05-08 21:25:07 +00:00
|
|
|
channelID = cID
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-11-03 17:16:42 +00:00
|
|
|
// https://discord.com/developers/docs/topics/voice-connections#retrieving-voice-server-information
|
2020-04-25 02:36:33 +00:00
|
|
|
// Send a Voice State Update event to the gateway.
|
2020-07-11 19:50:32 +00:00
|
|
|
err := s.session.Gateway.UpdateVoiceStateCtx(ctx, gateway.UpdateVoiceStateData{
|
2020-04-25 02:36:33 +00:00
|
|
|
GuildID: gID,
|
|
|
|
ChannelID: channelID,
|
2020-12-01 01:49:18 +00:00
|
|
|
SelfMute: mute,
|
|
|
|
SelfDeaf: deaf,
|
2020-04-25 02:36:33 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to send Voice State Update event")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// Wait for 2 replies. The above command should reply with these 2 events.
|
|
|
|
if err := s.waitForIncoming(ctx, 2); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to wait for needed gateway events")
|
|
|
|
}
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
// These 2 methods should've updated s.state before sending into these
|
|
|
|
// channels. Since s.state is already filled, we can go ahead and connect.
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
return s.reconnectCtx(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Session) waitForIncoming(ctx context.Context, n int) error {
|
|
|
|
for i := 0; i < n; i++ {
|
|
|
|
select {
|
|
|
|
case <-s.incoming:
|
|
|
|
continue
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// reconnect uses the current state to reconnect to a new gateway and UDP
|
|
|
|
// connection.
|
2020-07-11 19:50:32 +00:00
|
|
|
func (s *Session) reconnectCtx(ctx context.Context) (err error) {
|
2020-11-17 20:09:15 +00:00
|
|
|
wsutil.WSDebug("Sending stop handle.")
|
|
|
|
s.looper.Stop()
|
2020-11-15 19:45:47 +00:00
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
wsutil.WSDebug("Start gateway.")
|
2020-04-25 02:36:33 +00:00
|
|
|
s.gateway = voicegateway.New(s.state)
|
|
|
|
|
|
|
|
// Open the voice gateway. The function will block until Ready is received.
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := s.gateway.OpenCtx(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to open voice gateway")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-11-15 19:45:47 +00:00
|
|
|
// Start the handler dispatching
|
2020-11-17 20:09:15 +00:00
|
|
|
s.looper.Start(s.gateway.Events)
|
2020-11-15 19:45:47 +00:00
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
// Get the Ready event.
|
|
|
|
voiceReady := s.gateway.Ready()
|
|
|
|
|
|
|
|
// Prepare the UDP voice connection.
|
2020-07-11 19:50:32 +00:00
|
|
|
s.voiceUDP, err = udp.DialConnectionCtx(ctx, voiceReady.Addr(), voiceReady.SSRC)
|
2020-04-25 02:36:33 +00:00
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to open voice UDP connection")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get the session description from the voice gateway.
|
2020-07-11 19:50:32 +00:00
|
|
|
d, err := s.gateway.SessionDescriptionCtx(ctx, voicegateway.SelectProtocol{
|
2020-04-25 02:36:33 +00:00
|
|
|
Protocol: "udp",
|
|
|
|
Data: voicegateway.SelectProtocolData{
|
|
|
|
Address: s.voiceUDP.GatewayIP,
|
|
|
|
Port: s.voiceUDP.GatewayPort,
|
|
|
|
Mode: Protocol,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to select protocol")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-10-22 17:47:27 +00:00
|
|
|
s.voiceUDP.UseSecret(d.SecretKey)
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-17 22:43:00 +00:00
|
|
|
// Speaking tells Discord we're speaking. This method should not be called
|
2020-11-17 20:09:15 +00:00
|
|
|
// concurrently.
|
2020-04-25 02:36:33 +00:00
|
|
|
func (s *Session) Speaking(flag voicegateway.SpeakingFlag) error {
|
|
|
|
s.mut.RLock()
|
2020-11-17 20:09:15 +00:00
|
|
|
gateway := s.gateway
|
|
|
|
s.mut.RUnlock()
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
return gateway.Speaking(flag)
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// UseContext tells the UDP voice connection to write with the given context.
|
2020-10-22 17:47:27 +00:00
|
|
|
func (s *Session) UseContext(ctx context.Context) error {
|
2020-11-17 20:09:15 +00:00
|
|
|
s.mut.Lock()
|
|
|
|
defer s.mut.Unlock()
|
2020-10-22 17:47:27 +00:00
|
|
|
|
|
|
|
if s.voiceUDP == nil {
|
|
|
|
return ErrCannotSend
|
|
|
|
}
|
|
|
|
|
|
|
|
return s.voiceUDP.UseContext(ctx)
|
|
|
|
}
|
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
// VoiceUDPConn gets a voice UDP connection. The caller could use this method to
|
|
|
|
// circumvent the rapid mutex-read-lock acquire inside Write.
|
|
|
|
func (s *Session) VoiceUDPConn() *udp.Connection {
|
|
|
|
s.mut.RLock()
|
|
|
|
defer s.mut.RUnlock()
|
|
|
|
|
|
|
|
return s.voiceUDP
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write writes into the UDP voice connection WITHOUT a timeout. Refer to
|
|
|
|
// WriteCtx for more information.
|
2020-04-25 02:36:33 +00:00
|
|
|
func (s *Session) Write(b []byte) (int, error) {
|
2020-07-11 19:50:32 +00:00
|
|
|
return s.WriteCtx(context.Background(), b)
|
|
|
|
}
|
|
|
|
|
|
|
|
// WriteCtx writes into the UDP voice connection with a context for timeout.
|
2020-11-17 20:09:15 +00:00
|
|
|
// This method is thread safe as far as calling other methods of Session goes;
|
|
|
|
// HOWEVER it is not thread safe to call Write itself concurrently.
|
2020-07-11 19:50:32 +00:00
|
|
|
func (s *Session) WriteCtx(ctx context.Context, b []byte) (int, error) {
|
2020-11-17 20:09:15 +00:00
|
|
|
voiceUDP := s.VoiceUDPConn()
|
2020-04-25 02:36:33 +00:00
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
if voiceUDP == nil {
|
2020-04-25 02:36:33 +00:00
|
|
|
return 0, ErrCannotSend
|
|
|
|
}
|
2020-07-11 19:50:32 +00:00
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
return voiceUDP.WriteCtx(ctx, b)
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// Leave disconnects the current voice session from the currently connected
|
|
|
|
// channel.
|
|
|
|
func (s *Session) Leave() error {
|
2020-07-11 19:50:32 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), WSTimeout)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
return s.LeaveCtx(ctx)
|
2020-07-11 19:50:32 +00:00
|
|
|
}
|
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// LeaveCtx disconencts with a context. Refer to Leave for more information.
|
|
|
|
func (s *Session) LeaveCtx(ctx context.Context) error {
|
2020-04-25 02:36:33 +00:00
|
|
|
s.mut.Lock()
|
|
|
|
defer s.mut.Unlock()
|
|
|
|
|
|
|
|
// If we're already closed.
|
|
|
|
if s.gateway == nil && s.voiceUDP == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-17 20:09:15 +00:00
|
|
|
s.looper.Stop()
|
|
|
|
|
2020-04-25 02:36:33 +00:00
|
|
|
// Notify Discord that we're leaving. This will send a
|
|
|
|
// VoiceStateUpdateEvent, in which our handler will promptly remove the
|
|
|
|
// session from the map.
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
err := s.session.Gateway.UpdateVoiceStateCtx(ctx, gateway.UpdateVoiceStateData{
|
2020-04-25 02:36:33 +00:00
|
|
|
GuildID: s.state.GuildID,
|
2020-07-21 20:27:59 +00:00
|
|
|
ChannelID: discord.ChannelID(discord.NullSnowflake),
|
2020-04-25 02:36:33 +00:00
|
|
|
SelfMute: true,
|
|
|
|
SelfDeaf: true,
|
|
|
|
})
|
|
|
|
|
|
|
|
s.ensureClosed()
|
|
|
|
// wrap returns nil if err is nil
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to update voice state")
|
2020-04-25 02:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// close ensures everything is closed. It does not acquire the mutex.
|
|
|
|
func (s *Session) ensureClosed() {
|
2020-11-17 20:09:15 +00:00
|
|
|
s.looper.Stop()
|
2020-04-25 02:36:33 +00:00
|
|
|
|
|
|
|
// Disconnect the UDP connection.
|
|
|
|
if s.voiceUDP != nil {
|
|
|
|
s.voiceUDP.Close()
|
|
|
|
s.voiceUDP = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Disconnect the voice gateway, ignoring the error.
|
|
|
|
if s.gateway != nil {
|
|
|
|
if err := s.gateway.Close(); err != nil {
|
|
|
|
wsutil.WSDebug("Uncaught voice gateway close error:", err)
|
|
|
|
}
|
|
|
|
s.gateway = nil
|
|
|
|
}
|
|
|
|
}
|
2020-11-30 01:32:18 +00:00
|
|
|
|
2020-12-01 01:49:18 +00:00
|
|
|
// ReadPacket reads a single packet from the UDP connection. This is NOT at all
|
|
|
|
// thread safe, and must be used very carefully. The backing buffer is always
|
|
|
|
// reused.
|
2020-11-30 01:32:18 +00:00
|
|
|
func (s *Session) ReadPacket() (*udp.Packet, error) {
|
|
|
|
return s.voiceUDP.ReadPacket()
|
|
|
|
}
|