123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873 |
- package discordgo
- import (
- "encoding/binary"
- "encoding/json"
- "fmt"
- "log"
- "net"
- "runtime"
- "strings"
- "sync"
- "time"
- "github.com/gorilla/websocket"
- "golang.org/x/crypto/nacl/secretbox"
- )
- type VoiceConnection struct {
- sync.RWMutex
- Debug bool
- LogLevel int
- Ready bool
- UserID string
- GuildID string
- ChannelID string
- deaf bool
- mute bool
- speaking bool
- reconnecting bool
- OpusSend chan []byte
- OpusRecv chan *Packet
- wsConn *websocket.Conn
- wsMutex sync.Mutex
- udpConn *net.UDPConn
- session *Session
- sessionID string
- token string
- endpoint string
-
- close chan struct{}
-
- connected chan bool
-
-
- op4 voiceOP4
- op2 voiceOP2
- voiceSpeakingUpdateHandlers []VoiceSpeakingUpdateHandler
- }
- type VoiceSpeakingUpdateHandler func(vc *VoiceConnection, vs *VoiceSpeakingUpdate)
- // Speaking sends a speaking notification to Discord over the voice websocket.
- // This must be sent as true prior to sending audio and should be set to false
- // once finished sending audio.
- // b : Send true if speaking, false if not.
- func (v *VoiceConnection) Speaking(b bool) (err error) {
- v.log(LogDebug, "called (%t)", b)
- type voiceSpeakingData struct {
- Speaking bool `json:"speaking"`
- Delay int `json:"delay"`
- }
- type voiceSpeakingOp struct {
- Op int `json:"op"`
- Data voiceSpeakingData `json:"d"`
- }
- if v.wsConn == nil {
- return fmt.Errorf("No VoiceConnection websocket.")
- }
- data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
- v.wsMutex.Lock()
- err = v.wsConn.WriteJSON(data)
- v.wsMutex.Unlock()
- if err != nil {
- v.speaking = false
- log.Println("Speaking() write json error:", err)
- return
- }
- v.speaking = b
- return
- }
- func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) {
- v.log(LogInformational, "called")
- data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}}
- v.wsMutex.Lock()
- err = v.session.wsConn.WriteJSON(data)
- v.wsMutex.Unlock()
- if err != nil {
- return
- }
- v.ChannelID = channelID
- v.deaf = deaf
- v.mute = mute
- v.speaking = false
- return
- }
- func (v *VoiceConnection) Disconnect() (err error) {
-
- if v.sessionID != "" {
- data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
- v.wsMutex.Lock()
- err = v.session.wsConn.WriteJSON(data)
- v.wsMutex.Unlock()
- v.sessionID = ""
- }
-
- v.Close()
- v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID)
- delete(v.session.VoiceConnections, v.GuildID)
- return
- }
- func (v *VoiceConnection) Close() {
- v.log(LogInformational, "called")
- v.Lock()
- defer v.Unlock()
- v.Ready = false
- v.speaking = false
- if v.close != nil {
- close(v.close)
- v.close = nil
- }
- if v.udpConn != nil {
- err := v.udpConn.Close()
- if err != nil {
- log.Println("error closing udp connection: ", err)
- }
- v.udpConn = nil
- }
- if v.wsConn != nil {
- err := v.wsConn.Close()
- if err != nil {
- log.Println("error closing websocket connection: ", err)
- }
- v.wsConn = nil
- }
- }
- func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) {
- v.Lock()
- defer v.Unlock()
- v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h)
- }
- type VoiceSpeakingUpdate struct {
- UserID string `json:"user_id"`
- SSRC int `json:"ssrc"`
- Speaking bool `json:"speaking"`
- }
- type voiceOP4 struct {
- SecretKey [32]byte `json:"secret_key"`
- Mode string `json:"mode"`
- }
- type voiceOP2 struct {
- SSRC uint32 `json:"ssrc"`
- Port int `json:"port"`
- Modes []string `json:"modes"`
- HeartbeatInterval time.Duration `json:"heartbeat_interval"`
- }
- func (v *VoiceConnection) waitUntilConnected() error {
- v.log(LogInformational, "called")
- i := 0
- for {
- if v.Ready {
- return nil
- }
- if i > 10 {
- return fmt.Errorf("Timeout waiting for voice.")
- }
- time.Sleep(1 * time.Second)
- i++
- }
- }
- func (v *VoiceConnection) open() (err error) {
- v.log(LogInformational, "called")
- v.Lock()
- defer v.Unlock()
-
- if v.wsConn != nil {
- v.log(LogWarning, "refusing to overwrite non-nil websocket")
- return
- }
-
- i := 0
- for {
- if v.sessionID != "" {
- break
- }
- if i > 20 {
- return fmt.Errorf("Did not receive voice Session ID in time.")
- }
- time.Sleep(50 * time.Millisecond)
- i++
- }
-
- vg := fmt.Sprintf("wss://%s", strings.TrimSuffix(v.endpoint, ":80"))
- v.log(LogInformational, "connecting to voice endpoint %s", vg)
- v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
- if err != nil {
- v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err)
- v.log(LogDebug, "voice struct: %#v\n", v)
- return
- }
- type voiceHandshakeData struct {
- ServerID string `json:"server_id"`
- UserID string `json:"user_id"`
- SessionID string `json:"session_id"`
- Token string `json:"token"`
- }
- type voiceHandshakeOp struct {
- Op int `json:"op"`
- Data voiceHandshakeData `json:"d"`
- }
- data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}}
- err = v.wsConn.WriteJSON(data)
- if err != nil {
- v.log(LogWarning, "error sending init packet, %s", err)
- return
- }
- v.close = make(chan struct{})
- go v.wsListen(v.wsConn, v.close)
-
-
-
- return
- }
- func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) {
- v.log(LogInformational, "called")
- for {
- _, message, err := v.wsConn.ReadMessage()
- if err != nil {
-
-
-
- v.RLock()
- sameConnection := v.wsConn == wsConn
- v.RUnlock()
- if sameConnection {
- v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err)
-
- go v.reconnect()
- }
- return
- }
-
- select {
- case <-close:
- return
- default:
- go v.onEvent(message)
- }
- }
- }
- func (v *VoiceConnection) onEvent(message []byte) {
- v.log(LogDebug, "received: %s", string(message))
- var e Event
- if err := json.Unmarshal(message, &e); err != nil {
- v.log(LogError, "unmarshall error, %s", err)
- return
- }
- switch e.Operation {
- case 2:
- if err := json.Unmarshal(e.RawData, &v.op2); err != nil {
- v.log(LogError, "OP2 unmarshall error, %s, %s", err, string(e.RawData))
- return
- }
-
- go v.wsHeartbeat(v.wsConn, v.close, v.op2.HeartbeatInterval)
-
-
- err := v.udpOpen()
- if err != nil {
- v.log(LogError, "error opening udp connection, %s", err)
- return
- }
-
-
- if v.OpusSend == nil {
- v.OpusSend = make(chan []byte, 2)
- }
- go v.opusSender(v.udpConn, v.close, v.OpusSend, 48000, 960)
-
- if !v.deaf {
- if v.OpusRecv == nil {
- v.OpusRecv = make(chan *Packet, 2)
- }
- go v.opusReceiver(v.udpConn, v.close, v.OpusRecv)
- }
-
- v.connected <- true
- return
- case 3:
-
- return
- case 4:
- v.op4 = voiceOP4{}
- if err := json.Unmarshal(e.RawData, &v.op4); err != nil {
- v.log(LogError, "OP4 unmarshall error, %s, %s", err, string(e.RawData))
- return
- }
- return
- case 5:
- if len(v.voiceSpeakingUpdateHandlers) == 0 {
- return
- }
- voiceSpeakingUpdate := &VoiceSpeakingUpdate{}
- if err := json.Unmarshal(e.RawData, voiceSpeakingUpdate); err != nil {
- v.log(LogError, "OP5 unmarshall error, %s, %s", err, string(e.RawData))
- return
- }
- for _, h := range v.voiceSpeakingUpdateHandlers {
- h(v, voiceSpeakingUpdate)
- }
- default:
- v.log(LogError, "unknown voice operation, %d, %s", e.Operation, string(e.RawData))
- }
- return
- }
- type voiceHeartbeatOp struct {
- Op int `json:"op"`
- Data int `json:"d"`
- }
- func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {
- if close == nil || wsConn == nil {
- return
- }
- var err error
- ticker := time.NewTicker(i * time.Millisecond)
- for {
- v.log(LogDebug, "sending heartbeat packet")
- v.wsMutex.Lock()
- err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
- v.wsMutex.Unlock()
- if err != nil {
- v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err)
- return
- }
- select {
- case <-ticker.C:
-
- case <-close:
- return
- }
- }
- }
- type voiceUDPData struct {
- Address string `json:"address"`
- Port uint16 `json:"port"`
- Mode string `json:"mode"`
- }
- type voiceUDPD struct {
- Protocol string `json:"protocol"`
- Data voiceUDPData `json:"data"`
- }
- type voiceUDPOp struct {
- Op int `json:"op"`
- Data voiceUDPD `json:"d"`
- }
- func (v *VoiceConnection) udpOpen() (err error) {
- v.Lock()
- defer v.Unlock()
- if v.wsConn == nil {
- return fmt.Errorf("nil voice websocket")
- }
- if v.udpConn != nil {
- return fmt.Errorf("udp connection already open")
- }
- if v.close == nil {
- return fmt.Errorf("nil close channel")
- }
- if v.endpoint == "" {
- return fmt.Errorf("empty endpoint")
- }
- host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.op2.Port)
- addr, err := net.ResolveUDPAddr("udp", host)
- if err != nil {
- v.log(LogWarning, "error resolving udp host %s, %s", host, err)
- return
- }
- v.log(LogInformational, "connecting to udp addr %s", addr.String())
- v.udpConn, err = net.DialUDP("udp", nil, addr)
- if err != nil {
- v.log(LogWarning, "error connecting to udp addr %s, %s", addr.String(), err)
- return
- }
-
-
- sb := make([]byte, 70)
- binary.BigEndian.PutUint32(sb, v.op2.SSRC)
- _, err = v.udpConn.Write(sb)
- if err != nil {
- v.log(LogWarning, "udp write error to %s, %s", addr.String(), err)
- return
- }
-
-
-
-
- rb := make([]byte, 70)
- rlen, _, err := v.udpConn.ReadFromUDP(rb)
- if err != nil {
- v.log(LogWarning, "udp read error, %s, %s", addr.String(), err)
- return
- }
- if rlen < 70 {
- v.log(LogWarning, "received udp packet too small")
- return fmt.Errorf("received udp packet too small")
- }
-
-
- var ip string
- for i := 4; i < 20; i++ {
- if rb[i] == 0 {
- break
- }
- ip += string(rb[i])
- }
-
- port := binary.LittleEndian.Uint16(rb[68:70])
-
-
- data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}}
- v.wsMutex.Lock()
- err = v.wsConn.WriteJSON(data)
- v.wsMutex.Unlock()
- if err != nil {
- v.log(LogWarning, "udp write error, %#v, %s", data, err)
- return
- }
-
- go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second)
-
- return
- }
- func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) {
- if udpConn == nil || close == nil {
- return
- }
- var err error
- var sequence uint64
- packet := make([]byte, 8)
- ticker := time.NewTicker(i)
- for {
- binary.LittleEndian.PutUint64(packet, sequence)
- sequence++
- _, err = udpConn.Write(packet)
- if err != nil {
- v.log(LogError, "write error, %s")
- return
- }
- select {
- case <-ticker.C:
-
- case <-close:
- return
- }
- }
- }
- func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) {
- if udpConn == nil || close == nil {
- return
- }
- runtime.LockOSThread()
-
-
- v.Ready = true
- defer func() { v.Ready = false }()
- var sequence uint16
- var timestamp uint32
- var recvbuf []byte
- var ok bool
- udpHeader := make([]byte, 12)
- var nonce [24]byte
-
- udpHeader[0] = 0x80
- udpHeader[1] = 0x78
- binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC)
-
- ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
- for {
-
- select {
- case <-close:
- return
- case recvbuf, ok = <-opus:
- if !ok {
- return
- }
-
- }
- if !v.speaking {
- err := v.Speaking(true)
- if err != nil {
- v.log(LogError, "error sending speaking packet, %s", err)
- }
- }
-
- binary.BigEndian.PutUint16(udpHeader[2:], sequence)
- binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
-
- copy(nonce[:], udpHeader)
- sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey)
-
-
- select {
- case <-close:
- return
- case <-ticker.C:
-
- }
- _, err := udpConn.Write(sendbuf)
- if err != nil {
- v.log(LogError, "udp write error, %s", err)
- v.log(LogDebug, "voice struct: %#v\n", v)
- return
- }
- if (sequence) == 0xFFFF {
- sequence = 0
- } else {
- sequence++
- }
- if (timestamp + uint32(size)) >= 0xFFFFFFFF {
- timestamp = 0
- } else {
- timestamp += uint32(size)
- }
- }
- }
- type Packet struct {
- SSRC uint32
- Sequence uint16
- Timestamp uint32
- Type []byte
- Opus []byte
- PCM []int16
- }
- func (v *VoiceConnection) opusReceiver(udpConn *net.UDPConn, close <-chan struct{}, c chan *Packet) {
- if udpConn == nil || close == nil {
- return
- }
- p := Packet{}
- recvbuf := make([]byte, 1024)
- var nonce [24]byte
- for {
- rlen, err := udpConn.Read(recvbuf)
- if err != nil {
-
-
-
- v.RLock()
- sameConnection := v.udpConn == udpConn
- v.RUnlock()
- if sameConnection {
- v.log(LogError, "udp read error, %s, %s", v.endpoint, err)
- v.log(LogDebug, "voice struct: %#v\n", v)
- go v.reconnect()
- }
- return
- }
- select {
- case <-close:
- return
- default:
-
- }
-
- if rlen < 12 || recvbuf[0] != 0x80 {
- continue
- }
-
- p.Type = recvbuf[0:2]
- p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
- p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
- p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
-
- copy(nonce[:], recvbuf[0:12])
- p.Opus, _ = secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey)
- if c != nil {
- c <- &p
- }
- }
- }
- func (v *VoiceConnection) reconnect() {
- v.log(LogInformational, "called")
- v.Lock()
- if v.reconnecting {
- v.log(LogInformational, "already reconnecting, exiting.")
- return
- }
- v.reconnecting = true
- v.Unlock()
- defer func() { v.reconnecting = false }()
- if v.session == nil {
- v.log(LogInformational, "cannot reconnect with nil session")
- v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID)
- delete(v.session.VoiceConnections, v.GuildID)
- return
- }
-
- if v.sessionID != "" {
- data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
- v.wsMutex.Lock()
- err := v.session.wsConn.WriteJSON(data)
- if err != nil {
- v.log(LogError, "error sending disconnect packet, %s", err)
- }
- v.wsMutex.Unlock()
- v.sessionID = ""
- }
-
- v.Close()
- wait := time.Duration(1)
- i := 0
- for {
- if v.session == nil {
- v.log(LogInformational, "cannot reconnect with nil session")
- v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID)
- delete(v.session.VoiceConnections, v.GuildID)
- return
- }
- <-time.After(wait * time.Second)
- wait *= 2
- if wait > 600 {
- wait = 600
- }
- i++
- if v.session.DataReady == false {
- v.log(LogInformational, "cannot reconenct with unready session")
- continue
- }
- v.log(LogInformational, "trying to reconnect to voice")
-
-
-
- gID := v.GuildID
- v.GuildID = ""
- v.sessionID = ""
- _, err := v.session.ChannelVoiceJoin(gID, v.ChannelID, v.mute, v.deaf)
- if err == nil {
- v.log(LogInformational, "successfully reconnected to voice")
- return
- }
- v.log(LogInformational, "error reconnecting to voice, %s", err)
- if i >= 10 {
-
-
- v.log(LogInformational, "timeout reconnecting, I give up.")
- v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID)
- delete(v.session.VoiceConnections, v.GuildID)
- return
- }
- }
- }
|