voice.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 code related to Discord voice suppport
  7. package discordgo
  8. import (
  9. "encoding/binary"
  10. "encoding/json"
  11. "fmt"
  12. "net"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/gorilla/websocket"
  17. )
  18. // ------------------------------------------------------------------------------------------------
  19. // Code related to both Voice Websocket and UDP connections.
  20. // ------------------------------------------------------------------------------------------------
  21. // A Voice struct holds all data and functions related to Discord Voice support.
  22. type Voice struct {
  23. sync.Mutex // future use
  24. Ready bool // If true, voice is ready to send/receive audio
  25. Debug bool // If true, print extra logging
  26. Chan chan struct{} // future use
  27. UDPConn *net.UDPConn // exported for dgvoice, may change.
  28. OP2 *voiceOP2 // exported for dgvoice, may change.
  29. wsConn *websocket.Conn
  30. sessionID string
  31. token string
  32. endpoint string
  33. guildID string
  34. channelID string
  35. userID string
  36. }
  37. // ------------------------------------------------------------------------------------------------
  38. // Code related to the Voice websocket connection
  39. // ------------------------------------------------------------------------------------------------
  40. // A voiceOP2 stores the data for the voice operation 2 websocket event
  41. // which is sort of like the voice READY packet
  42. type voiceOP2 struct {
  43. SSRC uint32 `json:"ssrc"`
  44. Port int `json:"port"`
  45. Modes []string `json:"modes"`
  46. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  47. }
  48. type voiceHandshakeData struct {
  49. ServerID string `json:"server_id"`
  50. UserID string `json:"user_id"`
  51. SessionID string `json:"session_id"`
  52. Token string `json:"token"`
  53. }
  54. type voiceHandshakeOp struct {
  55. Op int `json:"op"` // Always 0
  56. Data voiceHandshakeData `json:"d"`
  57. }
  58. // Open opens a voice connection. This should be called
  59. // after VoiceChannelJoin is used and the data VOICE websocket events
  60. // are captured.
  61. func (v *Voice) Open() (err error) {
  62. // TODO: How do we handle changing channels?
  63. // Don't open a websocket if one is already open
  64. if v.wsConn != nil {
  65. return
  66. }
  67. // Connect to Voice Websocket
  68. vg := fmt.Sprintf("wss://%s", strings.TrimSuffix(v.endpoint, ":80"))
  69. v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  70. if err != nil {
  71. fmt.Println("VOICE error opening websocket:", err)
  72. return
  73. }
  74. data := voiceHandshakeOp{0, voiceHandshakeData{v.guildID, v.userID, v.sessionID, v.token}}
  75. err = v.wsConn.WriteJSON(data)
  76. if err != nil {
  77. fmt.Println("VOICE error sending init packet:", err)
  78. return
  79. }
  80. // Start a listening for voice websocket events
  81. // TODO add a check here to make sure Listen worked by monitoring
  82. // a chan or bool?
  83. go v.wsListen()
  84. return
  85. }
  86. // Close closes the voice connection
  87. func (v *Voice) Close() {
  88. if v.UDPConn != nil {
  89. v.UDPConn.Close()
  90. }
  91. if v.wsConn != nil {
  92. v.wsConn.Close()
  93. }
  94. }
  95. // wsListen listens on the voice websocket for messages and passes them
  96. // to the voice event handler. This is automaticly called by the Open func
  97. func (v *Voice) wsListen() {
  98. for {
  99. messageType, message, err := v.wsConn.ReadMessage()
  100. if err != nil {
  101. // TODO: Handle this problem better.
  102. // TODO: needs proper logging
  103. fmt.Println("Voice Listen Error:", err)
  104. break
  105. }
  106. // Pass received message to voice event handler
  107. go v.wsEvent(messageType, message)
  108. }
  109. return
  110. }
  111. // wsEvent handles any voice websocket events. This is only called by the
  112. // wsListen() function.
  113. func (v *Voice) wsEvent(messageType int, message []byte) {
  114. if v.Debug {
  115. fmt.Println("wsEvent received: ", messageType)
  116. printJSON(message)
  117. }
  118. var e Event
  119. if err := json.Unmarshal(message, &e); err != nil {
  120. fmt.Println("wsEvent Unmarshall error: ", err)
  121. return
  122. }
  123. switch e.Operation {
  124. case 2: // READY
  125. v.OP2 = &voiceOP2{}
  126. if err := json.Unmarshal(e.RawData, v.OP2); err != nil {
  127. fmt.Println("voiceWS.onEvent OP2 Unmarshall error: ", err)
  128. printJSON(e.RawData) // TODO: Better error logging
  129. return
  130. }
  131. // Start the voice websocket heartbeat to keep the connection alive
  132. go v.wsHeartbeat(v.OP2.HeartbeatInterval)
  133. // TODO monitor a chan/bool to verify this was successful
  134. // Start the UDP connection
  135. err := v.udpOpen()
  136. if err != nil {
  137. fmt.Println("Error opening udp connection: ", err)
  138. return
  139. }
  140. // start udpKeepAlive
  141. go v.udpKeepAlive(5 * time.Second)
  142. // TODO: find a way to check that it fired off okay
  143. return
  144. case 3: // HEARTBEAT response
  145. // add code to use this to track latency?
  146. return
  147. case 4:
  148. // TODO
  149. default:
  150. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  151. printJSON(e.RawData)
  152. }
  153. return
  154. }
  155. type voiceHeartbeatOp struct {
  156. Op int `json:"op"` // Always 3
  157. Data int `json:"d"`
  158. }
  159. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  160. // is still connected. If you do not send these heartbeats Discord will
  161. // disconnect the websocket connection after a few seconds.
  162. func (v *Voice) wsHeartbeat(i time.Duration) {
  163. ticker := time.NewTicker(i * time.Millisecond)
  164. for {
  165. err := v.wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  166. if err != nil {
  167. v.Ready = false
  168. fmt.Println("wsHeartbeat send error: ", err)
  169. return // TODO better logging
  170. }
  171. <-ticker.C
  172. }
  173. }
  174. type voiceSpeakingData struct {
  175. Speaking bool `json:"speaking"`
  176. Delay int `json:"delay"`
  177. }
  178. type voiceSpeakingOp struct {
  179. Op int `json:"op"` // Always 5
  180. Data voiceSpeakingData `json:"d"`
  181. }
  182. // Speaking sends a speaking notification to Discord over the voice websocket.
  183. // This must be sent as true prior to sending audio and should be set to false
  184. // once finished sending audio.
  185. // b : Send true if speaking, false if not.
  186. func (v *Voice) Speaking(b bool) (err error) {
  187. if v.wsConn == nil {
  188. return fmt.Errorf("No Voice websocket.")
  189. }
  190. data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
  191. err = v.wsConn.WriteJSON(data)
  192. if err != nil {
  193. fmt.Println("Speaking() write json error:", err)
  194. return
  195. }
  196. return
  197. }
  198. // ------------------------------------------------------------------------------------------------
  199. // Code related to the Voice UDP connection
  200. // ------------------------------------------------------------------------------------------------
  201. type voiceUDPData struct {
  202. Address string `json:"address"` // Public IP of machine running this code
  203. Port uint16 `json:"port"` // UDP Port of machine running this code
  204. Mode string `json:"mode"` // plain or ? (plain or encrypted)
  205. }
  206. type voiceUDPD struct {
  207. Protocol string `json:"protocol"` // Always "udp" ?
  208. Data voiceUDPData `json:"data"`
  209. }
  210. type voiceUDPOp struct {
  211. Op int `json:"op"` // Always 1
  212. Data voiceUDPD `json:"d"`
  213. }
  214. // udpOpen opens a UDP connection to the voice server and completes the
  215. // initial required handshake. This connection is left open in the session
  216. // and can be used to send or receive audio. This should only be called
  217. // from voice.wsEvent OP2
  218. func (v *Voice) udpOpen() (err error) {
  219. host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.OP2.Port)
  220. addr, err := net.ResolveUDPAddr("udp", host)
  221. if err != nil {
  222. fmt.Println("udpOpen resolve addr error: ", err)
  223. // TODO better logging
  224. return
  225. }
  226. v.UDPConn, err = net.DialUDP("udp", nil, addr)
  227. if err != nil {
  228. fmt.Println("udpOpen dial udp error: ", err)
  229. // TODO better logging
  230. return
  231. }
  232. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  233. // into it. Then send that over the UDP connection to Discord
  234. sb := make([]byte, 70)
  235. binary.BigEndian.PutUint32(sb, v.OP2.SSRC)
  236. _, err = v.UDPConn.Write(sb)
  237. if err != nil {
  238. fmt.Println("udpOpen udp write error : ", err)
  239. // TODO better logging
  240. return
  241. }
  242. // Create a 70 byte array and listen for the initial handshake response
  243. // from Discord. Once we get it parse the IP and PORT information out
  244. // of the response. This should be our public IP and PORT as Discord
  245. // saw us.
  246. rb := make([]byte, 70)
  247. rlen, _, err := v.UDPConn.ReadFromUDP(rb)
  248. if err != nil {
  249. fmt.Println("udpOpen udp read error : ", err)
  250. // TODO better logging
  251. return
  252. }
  253. if rlen < 70 {
  254. fmt.Println("Voice RLEN should be 70 but isn't")
  255. }
  256. // Loop over position 4 though 20 to grab the IP address
  257. // Should never be beyond position 20.
  258. var ip string
  259. for i := 4; i < 20; i++ {
  260. if rb[i] == 0 {
  261. break
  262. }
  263. ip += string(rb[i])
  264. }
  265. // Grab port from postion 68 and 69
  266. port := binary.LittleEndian.Uint16(rb[68:70])
  267. // Take the data from above and send it back to Discord to finalize
  268. // the UDP connection handshake.
  269. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "plain"}}}
  270. err = v.wsConn.WriteJSON(data)
  271. if err != nil {
  272. fmt.Println("udpOpen write json error:", err)
  273. return
  274. }
  275. v.Ready = true
  276. return
  277. }
  278. // udpKeepAlive sends a udp packet to keep the udp connection open
  279. // This is still a bit of a "proof of concept"
  280. func (v *Voice) udpKeepAlive(i time.Duration) {
  281. var err error
  282. var sequence uint64 = 0
  283. packet := make([]byte, 8)
  284. ticker := time.NewTicker(i)
  285. for {
  286. // TODO: Add a way to break from loop
  287. binary.LittleEndian.PutUint64(packet, sequence)
  288. sequence++
  289. _, err = v.UDPConn.Write(packet)
  290. if err != nil {
  291. fmt.Println("udpKeepAlive udp write error : ", err)
  292. return
  293. }
  294. <-ticker.C
  295. }
  296. }