voice.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 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. udpHost := fmt.Sprintf("%s:%d", strings.TrimSuffix(s.VEndpoint, ":80"), s.Vop2.Port)
  143. serverAddr, err := net.ResolveUDPAddr("udp", udpHost)
  144. if err != nil {
  145. fmt.Println(err)
  146. }
  147. s.UDPConn, err = net.DialUDP("udp", nil, serverAddr)
  148. if err != nil {
  149. fmt.Println(err)
  150. }
  151. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  152. // into it. Then send that over the UDP connection to Discord
  153. sb := make([]byte, 70)
  154. binary.BigEndian.PutUint32(sb, s.Vop2.SSRC)
  155. s.UDPConn.Write(sb)
  156. // Create a 70 byte array and listen for the initial handshake response
  157. // from Discord. Once we get it parse the IP and PORT information out
  158. // of the response. This should be our public IP and PORT as Discord
  159. // saw us.
  160. rb := make([]byte, 70)
  161. rlen, _, err := s.UDPConn.ReadFromUDP(rb)
  162. if rlen < 70 {
  163. fmt.Println("Voice RLEN should be 70 but isn't")
  164. }
  165. // Loop over position 4 though 20 to grab the IP address
  166. // Should never be beyond position 20.
  167. var ip string
  168. for i := 4; i < 20; i++ {
  169. if rb[i] == 0 {
  170. break
  171. }
  172. ip += string(rb[i])
  173. }
  174. // Grab port from postion 68 and 69
  175. port := binary.LittleEndian.Uint16(rb[68:70])
  176. // Take the parsed data from above and send it back to Discord
  177. // to finalize the UDP handshake.
  178. jsondata := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "plain"}}}
  179. err = s.VwsConn.WriteJSON(jsondata)
  180. if err != nil {
  181. fmt.Println("error:", err)
  182. return
  183. }
  184. s.UDPReady = true
  185. }
  186. // VoiceCloseUDP closes the voice UDP connection.
  187. func (s *Session) VoiceCloseUDP() {
  188. s.UDPConn.Close()
  189. }
  190. type voiceSpeakingData struct {
  191. Speaking bool `json:"speaking"`
  192. Delay int `json:"delay"`
  193. }
  194. type voiceSpeakingOp struct {
  195. Op int `json:"op"` // Always 5
  196. Data voiceSpeakingData `json:"d"`
  197. }
  198. func (s *Session) VoiceSpeaking() {
  199. if s.VwsConn == nil {
  200. // TODO return an error
  201. fmt.Println("No Voice websocket.")
  202. return
  203. }
  204. json := voiceSpeakingOp{5, voiceSpeakingData{true, 0}}
  205. err := s.VwsConn.WriteJSON(json)
  206. if err != nil {
  207. fmt.Println("error:", err)
  208. return
  209. }
  210. }
  211. // VoiceListenUDP is test code to listen for UDP packets
  212. func (s *Session) VoiceListenUDP() {
  213. // start the udp keep alive too. Otherwise listening doesn't get much.
  214. // THIS DOES NOT WORK YET
  215. // go s.VoiceUDPKeepalive(s.Vop2.HeartbeatInterval) // lets try the ws timer
  216. for {
  217. b := make([]byte, 1024) //TODO DO NOT PUT MAKE INSIDE LOOP
  218. rlen, _, err := s.UDPConn.ReadFromUDP(b)
  219. if err != nil {
  220. fmt.Println("Error reading from UDP:", err)
  221. // return
  222. }
  223. if rlen < 1 {
  224. fmt.Println("Empty UDP packet received")
  225. continue
  226. // empty packet?
  227. }
  228. fmt.Println("READ FROM UDP: ", b)
  229. }
  230. }
  231. // VoiceUDPKeepalive sends a packet to keep the UDP connection forwarding
  232. // alive for NATed clients. Without this no audio can be received
  233. // after short periods of silence.
  234. // Not sure how often this is supposed to be sent or even what payload
  235. // I am suppose to be sending. So this is very.. unfinished :)
  236. func (s *Session) VoiceUDPKeepalive(i time.Duration) {
  237. // NONE OF THIS WORKS. SO DON'T USE IT.
  238. //
  239. // testing with the above 70 byte SSRC packet.
  240. //
  241. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  242. // into it. Then send that over the UDP connection to Discord
  243. ticker := time.NewTicker(i * time.Millisecond)
  244. for _ = range ticker.C {
  245. sb := make([]byte, 8)
  246. sb[0] = 0x80
  247. sb[1] = 0xc9
  248. sb[2] = 0x00
  249. sb[3] = 0x01
  250. ssrcBE := make([]byte, 4)
  251. binary.BigEndian.PutUint32(ssrcBE, s.Vop2.SSRC)
  252. sb[4] = ssrcBE[0]
  253. sb[5] = ssrcBE[1]
  254. sb[6] = ssrcBE[2]
  255. sb[7] = ssrcBE[3]
  256. s.UDPConn.Write(ssrcBE)
  257. }
  258. }
  259. type voiceHeartbeatOp struct {
  260. Op int `json:"op"` // Always 3
  261. Data int `json:"d"`
  262. }
  263. // VoiceHeartbeat sends regular heartbeats to voice Discord so it knows the client
  264. // is still connected. If you do not send these heartbeats Discord will
  265. // disconnect the websocket connection after a few seconds.
  266. func (s *Session) VoiceHeartbeat(i time.Duration) {
  267. ticker := time.NewTicker(i * time.Millisecond)
  268. for {
  269. err := s.VwsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  270. if err != nil {
  271. s.VoiceReady = false
  272. fmt.Println(err)
  273. return // TODO LOG ERROR
  274. }
  275. s.VoiceReady = true
  276. <-ticker.C
  277. }
  278. }