wsapi.go 17 KB

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