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