wsapi.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. return
  190. }
  191. <-time.After(wait * time.Second)
  192. wait *= 2
  193. if wait > 600 {
  194. wait = 600
  195. }
  196. }
  197. }
  198. }
  199. return
  200. }
  201. select {
  202. case <-listening:
  203. return
  204. default:
  205. go s.onEvent(messageType, message)
  206. }
  207. }
  208. }
  209. type heartbeatOp struct {
  210. Op int `json:"op"`
  211. Data int `json:"d"`
  212. }
  213. // heartbeat sends regular heartbeats to Discord so it knows the client
  214. // is still connected. If you do not send these heartbeats Discord will
  215. // disconnect the websocket connection after a few seconds.
  216. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  217. s.log(LogInformational, "called")
  218. if listening == nil || wsConn == nil {
  219. return
  220. }
  221. s.Lock()
  222. s.DataReady = true
  223. s.Unlock()
  224. var err error
  225. ticker := time.NewTicker(i * time.Millisecond)
  226. for {
  227. s.log(LogDebug, "sending gateway websocket heartbeat seq %d", s.sequence)
  228. s.wsMutex.Lock()
  229. err = wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  230. s.wsMutex.Unlock()
  231. if err != nil {
  232. log.Println("Error sending heartbeat:", err)
  233. return
  234. }
  235. select {
  236. case <-ticker.C:
  237. // continue loop and send heartbeat
  238. case <-listening:
  239. return
  240. }
  241. }
  242. }
  243. type updateStatusData struct {
  244. IdleSince *int `json:"idle_since"`
  245. Game *Game `json:"game"`
  246. }
  247. type updateStatusOp struct {
  248. Op int `json:"op"`
  249. Data updateStatusData `json:"d"`
  250. }
  251. // UpdateStreamingStatus is used to update the user's streaming status.
  252. // If idle>0 then set status to idle.
  253. // If game!="" then set game.
  254. // If game!="" and url!="" then set the status type to streaming with the URL set.
  255. // if otherwise, set status to active, and no game.
  256. func (s *Session) UpdateStreamingStatus(idle int, game string, url string) (err error) {
  257. s.log(LogInformational, "called")
  258. s.RLock()
  259. defer s.RUnlock()
  260. if s.wsConn == nil {
  261. return errors.New("no websocket connection exists")
  262. }
  263. var usd updateStatusData
  264. if idle > 0 {
  265. usd.IdleSince = &idle
  266. }
  267. if game != "" {
  268. gameType := 0
  269. if url != "" {
  270. gameType = 1
  271. }
  272. usd.Game = &Game{
  273. Name: game,
  274. Type: gameType,
  275. URL: url,
  276. }
  277. }
  278. s.wsMutex.Lock()
  279. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  280. s.wsMutex.Unlock()
  281. return
  282. }
  283. // UpdateStatus is used to update the user's status.
  284. // If idle>0 then set status to idle.
  285. // If game!="" then set game.
  286. // if otherwise, set status to active, and no game.
  287. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  288. return s.UpdateStreamingStatus(idle, game, "")
  289. }
  290. // onEvent is the "event handler" for all messages received on the
  291. // Discord Gateway API websocket connection.
  292. //
  293. // If you use the AddHandler() function to register a handler for a
  294. // specific event this function will pass the event along to that handler.
  295. //
  296. // If you use the AddHandler() function to register a handler for the
  297. // "OnEvent" event then all events will be passed to that handler.
  298. //
  299. // TODO: You may also register a custom event handler entirely using...
  300. func (s *Session) onEvent(messageType int, message []byte) {
  301. var err error
  302. var reader io.Reader
  303. reader = bytes.NewBuffer(message)
  304. // If this is a compressed message, uncompress it.
  305. if messageType == 2 {
  306. z, err := zlib.NewReader(reader)
  307. if err != nil {
  308. s.log(LogError, "error uncompressing websocket message, %s", err)
  309. return
  310. }
  311. defer func() {
  312. err := z.Close()
  313. if err != nil {
  314. s.log(LogWarning, "error closing zlib, %s", err)
  315. }
  316. }()
  317. reader = z
  318. }
  319. // Decode the event into an Event struct.
  320. var e *Event
  321. decoder := json.NewDecoder(reader)
  322. if err = decoder.Decode(&e); err != nil {
  323. s.log(LogError, "error decoding websocket message, %s", err)
  324. return
  325. }
  326. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  327. // Ping request.
  328. // Must respond with a heartbeat packet within 5 seconds
  329. if e.Operation == 1 {
  330. s.log(LogInformational, "sending heartbeat in response to Op1")
  331. s.wsMutex.Lock()
  332. err = s.wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  333. s.wsMutex.Unlock()
  334. if err != nil {
  335. s.log(LogError, "error sending heartbeat in response to Op1")
  336. return
  337. }
  338. return
  339. }
  340. // Reconnect
  341. // Must immediately disconnect from gateway and reconnect to new gateway.
  342. if e.Operation == 7 {
  343. // TODO
  344. }
  345. // Invalid Session
  346. // Must respond with a Identify packet.
  347. if e.Operation == 9 {
  348. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  349. s.wsMutex.Lock()
  350. err = s.wsConn.WriteJSON(handshakeOp{2, handshakeData{s.Token, handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""}, 250, s.Compress}})
  351. s.wsMutex.Unlock()
  352. if err != nil {
  353. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  354. return
  355. }
  356. return
  357. }
  358. // Do not try to Dispatch a non-Dispatch Message
  359. if e.Operation != 0 {
  360. // But we probably should be doing something with them.
  361. // TEMP
  362. 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))
  363. return
  364. }
  365. // Store the message sequence
  366. s.sequence = e.Sequence
  367. // Map event to registered event handlers and pass it along
  368. // to any registered functions
  369. i := eventToInterface[e.Type]
  370. if i != nil {
  371. // Create a new instance of the event type.
  372. i = reflect.New(reflect.TypeOf(i)).Interface()
  373. // Attempt to unmarshal our event.
  374. if err = json.Unmarshal(e.RawData, i); err != nil {
  375. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  376. }
  377. // Send event to any registered event handlers for it's type.
  378. // Because the above doesn't cancel this, in case of an error
  379. // the struct could be partially populated or at default values.
  380. // However, most errors are due to a single field and I feel
  381. // it's better to pass along what we received than nothing at all.
  382. // TODO: Think about that decision :)
  383. // Either way, READY events must fire, even with errors.
  384. s.handle(i)
  385. } else {
  386. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  387. }
  388. // Emit event to the OnEvent handler
  389. e.Struct = i
  390. s.handle(e)
  391. }
  392. // ------------------------------------------------------------------------------------------------
  393. // Code related to voice connections that initiate over the data websocket
  394. // ------------------------------------------------------------------------------------------------
  395. // A VoiceServerUpdate stores the data received during the Voice Server Update
  396. // data websocket event. This data is used during the initial Voice Channel
  397. // join handshaking.
  398. type VoiceServerUpdate struct {
  399. Token string `json:"token"`
  400. GuildID string `json:"guild_id"`
  401. Endpoint string `json:"endpoint"`
  402. }
  403. type voiceChannelJoinData struct {
  404. GuildID *string `json:"guild_id"`
  405. ChannelID *string `json:"channel_id"`
  406. SelfMute bool `json:"self_mute"`
  407. SelfDeaf bool `json:"self_deaf"`
  408. }
  409. type voiceChannelJoinOp struct {
  410. Op int `json:"op"`
  411. Data voiceChannelJoinData `json:"d"`
  412. }
  413. // ChannelVoiceJoin joins the session user to a voice channel.
  414. //
  415. // gID : Guild ID of the channel to join.
  416. // cID : Channel ID of the channel to join.
  417. // mute : If true, you will be set to muted upon joining.
  418. // deaf : If true, you will be set to deafened upon joining.
  419. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  420. // If a voice connection already exists for this guild then
  421. // return that connection. If the channel differs, also change channels.
  422. var ok bool
  423. if voice, ok = s.VoiceConnections[gID]; ok && voice.GuildID != "" {
  424. //TODO: consider a better variable than GuildID in the above check
  425. // to verify if this connection is valid or not.
  426. if voice.ChannelID != cID {
  427. err = voice.ChangeChannel(cID, mute, deaf)
  428. }
  429. return
  430. }
  431. if voice == nil {
  432. voice = &VoiceConnection{}
  433. s.VoiceConnections[gID] = voice
  434. }
  435. voice.GuildID = gID
  436. voice.ChannelID = cID
  437. voice.deaf = deaf
  438. voice.mute = mute
  439. voice.session = s
  440. // Send the request to Discord that we want to join the voice channel
  441. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  442. s.wsMutex.Lock()
  443. err = s.wsConn.WriteJSON(data)
  444. s.wsMutex.Unlock()
  445. if err != nil {
  446. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  447. delete(s.VoiceConnections, gID)
  448. return
  449. }
  450. // doesn't exactly work perfect yet.. TODO
  451. err = voice.waitUntilConnected()
  452. if err != nil {
  453. voice.Close()
  454. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  455. delete(s.VoiceConnections, gID)
  456. return
  457. }
  458. return
  459. }
  460. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  461. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  462. // If we don't have a connection for the channel, don't bother
  463. if st.ChannelID == "" {
  464. return
  465. }
  466. // Check if we have a voice connection to update
  467. voice, exists := s.VoiceConnections[st.GuildID]
  468. if !exists {
  469. return
  470. }
  471. // Need to have this happen at login and store it in the Session
  472. // TODO : This should be done upon connecting to Discord, or
  473. // be moved to a small helper function
  474. self, err := s.User("@me") // TODO: move to Login/New
  475. if err != nil {
  476. log.Println(err)
  477. return
  478. }
  479. // We only care about events that are about us
  480. if st.UserID != self.ID {
  481. return
  482. }
  483. // Store the SessionID for later use.
  484. voice.UserID = self.ID // TODO: Review
  485. voice.sessionID = st.SessionID
  486. }
  487. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  488. //
  489. // This is also fired if the Guild's voice region changes while connected
  490. // to a voice channel. In that case, need to re-establish connection to
  491. // the new region endpoint.
  492. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  493. voice, exists := s.VoiceConnections[st.GuildID]
  494. // If no VoiceConnection exists, just skip this
  495. if !exists {
  496. return
  497. }
  498. // If currently connected to voice ws/udp, then disconnect.
  499. // Has no effect if not connected.
  500. voice.Close()
  501. // Store values for later use
  502. voice.token = st.Token
  503. voice.endpoint = st.Endpoint
  504. voice.GuildID = st.GuildID
  505. // Open a conenction to the voice server
  506. err := voice.open()
  507. if err != nil {
  508. s.log(LogError, "onVoiceServerUpdate voice.open, ", err)
  509. }
  510. }