wsapi.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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 resumePacket struct {
  24. Op int `json:"op"`
  25. Data struct {
  26. Token string `json:"token"`
  27. SessionID string `json:"session_id"`
  28. Sequence int `json:"seq"`
  29. } `json:"d"`
  30. }
  31. // Open opens a websocket connection to Discord.
  32. func (s *Session) Open() (err error) {
  33. s.log(LogInformational, "called")
  34. s.Lock()
  35. defer func() {
  36. if err != nil {
  37. s.Unlock()
  38. }
  39. }()
  40. // A basic state is a hard requirement for Voice.
  41. if s.State == nil {
  42. state := NewState()
  43. state.TrackChannels = false
  44. state.TrackEmojis = false
  45. state.TrackMembers = false
  46. state.TrackRoles = false
  47. state.TrackVoice = false
  48. s.State = state
  49. }
  50. if s.wsConn != nil {
  51. err = errors.New("Web socket already opened.")
  52. return
  53. }
  54. if s.VoiceConnections == nil {
  55. s.log(LogInformational, "creating new VoiceConnections map")
  56. s.VoiceConnections = make(map[string]*VoiceConnection)
  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=4&encoding=json", s.gateway)
  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. p := resumePacket{}
  79. p.Op = 6
  80. p.Data.Token = s.Token
  81. p.Data.SessionID = s.sessionID
  82. p.Data.Sequence = s.sequence
  83. s.log(LogInformational, "sending resume packet to gateway")
  84. err = s.wsConn.WriteJSON(p)
  85. if err != nil {
  86. s.log(LogWarning, "error sending gateway resume packet, %s, %s", s.gateway, err)
  87. return
  88. }
  89. } else {
  90. err = s.identify()
  91. if err != nil {
  92. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  93. return
  94. }
  95. }
  96. // Create listening outside of listen, as it needs to happen inside the mutex
  97. // lock.
  98. s.listening = make(chan interface{})
  99. go s.listen(s.wsConn, s.listening)
  100. s.Unlock()
  101. s.initialize()
  102. s.log(LogInformational, "emit connect event")
  103. s.handle(&Connect{})
  104. s.log(LogInformational, "exiting")
  105. return
  106. }
  107. // listen polls the websocket connection for events, it will stop when the
  108. // listening channel is closed, or an error occurs.
  109. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  110. s.log(LogInformational, "called")
  111. for {
  112. messageType, message, err := wsConn.ReadMessage()
  113. if err != nil {
  114. // Detect if we have been closed manually. If a Close() has already
  115. // happened, the websocket we are listening on will be different to
  116. // the current session.
  117. s.RLock()
  118. sameConnection := s.wsConn == wsConn
  119. s.RUnlock()
  120. if sameConnection {
  121. s.log(LogWarning, "error reading from gateway %s websocket, %s", s.gateway, err)
  122. // There has been an error reading, close the websocket so that
  123. // OnDisconnect event is emitted.
  124. err := s.Close()
  125. if err != nil {
  126. s.log(LogWarning, "error closing session connection, %s", err)
  127. }
  128. s.log(LogInformational, "calling reconnect() now")
  129. s.reconnect()
  130. }
  131. return
  132. }
  133. select {
  134. case <-listening:
  135. return
  136. default:
  137. s.onEvent(messageType, message)
  138. }
  139. }
  140. }
  141. type heartbeatOp struct {
  142. Op int `json:"op"`
  143. Data int `json:"d"`
  144. }
  145. // heartbeat sends regular heartbeats to Discord so it knows the client
  146. // is still connected. If you do not send these heartbeats Discord will
  147. // disconnect the websocket connection after a few seconds.
  148. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  149. s.log(LogInformational, "called")
  150. if listening == nil || wsConn == nil {
  151. return
  152. }
  153. var err error
  154. ticker := time.NewTicker(i * time.Millisecond)
  155. for {
  156. s.log(LogInformational, "sending gateway websocket heartbeat seq %d", s.sequence)
  157. s.wsMutex.Lock()
  158. err = wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  159. s.wsMutex.Unlock()
  160. if err != nil {
  161. s.log(LogError, "error sending heartbeat to gateway %s, %s", s.gateway, err)
  162. s.Lock()
  163. s.DataReady = false
  164. s.Unlock()
  165. return
  166. }
  167. s.Lock()
  168. s.DataReady = true
  169. s.Unlock()
  170. select {
  171. case <-ticker.C:
  172. // continue loop and send heartbeat
  173. case <-listening:
  174. return
  175. }
  176. }
  177. }
  178. type updateStatusData struct {
  179. IdleSince *int `json:"idle_since"`
  180. Game *Game `json:"game"`
  181. }
  182. type updateStatusOp struct {
  183. Op int `json:"op"`
  184. Data updateStatusData `json:"d"`
  185. }
  186. // UpdateStreamingStatus is used to update the user's streaming status.
  187. // If idle>0 then set status to idle.
  188. // If game!="" then set game.
  189. // If game!="" and url!="" then set the status type to streaming with the URL set.
  190. // if otherwise, set status to active, and no game.
  191. func (s *Session) UpdateStreamingStatus(idle int, game string, url string) (err error) {
  192. s.log(LogInformational, "called")
  193. s.RLock()
  194. defer s.RUnlock()
  195. if s.wsConn == nil {
  196. return errors.New("no websocket connection exists")
  197. }
  198. var usd updateStatusData
  199. if idle > 0 {
  200. usd.IdleSince = &idle
  201. }
  202. if game != "" {
  203. gameType := 0
  204. if url != "" {
  205. gameType = 1
  206. }
  207. usd.Game = &Game{
  208. Name: game,
  209. Type: gameType,
  210. URL: url,
  211. }
  212. }
  213. s.wsMutex.Lock()
  214. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  215. s.wsMutex.Unlock()
  216. return
  217. }
  218. // UpdateStatus is used to update the user's status.
  219. // If idle>0 then set status to idle.
  220. // If game!="" then set game.
  221. // if otherwise, set status to active, and no game.
  222. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  223. return s.UpdateStreamingStatus(idle, game, "")
  224. }
  225. // onEvent is the "event handler" for all messages received on the
  226. // Discord Gateway API websocket connection.
  227. //
  228. // If you use the AddHandler() function to register a handler for a
  229. // specific event this function will pass the event along to that handler.
  230. //
  231. // If you use the AddHandler() function to register a handler for the
  232. // "OnEvent" event then all events will be passed to that handler.
  233. //
  234. // TODO: You may also register a custom event handler entirely using...
  235. func (s *Session) onEvent(messageType int, message []byte) {
  236. var err error
  237. var reader io.Reader
  238. reader = bytes.NewBuffer(message)
  239. // If this is a compressed message, uncompress it.
  240. if messageType == websocket.BinaryMessage {
  241. z, err2 := zlib.NewReader(reader)
  242. if err2 != nil {
  243. s.log(LogError, "error uncompressing websocket message, %s", err)
  244. return
  245. }
  246. defer func() {
  247. err3 := z.Close()
  248. if err3 != nil {
  249. s.log(LogWarning, "error closing zlib, %s", err)
  250. }
  251. }()
  252. reader = z
  253. }
  254. // Decode the event into an Event struct.
  255. var e *Event
  256. decoder := json.NewDecoder(reader)
  257. if err = decoder.Decode(&e); err != nil {
  258. s.log(LogError, "error decoding websocket message, %s", err)
  259. return
  260. }
  261. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  262. // Ping request.
  263. // Must respond with a heartbeat packet within 5 seconds
  264. if e.Operation == 1 {
  265. s.log(LogInformational, "sending heartbeat in response to Op1")
  266. s.wsMutex.Lock()
  267. err = s.wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  268. s.wsMutex.Unlock()
  269. if err != nil {
  270. s.log(LogError, "error sending heartbeat in response to Op1")
  271. return
  272. }
  273. return
  274. }
  275. // Reconnect
  276. // Must immediately disconnect from gateway and reconnect to new gateway.
  277. if e.Operation == 7 {
  278. // TODO
  279. }
  280. // Invalid Session
  281. // Must respond with a Identify packet.
  282. if e.Operation == 9 {
  283. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  284. err = s.identify()
  285. if err != nil {
  286. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  287. return
  288. }
  289. return
  290. }
  291. // Do not try to Dispatch a non-Dispatch Message
  292. if e.Operation != 0 {
  293. // But we probably should be doing something with them.
  294. // TEMP
  295. 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))
  296. return
  297. }
  298. // Store the message sequence
  299. s.sequence = e.Sequence
  300. // Map event to registered event handlers and pass it along
  301. // to any registered functions
  302. i := eventToInterface[e.Type]
  303. if i != nil {
  304. // Create a new instance of the event type.
  305. i = reflect.New(reflect.TypeOf(i)).Interface()
  306. // Attempt to unmarshal our event.
  307. if err = json.Unmarshal(e.RawData, i); err != nil {
  308. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  309. }
  310. // Send event to any registered event handlers for it's type.
  311. // Because the above doesn't cancel this, in case of an error
  312. // the struct could be partially populated or at default values.
  313. // However, most errors are due to a single field and I feel
  314. // it's better to pass along what we received than nothing at all.
  315. // TODO: Think about that decision :)
  316. // Either way, READY events must fire, even with errors.
  317. go s.handle(i)
  318. } else {
  319. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  320. }
  321. // Emit event to the OnEvent handler
  322. e.Struct = i
  323. go s.handle(e)
  324. }
  325. // ------------------------------------------------------------------------------------------------
  326. // Code related to voice connections that initiate over the data websocket
  327. // ------------------------------------------------------------------------------------------------
  328. // A VoiceServerUpdate stores the data received during the Voice Server Update
  329. // data websocket event. This data is used during the initial Voice Channel
  330. // join handshaking.
  331. type VoiceServerUpdate struct {
  332. Token string `json:"token"`
  333. GuildID string `json:"guild_id"`
  334. Endpoint string `json:"endpoint"`
  335. }
  336. type voiceChannelJoinData struct {
  337. GuildID *string `json:"guild_id"`
  338. ChannelID *string `json:"channel_id"`
  339. SelfMute bool `json:"self_mute"`
  340. SelfDeaf bool `json:"self_deaf"`
  341. }
  342. type voiceChannelJoinOp struct {
  343. Op int `json:"op"`
  344. Data voiceChannelJoinData `json:"d"`
  345. }
  346. // ChannelVoiceJoin joins the session user to a voice channel.
  347. //
  348. // gID : Guild ID of the channel to join.
  349. // cID : Channel ID of the channel to join.
  350. // mute : If true, you will be set to muted upon joining.
  351. // deaf : If true, you will be set to deafened upon joining.
  352. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  353. s.log(LogInformational, "called")
  354. voice, _ = s.VoiceConnections[gID]
  355. if voice == nil {
  356. voice = &VoiceConnection{}
  357. s.VoiceConnections[gID] = voice
  358. }
  359. voice.GuildID = gID
  360. voice.ChannelID = cID
  361. voice.deaf = deaf
  362. voice.mute = mute
  363. voice.session = s
  364. // Send the request to Discord that we want to join the voice channel
  365. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  366. s.wsMutex.Lock()
  367. err = s.wsConn.WriteJSON(data)
  368. s.wsMutex.Unlock()
  369. if err != nil {
  370. return
  371. }
  372. // doesn't exactly work perfect yet.. TODO
  373. err = voice.waitUntilConnected()
  374. if err != nil {
  375. s.log(LogWarning, "error waiting for voice to connect, %s", err)
  376. voice.Close()
  377. return
  378. }
  379. return
  380. }
  381. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  382. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  383. // If we don't have a connection for the channel, don't bother
  384. if st.ChannelID == "" {
  385. return
  386. }
  387. // Check if we have a voice connection to update
  388. voice, exists := s.VoiceConnections[st.GuildID]
  389. if !exists {
  390. return
  391. }
  392. // Need to have this happen at login and store it in the Session
  393. // TODO : This should be done upon connecting to Discord, or
  394. // be moved to a small helper function
  395. self, err := s.User("@me") // TODO: move to Login/New
  396. if err != nil {
  397. log.Println(err)
  398. return
  399. }
  400. // We only care about events that are about us
  401. if st.UserID != self.ID {
  402. return
  403. }
  404. // Store the SessionID for later use.
  405. voice.UserID = self.ID // TODO: Review
  406. voice.sessionID = st.SessionID
  407. }
  408. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  409. //
  410. // This is also fired if the Guild's voice region changes while connected
  411. // to a voice channel. In that case, need to re-establish connection to
  412. // the new region endpoint.
  413. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  414. s.log(LogInformational, "called")
  415. voice, exists := s.VoiceConnections[st.GuildID]
  416. // If no VoiceConnection exists, just skip this
  417. if !exists {
  418. return
  419. }
  420. // If currently connected to voice ws/udp, then disconnect.
  421. // Has no effect if not connected.
  422. voice.Close()
  423. // Store values for later use
  424. voice.token = st.Token
  425. voice.endpoint = st.Endpoint
  426. voice.GuildID = st.GuildID
  427. // Open a conenction to the voice server
  428. err := voice.open()
  429. if err != nil {
  430. s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
  431. }
  432. }
  433. type identifyProperties struct {
  434. OS string `json:"$os"`
  435. Browser string `json:"$browser"`
  436. Device string `json:"$device"`
  437. Referer string `json:"$referer"`
  438. ReferringDomain string `json:"$referring_domain"`
  439. }
  440. type identifyData struct {
  441. Token string `json:"token"`
  442. Properties identifyProperties `json:"properties"`
  443. LargeThreshold int `json:"large_threshold"`
  444. Compress bool `json:"compress"`
  445. Shard *[2]int `json:"shard,omitempty"`
  446. }
  447. type identifyOp struct {
  448. Op int `json:"op"`
  449. Data identifyData `json:"d"`
  450. }
  451. // identify sends the identify packet to the gateway
  452. func (s *Session) identify() error {
  453. properties := identifyProperties{runtime.GOOS,
  454. "Discordgo v" + VERSION,
  455. "",
  456. "",
  457. "",
  458. }
  459. data := identifyData{s.Token,
  460. properties,
  461. 250,
  462. s.Compress,
  463. nil,
  464. }
  465. if s.ShardCount > 1 {
  466. if s.ShardID >= s.ShardCount {
  467. return errors.New("ShardID must be less than ShardCount")
  468. }
  469. data.Shard = &[2]int{s.ShardID, s.ShardCount}
  470. }
  471. op := identifyOp{2, data}
  472. s.wsMutex.Lock()
  473. err := s.wsConn.WriteJSON(op)
  474. s.wsMutex.Unlock()
  475. if err != nil {
  476. return err
  477. }
  478. return nil
  479. }
  480. func (s *Session) reconnect() {
  481. s.log(LogInformational, "called")
  482. var err error
  483. if s.ShouldReconnectOnError {
  484. wait := time.Duration(1)
  485. for {
  486. s.log(LogInformational, "trying to reconnect to gateway")
  487. err = s.Open()
  488. if err == nil {
  489. s.log(LogInformational, "successfully reconnected to gateway")
  490. // I'm not sure if this is actually needed.
  491. // if the gw reconnect works properly, voice should stay alive
  492. // However, there seems to be cases where something "weird"
  493. // happens. So we're doing this for now just to improve
  494. // stability in those edge cases.
  495. for _, v := range s.VoiceConnections {
  496. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  497. go v.reconnect()
  498. // This is here just to prevent violently spamming the
  499. // voice reconnects
  500. time.Sleep(1 * time.Second)
  501. }
  502. return
  503. }
  504. s.log(LogError, "error reconnecting to gateway, %s", err)
  505. <-time.After(wait * time.Second)
  506. wait *= 2
  507. if wait > 600 {
  508. wait = 600
  509. }
  510. }
  511. }
  512. }
  513. // Close closes a websocket and stops all listening/heartbeat goroutines.
  514. // TODO: Add support for Voice WS/UDP connections
  515. func (s *Session) Close() (err error) {
  516. s.log(LogInformational, "called")
  517. s.Lock()
  518. s.DataReady = false
  519. if s.listening != nil {
  520. s.log(LogInformational, "closing listening channel")
  521. close(s.listening)
  522. s.listening = nil
  523. }
  524. // TODO: Close all active Voice Connections too
  525. // this should force stop any reconnecting voice channels too
  526. if s.wsConn != nil {
  527. s.log(LogInformational, "sending close frame")
  528. // To cleanly close a connection, a client should send a close
  529. // frame and wait for the server to close the connection.
  530. err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  531. if err != nil {
  532. s.log(LogError, "error closing websocket, %s", err)
  533. }
  534. // TODO: Wait for Discord to actually close the connection.
  535. time.Sleep(1 * time.Second)
  536. s.log(LogInformational, "closing gateway websocket")
  537. err = s.wsConn.Close()
  538. if err != nil {
  539. s.log(LogError, "error closing websocket, %s", err)
  540. }
  541. s.wsConn = nil
  542. }
  543. s.Unlock()
  544. s.log(LogInformational, "emit disconnect event")
  545. s.handle(&Disconnect{})
  546. return
  547. }