wsapi.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. if s.wsConn != nil {
  41. err = errors.New("Web socket already opened.")
  42. return
  43. }
  44. if s.VoiceConnections == nil {
  45. s.log(LogInformational, "creating new VoiceConnections map")
  46. s.VoiceConnections = make(map[string]*VoiceConnection)
  47. }
  48. // Get the gateway to use for the Websocket connection
  49. if s.gateway == "" {
  50. s.gateway, err = s.Gateway()
  51. if err != nil {
  52. return
  53. }
  54. // Add the version and encoding to the URL
  55. s.gateway = fmt.Sprintf("%s?v=4&encoding=json", s.gateway)
  56. }
  57. header := http.Header{}
  58. header.Add("accept-encoding", "zlib")
  59. s.log(LogInformational, "connecting to gateway %s", s.gateway)
  60. s.wsConn, _, err = websocket.DefaultDialer.Dial(s.gateway, header)
  61. if err != nil {
  62. s.log(LogWarning, "error connecting to gateway %s, %s", s.gateway, err)
  63. s.gateway = "" // clear cached gateway
  64. // TODO: should we add a retry block here?
  65. return
  66. }
  67. if s.sessionID != "" && s.sequence > 0 {
  68. p := resumePacket{}
  69. p.Op = 6
  70. p.Data.Token = s.Token
  71. p.Data.SessionID = s.sessionID
  72. p.Data.Sequence = s.sequence
  73. s.log(LogInformational, "sending resume packet to gateway")
  74. err = s.wsConn.WriteJSON(p)
  75. if err != nil {
  76. s.log(LogWarning, "error sending gateway resume packet, %s, %s", s.gateway, err)
  77. return
  78. }
  79. } else {
  80. err = s.identify()
  81. if err != nil {
  82. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  83. return
  84. }
  85. }
  86. // Create listening outside of listen, as it needs to happen inside the mutex
  87. // lock.
  88. s.listening = make(chan interface{})
  89. go s.listen(s.wsConn, s.listening)
  90. s.Unlock()
  91. s.initialize()
  92. s.log(LogInformational, "emit connect event")
  93. s.handle(&Connect{})
  94. s.log(LogInformational, "exiting")
  95. return
  96. }
  97. // listen polls the websocket connection for events, it will stop when the
  98. // listening channel is closed, or an error occurs.
  99. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  100. s.log(LogInformational, "called")
  101. for {
  102. messageType, message, err := wsConn.ReadMessage()
  103. if err != nil {
  104. // Detect if we have been closed manually. If a Close() has already
  105. // happened, the websocket we are listening on will be different to
  106. // the current session.
  107. s.RLock()
  108. sameConnection := s.wsConn == wsConn
  109. s.RUnlock()
  110. if sameConnection {
  111. s.log(LogWarning, "error reading from gateway %s websocket, %s", s.gateway, err)
  112. // There has been an error reading, close the websocket so that
  113. // OnDisconnect event is emitted.
  114. err := s.Close()
  115. if err != nil {
  116. s.log(LogWarning, "error closing session connection, %s", err)
  117. }
  118. s.log(LogInformational, "calling reconnect() now")
  119. s.reconnect()
  120. }
  121. return
  122. }
  123. select {
  124. case <-listening:
  125. return
  126. default:
  127. s.onEvent(messageType, message)
  128. }
  129. }
  130. }
  131. type heartbeatOp struct {
  132. Op int `json:"op"`
  133. Data int `json:"d"`
  134. }
  135. // heartbeat sends regular heartbeats to Discord so it knows the client
  136. // is still connected. If you do not send these heartbeats Discord will
  137. // disconnect the websocket connection after a few seconds.
  138. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  139. s.log(LogInformational, "called")
  140. if listening == nil || wsConn == nil {
  141. return
  142. }
  143. var err error
  144. ticker := time.NewTicker(i * time.Millisecond)
  145. for {
  146. s.log(LogInformational, "sending gateway websocket heartbeat seq %d", s.sequence)
  147. s.wsMutex.Lock()
  148. err = wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  149. s.wsMutex.Unlock()
  150. if err != nil {
  151. s.log(LogError, "error sending heartbeat to gateway %s, %s", s.gateway, err)
  152. s.Lock()
  153. s.DataReady = false
  154. s.Unlock()
  155. return
  156. }
  157. s.Lock()
  158. s.DataReady = true
  159. s.Unlock()
  160. select {
  161. case <-ticker.C:
  162. // continue loop and send heartbeat
  163. case <-listening:
  164. return
  165. }
  166. }
  167. }
  168. type updateStatusData struct {
  169. IdleSince *int `json:"idle_since"`
  170. Game *Game `json:"game"`
  171. }
  172. type updateStatusOp struct {
  173. Op int `json:"op"`
  174. Data updateStatusData `json:"d"`
  175. }
  176. // UpdateStreamingStatus is used to update the user's streaming status.
  177. // If idle>0 then set status to idle.
  178. // If game!="" then set game.
  179. // If game!="" and url!="" then set the status type to streaming with the URL set.
  180. // if otherwise, set status to active, and no game.
  181. func (s *Session) UpdateStreamingStatus(idle int, game string, url string) (err error) {
  182. s.log(LogInformational, "called")
  183. s.RLock()
  184. defer s.RUnlock()
  185. if s.wsConn == nil {
  186. return errors.New("no websocket connection exists")
  187. }
  188. var usd updateStatusData
  189. if idle > 0 {
  190. usd.IdleSince = &idle
  191. }
  192. if game != "" {
  193. gameType := 0
  194. if url != "" {
  195. gameType = 1
  196. }
  197. usd.Game = &Game{
  198. Name: game,
  199. Type: gameType,
  200. URL: url,
  201. }
  202. }
  203. s.wsMutex.Lock()
  204. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  205. s.wsMutex.Unlock()
  206. return
  207. }
  208. // UpdateStatus is used to update the user's status.
  209. // If idle>0 then set status to idle.
  210. // If game!="" then set game.
  211. // if otherwise, set status to active, and no game.
  212. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  213. return s.UpdateStreamingStatus(idle, game, "")
  214. }
  215. type requestGuildMembersData struct {
  216. GuildID string `json:"guild_id"`
  217. Query string `json:"query"`
  218. Limit int `json:"limit"`
  219. }
  220. type requestGuildMembersOp struct {
  221. Op int `json:"op"`
  222. Data requestGuildMembersData `json:"d"`
  223. }
  224. // RequestGuildMembers requests guild members from the gateway
  225. // The gateway responds with GuildMembersChunk events
  226. // guildID : the ID of the guild to request members of
  227. // query : string hat username sarts with, leave empty to return all members
  228. // limit : max number of items to return, or 0 o reques all members matched
  229. func (s *Session) RequestGuildMembers(guildID, query string, limit int) (err error) {
  230. s.log(LogInformational, "called")
  231. s.RLock()
  232. defer s.RUnlock()
  233. if s.wsConn == nil {
  234. return errors.New("no websocket connection exists")
  235. }
  236. data := requestGuildMembersData{
  237. GuildID: guildID,
  238. Query: query,
  239. Limit: limit,
  240. }
  241. s.wsMutex.Lock()
  242. err = s.wsConn.WriteJSON(requestGuildMembersOp{8, data})
  243. s.wsMutex.Unlock()
  244. return
  245. }
  246. // onEvent is the "event handler" for all messages received on the
  247. // Discord Gateway API websocket connection.
  248. //
  249. // If you use the AddHandler() function to register a handler for a
  250. // specific event this function will pass the event along to that handler.
  251. //
  252. // If you use the AddHandler() function to register a handler for the
  253. // "OnEvent" event then all events will be passed to that handler.
  254. //
  255. // TODO: You may also register a custom event handler entirely using...
  256. func (s *Session) onEvent(messageType int, message []byte) {
  257. var err error
  258. var reader io.Reader
  259. reader = bytes.NewBuffer(message)
  260. // If this is a compressed message, uncompress it.
  261. if messageType == websocket.BinaryMessage {
  262. z, err2 := zlib.NewReader(reader)
  263. if err2 != nil {
  264. s.log(LogError, "error uncompressing websocket message, %s", err)
  265. return
  266. }
  267. defer func() {
  268. err3 := z.Close()
  269. if err3 != nil {
  270. s.log(LogWarning, "error closing zlib, %s", err)
  271. }
  272. }()
  273. reader = z
  274. }
  275. // Decode the event into an Event struct.
  276. var e *Event
  277. decoder := json.NewDecoder(reader)
  278. if err = decoder.Decode(&e); err != nil {
  279. s.log(LogError, "error decoding websocket message, %s", err)
  280. return
  281. }
  282. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  283. // Ping request.
  284. // Must respond with a heartbeat packet within 5 seconds
  285. if e.Operation == 1 {
  286. s.log(LogInformational, "sending heartbeat in response to Op1")
  287. s.wsMutex.Lock()
  288. err = s.wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  289. s.wsMutex.Unlock()
  290. if err != nil {
  291. s.log(LogError, "error sending heartbeat in response to Op1")
  292. return
  293. }
  294. return
  295. }
  296. // Reconnect
  297. // Must immediately disconnect from gateway and reconnect to new gateway.
  298. if e.Operation == 7 {
  299. // TODO
  300. }
  301. // Invalid Session
  302. // Must respond with a Identify packet.
  303. if e.Operation == 9 {
  304. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  305. err = s.identify()
  306. if err != nil {
  307. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  308. return
  309. }
  310. return
  311. }
  312. // Do not try to Dispatch a non-Dispatch Message
  313. if e.Operation != 0 {
  314. // But we probably should be doing something with them.
  315. // TEMP
  316. 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))
  317. return
  318. }
  319. // Store the message sequence
  320. s.sequence = e.Sequence
  321. // Map event to registered event handlers and pass it along
  322. // to any registered functions
  323. i := eventToInterface[e.Type]
  324. if i != nil {
  325. // Create a new instance of the event type.
  326. i = reflect.New(reflect.TypeOf(i)).Interface()
  327. // Attempt to unmarshal our event.
  328. if err = json.Unmarshal(e.RawData, i); err != nil {
  329. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  330. }
  331. // Send event to any registered event handlers for it's type.
  332. // Because the above doesn't cancel this, in case of an error
  333. // the struct could be partially populated or at default values.
  334. // However, most errors are due to a single field and I feel
  335. // it's better to pass along what we received than nothing at all.
  336. // TODO: Think about that decision :)
  337. // Either way, READY events must fire, even with errors.
  338. go s.handle(i)
  339. } else {
  340. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  341. }
  342. // Emit event to the OnEvent handler
  343. e.Struct = i
  344. go s.handle(e)
  345. }
  346. // ------------------------------------------------------------------------------------------------
  347. // Code related to voice connections that initiate over the data websocket
  348. // ------------------------------------------------------------------------------------------------
  349. // A VoiceServerUpdate stores the data received during the Voice Server Update
  350. // data websocket event. This data is used during the initial Voice Channel
  351. // join handshaking.
  352. type VoiceServerUpdate struct {
  353. Token string `json:"token"`
  354. GuildID string `json:"guild_id"`
  355. Endpoint string `json:"endpoint"`
  356. }
  357. type voiceChannelJoinData struct {
  358. GuildID *string `json:"guild_id"`
  359. ChannelID *string `json:"channel_id"`
  360. SelfMute bool `json:"self_mute"`
  361. SelfDeaf bool `json:"self_deaf"`
  362. }
  363. type voiceChannelJoinOp struct {
  364. Op int `json:"op"`
  365. Data voiceChannelJoinData `json:"d"`
  366. }
  367. // ChannelVoiceJoin joins the session user to a voice channel.
  368. //
  369. // gID : Guild ID of the channel to join.
  370. // cID : Channel ID of the channel to join.
  371. // mute : If true, you will be set to muted upon joining.
  372. // deaf : If true, you will be set to deafened upon joining.
  373. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  374. s.log(LogInformational, "called")
  375. voice, _ = s.VoiceConnections[gID]
  376. if voice == nil {
  377. voice = &VoiceConnection{}
  378. s.VoiceConnections[gID] = voice
  379. }
  380. voice.GuildID = gID
  381. voice.ChannelID = cID
  382. voice.deaf = deaf
  383. voice.mute = mute
  384. voice.session = s
  385. // Send the request to Discord that we want to join the voice channel
  386. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  387. s.wsMutex.Lock()
  388. err = s.wsConn.WriteJSON(data)
  389. s.wsMutex.Unlock()
  390. if err != nil {
  391. return
  392. }
  393. // doesn't exactly work perfect yet.. TODO
  394. err = voice.waitUntilConnected()
  395. if err != nil {
  396. s.log(LogWarning, "error waiting for voice to connect, %s", err)
  397. voice.Close()
  398. return
  399. }
  400. return
  401. }
  402. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  403. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  404. // If we don't have a connection for the channel, don't bother
  405. if st.ChannelID == "" {
  406. return
  407. }
  408. // Check if we have a voice connection to update
  409. voice, exists := s.VoiceConnections[st.GuildID]
  410. if !exists {
  411. return
  412. }
  413. // Need to have this happen at login and store it in the Session
  414. // TODO : This should be done upon connecting to Discord, or
  415. // be moved to a small helper function
  416. self, err := s.User("@me") // TODO: move to Login/New
  417. if err != nil {
  418. log.Println(err)
  419. return
  420. }
  421. // We only care about events that are about us
  422. if st.UserID != self.ID {
  423. return
  424. }
  425. // Store the SessionID for later use.
  426. voice.UserID = self.ID // TODO: Review
  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(se *Session, 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(LogError, "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(LogError, "error closing websocket, %s", err)
  561. }
  562. s.wsConn = nil
  563. }
  564. s.Unlock()
  565. s.log(LogInformational, "emit disconnect event")
  566. s.handle(&Disconnect{})
  567. return
  568. }