voice.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // EVERYTHING in this file is very experimental and will change.
  2. // these structs and functions setup a voice websocket and
  3. // create the voice UDP connection.
  4. package discordgo
  5. import (
  6. "encoding/binary"
  7. "encoding/json"
  8. "fmt"
  9. "net"
  10. "strings"
  11. "time"
  12. "github.com/gorilla/websocket"
  13. )
  14. // A VEvent is the inital structure for voice websocket events. I think
  15. // I can reuse the data websocket structure here.
  16. type VEvent struct {
  17. Type string `json:"t"`
  18. State int `json:"s"`
  19. Operation int `json:"op"`
  20. RawData json.RawMessage `json:"d"`
  21. }
  22. // A VoiceOP2 stores the data for voice operation 2 websocket events
  23. // which is sort of like the voice READY packet
  24. type VoiceOP2 struct {
  25. SSRC uint32 `json:"ssrc"`
  26. Port int `json:"port"`
  27. Modes []string `json:"modes"`
  28. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  29. }
  30. // VoiceOpenWS opens a voice websocket connection. This should be called
  31. // after VoiceChannelJoin is used and the data VOICE websocket events
  32. // are captured.
  33. func (s *Session) VoiceOpenWS() {
  34. var self User
  35. var err error
  36. self, err = s.User("@me") // AGAIN, Move to @ login and store in session
  37. // Connect to Voice Websocket
  38. vg := fmt.Sprintf("wss://%s", strings.TrimSuffix(s.VEndpoint, ":80"))
  39. s.VwsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  40. if err != nil {
  41. fmt.Println("VOICE cannot open websocket:", err)
  42. }
  43. // Send initial handshake data to voice websocket. This is required.
  44. json := map[string]interface{}{
  45. "op": 0,
  46. "d": map[string]interface{}{
  47. "server_id": s.VGuildID,
  48. "user_id": self.ID,
  49. "session_id": s.VSessionID,
  50. "token": s.VToken,
  51. },
  52. }
  53. err = s.VwsConn.WriteJSON(json)
  54. if err != nil {
  55. fmt.Println("VOICE ERROR sending init packet:", err)
  56. }
  57. // Start a listening for voice websocket events
  58. go s.VListen()
  59. }
  60. // Close closes the connection to the voice websocket.
  61. func (s *Session) VoiceCloseWS() {
  62. s.VwsConn.Close()
  63. }
  64. // VListen listens on the voice websocket for messages and passes them
  65. // to the voice event handler.
  66. func (s *Session) VListen() (err error) {
  67. for {
  68. messageType, message, err := s.VwsConn.ReadMessage()
  69. if err != nil {
  70. fmt.Println("Voice Listen Error:", err)
  71. break
  72. }
  73. // Pass received message to voice event handler
  74. go s.VoiceEvent(messageType, message)
  75. }
  76. return
  77. }
  78. // VoiceEvent handles any messages received on the voice websocket
  79. func (s *Session) VoiceEvent(messageType int, message []byte) (err error) {
  80. if s.Debug {
  81. fmt.Println("VOICE EVENT:", messageType)
  82. printJSON(message)
  83. }
  84. var e VEvent
  85. if err := json.Unmarshal(message, &e); err != nil {
  86. return err
  87. }
  88. switch e.Operation {
  89. case 2: // READY packet
  90. var st VoiceOP2
  91. if err := json.Unmarshal(e.RawData, &st); err != nil {
  92. fmt.Println(e.Type, err)
  93. printJSON(e.RawData) // TODO: Better error logginEventg
  94. return err
  95. }
  96. // Start the voice websocket heartbeat to keep the connection alive
  97. go s.VoiceHeartbeat(st.HeartbeatInterval)
  98. // Store all event data into the session
  99. s.Vop2 = st
  100. // We now have enough data to start the UDP connection
  101. s.VoiceOpenUDP()
  102. return
  103. case 3: // HEARTBEAT response
  104. // add code to use this to track latency?
  105. return
  106. default:
  107. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  108. printJSON(e.RawData)
  109. }
  110. return
  111. }
  112. // VoiceOpenUDP opens a UDP connect to the voice server and completes the
  113. // initial required handshake. This connect is left open in the session
  114. // and can be used to send or receive audio.
  115. func (s *Session) VoiceOpenUDP() {
  116. // TODO: add code to convert hostname into an IP address to avoid problems
  117. // with frequent DNS lookups.
  118. udpHost := fmt.Sprintf("%s:%d", strings.TrimSuffix(s.VEndpoint, ":80"), s.Vop2.Port)
  119. serverAddr, err := net.ResolveUDPAddr("udp", udpHost)
  120. if err != nil {
  121. fmt.Println(err)
  122. }
  123. s.UDPConn, err = net.DialUDP("udp", nil, serverAddr)
  124. if err != nil {
  125. fmt.Println(err)
  126. }
  127. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  128. // into it. Then send that over the UDP connection to Discord
  129. sb := make([]byte, 70)
  130. binary.BigEndian.PutUint32(sb, s.Vop2.SSRC)
  131. s.UDPConn.Write(sb)
  132. // Create a 70 byte array and listen for the initial handshake response
  133. // from Discord. Once we get it parse the IP and PORT information out
  134. // of the response. This should be our public IP and PORT as Discord
  135. // saw us.
  136. rb := make([]byte, 70)
  137. rlen, _, err := s.UDPConn.ReadFromUDP(rb)
  138. if rlen < 70 {
  139. fmt.Println("Voice RLEN should be 70 but isn't")
  140. }
  141. ip := string(rb[4:16]) // must be a better way. TODO: NEEDS TESTING
  142. port := make([]byte, 2)
  143. port[0] = rb[68]
  144. port[1] = rb[69]
  145. p := binary.LittleEndian.Uint16(port)
  146. // Take the parsed data from above and send it back to Discord
  147. // to finalize the UDP handshake.
  148. json := fmt.Sprintf(`{"op":1,"d":{"protocol":"udp","data":{"address":"%s","port":"%d","mode":"plain"}}}`, ip, p)
  149. jsonb := []byte(json)
  150. err = s.VwsConn.WriteMessage(websocket.TextMessage, jsonb)
  151. if err != nil {
  152. fmt.Println("error:", err)
  153. return
  154. }
  155. // continue to listen for future packets
  156. go s.VoiceListenUDP()
  157. }
  158. // VoiceCloseUDP closes the voice UDP connection.
  159. func (s *Session) VoiceCloseUDP() {
  160. s.UDPConn.Close()
  161. }
  162. // VoiceListenUDP is test code to listen for UDP packets
  163. func (s *Session) VoiceListenUDP() {
  164. for {
  165. fmt.Println("READ FROM UDP LOOP:")
  166. b := make([]byte, 1024)
  167. s.UDPConn.ReadFromUDP(b)
  168. fmt.Println("READ FROM UDP: ", b)
  169. }
  170. }
  171. // VoiceHeartbeat sends regular heartbeats to voice Discord so it knows the client
  172. // is still connected. If you do not send these heartbeats Discord will
  173. // disconnect the websocket connection after a few seconds.
  174. func (s *Session) VoiceHeartbeat(i time.Duration) {
  175. ticker := time.NewTicker(i * time.Millisecond)
  176. for range ticker.C {
  177. timestamp := int(time.Now().Unix())
  178. err := s.VwsConn.WriteJSON(map[string]int{
  179. "op": 3,
  180. "d": timestamp,
  181. })
  182. if err != nil {
  183. fmt.Println(err)
  184. return // log error?
  185. }
  186. }
  187. }