wsapi.go 13 KB

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