voice.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. v.udpOpen()
  136. return
  137. case 3: // HEARTBEAT response
  138. // add code to use this to track latency?
  139. return
  140. case 4:
  141. // TODO
  142. default:
  143. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  144. printJSON(e.RawData)
  145. }
  146. return
  147. }
  148. type voiceHeartbeatOp struct {
  149. Op int `json:"op"` // Always 3
  150. Data int `json:"d"`
  151. }
  152. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  153. // is still connected. If you do not send these heartbeats Discord will
  154. // disconnect the websocket connection after a few seconds.
  155. func (v *Voice) wsHeartbeat(i time.Duration) {
  156. ticker := time.NewTicker(i * time.Millisecond)
  157. for {
  158. err := v.wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  159. if err != nil {
  160. v.Ready = false
  161. fmt.Println("wsHeartbeat send error: ", err)
  162. return // TODO better logging
  163. }
  164. <-ticker.C
  165. }
  166. }
  167. type voiceSpeakingData struct {
  168. Speaking bool `json:"speaking"`
  169. Delay int `json:"delay"`
  170. }
  171. type voiceSpeakingOp struct {
  172. Op int `json:"op"` // Always 5
  173. Data voiceSpeakingData `json:"d"`
  174. }
  175. // Speaking sends a speaking notification to Discord over the voice websocket.
  176. // This must be sent as true prior to sending audio and should be set to false
  177. // once finished sending audio.
  178. // b : Send true if speaking, false if not.
  179. func (v *Voice) Speaking(b bool) (err error) {
  180. if v.wsConn == nil {
  181. return fmt.Errorf("No Voice websocket.")
  182. }
  183. data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
  184. err = v.wsConn.WriteJSON(data)
  185. if err != nil {
  186. fmt.Println("Speaking() write json error:", err)
  187. return
  188. }
  189. return
  190. }
  191. // ------------------------------------------------------------------------------------------------
  192. // Code related to the Voice UDP connection
  193. // ------------------------------------------------------------------------------------------------
  194. type voiceUDPData struct {
  195. Address string `json:"address"` // Public IP of machine running this code
  196. Port uint16 `json:"port"` // UDP Port of machine running this code
  197. Mode string `json:"mode"` // plain or ? (plain or encrypted)
  198. }
  199. type voiceUDPD struct {
  200. Protocol string `json:"protocol"` // Always "udp" ?
  201. Data voiceUDPData `json:"data"`
  202. }
  203. type voiceUDPOp struct {
  204. Op int `json:"op"` // Always 1
  205. Data voiceUDPD `json:"d"`
  206. }
  207. // udpOpen opens a UDP connection to the voice server and completes the
  208. // initial required handshake. This connection is left open in the session
  209. // and can be used to send or receive audio. This should only be called
  210. // from voice.wsEvent OP2
  211. func (v *Voice) udpOpen() (err error) {
  212. host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.OP2.Port)
  213. addr, err := net.ResolveUDPAddr("udp", host)
  214. if err != nil {
  215. fmt.Println("udpOpen resolve addr error: ", err)
  216. // TODO better logging
  217. return
  218. }
  219. v.UDPConn, err = net.DialUDP("udp", nil, addr)
  220. if err != nil {
  221. fmt.Println("udpOpen dial udp error: ", err)
  222. // TODO better logging
  223. return
  224. }
  225. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  226. // into it. Then send that over the UDP connection to Discord
  227. sb := make([]byte, 70)
  228. binary.BigEndian.PutUint32(sb, v.OP2.SSRC)
  229. _, err = v.UDPConn.Write(sb)
  230. if err != nil {
  231. fmt.Println("udpOpen udp write error : ", err)
  232. // TODO better logging
  233. return
  234. }
  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 err != nil {
  242. fmt.Println("udpOpen udp read error : ", err)
  243. // TODO better logging
  244. return
  245. }
  246. if rlen < 70 {
  247. fmt.Println("Voice RLEN should be 70 but isn't")
  248. }
  249. // Loop over position 4 though 20 to grab the IP address
  250. // Should never be beyond position 20.
  251. var ip string
  252. for i := 4; i < 20; i++ {
  253. if rb[i] == 0 {
  254. break
  255. }
  256. ip += string(rb[i])
  257. }
  258. // Grab port from postion 68 and 69
  259. port := binary.LittleEndian.Uint16(rb[68:70])
  260. // Take the data from above and send it back to Discord to finalize
  261. // the UDP connection handshake.
  262. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "plain"}}}
  263. err = v.wsConn.WriteJSON(data)
  264. if err != nil {
  265. fmt.Println("udpOpen write json error:", err)
  266. return
  267. }
  268. v.Ready = true
  269. return
  270. }