voice.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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.VoiceListen()
  59. }
  60. // Close closes the connection to the voice websocket.
  61. func (s *Session) VoiceCloseWS() {
  62. s.VwsConn.Close()
  63. }
  64. // VoiceListen listens on the voice websocket for messages and passes them
  65. // to the voice event handler.
  66. func (s *Session) VoiceListen() (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. case 4:
  107. // TODO
  108. default:
  109. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  110. printJSON(e.RawData)
  111. }
  112. return
  113. }
  114. // VoiceOpenUDP opens a UDP connect to the voice server and completes the
  115. // initial required handshake. This connect is left open in the session
  116. // and can be used to send or receive audio.
  117. func (s *Session) VoiceOpenUDP() {
  118. // TODO: add code to convert hostname into an IP address to avoid problems
  119. // with frequent DNS lookups.
  120. udpHost := fmt.Sprintf("%s:%d", strings.TrimSuffix(s.VEndpoint, ":80"), s.Vop2.Port)
  121. serverAddr, err := net.ResolveUDPAddr("udp", udpHost)
  122. if err != nil {
  123. fmt.Println(err)
  124. }
  125. s.UDPConn, err = net.DialUDP("udp", nil, serverAddr)
  126. if err != nil {
  127. fmt.Println(err)
  128. }
  129. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  130. // into it. Then send that over the UDP connection to Discord
  131. sb := make([]byte, 70)
  132. binary.BigEndian.PutUint32(sb, s.Vop2.SSRC)
  133. s.UDPConn.Write(sb)
  134. // Create a 70 byte array and listen for the initial handshake response
  135. // from Discord. Once we get it parse the IP and PORT information out
  136. // of the response. This should be our public IP and PORT as Discord
  137. // saw us.
  138. rb := make([]byte, 70)
  139. rlen, _, err := s.UDPConn.ReadFromUDP(rb)
  140. if rlen < 70 {
  141. fmt.Println("Voice RLEN should be 70 but isn't")
  142. }
  143. ip := string(rb[4:16]) // must be a better way. TODO: NEEDS TESTING
  144. port := make([]byte, 2)
  145. port[0] = rb[68]
  146. port[1] = rb[69]
  147. p := binary.LittleEndian.Uint16(port)
  148. // Take the parsed data from above and send it back to Discord
  149. // to finalize the UDP handshake.
  150. json := fmt.Sprintf(`{"op":1,"d":{"protocol":"udp","data":{"address":"%s","port":%d,"mode":"plain"}}}`, ip, p)
  151. jsonb := []byte(json)
  152. err = s.VwsConn.WriteMessage(websocket.TextMessage, jsonb)
  153. if err != nil {
  154. fmt.Println("error:", err)
  155. return
  156. }
  157. // continue to listen for future packets
  158. // go s.VoiceListenUDP()
  159. }
  160. // VoiceCloseUDP closes the voice UDP connection.
  161. func (s *Session) VoiceCloseUDP() {
  162. s.UDPConn.Close()
  163. }
  164. func (s *Session) VoiceSpeaking() {
  165. jsonb := []byte(`{"op":5,"d":{"speaking":true,"delay":0}}`)
  166. err := s.VwsConn.WriteMessage(websocket.TextMessage, jsonb)
  167. if err != nil {
  168. fmt.Println("error:", err)
  169. return
  170. }
  171. }
  172. // VoiceListenUDP is test code to listen for UDP packets
  173. func (s *Session) VoiceListenUDP() {
  174. // start the udp keep alive too. Otherwise listening doesn't get much.
  175. // THIS DOES NOT WORK YET
  176. // go s.VoiceUDPKeepalive(s.Vop2.HeartbeatInterval) // lets try the ws timer
  177. for {
  178. b := make([]byte, 1024)
  179. rlen, _, err := s.UDPConn.ReadFromUDP(b)
  180. if err != nil {
  181. fmt.Println("Error reading from UDP:", err)
  182. // return
  183. }
  184. if rlen < 1 {
  185. fmt.Println("Empty UDP packet received")
  186. continue
  187. // empty packet?
  188. }
  189. fmt.Println("READ FROM UDP: ", b)
  190. }
  191. }
  192. // VoiceUDPKeepalive sends a packet to keep the UDP connection forwarding
  193. // alive for NATed clients. Without this no audio can be received
  194. // after short periods of silence.
  195. // Not sure how often this is supposed to be sent or even what payload
  196. // I am suppose to be sending. So this is very.. unfinished :)
  197. func (s *Session) VoiceUDPKeepalive(i time.Duration) {
  198. // NONE OF THIS WORKS. SO DON'T USE IT.
  199. //
  200. // testing with the above 70 byte SSRC packet.
  201. //
  202. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  203. // into it. Then send that over the UDP connection to Discord
  204. ticker := time.NewTicker(i * time.Millisecond)
  205. for range ticker.C {
  206. sb := make([]byte, 8)
  207. sb[0] = 0x80
  208. sb[1] = 0xc9
  209. sb[2] = 0x00
  210. sb[3] = 0x01
  211. ssrcBE := make([]byte, 4)
  212. binary.BigEndian.PutUint32(ssrcBE, s.Vop2.SSRC)
  213. sb[4] = ssrcBE[0]
  214. sb[5] = ssrcBE[1]
  215. sb[6] = ssrcBE[2]
  216. sb[7] = ssrcBE[3]
  217. s.UDPConn.Write(ssrcBE)
  218. }
  219. }
  220. // VoiceHeartbeat sends regular heartbeats to voice Discord so it knows the client
  221. // is still connected. If you do not send these heartbeats Discord will
  222. // disconnect the websocket connection after a few seconds.
  223. func (s *Session) VoiceHeartbeat(i time.Duration) {
  224. ticker := time.NewTicker(i * time.Millisecond)
  225. for range ticker.C {
  226. timestamp := int(time.Now().Unix())
  227. err := s.VwsConn.WriteJSON(map[string]int{
  228. "op": 3,
  229. "d": timestamp,
  230. })
  231. if err != nil {
  232. fmt.Println(err)
  233. return // log error?
  234. }
  235. }
  236. }