wsapi.go 16 KB

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