voice.go 8.9 KB

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