wsapi.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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 handshakeProperties struct {
  24. OS string `json:"$os"`
  25. Browser string `json:"$browser"`
  26. Device string `json:"$device"`
  27. Referer string `json:"$referer"`
  28. ReferringDomain string `json:"$referring_domain"`
  29. }
  30. type handshakeData struct {
  31. Token string `json:"token"`
  32. Properties handshakeProperties `json:"properties"`
  33. LargeThreshold int `json:"large_threshold"`
  34. Compress bool `json:"compress"`
  35. }
  36. type handshakeOp struct {
  37. Op int `json:"op"`
  38. Data handshakeData `json:"d"`
  39. }
  40. type resumePacket struct {
  41. Op int `json:"op"`
  42. Data struct {
  43. Token string `json:"token"`
  44. SessionID string `json:"session_id"`
  45. Sequence int `json:"seq"`
  46. } `json:"d"`
  47. }
  48. // Open opens a websocket connection to Discord.
  49. func (s *Session) Open() (err error) {
  50. s.log(LogInformational, "called")
  51. s.Lock()
  52. defer func() {
  53. if err != nil {
  54. s.Unlock()
  55. }
  56. }()
  57. if s.wsConn != nil {
  58. err = errors.New("Web socket already opened.")
  59. return
  60. }
  61. if s.VoiceConnections == nil {
  62. s.log(LogInformational, "creating new VoiceConnections map")
  63. s.VoiceConnections = make(map[string]*VoiceConnection)
  64. }
  65. // Get the gateway to use for the Websocket connection
  66. if s.gateway == "" {
  67. s.gateway, err = s.Gateway()
  68. if err != nil {
  69. return
  70. }
  71. // Add the version and encoding to the URL
  72. s.gateway = fmt.Sprintf("%s?v=4&encoding=json", s.gateway)
  73. }
  74. header := http.Header{}
  75. header.Add("accept-encoding", "zlib")
  76. s.log(LogInformational, "connecting to gateway %s", s.gateway)
  77. s.wsConn, _, err = websocket.DefaultDialer.Dial(s.gateway, header)
  78. if err != nil {
  79. s.log(LogWarning, "error connecting to gateway %s, %s", s.gateway, err)
  80. s.gateway = "" // clear cached gateway
  81. // TODO: should we add a retry block here?
  82. return
  83. }
  84. if s.sessionID != "" && s.sequence > 0 {
  85. p := resumePacket{}
  86. p.Op = 6
  87. p.Data.Token = s.Token
  88. p.Data.SessionID = s.sessionID
  89. p.Data.Sequence = s.sequence
  90. s.log(LogInformational, "sending resume packet to gateway")
  91. err = s.wsConn.WriteJSON(p)
  92. if err != nil {
  93. s.log(LogWarning, "error sending gateway resume packet, %s, %s", s.gateway, err)
  94. return
  95. }
  96. } else {
  97. data := handshakeOp{
  98. 2,
  99. handshakeData{
  100. s.Token,
  101. handshakeProperties{
  102. runtime.GOOS,
  103. "Discordgo v" + VERSION,
  104. "",
  105. "",
  106. "",
  107. },
  108. 250,
  109. s.Compress,
  110. },
  111. }
  112. s.log(LogInformational, "sending identify packet to gateway")
  113. err = s.wsConn.WriteJSON(data)
  114. if err != nil {
  115. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  116. return
  117. }
  118. }
  119. // Create listening outside of listen, as it needs to happen inside the mutex
  120. // lock.
  121. s.listening = make(chan interface{})
  122. go s.listen(s.wsConn, s.listening)
  123. s.Unlock()
  124. s.initialize()
  125. s.log(LogInformational, "emit connect event")
  126. s.handle(&Connect{})
  127. s.log(LogInformational, "exiting")
  128. return
  129. }
  130. // listen polls the websocket connection for events, it will stop when the
  131. // listening channel is closed, or an error occurs.
  132. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  133. s.log(LogInformational, "called")
  134. for {
  135. messageType, message, err := wsConn.ReadMessage()
  136. if err != nil {
  137. // Detect if we have been closed manually. If a Close() has already
  138. // happened, the websocket we are listening on will be different to
  139. // the current session.
  140. s.RLock()
  141. sameConnection := s.wsConn == wsConn
  142. s.RUnlock()
  143. if sameConnection {
  144. s.log(LogWarning, "error reading from gateway %s websocket, %s", s.gateway, err)
  145. // There has been an error reading, close the websocket so that
  146. // OnDisconnect event is emitted.
  147. err := s.Close()
  148. if err != nil {
  149. s.log(LogWarning, "error closing session connection, %s", err)
  150. }
  151. s.log(LogInformational, "calling reconnect() now")
  152. s.reconnect()
  153. }
  154. return
  155. }
  156. select {
  157. case <-listening:
  158. return
  159. default:
  160. go s.onEvent(messageType, message)
  161. }
  162. }
  163. }
  164. type heartbeatOp struct {
  165. Op int `json:"op"`
  166. Data int `json:"d"`
  167. }
  168. // heartbeat sends regular heartbeats to Discord so it knows the client
  169. // is still connected. If you do not send these heartbeats Discord will
  170. // disconnect the websocket connection after a few seconds.
  171. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  172. s.log(LogInformational, "called")
  173. if listening == nil || wsConn == nil {
  174. return
  175. }
  176. var err error
  177. ticker := time.NewTicker(i * time.Millisecond)
  178. for {
  179. s.log(LogInformational, "sending gateway websocket heartbeat seq %d", s.sequence)
  180. s.wsMutex.Lock()
  181. err = wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  182. s.wsMutex.Unlock()
  183. if err != nil {
  184. s.log(LogError, "error sending heartbeat to gateway %s, %s", s.gateway, err)
  185. s.DataReady = false
  186. return
  187. }
  188. s.DataReady = true
  189. select {
  190. case <-ticker.C:
  191. // continue loop and send heartbeat
  192. case <-listening:
  193. return
  194. }
  195. }
  196. }
  197. type updateStatusData struct {
  198. IdleSince *int `json:"idle_since"`
  199. Game *Game `json:"game"`
  200. }
  201. type updateStatusOp struct {
  202. Op int `json:"op"`
  203. Data updateStatusData `json:"d"`
  204. }
  205. // UpdateStreamingStatus is used to update the user's streaming status.
  206. // If idle>0 then set status to idle.
  207. // If game!="" then set game.
  208. // If game!="" and url!="" then set the status type to streaming with the URL set.
  209. // if otherwise, set status to active, and no game.
  210. func (s *Session) UpdateStreamingStatus(idle int, game string, url string) (err error) {
  211. s.log(LogInformational, "called")
  212. s.RLock()
  213. defer s.RUnlock()
  214. if s.wsConn == nil {
  215. return errors.New("no websocket connection exists")
  216. }
  217. var usd updateStatusData
  218. if idle > 0 {
  219. usd.IdleSince = &idle
  220. }
  221. if game != "" {
  222. gameType := 0
  223. if url != "" {
  224. gameType = 1
  225. }
  226. usd.Game = &Game{
  227. Name: game,
  228. Type: gameType,
  229. URL: url,
  230. }
  231. }
  232. s.wsMutex.Lock()
  233. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  234. s.wsMutex.Unlock()
  235. return
  236. }
  237. // UpdateStatus is used to update the user's status.
  238. // If idle>0 then set status to idle.
  239. // If game!="" then set game.
  240. // if otherwise, set status to active, and no game.
  241. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  242. return s.UpdateStreamingStatus(idle, game, "")
  243. }
  244. // onEvent is the "event handler" for all messages received on the
  245. // Discord Gateway API websocket connection.
  246. //
  247. // If you use the AddHandler() function to register a handler for a
  248. // specific event this function will pass the event along to that handler.
  249. //
  250. // If you use the AddHandler() function to register a handler for the
  251. // "OnEvent" event then all events will be passed to that handler.
  252. //
  253. // TODO: You may also register a custom event handler entirely using...
  254. func (s *Session) onEvent(messageType int, message []byte) {
  255. var err error
  256. var reader io.Reader
  257. reader = bytes.NewBuffer(message)
  258. // If this is a compressed message, uncompress it.
  259. if messageType == websocket.BinaryMessage {
  260. z, err := zlib.NewReader(reader)
  261. if err != nil {
  262. s.log(LogError, "error uncompressing websocket message, %s", err)
  263. return
  264. }
  265. defer func() {
  266. err := z.Close()
  267. if err != nil {
  268. s.log(LogWarning, "error closing zlib, %s", err)
  269. }
  270. }()
  271. reader = z
  272. }
  273. // Decode the event into an Event struct.
  274. var e *Event
  275. decoder := json.NewDecoder(reader)
  276. if err = decoder.Decode(&e); err != nil {
  277. s.log(LogError, "error decoding websocket message, %s", err)
  278. return
  279. }
  280. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  281. // Ping request.
  282. // Must respond with a heartbeat packet within 5 seconds
  283. if e.Operation == 1 {
  284. s.log(LogInformational, "sending heartbeat in response to Op1")
  285. s.wsMutex.Lock()
  286. err = s.wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  287. s.wsMutex.Unlock()
  288. if err != nil {
  289. s.log(LogError, "error sending heartbeat in response to Op1")
  290. return
  291. }
  292. return
  293. }
  294. // Reconnect
  295. // Must immediately disconnect from gateway and reconnect to new gateway.
  296. if e.Operation == 7 {
  297. // TODO
  298. }
  299. // Invalid Session
  300. // Must respond with a Identify packet.
  301. if e.Operation == 9 {
  302. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  303. s.wsMutex.Lock()
  304. err = s.wsConn.WriteJSON(handshakeOp{2, handshakeData{s.Token, handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""}, 250, s.Compress}})
  305. s.wsMutex.Unlock()
  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. 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. 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. // If a voice connection already exists for this guild then
  376. // return that connection. If the channel differs, also change channels.
  377. var ok bool
  378. if voice, ok = s.VoiceConnections[gID]; ok && voice.GuildID != "" {
  379. //TODO: consider a better variable than GuildID in the above check
  380. // to verify if this connection is valid or not.
  381. if voice.ChannelID != cID {
  382. err = voice.ChangeChannel(cID, mute, deaf)
  383. }
  384. return
  385. }
  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. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  402. delete(s.VoiceConnections, gID)
  403. return
  404. }
  405. // doesn't exactly work perfect yet.. TODO
  406. err = voice.waitUntilConnected()
  407. if err != nil {
  408. voice.Close()
  409. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  410. delete(s.VoiceConnections, gID)
  411. return
  412. }
  413. return
  414. }
  415. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  416. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  417. // If we don't have a connection for the channel, don't bother
  418. if st.ChannelID == "" {
  419. return
  420. }
  421. // Check if we have a voice connection to update
  422. voice, exists := s.VoiceConnections[st.GuildID]
  423. if !exists {
  424. return
  425. }
  426. // Need to have this happen at login and store it in the Session
  427. // TODO : This should be done upon connecting to Discord, or
  428. // be moved to a small helper function
  429. self, err := s.User("@me") // TODO: move to Login/New
  430. if err != nil {
  431. log.Println(err)
  432. return
  433. }
  434. // We only care about events that are about us
  435. if st.UserID != self.ID {
  436. return
  437. }
  438. // Store the SessionID for later use.
  439. voice.UserID = self.ID // TODO: Review
  440. voice.sessionID = st.SessionID
  441. }
  442. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  443. //
  444. // This is also fired if the Guild's voice region changes while connected
  445. // to a voice channel. In that case, need to re-establish connection to
  446. // the new region endpoint.
  447. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  448. s.log(LogInformational, "called")
  449. voice, exists := s.VoiceConnections[st.GuildID]
  450. // If no VoiceConnection exists, just skip this
  451. if !exists {
  452. return
  453. }
  454. // If currently connected to voice ws/udp, then disconnect.
  455. // Has no effect if not connected.
  456. voice.Close()
  457. // Store values for later use
  458. voice.token = st.Token
  459. voice.endpoint = st.Endpoint
  460. voice.GuildID = st.GuildID
  461. // Open a conenction to the voice server
  462. err := voice.open()
  463. if err != nil {
  464. s.log(LogError, "onVoiceServerUpdate voice.open, ", err)
  465. }
  466. }
  467. func (s *Session) reconnect() {
  468. s.log(LogInformational, "called")
  469. var err error
  470. if s.ShouldReconnectOnError {
  471. wait := time.Duration(1)
  472. for {
  473. s.log(LogInformational, "trying to reconnect to gateway")
  474. err = s.Open()
  475. if err == nil {
  476. s.log(LogInformational, "successfully reconnected to gateway")
  477. // I'm not sure if this is actually needed.
  478. // if the gw reconnect works properly, voice should stay alive
  479. // However, there seems to be cases where something "weird"
  480. // happens. So we're doing this for now just to improve
  481. // stability in those edge cases.
  482. for _, v := range s.VoiceConnections {
  483. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  484. go v.reconnect()
  485. // This is here just to prevent violently spamming the
  486. // voice reconnects
  487. time.Sleep(1 * time.Second)
  488. }
  489. return
  490. }
  491. s.log(LogError, "error reconnecting to gateway, %s", err)
  492. <-time.After(wait * time.Second)
  493. wait *= 2
  494. if wait > 600 {
  495. wait = 600
  496. }
  497. }
  498. }
  499. }
  500. // Close closes a websocket and stops all listening/heartbeat goroutines.
  501. // TODO: Add support for Voice WS/UDP connections
  502. func (s *Session) Close() (err error) {
  503. s.log(LogInformational, "called")
  504. s.Lock()
  505. s.DataReady = false
  506. if s.listening != nil {
  507. s.log(LogInformational, "closing listening channel")
  508. close(s.listening)
  509. s.listening = nil
  510. }
  511. if s.wsConn != nil {
  512. s.log(LogInformational, "closing gateway websocket")
  513. err = s.wsConn.Close()
  514. s.wsConn = nil
  515. }
  516. s.Unlock()
  517. s.log(LogInformational, "emit disconnect event")
  518. s.handle(&Disconnect{})
  519. return
  520. }