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