voice.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 initial 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. type voiceHandshakeData struct {
  37. ServerID string `json:"server_id"`
  38. UserID string `json:"user_id"`
  39. SessionID string `json:"session_id"`
  40. Token string `json:"token"`
  41. }
  42. type voiceHandshakeOp struct {
  43. Op int `json:"op"` // Always 0
  44. Data voiceHandshakeData `json:"d"`
  45. }
  46. // VoiceOpenWS opens a voice websocket connection. This should be called
  47. // after VoiceChannelJoin is used and the data VOICE websocket events
  48. // are captured.
  49. func (s *Session) VoiceOpenWS() {
  50. // Don't open a socket if one is already open
  51. if s.VwsConn != nil {
  52. return
  53. }
  54. var self User
  55. var err error
  56. self, err = s.User("@me") // TODO: Move to @ login and store in session
  57. // Connect to Voice Websocket
  58. vg := fmt.Sprintf("wss://%s", strings.TrimSuffix(s.VEndpoint, ":80"))
  59. s.VwsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  60. if err != nil {
  61. fmt.Println("VOICE cannot open websocket:", err)
  62. }
  63. json := voiceHandshakeOp{0, voiceHandshakeData{s.VGuildID, self.ID, s.VSessionID, s.VToken}}
  64. err = s.VwsConn.WriteJSON(json)
  65. if err != nil {
  66. fmt.Println("VOICE ERROR sending init packet:", err)
  67. }
  68. // Start a listening for voice websocket events
  69. go s.VoiceListen()
  70. }
  71. // Close closes the connection to the voice websocket.
  72. func (s *Session) VoiceCloseWS() {
  73. s.VwsConn.Close()
  74. }
  75. // VoiceListen listens on the voice websocket for messages and passes them
  76. // to the voice event handler.
  77. func (s *Session) VoiceListen() (err error) {
  78. for {
  79. messageType, message, err := s.VwsConn.ReadMessage()
  80. if err != nil {
  81. fmt.Println("Voice Listen Error:", err)
  82. break
  83. }
  84. // Pass received message to voice event handler
  85. go s.VoiceEvent(messageType, message)
  86. }
  87. return
  88. }
  89. // VoiceEvent handles any messages received on the voice websocket
  90. func (s *Session) VoiceEvent(messageType int, message []byte) (err error) {
  91. if s.Debug {
  92. fmt.Println("VOICE EVENT:", messageType)
  93. printJSON(message)
  94. }
  95. var e VEvent
  96. if err := json.Unmarshal(message, &e); err != nil {
  97. return err
  98. }
  99. switch e.Operation {
  100. case 2: // READY packet
  101. var st VoiceOP2
  102. if err := json.Unmarshal(e.RawData, &st); err != nil {
  103. fmt.Println(e.Type, err)
  104. printJSON(e.RawData) // TODO: Better error logginEventg
  105. return err
  106. }
  107. // Start the voice websocket heartbeat to keep the connection alive
  108. go s.VoiceHeartbeat(st.HeartbeatInterval)
  109. // Store all event data into the session
  110. s.Vop2 = st
  111. // We now have enough data to start the UDP connection
  112. s.VoiceOpenUDP()
  113. return
  114. case 3: // HEARTBEAT response
  115. // add code to use this to track latency?
  116. return
  117. case 4:
  118. // TODO
  119. default:
  120. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  121. printJSON(e.RawData)
  122. }
  123. return
  124. }
  125. type voiceUDPData struct {
  126. Address string `json:"address"` // Public IP of machine running this code
  127. Port uint16 `json:"port"` // UDP Port of machine running this code
  128. Mode string `json:"mode"` // plain or ? (plain or encrypted)
  129. }
  130. type voiceUDPD struct {
  131. Protocol string `json:"protocol"` // Always "udp" ?
  132. Data voiceUDPData `json:"data"`
  133. }
  134. type voiceUDPOp struct {
  135. Op int `json:"op"` // Always 1
  136. Data voiceUDPD `json:"d"`
  137. }
  138. // VoiceOpenUDP opens a UDP connect to the voice server and completes the
  139. // initial required handshake. This connect is left open in the session
  140. // and can be used to send or receive audio.
  141. func (s *Session) VoiceOpenUDP() {
  142. // TODO: add code to convert hostname into an IP address to avoid problems
  143. // with frequent DNS lookups. ??
  144. udpHost := fmt.Sprintf("%s:%d", strings.TrimSuffix(s.VEndpoint, ":80"), s.Vop2.Port)
  145. serverAddr, err := net.ResolveUDPAddr("udp", udpHost)
  146. if err != nil {
  147. fmt.Println(err)
  148. }
  149. s.UDPConn, err = net.DialUDP("udp", nil, serverAddr)
  150. if err != nil {
  151. fmt.Println(err)
  152. }
  153. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  154. // into it. Then send that over the UDP connection to Discord
  155. sb := make([]byte, 70)
  156. binary.BigEndian.PutUint32(sb, s.Vop2.SSRC)
  157. s.UDPConn.Write(sb)
  158. // Create a 70 byte array and listen for the initial handshake response
  159. // from Discord. Once we get it parse the IP and PORT information out
  160. // of the response. This should be our public IP and PORT as Discord
  161. // saw us.
  162. rb := make([]byte, 70)
  163. rlen, _, err := s.UDPConn.ReadFromUDP(rb)
  164. if rlen < 70 {
  165. fmt.Println("Voice RLEN should be 70 but isn't")
  166. }
  167. // TODO need serious changes, this will likely not work on all IPs!
  168. ip := string(rb[4:16]) // must be a better way. TODO: NEEDS TESTING
  169. port := make([]byte, 2)
  170. port[0] = rb[68]
  171. port[1] = rb[69]
  172. p := binary.LittleEndian.Uint16(port)
  173. // Take the parsed data from above and send it back to Discord
  174. // to finalize the UDP handshake.
  175. jsondata := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, p, "plain"}}}
  176. err = s.VwsConn.WriteJSON(jsondata)
  177. if err != nil {
  178. fmt.Println("error:", err)
  179. return
  180. }
  181. s.UDPReady = true
  182. // continue to listen for future packets
  183. // go s.VoiceListenUDP()
  184. }
  185. // VoiceCloseUDP closes the voice UDP connection.
  186. func (s *Session) VoiceCloseUDP() {
  187. s.UDPConn.Close()
  188. }
  189. type voiceSpeakingData struct {
  190. Speaking bool `json:"speaking"`
  191. Delay int `json:"delay"`
  192. }
  193. type voiceSpeakingOp struct {
  194. Op int `json:"op"` // Always 5
  195. Data voiceSpeakingData `json:"d"`
  196. }
  197. func (s *Session) VoiceSpeaking() {
  198. if s.VwsConn == nil {
  199. // TODO return an error
  200. fmt.Println("No Voice websocket.")
  201. return
  202. }
  203. json := voiceSpeakingOp{5, voiceSpeakingData{true, 0}}
  204. err := s.VwsConn.WriteJSON(json)
  205. if err != nil {
  206. fmt.Println("error:", err)
  207. return
  208. }
  209. }
  210. // VoiceListenUDP is test code to listen for UDP packets
  211. func (s *Session) VoiceListenUDP() {
  212. // start the udp keep alive too. Otherwise listening doesn't get much.
  213. // THIS DOES NOT WORK YET
  214. // go s.VoiceUDPKeepalive(s.Vop2.HeartbeatInterval) // lets try the ws timer
  215. for {
  216. b := make([]byte, 1024)
  217. rlen, _, err := s.UDPConn.ReadFromUDP(b)
  218. if err != nil {
  219. fmt.Println("Error reading from UDP:", err)
  220. // return
  221. }
  222. if rlen < 1 {
  223. fmt.Println("Empty UDP packet received")
  224. continue
  225. // empty packet?
  226. }
  227. fmt.Println("READ FROM UDP: ", b)
  228. }
  229. }
  230. // VoiceUDPKeepalive sends a packet to keep the UDP connection forwarding
  231. // alive for NATed clients. Without this no audio can be received
  232. // after short periods of silence.
  233. // Not sure how often this is supposed to be sent or even what payload
  234. // I am suppose to be sending. So this is very.. unfinished :)
  235. func (s *Session) VoiceUDPKeepalive(i time.Duration) {
  236. // NONE OF THIS WORKS. SO DON'T USE IT.
  237. //
  238. // testing with the above 70 byte SSRC packet.
  239. //
  240. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  241. // into it. Then send that over the UDP connection to Discord
  242. ticker := time.NewTicker(i * time.Millisecond)
  243. for range ticker.C {
  244. sb := make([]byte, 8)
  245. sb[0] = 0x80
  246. sb[1] = 0xc9
  247. sb[2] = 0x00
  248. sb[3] = 0x01
  249. ssrcBE := make([]byte, 4)
  250. binary.BigEndian.PutUint32(ssrcBE, s.Vop2.SSRC)
  251. sb[4] = ssrcBE[0]
  252. sb[5] = ssrcBE[1]
  253. sb[6] = ssrcBE[2]
  254. sb[7] = ssrcBE[3]
  255. s.UDPConn.Write(ssrcBE)
  256. }
  257. }
  258. type voiceHeartbeatOp struct {
  259. Op int `json:"op"` // Always 3
  260. Data int `json:"d"`
  261. }
  262. // VoiceHeartbeat sends regular heartbeats to voice Discord so it knows the client
  263. // is still connected. If you do not send these heartbeats Discord will
  264. // disconnect the websocket connection after a few seconds.
  265. func (s *Session) VoiceHeartbeat(i time.Duration) {
  266. ticker := time.NewTicker(i * time.Millisecond)
  267. for {
  268. timestamp := int(time.Now().Unix())
  269. json := voiceHeartbeatOp{3, timestamp}
  270. err := s.VwsConn.WriteJSON(json)
  271. if err != nil {
  272. s.VoiceReady = false
  273. fmt.Println(err)
  274. return // log error?
  275. }
  276. s.VoiceReady = true
  277. <-ticker.C
  278. }
  279. }