voice.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // Discordgo - Go bindings for Discord
  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. // continue to listen for future packets
  164. // go s.VoiceListenUDP()
  165. }
  166. // VoiceCloseUDP closes the voice UDP connection.
  167. func (s *Session) VoiceCloseUDP() {
  168. s.UDPConn.Close()
  169. }
  170. func (s *Session) VoiceSpeaking() {
  171. jsonb := []byte(`{"op":5,"d":{"speaking":true,"delay":0}}`)
  172. err := s.VwsConn.WriteMessage(websocket.TextMessage, jsonb)
  173. if err != nil {
  174. fmt.Println("error:", err)
  175. return
  176. }
  177. }
  178. // VoiceListenUDP is test code to listen for UDP packets
  179. func (s *Session) VoiceListenUDP() {
  180. // start the udp keep alive too. Otherwise listening doesn't get much.
  181. // THIS DOES NOT WORK YET
  182. // go s.VoiceUDPKeepalive(s.Vop2.HeartbeatInterval) // lets try the ws timer
  183. for {
  184. b := make([]byte, 1024)
  185. rlen, _, err := s.UDPConn.ReadFromUDP(b)
  186. if err != nil {
  187. fmt.Println("Error reading from UDP:", err)
  188. // return
  189. }
  190. if rlen < 1 {
  191. fmt.Println("Empty UDP packet received")
  192. continue
  193. // empty packet?
  194. }
  195. fmt.Println("READ FROM UDP: ", b)
  196. }
  197. }
  198. // VoiceUDPKeepalive sends a packet to keep the UDP connection forwarding
  199. // alive for NATed clients. Without this no audio can be received
  200. // after short periods of silence.
  201. // Not sure how often this is supposed to be sent or even what payload
  202. // I am suppose to be sending. So this is very.. unfinished :)
  203. func (s *Session) VoiceUDPKeepalive(i time.Duration) {
  204. // NONE OF THIS WORKS. SO DON'T USE IT.
  205. //
  206. // testing with the above 70 byte SSRC packet.
  207. //
  208. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  209. // into it. Then send that over the UDP connection to Discord
  210. ticker := time.NewTicker(i * time.Millisecond)
  211. for range ticker.C {
  212. sb := make([]byte, 8)
  213. sb[0] = 0x80
  214. sb[1] = 0xc9
  215. sb[2] = 0x00
  216. sb[3] = 0x01
  217. ssrcBE := make([]byte, 4)
  218. binary.BigEndian.PutUint32(ssrcBE, s.Vop2.SSRC)
  219. sb[4] = ssrcBE[0]
  220. sb[5] = ssrcBE[1]
  221. sb[6] = ssrcBE[2]
  222. sb[7] = ssrcBE[3]
  223. s.UDPConn.Write(ssrcBE)
  224. }
  225. }
  226. // VoiceHeartbeat sends regular heartbeats to voice Discord so it knows the client
  227. // is still connected. If you do not send these heartbeats Discord will
  228. // disconnect the websocket connection after a few seconds.
  229. func (s *Session) VoiceHeartbeat(i time.Duration) {
  230. ticker := time.NewTicker(i * time.Millisecond)
  231. for range ticker.C {
  232. timestamp := int(time.Now().Unix())
  233. err := s.VwsConn.WriteJSON(map[string]int{
  234. "op": 3,
  235. "d": timestamp,
  236. })
  237. if err != nil {
  238. fmt.Println(err)
  239. return // log error?
  240. }
  241. }
  242. }