wsapi.go 13 KB

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