wsapi.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. "io"
  15. "log"
  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. s.VoiceConnections = make(map[string]*VoiceConnection)
  49. if s.wsConn != nil {
  50. err = errors.New("Web socket already opened.")
  51. return
  52. }
  53. // Get the gateway to use for the Websocket connection
  54. g, err := s.Gateway()
  55. if err != nil {
  56. return
  57. }
  58. header := http.Header{}
  59. header.Add("accept-encoding", "zlib")
  60. // TODO: See if there's a use for the http response.
  61. // conn, response, err := websocket.DefaultDialer.Dial(session.Gateway, nil)
  62. s.wsConn, _, err = websocket.DefaultDialer.Dial(g, header)
  63. if err != nil {
  64. return
  65. }
  66. err = s.wsConn.WriteJSON(handshakeOp{2, handshakeData{3, s.Token, handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""}, 250, s.Compress}})
  67. if err != nil {
  68. return
  69. }
  70. // Create listening outside of listen, as it needs to happen inside the mutex
  71. // lock.
  72. s.listening = make(chan interface{})
  73. go s.listen(s.wsConn, s.listening)
  74. s.Unlock()
  75. s.initialize()
  76. s.handle(&Connect{})
  77. return
  78. }
  79. // Close closes a websocket and stops all listening/heartbeat goroutines.
  80. // TODO: Add support for Voice WS/UDP connections
  81. func (s *Session) Close() (err error) {
  82. s.Lock()
  83. s.DataReady = false
  84. if s.listening != nil {
  85. close(s.listening)
  86. s.listening = nil
  87. }
  88. if s.wsConn != nil {
  89. err = s.wsConn.Close()
  90. s.wsConn = nil
  91. }
  92. s.Unlock()
  93. s.handle(&Disconnect{})
  94. return
  95. }
  96. // listen polls the websocket connection for events, it will stop when
  97. // the listening channel is closed, or an error occurs.
  98. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  99. for {
  100. messageType, message, err := wsConn.ReadMessage()
  101. if err != nil {
  102. // Detect if we have been closed manually. If a Close() has already
  103. // happened, the websocket we are listening on will be different to the
  104. // current session.
  105. s.RLock()
  106. sameConnection := s.wsConn == wsConn
  107. s.RUnlock()
  108. if sameConnection {
  109. // There has been an error reading, Close() the websocket so that
  110. // OnDisconnect is fired.
  111. err := s.Close()
  112. if err != nil {
  113. log.Println("error closing session connection: ", err)
  114. }
  115. // Attempt to reconnect, with expenonential backoff up to 10 minutes.
  116. if s.ShouldReconnectOnError {
  117. wait := time.Duration(1)
  118. for {
  119. if s.Open() == nil {
  120. return
  121. }
  122. <-time.After(wait * time.Second)
  123. wait *= 2
  124. if wait > 600 {
  125. wait = 600
  126. }
  127. }
  128. }
  129. }
  130. return
  131. }
  132. select {
  133. case <-listening:
  134. return
  135. default:
  136. go s.event(messageType, message)
  137. }
  138. }
  139. }
  140. type heartbeatOp struct {
  141. Op int `json:"op"`
  142. Data int `json:"d"`
  143. }
  144. // heartbeat sends regular heartbeats to Discord so it knows the client
  145. // is still connected. If you do not send these heartbeats Discord will
  146. // disconnect the websocket connection after a few seconds.
  147. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  148. if listening == nil || wsConn == nil {
  149. return
  150. }
  151. s.Lock()
  152. s.DataReady = true
  153. s.Unlock()
  154. var err error
  155. ticker := time.NewTicker(i * time.Millisecond)
  156. for {
  157. err = wsConn.WriteJSON(heartbeatOp{1, int(time.Now().Unix())})
  158. if err != nil {
  159. log.Println("Error sending heartbeat:", err)
  160. return
  161. }
  162. select {
  163. case <-ticker.C:
  164. // continue loop and send heartbeat
  165. case <-listening:
  166. return
  167. }
  168. }
  169. }
  170. type updateStatusGame struct {
  171. Name string `json:"name"`
  172. }
  173. type updateStatusData struct {
  174. IdleSince *int `json:"idle_since"`
  175. Game *updateStatusGame `json:"game"`
  176. }
  177. type updateStatusOp struct {
  178. Op int `json:"op"`
  179. Data updateStatusData `json:"d"`
  180. }
  181. // UpdateStatus is used to update the authenticated user's status.
  182. // If idle>0 then set status to idle. If game>0 then set game.
  183. // if otherwise, set status to active, and no game.
  184. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  185. s.RLock()
  186. defer s.RUnlock()
  187. if s.wsConn == nil {
  188. return errors.New("No websocket connection exists.")
  189. }
  190. var usd updateStatusData
  191. if idle > 0 {
  192. usd.IdleSince = &idle
  193. }
  194. if game != "" {
  195. usd.Game = &updateStatusGame{game}
  196. }
  197. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  198. return
  199. }
  200. // Front line handler for all Websocket Events. Determines the
  201. // event type and passes the message along to the next handler.
  202. // event is the front line handler for all events. This needs to be
  203. // broken up into smaller functions to be more idiomatic Go.
  204. // Events will be handled by any implemented handler in Session.
  205. // All unhandled events will then be handled by OnEvent.
  206. func (s *Session) event(messageType int, message []byte) {
  207. var err error
  208. var reader io.Reader
  209. reader = bytes.NewBuffer(message)
  210. if messageType == 2 {
  211. z, err1 := zlib.NewReader(reader)
  212. if err1 != nil {
  213. log.Println(err1)
  214. return
  215. }
  216. defer func() {
  217. err := z.Close()
  218. if err != nil {
  219. log.Println("error closing zlib:", err)
  220. }
  221. }()
  222. reader = z
  223. }
  224. var e *Event
  225. decoder := json.NewDecoder(reader)
  226. if err = decoder.Decode(&e); err != nil {
  227. log.Println(err)
  228. return
  229. }
  230. if s.Debug {
  231. printEvent(e)
  232. }
  233. i := eventToInterface[e.Type]
  234. if i != nil {
  235. // Create a new instance of the event type.
  236. i = reflect.New(reflect.TypeOf(i)).Interface()
  237. // Attempt to unmarshal our event.
  238. // If there is an error we should handle the event itself.
  239. if err = unmarshal(e.RawData, i); err != nil {
  240. log.Println("Unable to unmarshal event data.", err)
  241. // Ready events must fire, even if they are empty.
  242. if e.Type != "READY" {
  243. i = nil
  244. }
  245. }
  246. } else {
  247. log.Println("Unknown event.")
  248. i = nil
  249. }
  250. if i != nil {
  251. s.handle(i)
  252. }
  253. s.handle(e)
  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.
  278. //
  279. // gID : Guild ID of the channel to join.
  280. // cID : Channel ID of the channel to join.
  281. // mute : If true, you will be set to muted upon joining.
  282. // deaf : If true, you will be set to deafened upon joining.
  283. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  284. // If a voice connection already exists for this guild then
  285. // return that connection. If the channel differs, also change channels.
  286. var ok bool
  287. if voice, ok = s.VoiceConnections[gID]; ok && voice.GuildID != "" {
  288. //TODO: consider a better variable than GuildID in the above check
  289. // to verify if this connection is valid or not.
  290. if voice.ChannelID != cID {
  291. err = voice.ChangeChannel(cID, mute, deaf)
  292. }
  293. return
  294. }
  295. // Create a new voice session
  296. // TODO review what all these things are for....
  297. voice = &VoiceConnection{
  298. GuildID: gID,
  299. ChannelID: cID,
  300. session: s,
  301. connected: make(chan bool),
  302. sessionRecv: make(chan string),
  303. }
  304. // Store voice in VoiceConnections map for this GuildID
  305. s.VoiceConnections[gID] = voice
  306. // Send the request to Discord that we want to join the voice channel
  307. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  308. err = s.wsConn.WriteJSON(data)
  309. if err != nil {
  310. delete(s.VoiceConnections, gID)
  311. return
  312. }
  313. // doesn't exactly work perfect yet.. TODO
  314. err = voice.waitUntilConnected()
  315. if err != nil {
  316. voice.Close()
  317. delete(s.VoiceConnections, gID)
  318. return
  319. }
  320. return
  321. }
  322. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  323. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  324. // If we don't have a connection for the channel, don't bother
  325. if st.ChannelID == "" {
  326. return
  327. }
  328. // Check if we have a voice connection to update
  329. voice, exists := s.VoiceConnections[st.GuildID]
  330. if !exists {
  331. return
  332. }
  333. // Need to have this happen at login and store it in the Session
  334. // TODO : This should be done upon connecting to Discord, or
  335. // be moved to a small helper function
  336. self, err := s.User("@me") // TODO: move to Login/New
  337. if err != nil {
  338. log.Println(err)
  339. return
  340. }
  341. // We only care about events that are about us
  342. if st.UserID != self.ID {
  343. return
  344. }
  345. // Store the SessionID for later use.
  346. voice.UserID = self.ID // TODO: Review
  347. voice.sessionID = st.SessionID
  348. // TODO: Consider this...
  349. // voice.sessionRecv <- st.SessionID
  350. }
  351. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  352. //
  353. // This is also fired if the Guild's voice region changes while connected
  354. // to a voice channel. In that case, need to re-establish connection to
  355. // the new region endpoint.
  356. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  357. voice, exists := s.VoiceConnections[st.GuildID]
  358. // If no VoiceConnection exists, just skip this
  359. if !exists {
  360. return
  361. }
  362. // Store values for later use
  363. voice.token = st.Token
  364. voice.endpoint = st.Endpoint
  365. voice.GuildID = st.GuildID
  366. // If currently connected to voice ws/udp, then disconnect.
  367. // Has no effect if not connected.
  368. // voice.Close()
  369. // Wait for the sessionID from onVoiceStateUpdate
  370. // voice.sessionID = <-voice.sessionRecv
  371. // TODO review above
  372. // wouldn't this cause a huge problem, if it's just a guild server
  373. // update.. ?
  374. // I could add a timeout loop of some sort and also check if the
  375. // sessionID doesn't or does exist already...
  376. // something.. a bit smarter.
  377. // We now have enough information to open a voice websocket conenction
  378. // so, that's what the next call does.
  379. err := voice.open()
  380. if err != nil {
  381. log.Println("onVoiceServerUpdate Voice.Open error: ", err)
  382. // TODO better logging
  383. }
  384. }