wsapi.go 12 KB

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