wsapi.go 18 KB

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