voice.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. case 5:
  150. // SPEAKING TRUE/FALSE NOTIFICATION
  151. /*
  152. {
  153. "user_id": "1238921738912",
  154. "ssrc": 2,
  155. "speaking": false
  156. }
  157. */
  158. default:
  159. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  160. printJSON(e.RawData)
  161. }
  162. return
  163. }
  164. type voiceHeartbeatOp struct {
  165. Op int `json:"op"` // Always 3
  166. Data int `json:"d"`
  167. }
  168. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  169. // is still connected. If you do not send these heartbeats Discord will
  170. // disconnect the websocket connection after a few seconds.
  171. func (v *Voice) wsHeartbeat(i time.Duration) {
  172. ticker := time.NewTicker(i * time.Millisecond)
  173. for {
  174. err := v.wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  175. if err != nil {
  176. v.Ready = false
  177. fmt.Println("wsHeartbeat send error: ", err)
  178. return // TODO better logging
  179. }
  180. <-ticker.C
  181. }
  182. }
  183. type voiceSpeakingData struct {
  184. Speaking bool `json:"speaking"`
  185. Delay int `json:"delay"`
  186. }
  187. type voiceSpeakingOp struct {
  188. Op int `json:"op"` // Always 5
  189. Data voiceSpeakingData `json:"d"`
  190. }
  191. // Speaking sends a speaking notification to Discord over the voice websocket.
  192. // This must be sent as true prior to sending audio and should be set to false
  193. // once finished sending audio.
  194. // b : Send true if speaking, false if not.
  195. func (v *Voice) Speaking(b bool) (err error) {
  196. if v.wsConn == nil {
  197. return fmt.Errorf("No Voice websocket.")
  198. }
  199. data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
  200. err = v.wsConn.WriteJSON(data)
  201. if err != nil {
  202. fmt.Println("Speaking() write json error:", err)
  203. return
  204. }
  205. return
  206. }
  207. // ------------------------------------------------------------------------------------------------
  208. // Code related to the Voice UDP connection
  209. // ------------------------------------------------------------------------------------------------
  210. type voiceUDPData struct {
  211. Address string `json:"address"` // Public IP of machine running this code
  212. Port uint16 `json:"port"` // UDP Port of machine running this code
  213. Mode string `json:"mode"` // plain or ? (plain or encrypted)
  214. }
  215. type voiceUDPD struct {
  216. Protocol string `json:"protocol"` // Always "udp" ?
  217. Data voiceUDPData `json:"data"`
  218. }
  219. type voiceUDPOp struct {
  220. Op int `json:"op"` // Always 1
  221. Data voiceUDPD `json:"d"`
  222. }
  223. // udpOpen opens a UDP connection to the voice server and completes the
  224. // initial required handshake. This connection is left open in the session
  225. // and can be used to send or receive audio. This should only be called
  226. // from voice.wsEvent OP2
  227. func (v *Voice) udpOpen() (err error) {
  228. host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.OP2.Port)
  229. addr, err := net.ResolveUDPAddr("udp", host)
  230. if err != nil {
  231. fmt.Println("udpOpen resolve addr error: ", err)
  232. // TODO better logging
  233. return
  234. }
  235. v.UDPConn, err = net.DialUDP("udp", nil, addr)
  236. if err != nil {
  237. fmt.Println("udpOpen dial udp error: ", err)
  238. // TODO better logging
  239. return
  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. sb := make([]byte, 70)
  244. binary.BigEndian.PutUint32(sb, v.OP2.SSRC)
  245. _, err = v.UDPConn.Write(sb)
  246. if err != nil {
  247. fmt.Println("udpOpen udp write error : ", err)
  248. // TODO better logging
  249. return
  250. }
  251. // Create a 70 byte array and listen for the initial handshake response
  252. // from Discord. Once we get it parse the IP and PORT information out
  253. // of the response. This should be our public IP and PORT as Discord
  254. // saw us.
  255. rb := make([]byte, 70)
  256. rlen, _, err := v.UDPConn.ReadFromUDP(rb)
  257. if err != nil {
  258. fmt.Println("udpOpen udp read error : ", err)
  259. // TODO better logging
  260. return
  261. }
  262. if rlen < 70 {
  263. fmt.Println("Voice RLEN should be 70 but isn't")
  264. }
  265. // Loop over position 4 though 20 to grab the IP address
  266. // Should never be beyond position 20.
  267. var ip string
  268. for i := 4; i < 20; i++ {
  269. if rb[i] == 0 {
  270. break
  271. }
  272. ip += string(rb[i])
  273. }
  274. // Grab port from postion 68 and 69
  275. port := binary.LittleEndian.Uint16(rb[68:70])
  276. // Take the data from above and send it back to Discord to finalize
  277. // the UDP connection handshake.
  278. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "plain"}}}
  279. err = v.wsConn.WriteJSON(data)
  280. if err != nil {
  281. fmt.Println("udpOpen write json error:", err)
  282. return
  283. }
  284. v.Ready = true
  285. return
  286. }
  287. // udpKeepAlive sends a udp packet to keep the udp connection open
  288. // This is still a bit of a "proof of concept"
  289. func (v *Voice) udpKeepAlive(i time.Duration) {
  290. var err error
  291. var sequence uint64 = 0
  292. packet := make([]byte, 8)
  293. ticker := time.NewTicker(i)
  294. for {
  295. // TODO: Add a way to break from loop
  296. binary.LittleEndian.PutUint64(packet, sequence)
  297. sequence++
  298. _, err = v.UDPConn.Write(packet)
  299. if err != nil {
  300. fmt.Println("udpKeepAlive udp write error : ", err)
  301. return
  302. }
  303. <-ticker.C
  304. }
  305. }