voice.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains experimental functions for interacting with the Discord
  7. // Voice websocket and UDP connections.
  8. //
  9. // EVERYTHING in this file is very experimental and will change.
  10. package discordgo
  11. import (
  12. "encoding/binary"
  13. "encoding/json"
  14. "fmt"
  15. "net"
  16. "strings"
  17. "time"
  18. "github.com/gorilla/websocket"
  19. )
  20. // A VEvent is the inital structure for voice websocket events. I think
  21. // I can reuse the data websocket structure here.
  22. type VEvent struct {
  23. Type string `json:"t"`
  24. State int `json:"s"`
  25. Operation int `json:"op"`
  26. RawData json.RawMessage `json:"d"`
  27. }
  28. // A VoiceOP2 stores the data for voice operation 2 websocket events
  29. // which is sort of like the voice READY packet
  30. type VoiceOP2 struct {
  31. SSRC uint32 `json:"ssrc"`
  32. Port int `json:"port"`
  33. Modes []string `json:"modes"`
  34. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  35. }
  36. // VoiceOpenWS opens a voice websocket connection. This should be called
  37. // after VoiceChannelJoin is used and the data VOICE websocket events
  38. // are captured.
  39. func (s *Session) VoiceOpenWS() {
  40. var self User
  41. var err error
  42. self, err = s.User("@me") // AGAIN, Move to @ login and store in session
  43. // Connect to Voice Websocket
  44. vg := fmt.Sprintf("wss://%s", strings.TrimSuffix(s.VEndpoint, ":80"))
  45. s.VwsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  46. if err != nil {
  47. fmt.Println("VOICE cannot open websocket:", err)
  48. }
  49. // Send initial handshake data to voice websocket. This is required.
  50. json := map[string]interface{}{
  51. "op": 0,
  52. "d": map[string]interface{}{
  53. "server_id": s.VGuildID,
  54. "user_id": self.ID,
  55. "session_id": s.VSessionID,
  56. "token": s.VToken,
  57. },
  58. }
  59. err = s.VwsConn.WriteJSON(json)
  60. if err != nil {
  61. fmt.Println("VOICE ERROR sending init packet:", err)
  62. }
  63. // Start a listening for voice websocket events
  64. go s.VoiceListen()
  65. }
  66. // Close closes the connection to the voice websocket.
  67. func (s *Session) VoiceCloseWS() {
  68. s.VwsConn.Close()
  69. }
  70. // VoiceListen listens on the voice websocket for messages and passes them
  71. // to the voice event handler.
  72. func (s *Session) VoiceListen() (err error) {
  73. for {
  74. messageType, message, err := s.VwsConn.ReadMessage()
  75. if err != nil {
  76. fmt.Println("Voice Listen Error:", err)
  77. break
  78. }
  79. // Pass received message to voice event handler
  80. go s.VoiceEvent(messageType, message)
  81. }
  82. return
  83. }
  84. // VoiceEvent handles any messages received on the voice websocket
  85. func (s *Session) VoiceEvent(messageType int, message []byte) (err error) {
  86. if s.Debug {
  87. fmt.Println("VOICE EVENT:", messageType)
  88. printJSON(message)
  89. }
  90. var e VEvent
  91. if err := json.Unmarshal(message, &e); err != nil {
  92. return err
  93. }
  94. switch e.Operation {
  95. case 2: // READY packet
  96. var st VoiceOP2
  97. if err := json.Unmarshal(e.RawData, &st); err != nil {
  98. fmt.Println(e.Type, err)
  99. printJSON(e.RawData) // TODO: Better error logginEventg
  100. return err
  101. }
  102. // Start the voice websocket heartbeat to keep the connection alive
  103. go s.VoiceHeartbeat(st.HeartbeatInterval)
  104. // Store all event data into the session
  105. s.Vop2 = st
  106. // We now have enough data to start the UDP connection
  107. s.VoiceOpenUDP()
  108. return
  109. case 3: // HEARTBEAT response
  110. // add code to use this to track latency?
  111. return
  112. case 4:
  113. // TODO
  114. default:
  115. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  116. printJSON(e.RawData)
  117. }
  118. return
  119. }
  120. // VoiceOpenUDP opens a UDP connect to the voice server and completes the
  121. // initial required handshake. This connect is left open in the session
  122. // and can be used to send or receive audio.
  123. func (s *Session) VoiceOpenUDP() {
  124. // TODO: add code to convert hostname into an IP address to avoid problems
  125. // with frequent DNS lookups.
  126. udpHost := fmt.Sprintf("%s:%d", strings.TrimSuffix(s.VEndpoint, ":80"), s.Vop2.Port)
  127. serverAddr, err := net.ResolveUDPAddr("udp", udpHost)
  128. if err != nil {
  129. fmt.Println(err)
  130. }
  131. s.UDPConn, err = net.DialUDP("udp", nil, serverAddr)
  132. if err != nil {
  133. fmt.Println(err)
  134. }
  135. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  136. // into it. Then send that over the UDP connection to Discord
  137. sb := make([]byte, 70)
  138. binary.BigEndian.PutUint32(sb, s.Vop2.SSRC)
  139. s.UDPConn.Write(sb)
  140. // Create a 70 byte array and listen for the initial handshake response
  141. // from Discord. Once we get it parse the IP and PORT information out
  142. // of the response. This should be our public IP and PORT as Discord
  143. // saw us.
  144. rb := make([]byte, 70)
  145. rlen, _, err := s.UDPConn.ReadFromUDP(rb)
  146. if rlen < 70 {
  147. fmt.Println("Voice RLEN should be 70 but isn't")
  148. }
  149. ip := string(rb[4:16]) // must be a better way. TODO: NEEDS TESTING
  150. port := make([]byte, 2)
  151. port[0] = rb[68]
  152. port[1] = rb[69]
  153. p := binary.LittleEndian.Uint16(port)
  154. // Take the parsed data from above and send it back to Discord
  155. // to finalize the UDP handshake.
  156. json := fmt.Sprintf(`{"op":1,"d":{"protocol":"udp","data":{"address":"%s","port":%d,"mode":"plain"}}}`, ip, p)
  157. jsonb := []byte(json)
  158. err = s.VwsConn.WriteMessage(websocket.TextMessage, jsonb)
  159. if err != nil {
  160. fmt.Println("error:", err)
  161. return
  162. }
  163. s.UDPReady = true
  164. // continue to listen for future packets
  165. // go s.VoiceListenUDP()
  166. }
  167. // VoiceCloseUDP closes the voice UDP connection.
  168. func (s *Session) VoiceCloseUDP() {
  169. s.UDPConn.Close()
  170. }
  171. func (s *Session) VoiceSpeaking() {
  172. if s.VwsConn == nil {
  173. // TODO return an error
  174. fmt.Println("No Voice websocket.")
  175. return
  176. }
  177. jsonb := []byte(`{"op":5,"d":{"speaking":true,"delay":0}}`)
  178. err := s.VwsConn.WriteMessage(websocket.TextMessage, jsonb)
  179. if err != nil {
  180. fmt.Println("error:", err)
  181. return
  182. }
  183. }
  184. // VoiceListenUDP is test code to listen for UDP packets
  185. func (s *Session) VoiceListenUDP() {
  186. // start the udp keep alive too. Otherwise listening doesn't get much.
  187. // THIS DOES NOT WORK YET
  188. // go s.VoiceUDPKeepalive(s.Vop2.HeartbeatInterval) // lets try the ws timer
  189. for {
  190. b := make([]byte, 1024)
  191. rlen, _, err := s.UDPConn.ReadFromUDP(b)
  192. if err != nil {
  193. fmt.Println("Error reading from UDP:", err)
  194. // return
  195. }
  196. if rlen < 1 {
  197. fmt.Println("Empty UDP packet received")
  198. continue
  199. // empty packet?
  200. }
  201. fmt.Println("READ FROM UDP: ", b)
  202. }
  203. }
  204. // VoiceUDPKeepalive sends a packet to keep the UDP connection forwarding
  205. // alive for NATed clients. Without this no audio can be received
  206. // after short periods of silence.
  207. // Not sure how often this is supposed to be sent or even what payload
  208. // I am suppose to be sending. So this is very.. unfinished :)
  209. func (s *Session) VoiceUDPKeepalive(i time.Duration) {
  210. // NONE OF THIS WORKS. SO DON'T USE IT.
  211. //
  212. // testing with the above 70 byte SSRC packet.
  213. //
  214. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  215. // into it. Then send that over the UDP connection to Discord
  216. ticker := time.NewTicker(i * time.Millisecond)
  217. for range ticker.C {
  218. sb := make([]byte, 8)
  219. sb[0] = 0x80
  220. sb[1] = 0xc9
  221. sb[2] = 0x00
  222. sb[3] = 0x01
  223. ssrcBE := make([]byte, 4)
  224. binary.BigEndian.PutUint32(ssrcBE, s.Vop2.SSRC)
  225. sb[4] = ssrcBE[0]
  226. sb[5] = ssrcBE[1]
  227. sb[6] = ssrcBE[2]
  228. sb[7] = ssrcBE[3]
  229. s.UDPConn.Write(ssrcBE)
  230. }
  231. }
  232. // VoiceHeartbeat sends regular heartbeats to voice Discord so it knows the client
  233. // is still connected. If you do not send these heartbeats Discord will
  234. // disconnect the websocket connection after a few seconds.
  235. func (s *Session) VoiceHeartbeat(i time.Duration) {
  236. ticker := time.NewTicker(i * time.Millisecond)
  237. for {
  238. timestamp := int(time.Now().Unix())
  239. err := s.VwsConn.WriteJSON(map[string]int{
  240. "op": 3,
  241. "d": timestamp,
  242. })
  243. if err != nil {
  244. s.VoiceReady = false
  245. fmt.Println(err)
  246. return // log error?
  247. }
  248. s.VoiceReady = true
  249. <-ticker.C
  250. }
  251. }