wsapi.go 18 KB

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