wsapi.go 18 KB

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