wsapi.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 = e
  244. }
  245. }
  246. } else {
  247. log.Println("Unknown event.")
  248. i = e
  249. }
  250. s.handle(i)
  251. return
  252. }
  253. // ------------------------------------------------------------------------------------------------
  254. // Code related to voice connections that initiate over the data websocket
  255. // ------------------------------------------------------------------------------------------------
  256. // A VoiceServerUpdate stores the data received during the Voice Server Update
  257. // data websocket event. This data is used during the initial Voice Channel
  258. // join handshaking.
  259. type VoiceServerUpdate struct {
  260. Token string `json:"token"`
  261. GuildID string `json:"guild_id"`
  262. Endpoint string `json:"endpoint"`
  263. }
  264. type voiceChannelJoinData struct {
  265. GuildID *string `json:"guild_id"`
  266. ChannelID *string `json:"channel_id"`
  267. SelfMute bool `json:"self_mute"`
  268. SelfDeaf bool `json:"self_deaf"`
  269. }
  270. type voiceChannelJoinOp struct {
  271. Op int `json:"op"`
  272. Data voiceChannelJoinData `json:"d"`
  273. }
  274. // ChannelVoiceJoin joins the session user to a voice channel.
  275. //
  276. // gID : Guild ID of the channel to join.
  277. // cID : Channel ID of the channel to join.
  278. // mute : If true, you will be set to muted upon joining.
  279. // deaf : If true, you will be set to deafened upon joining.
  280. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  281. // If a voice connection already exists for this guild then
  282. // return that connection. If the channel differs, also change channels.
  283. var ok bool
  284. if voice, ok = s.VoiceConnections[gID]; ok && voice.GuildID != "" {
  285. //TODO: consider a better variable than GuildID in the above check
  286. // to verify if this connection is valid or not.
  287. if voice.ChannelID != cID {
  288. err = voice.ChangeChannel(cID, mute, deaf)
  289. }
  290. return
  291. }
  292. // Create a new voice session
  293. // TODO review what all these things are for....
  294. voice = &VoiceConnection{
  295. GuildID: gID,
  296. ChannelID: cID,
  297. session: s,
  298. connected: make(chan bool),
  299. sessionRecv: make(chan string),
  300. }
  301. // Store voice in VoiceConnections map for this GuildID
  302. s.VoiceConnections[gID] = voice
  303. // Send the request to Discord that we want to join the voice channel
  304. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  305. err = s.wsConn.WriteJSON(data)
  306. if err != nil {
  307. delete(s.VoiceConnections, gID)
  308. return
  309. }
  310. // doesn't exactly work perfect yet.. TODO
  311. err = voice.waitUntilConnected()
  312. if err != nil {
  313. voice.Close()
  314. delete(s.VoiceConnections, gID)
  315. return
  316. }
  317. return
  318. }
  319. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  320. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  321. // If we don't have a connection for the channel, don't bother
  322. if st.ChannelID == "" {
  323. return
  324. }
  325. // Check if we have a voice connection to update
  326. voice, exists := s.VoiceConnections[st.GuildID]
  327. if !exists {
  328. return
  329. }
  330. // Need to have this happen at login and store it in the Session
  331. // TODO : This should be done upon connecting to Discord, or
  332. // be moved to a small helper function
  333. self, err := s.User("@me") // TODO: move to Login/New
  334. if err != nil {
  335. log.Println(err)
  336. return
  337. }
  338. // We only care about events that are about us
  339. if st.UserID != self.ID {
  340. return
  341. }
  342. // Store the SessionID for later use.
  343. voice.UserID = self.ID // TODO: Review
  344. voice.sessionID = st.SessionID
  345. // TODO: Consider this...
  346. // voice.sessionRecv <- st.SessionID
  347. }
  348. // onVoiceServerUpdate handles the Voice Server Update data websocket 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. voice, exists := s.VoiceConnections[st.GuildID]
  355. // If no VoiceConnection exists, just skip this
  356. if !exists {
  357. return
  358. }
  359. // Store values for later use
  360. voice.token = st.Token
  361. voice.endpoint = st.Endpoint
  362. voice.GuildID = st.GuildID
  363. // If currently connected to voice ws/udp, then disconnect.
  364. // Has no effect if not connected.
  365. // voice.Close()
  366. // Wait for the sessionID from onVoiceStateUpdate
  367. // voice.sessionID = <-voice.sessionRecv
  368. // TODO review above
  369. // wouldn't this cause a huge problem, if it's just a guild server
  370. // update.. ?
  371. // I could add a timeout loop of some sort and also check if the
  372. // sessionID doesn't or does exist already...
  373. // something.. a bit smarter.
  374. // We now have enough information to open a voice websocket conenction
  375. // so, that's what the next call does.
  376. err := voice.open()
  377. if err != nil {
  378. log.Println("onVoiceServerUpdate Voice.Open error: ", err)
  379. // TODO better logging
  380. }
  381. }