wsapi.go 12 KB

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