wsapi.go 11 KB

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