wsapi.go 11 KB

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