wsapi.go 18 KB

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