wsapi.go 12 KB

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