wsapi.go 18 KB

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