voice.go 8.6 KB

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