wsapi.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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. // onEvent is the "event handler" for all messages received on the
  216. // Discord Gateway API websocket connection.
  217. //
  218. // If you use the AddHandler() function to register a handler for a
  219. // specific event this function will pass the event along to that handler.
  220. //
  221. // If you use the AddHandler() function to register a handler for the
  222. // "OnEvent" event then all events will be passed to that handler.
  223. //
  224. // TODO: You may also register a custom event handler entirely using...
  225. func (s *Session) onEvent(messageType int, message []byte) {
  226. var err error
  227. var reader io.Reader
  228. reader = bytes.NewBuffer(message)
  229. // If this is a compressed message, uncompress it.
  230. if messageType == websocket.BinaryMessage {
  231. z, err2 := zlib.NewReader(reader)
  232. if err2 != nil {
  233. s.log(LogError, "error uncompressing websocket message, %s", err)
  234. return
  235. }
  236. defer func() {
  237. err3 := z.Close()
  238. if err3 != nil {
  239. s.log(LogWarning, "error closing zlib, %s", err)
  240. }
  241. }()
  242. reader = z
  243. }
  244. // Decode the event into an Event struct.
  245. var e *Event
  246. decoder := json.NewDecoder(reader)
  247. if err = decoder.Decode(&e); err != nil {
  248. s.log(LogError, "error decoding websocket message, %s", err)
  249. return
  250. }
  251. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  252. // Ping request.
  253. // Must respond with a heartbeat packet within 5 seconds
  254. if e.Operation == 1 {
  255. s.log(LogInformational, "sending heartbeat in response to Op1")
  256. s.wsMutex.Lock()
  257. err = s.wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  258. s.wsMutex.Unlock()
  259. if err != nil {
  260. s.log(LogError, "error sending heartbeat in response to Op1")
  261. return
  262. }
  263. return
  264. }
  265. // Reconnect
  266. // Must immediately disconnect from gateway and reconnect to new gateway.
  267. if e.Operation == 7 {
  268. // TODO
  269. }
  270. // Invalid Session
  271. // Must respond with a Identify packet.
  272. if e.Operation == 9 {
  273. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  274. err = s.identify()
  275. if err != nil {
  276. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  277. return
  278. }
  279. return
  280. }
  281. // Do not try to Dispatch a non-Dispatch Message
  282. if e.Operation != 0 {
  283. // But we probably should be doing something with them.
  284. // TEMP
  285. 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))
  286. return
  287. }
  288. // Store the message sequence
  289. s.sequence = e.Sequence
  290. // Map event to registered event handlers and pass it along
  291. // to any registered functions
  292. i := eventToInterface[e.Type]
  293. if i != nil {
  294. // Create a new instance of the event type.
  295. i = reflect.New(reflect.TypeOf(i)).Interface()
  296. // Attempt to unmarshal our event.
  297. if err = json.Unmarshal(e.RawData, i); err != nil {
  298. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  299. }
  300. // Send event to any registered event handlers for it's type.
  301. // Because the above doesn't cancel this, in case of an error
  302. // the struct could be partially populated or at default values.
  303. // However, most errors are due to a single field and I feel
  304. // it's better to pass along what we received than nothing at all.
  305. // TODO: Think about that decision :)
  306. // Either way, READY events must fire, even with errors.
  307. go s.handle(i)
  308. } else {
  309. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  310. }
  311. // Emit event to the OnEvent handler
  312. e.Struct = i
  313. go s.handle(e)
  314. }
  315. // ------------------------------------------------------------------------------------------------
  316. // Code related to voice connections that initiate over the data websocket
  317. // ------------------------------------------------------------------------------------------------
  318. // A VoiceServerUpdate stores the data received during the Voice Server Update
  319. // data websocket event. This data is used during the initial Voice Channel
  320. // join handshaking.
  321. type VoiceServerUpdate struct {
  322. Token string `json:"token"`
  323. GuildID string `json:"guild_id"`
  324. Endpoint string `json:"endpoint"`
  325. }
  326. type voiceChannelJoinData struct {
  327. GuildID *string `json:"guild_id"`
  328. ChannelID *string `json:"channel_id"`
  329. SelfMute bool `json:"self_mute"`
  330. SelfDeaf bool `json:"self_deaf"`
  331. }
  332. type voiceChannelJoinOp struct {
  333. Op int `json:"op"`
  334. Data voiceChannelJoinData `json:"d"`
  335. }
  336. // ChannelVoiceJoin joins the session user to a voice channel.
  337. //
  338. // gID : Guild ID of the channel to join.
  339. // cID : Channel ID of the channel to join.
  340. // mute : If true, you will be set to muted upon joining.
  341. // deaf : If true, you will be set to deafened upon joining.
  342. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  343. s.log(LogInformational, "called")
  344. // If a voice connection already exists for this guild then
  345. // return that connection. If the channel differs, also change channels.
  346. var ok bool
  347. if voice, ok = s.VoiceConnections[gID]; ok && voice.GuildID != "" {
  348. //TODO: consider a better variable than GuildID in the above check
  349. // to verify if this connection is valid or not.
  350. if voice.ChannelID != cID {
  351. err = voice.ChangeChannel(cID, mute, deaf)
  352. }
  353. return
  354. }
  355. if voice == nil {
  356. voice = &VoiceConnection{}
  357. s.VoiceConnections[gID] = voice
  358. }
  359. voice.GuildID = gID
  360. voice.ChannelID = cID
  361. voice.deaf = deaf
  362. voice.mute = mute
  363. voice.session = s
  364. // Send the request to Discord that we want to join the voice channel
  365. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  366. s.wsMutex.Lock()
  367. err = s.wsConn.WriteJSON(data)
  368. s.wsMutex.Unlock()
  369. if err != nil {
  370. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  371. delete(s.VoiceConnections, gID)
  372. return
  373. }
  374. // doesn't exactly work perfect yet.. TODO
  375. err = voice.waitUntilConnected()
  376. if err != nil {
  377. s.log(LogWarning, "error waiting for voice connecting, %s", err)
  378. voice.Close()
  379. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  380. delete(s.VoiceConnections, gID)
  381. return
  382. }
  383. return
  384. }
  385. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  386. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  387. // If we don't have a connection for the channel, don't bother
  388. if st.ChannelID == "" {
  389. return
  390. }
  391. // Check if we have a voice connection to update
  392. voice, exists := s.VoiceConnections[st.GuildID]
  393. if !exists {
  394. return
  395. }
  396. // Need to have this happen at login and store it in the Session
  397. // TODO : This should be done upon connecting to Discord, or
  398. // be moved to a small helper function
  399. self, err := s.User("@me") // TODO: move to Login/New
  400. if err != nil {
  401. log.Println(err)
  402. return
  403. }
  404. // We only care about events that are about us
  405. if st.UserID != self.ID {
  406. return
  407. }
  408. // Store the SessionID for later use.
  409. voice.UserID = self.ID // TODO: Review
  410. voice.sessionID = st.SessionID
  411. }
  412. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  413. //
  414. // This is also fired if the Guild's voice region changes while connected
  415. // to a voice channel. In that case, need to re-establish connection to
  416. // the new region endpoint.
  417. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  418. s.log(LogInformational, "called")
  419. voice, exists := s.VoiceConnections[st.GuildID]
  420. // If no VoiceConnection exists, just skip this
  421. if !exists {
  422. return
  423. }
  424. // If currently connected to voice ws/udp, then disconnect.
  425. // Has no effect if not connected.
  426. voice.Close()
  427. // Store values for later use
  428. voice.token = st.Token
  429. voice.endpoint = st.Endpoint
  430. voice.GuildID = st.GuildID
  431. // Open a conenction to the voice server
  432. err := voice.open()
  433. if err != nil {
  434. s.log(LogError, "onVoiceServerUpdate voice.open, ", err)
  435. }
  436. }
  437. type identifyProperties struct {
  438. OS string `json:"$os"`
  439. Browser string `json:"$browser"`
  440. Device string `json:"$device"`
  441. Referer string `json:"$referer"`
  442. ReferringDomain string `json:"$referring_domain"`
  443. }
  444. type identifyData struct {
  445. Token string `json:"token"`
  446. Properties identifyProperties `json:"properties"`
  447. LargeThreshold int `json:"large_threshold"`
  448. Compress bool `json:"compress"`
  449. Shard *[2]int `json:"shard,omitempty"`
  450. }
  451. type identifyOp struct {
  452. Op int `json:"op"`
  453. Data identifyData `json:"d"`
  454. }
  455. // identify sends the identify packet to the gateway
  456. func (s *Session) identify() error {
  457. properties := identifyProperties{runtime.GOOS,
  458. "Discordgo v" + VERSION,
  459. "",
  460. "",
  461. "",
  462. }
  463. data := identifyData{s.Token,
  464. properties,
  465. 250,
  466. s.Compress,
  467. nil,
  468. }
  469. if s.ShardCount > 1 {
  470. if s.ShardID >= s.ShardCount {
  471. return errors.New("ShardID must be less than ShardCount")
  472. }
  473. data.Shard = &[2]int{s.ShardID, s.ShardCount}
  474. }
  475. op := identifyOp{2, data}
  476. s.wsMutex.Lock()
  477. err := s.wsConn.WriteJSON(op)
  478. s.wsMutex.Unlock()
  479. if err != nil {
  480. return err
  481. }
  482. return nil
  483. }
  484. func (s *Session) reconnect() {
  485. s.log(LogInformational, "called")
  486. var err error
  487. if s.ShouldReconnectOnError {
  488. wait := time.Duration(1)
  489. for {
  490. s.log(LogInformational, "trying to reconnect to gateway")
  491. err = s.Open()
  492. if err == nil {
  493. s.log(LogInformational, "successfully reconnected to gateway")
  494. // I'm not sure if this is actually needed.
  495. // if the gw reconnect works properly, voice should stay alive
  496. // However, there seems to be cases where something "weird"
  497. // happens. So we're doing this for now just to improve
  498. // stability in those edge cases.
  499. for _, v := range s.VoiceConnections {
  500. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  501. go v.reconnect()
  502. // This is here just to prevent violently spamming the
  503. // voice reconnects
  504. time.Sleep(1 * time.Second)
  505. }
  506. return
  507. }
  508. s.log(LogError, "error reconnecting to gateway, %s", err)
  509. <-time.After(wait * time.Second)
  510. wait *= 2
  511. if wait > 600 {
  512. wait = 600
  513. }
  514. }
  515. }
  516. }
  517. // Close closes a websocket and stops all listening/heartbeat goroutines.
  518. // TODO: Add support for Voice WS/UDP connections
  519. func (s *Session) Close() (err error) {
  520. s.log(LogInformational, "called")
  521. s.Lock()
  522. s.DataReady = false
  523. if s.listening != nil {
  524. s.log(LogInformational, "closing listening channel")
  525. close(s.listening)
  526. s.listening = nil
  527. }
  528. if s.wsConn != nil {
  529. s.log(LogInformational, "closing gateway websocket")
  530. err = s.wsConn.Close()
  531. s.wsConn = nil
  532. }
  533. s.Unlock()
  534. s.log(LogInformational, "emit disconnect event")
  535. s.handle(&Disconnect{})
  536. return
  537. }