From 60346f23bbff9d0d393d494c3dda18c32252125f Mon Sep 17 00:00:00 2001 From: Matthew Penner Date: Wed, 13 May 2020 14:43:00 -0600 Subject: [PATCH] Close voice connections when Close() is called --- voice/voice.go | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/voice/voice.go b/voice/voice.go index 0eb0279..be2b82e 100644 --- a/voice/voice.go +++ b/voice/voice.go @@ -6,6 +6,7 @@ package voice import ( "log" + "strconv" "sync" "github.com/diamondburned/arikawa/discord" @@ -137,3 +138,65 @@ func (v *Voice) JoinChannel(gID, cID discord.Snowflake, muted, deafened bool) (* // Connect. return conn, conn.JoinChannel(gID, cID, muted, deafened) } + +type CloseError struct { + SessionErrors map[discord.Snowflake]error + StateErr error +} + +func (e *CloseError) HasError() bool { + if e.StateErr != nil { + return true + } + + for _, err := range e.SessionErrors { + if err == nil { + continue + } + + return true + } + + return false +} + +func (e *CloseError) Error() string { + if e.StateErr != nil { + return e.StateErr.Error() + } + + var errorCount int + for _, err := range e.SessionErrors { + if err == nil { + continue + } + + errorCount++ + } + + if errorCount < 1 { + return "" + } + + return strconv.Itoa(errorCount) + " voice sessions returned errors while attempting to disconnect" +} + +func (v *Voice) Close() error { + err := &CloseError{ + SessionErrors: make(map[discord.Snowflake]error), + } + + v.mapmutex.Lock() + defer v.mapmutex.Unlock() + + for gID, s := range v.sessions { + err.SessionErrors[gID] = s.Disconnect() + } + + err.StateErr = v.State.Close() + if err.HasError() { + return err + } + + return nil +}