wsapi.go 16 KB

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