wsapi.go 16 KB

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