wsapi.go 16 KB

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