wsapi.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 low level functions for interacting with the Discord
  7. // data websocket interface.
  8. package discordgo
  9. import (
  10. "bytes"
  11. "compress/zlib"
  12. "encoding/json"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "net/http"
  17. "reflect"
  18. "runtime"
  19. "time"
  20. "github.com/gorilla/websocket"
  21. )
  22. type handshakeProperties struct {
  23. OS string `json:"$os"`
  24. Browser string `json:"$browser"`
  25. Device string `json:"$device"`
  26. Referer string `json:"$referer"`
  27. ReferringDomain string `json:"$referring_domain"`
  28. }
  29. type handshakeData struct {
  30. Version int `json:"v"`
  31. Token string `json:"token"`
  32. Properties handshakeProperties `json:"properties"`
  33. LargeThreshold int `json:"large_threshold"`
  34. Compress bool `json:"compress"`
  35. }
  36. type handshakeOp struct {
  37. Op int `json:"op"`
  38. Data handshakeData `json:"d"`
  39. }
  40. // Open opens a websocket connection to Discord.
  41. func (s *Session) Open() (err error) {
  42. s.Lock()
  43. defer func() {
  44. if err != nil {
  45. s.Unlock()
  46. }
  47. }()
  48. if s.wsConn != nil {
  49. err = errors.New("Web socket already opened.")
  50. return
  51. }
  52. // Get the gateway to use for the Websocket connection
  53. g, err := s.Gateway()
  54. if err != nil {
  55. return
  56. }
  57. header := http.Header{}
  58. header.Add("accept-encoding", "zlib")
  59. // TODO: See if there's a use for the http response.
  60. // conn, response, err := websocket.DefaultDialer.Dial(session.Gateway, nil)
  61. s.wsConn, _, err = websocket.DefaultDialer.Dial(g, header)
  62. if err != nil {
  63. return
  64. }
  65. err = s.wsConn.WriteJSON(handshakeOp{2, handshakeData{3, s.Token, handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""}, 250, s.Compress}})
  66. if err != nil {
  67. return
  68. }
  69. // Create listening outside of listen, as it needs to happen inside the mutex
  70. // lock.
  71. s.listening = make(chan interface{})
  72. go s.listen(s.wsConn, s.listening)
  73. s.Unlock()
  74. s.initialize()
  75. s.handle(&Connect{})
  76. return
  77. }
  78. // Close closes a websocket and stops all listening/heartbeat goroutines.
  79. // TODO: Add support for Voice WS/UDP connections
  80. func (s *Session) Close() (err error) {
  81. s.Lock()
  82. s.DataReady = false
  83. if s.listening != nil {
  84. close(s.listening)
  85. s.listening = nil
  86. }
  87. if s.wsConn != nil {
  88. err = s.wsConn.Close()
  89. s.wsConn = nil
  90. }
  91. s.Unlock()
  92. s.handle(&Disconnect{})
  93. return
  94. }
  95. // listen polls the websocket connection for events, it will stop when
  96. // the listening channel is closed, or an error occurs.
  97. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  98. for {
  99. messageType, message, err := wsConn.ReadMessage()
  100. if err != nil {
  101. // Detect if we have been closed manually. If a Close() has already
  102. // happened, the websocket we are listening on will be different to the
  103. // current session.
  104. s.RLock()
  105. sameConnection := s.wsConn == wsConn
  106. s.RUnlock()
  107. if sameConnection {
  108. // There has been an error reading, Close() the websocket so that
  109. // OnDisconnect is fired.
  110. err := s.Close()
  111. if err != nil {
  112. fmt.Println("error closing session connection: ", err)
  113. }
  114. // Attempt to reconnect, with expenonential backoff up to 10 minutes.
  115. if s.ShouldReconnectOnError {
  116. wait := time.Duration(1)
  117. for {
  118. if s.Open() == nil {
  119. return
  120. }
  121. <-time.After(wait * time.Second)
  122. wait *= 2
  123. if wait > 600 {
  124. wait = 600
  125. }
  126. }
  127. }
  128. }
  129. return
  130. }
  131. select {
  132. case <-listening:
  133. return
  134. default:
  135. go s.event(messageType, message)
  136. }
  137. }
  138. }
  139. type heartbeatOp struct {
  140. Op int `json:"op"`
  141. Data int `json:"d"`
  142. }
  143. func (s *Session) sendHeartbeat(wsConn *websocket.Conn) error {
  144. return wsConn.WriteJSON(heartbeatOp{1, int(time.Now().Unix())})
  145. }
  146. // heartbeat sends regular heartbeats to Discord so it knows the client
  147. // is still connected. If you do not send these heartbeats Discord will
  148. // disconnect the websocket connection after a few seconds.
  149. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  150. if listening == nil || wsConn == nil {
  151. return
  152. }
  153. s.Lock()
  154. s.DataReady = true
  155. s.Unlock()
  156. // Send first heartbeat immediately because lag could put the
  157. // first heartbeat outside the required heartbeat interval window.
  158. err := s.sendHeartbeat(wsConn)
  159. if err != nil {
  160. fmt.Println("Error sending initial heartbeat:", err)
  161. return
  162. }
  163. ticker := time.NewTicker(i * time.Millisecond)
  164. for {
  165. select {
  166. case <-ticker.C:
  167. err := s.sendHeartbeat(wsConn)
  168. if err != nil {
  169. fmt.Println("Error sending heartbeat:", err)
  170. return
  171. }
  172. case <-listening:
  173. return
  174. }
  175. }
  176. }
  177. type updateStatusGame struct {
  178. Name string `json:"name"`
  179. }
  180. type updateStatusData struct {
  181. IdleSince *int `json:"idle_since"`
  182. Game *updateStatusGame `json:"game"`
  183. }
  184. type updateStatusOp struct {
  185. Op int `json:"op"`
  186. Data updateStatusData `json:"d"`
  187. }
  188. // UpdateStatus is used to update the authenticated user's status.
  189. // If idle>0 then set status to idle. If game>0 then set game.
  190. // if otherwise, set status to active, and no game.
  191. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  192. s.RLock()
  193. defer s.RUnlock()
  194. if s.wsConn == nil {
  195. return errors.New("No websocket connection exists.")
  196. }
  197. var usd updateStatusData
  198. if idle > 0 {
  199. usd.IdleSince = &idle
  200. }
  201. if game != "" {
  202. usd.Game = &updateStatusGame{game}
  203. }
  204. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  205. return
  206. }
  207. // Front line handler for all Websocket Events. Determines the
  208. // event type and passes the message along to the next handler.
  209. // event is the front line handler for all events. This needs to be
  210. // broken up into smaller functions to be more idiomatic Go.
  211. // Events will be handled by any implemented handler in Session.
  212. // All unhandled events will then be handled by OnEvent.
  213. func (s *Session) event(messageType int, message []byte) {
  214. var err error
  215. var reader io.Reader
  216. reader = bytes.NewBuffer(message)
  217. if messageType == 2 {
  218. z, err1 := zlib.NewReader(reader)
  219. if err1 != nil {
  220. fmt.Println(err1)
  221. return
  222. }
  223. defer func() {
  224. err := z.Close()
  225. if err != nil {
  226. fmt.Println("error closing zlib:", err)
  227. }
  228. }()
  229. reader = z
  230. }
  231. var e *Event
  232. decoder := json.NewDecoder(reader)
  233. if err = decoder.Decode(&e); err != nil {
  234. fmt.Println(err)
  235. return
  236. }
  237. if s.Debug {
  238. printEvent(e)
  239. }
  240. i := eventToInterface[e.Type]
  241. if i != nil {
  242. // Create a new instance of the event type.
  243. i = reflect.New(reflect.TypeOf(i)).Interface()
  244. // Attempt to unmarshal our event.
  245. // If there is an error we should handle the event itself.
  246. if err = unmarshal(e.RawData, i); err != nil {
  247. fmt.Println("Unable to unmarshal event data.")
  248. i = e
  249. }
  250. } else {
  251. fmt.Println("Unknown event.")
  252. i = e
  253. }
  254. s.handle(i)
  255. return
  256. }
  257. // ------------------------------------------------------------------------------------------------
  258. // Code related to voice connections that initiate over the data websocket
  259. // ------------------------------------------------------------------------------------------------
  260. // A VoiceServerUpdate stores the data received during the Voice Server Update
  261. // data websocket event. This data is used during the initial Voice Channel
  262. // join handshaking.
  263. type VoiceServerUpdate struct {
  264. Token string `json:"token"`
  265. GuildID string `json:"guild_id"`
  266. Endpoint string `json:"endpoint"`
  267. }
  268. type voiceChannelJoinData struct {
  269. GuildID *string `json:"guild_id"`
  270. ChannelID *string `json:"channel_id"`
  271. SelfMute bool `json:"self_mute"`
  272. SelfDeaf bool `json:"self_deaf"`
  273. }
  274. type voiceChannelJoinOp struct {
  275. Op int `json:"op"`
  276. Data voiceChannelJoinData `json:"d"`
  277. }
  278. // ChannelVoiceJoin joins the session user to a voice channel. After calling
  279. // this func please monitor the Session.Voice.Ready bool to determine when
  280. // it is ready and able to send/receive audio, that should happen quickly.
  281. //
  282. // gID : Guild ID of the channel to join.
  283. // cID : Channel ID of the channel to join.
  284. // mute : If true, you will be set to muted upon joining.
  285. // deaf : If true, you will be set to deafened upon joining.
  286. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (err error) {
  287. // Create new voice{} struct if one does not exist.
  288. // If you create this prior to calling this func then you can manually
  289. // set some variables if needed, such as to enable debugging.
  290. if s.Voice == nil {
  291. s.Voice = &Voice{}
  292. }
  293. // Send the request to Discord that we want to join the voice channel
  294. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  295. err = s.wsConn.WriteJSON(data)
  296. if err != nil {
  297. return
  298. }
  299. // Store gID and cID for later use
  300. s.Voice.guildID = gID
  301. s.Voice.channelID = cID
  302. return
  303. }
  304. // ChannelVoiceLeave disconnects from the currently connected
  305. // voice channel.
  306. func (s *Session) ChannelVoiceLeave() (err error) {
  307. if s.Voice == nil {
  308. return
  309. }
  310. // Send the request to Discord that we want to leave voice
  311. data := voiceChannelJoinOp{4, voiceChannelJoinData{nil, nil, true, true}}
  312. err = s.wsConn.WriteJSON(data)
  313. if err != nil {
  314. return
  315. }
  316. // Close voice and nil data struct
  317. s.Voice.Close()
  318. s.Voice = nil
  319. return
  320. }
  321. // onVoiceStateUpdate handles Voice State Update events on the data
  322. // websocket. This comes immediately after the call to VoiceChannelJoin
  323. // for the session user.
  324. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  325. // Ignore if Voice is nil
  326. if s.Voice == nil {
  327. return
  328. }
  329. // Need to have this happen at login and store it in the Session
  330. // TODO : This should be done upon connecting to Discord, or
  331. // be moved to a small helper function
  332. self, err := s.User("@me") // TODO: move to Login/New
  333. if err != nil {
  334. fmt.Println(err)
  335. return
  336. }
  337. // This event comes for all users, if it's not for the session
  338. // user just ignore it.
  339. // TODO Move this IF to the event() func
  340. if st.UserID != self.ID {
  341. return
  342. }
  343. // Store the SessionID for later use.
  344. s.Voice.userID = self.ID // TODO: Review
  345. s.Voice.sessionID = st.SessionID
  346. }
  347. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  348. // This event tells us the information needed to open a voice websocket
  349. // connection and should happen after the VOICE_STATE event.
  350. //
  351. // This is also fired if the Guild's voice region changes while connected
  352. // to a voice channel. In that case, need to re-establish connection to
  353. // the new region endpoint.
  354. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  355. // Store values for later use
  356. s.Voice.token = st.Token
  357. s.Voice.endpoint = st.Endpoint
  358. s.Voice.guildID = st.GuildID
  359. // If currently connected to voice ws/udp, then disconnect.
  360. // Has no effect if not connected.
  361. s.Voice.Close()
  362. // We now have enough information to open a voice websocket conenction
  363. // so, that's what the next call does.
  364. err := s.Voice.Open()
  365. if err != nil {
  366. fmt.Println("onVoiceServerUpdate Voice.Open error: ", err)
  367. // TODO better logging
  368. }
  369. }