wsapi.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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.")
  240. i = e
  241. }
  242. } else {
  243. fmt.Println("Unknown event.")
  244. i = e
  245. }
  246. s.handle(i)
  247. return
  248. }
  249. // ------------------------------------------------------------------------------------------------
  250. // Code related to voice connections that initiate over the data websocket
  251. // ------------------------------------------------------------------------------------------------
  252. // A VoiceServerUpdate stores the data received during the Voice Server Update
  253. // data websocket event. This data is used during the initial Voice Channel
  254. // join handshaking.
  255. type VoiceServerUpdate struct {
  256. Token string `json:"token"`
  257. GuildID string `json:"guild_id"`
  258. Endpoint string `json:"endpoint"`
  259. }
  260. type voiceChannelJoinData struct {
  261. GuildID *string `json:"guild_id"`
  262. ChannelID *string `json:"channel_id"`
  263. SelfMute bool `json:"self_mute"`
  264. SelfDeaf bool `json:"self_deaf"`
  265. }
  266. type voiceChannelJoinOp struct {
  267. Op int `json:"op"`
  268. Data voiceChannelJoinData `json:"d"`
  269. }
  270. // ChannelVoiceJoin joins the session user to a voice channel. After calling
  271. // this func please monitor the Session.Voice.Ready bool to determine when
  272. // it is ready and able to send/receive audio, that should happen quickly.
  273. //
  274. // gID : Guild ID of the channel to join.
  275. // cID : Channel ID of the channel to join.
  276. // mute : If true, you will be set to muted upon joining.
  277. // deaf : If true, you will be set to deafened upon joining.
  278. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (err error) {
  279. // Create new voice{} struct if one does not exist.
  280. // If you create this prior to calling this func then you can manually
  281. // set some variables if needed, such as to enable debugging.
  282. if s.Voice == nil {
  283. s.Voice = &Voice{}
  284. }
  285. // Send the request to Discord that we want to join the voice channel
  286. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  287. err = s.wsConn.WriteJSON(data)
  288. if err != nil {
  289. return
  290. }
  291. // Store gID and cID for later use
  292. s.Voice.guildID = gID
  293. s.Voice.channelID = cID
  294. return
  295. }
  296. // ChannelVoiceLeave disconnects from the currently connected
  297. // voice channel.
  298. func (s *Session) ChannelVoiceLeave() (err error) {
  299. if s.Voice == nil {
  300. return
  301. }
  302. // Send the request to Discord that we want to leave voice
  303. data := voiceChannelJoinOp{4, voiceChannelJoinData{nil, nil, true, true}}
  304. err = s.wsConn.WriteJSON(data)
  305. if err != nil {
  306. return
  307. }
  308. // Close voice and nil data struct
  309. s.Voice.Close()
  310. s.Voice = nil
  311. return
  312. }
  313. // onVoiceStateUpdate handles Voice State Update events on the data
  314. // websocket. This comes immediately after the call to VoiceChannelJoin
  315. // for the session user.
  316. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  317. // Ignore if Voice is nil
  318. if s.Voice == nil {
  319. return
  320. }
  321. // Need to have this happen at login and store it in the Session
  322. // TODO : This should be done upon connecting to Discord, or
  323. // be moved to a small helper function
  324. self, err := s.User("@me") // TODO: move to Login/New
  325. if err != nil {
  326. fmt.Println(err)
  327. return
  328. }
  329. // This event comes for all users, if it's not for the session
  330. // user just ignore it.
  331. // TODO Move this IF to the event() func
  332. if st.UserID != self.ID {
  333. return
  334. }
  335. // Store the SessionID for later use.
  336. s.Voice.userID = self.ID // TODO: Review
  337. s.Voice.sessionID = st.SessionID
  338. }
  339. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  340. // This event tells us the information needed to open a voice websocket
  341. // connection and should happen after the VOICE_STATE event.
  342. //
  343. // This is also fired if the Guild's voice region changes while connected
  344. // to a voice channel. In that case, need to re-establish connection to
  345. // the new region endpoint.
  346. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  347. // Store values for later use
  348. s.Voice.token = st.Token
  349. s.Voice.endpoint = st.Endpoint
  350. s.Voice.guildID = st.GuildID
  351. // If currently connected to voice ws/udp, then disconnect.
  352. // Has no effect if not connected.
  353. s.Voice.Close()
  354. // We now have enough information to open a voice websocket conenction
  355. // so, that's what the next call does.
  356. err := s.Voice.Open()
  357. if err != nil {
  358. fmt.Println("onVoiceServerUpdate Voice.Open error: ", err)
  359. // TODO better logging
  360. }
  361. }