wsapi.go 11 KB

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