wsapi.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. // UpdateStatus is used to update the user's 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) UpdateStatus(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. // onEvent is the "event handler" for all messages received on the
  284. // Discord Gateway API websocket connection.
  285. //
  286. // If you use the AddHandler() function to register a handler for a
  287. // specific event this function will pass the event along to that handler.
  288. //
  289. // If you use the AddHandler() function to register a handler for the
  290. // "OnEvent" event then all events will be passed to that handler.
  291. //
  292. // TODO: You may also register a custom event handler entirely using...
  293. func (s *Session) onEvent(messageType int, message []byte) {
  294. var err error
  295. var reader io.Reader
  296. reader = bytes.NewBuffer(message)
  297. // If this is a compressed message, uncompress it.
  298. if messageType == 2 {
  299. z, err := zlib.NewReader(reader)
  300. if err != nil {
  301. s.log(LogError, "error uncompressing websocket message, %s", err)
  302. return
  303. }
  304. defer func() {
  305. err := z.Close()
  306. if err != nil {
  307. s.log(LogWarning, "error closing zlib, %s", err)
  308. }
  309. }()
  310. reader = z
  311. }
  312. // Decode the event into an Event struct.
  313. var e *Event
  314. decoder := json.NewDecoder(reader)
  315. if err = decoder.Decode(&e); err != nil {
  316. s.log(LogError, "error decoding websocket message, %s", err)
  317. return
  318. }
  319. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  320. // Ping request.
  321. // Must respond with a heartbeat packet within 5 seconds
  322. if e.Operation == 1 {
  323. s.log(LogInformational, "sending heartbeat in response to Op1")
  324. s.wsMutex.Lock()
  325. err = s.wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  326. s.wsMutex.Unlock()
  327. if err != nil {
  328. s.log(LogError, "error sending heartbeat in response to Op1")
  329. return
  330. }
  331. return
  332. }
  333. // Reconnect
  334. // Must immediately disconnect from gateway and reconnect to new gateway.
  335. if e.Operation == 7 {
  336. // TODO
  337. }
  338. // Invalid Session
  339. // Must respond with a Identify packet.
  340. if e.Operation == 9 {
  341. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  342. s.wsMutex.Lock()
  343. err = s.wsConn.WriteJSON(handshakeOp{2, handshakeData{s.Token, handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""}, 250, s.Compress}})
  344. s.wsMutex.Unlock()
  345. if err != nil {
  346. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  347. return
  348. }
  349. return
  350. }
  351. // Do not try to Dispatch a non-Dispatch Message
  352. if e.Operation != 0 {
  353. // But we probably should be doing something with them.
  354. // TEMP
  355. 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))
  356. return
  357. }
  358. // Store the message sequence
  359. s.sequence = e.Sequence
  360. // Map event to registered event handlers and pass it along
  361. // to any registered functions
  362. i := eventToInterface[e.Type]
  363. if i != nil {
  364. // Create a new instance of the event type.
  365. i = reflect.New(reflect.TypeOf(i)).Interface()
  366. // Attempt to unmarshal our event.
  367. if err = json.Unmarshal(e.RawData, i); err != nil {
  368. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  369. }
  370. // Send event to any registered event handlers for it's type.
  371. // Because the above doesn't cancel this, in case of an error
  372. // the struct could be partially populated or at default values.
  373. // However, most errors are due to a single field and I feel
  374. // it's better to pass along what we received than nothing at all.
  375. // TODO: Think about that decision :)
  376. // Either way, READY events must fire, even with errors.
  377. s.handle(i)
  378. } else {
  379. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  380. }
  381. // Emit event to the OnEvent handler
  382. e.Struct = i
  383. s.handle(e)
  384. }
  385. // ------------------------------------------------------------------------------------------------
  386. // Code related to voice connections that initiate over the data websocket
  387. // ------------------------------------------------------------------------------------------------
  388. // A VoiceServerUpdate stores the data received during the Voice Server Update
  389. // data websocket event. This data is used during the initial Voice Channel
  390. // join handshaking.
  391. type VoiceServerUpdate struct {
  392. Token string `json:"token"`
  393. GuildID string `json:"guild_id"`
  394. Endpoint string `json:"endpoint"`
  395. }
  396. type voiceChannelJoinData struct {
  397. GuildID *string `json:"guild_id"`
  398. ChannelID *string `json:"channel_id"`
  399. SelfMute bool `json:"self_mute"`
  400. SelfDeaf bool `json:"self_deaf"`
  401. }
  402. type voiceChannelJoinOp struct {
  403. Op int `json:"op"`
  404. Data voiceChannelJoinData `json:"d"`
  405. }
  406. // ChannelVoiceJoin joins the session user to a voice channel.
  407. //
  408. // gID : Guild ID of the channel to join.
  409. // cID : Channel ID of the channel to join.
  410. // mute : If true, you will be set to muted upon joining.
  411. // deaf : If true, you will be set to deafened upon joining.
  412. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  413. // If a voice connection already exists for this guild then
  414. // return that connection. If the channel differs, also change channels.
  415. var ok bool
  416. if voice, ok = s.VoiceConnections[gID]; ok && voice.GuildID != "" {
  417. //TODO: consider a better variable than GuildID in the above check
  418. // to verify if this connection is valid or not.
  419. if voice.ChannelID != cID {
  420. err = voice.ChangeChannel(cID, mute, deaf)
  421. }
  422. return
  423. }
  424. // Create a new voice session
  425. // TODO review what all these things are for....
  426. voice = &VoiceConnection{
  427. GuildID: gID,
  428. ChannelID: cID,
  429. deaf: deaf,
  430. mute: mute,
  431. session: s,
  432. }
  433. // Store voice in VoiceConnections map for this GuildID
  434. s.VoiceConnections[gID] = voice
  435. // Send the request to Discord that we want to join the voice channel
  436. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  437. s.wsMutex.Lock()
  438. err = s.wsConn.WriteJSON(data)
  439. s.wsMutex.Unlock()
  440. if err != nil {
  441. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  442. delete(s.VoiceConnections, gID)
  443. return
  444. }
  445. // doesn't exactly work perfect yet.. TODO
  446. err = voice.waitUntilConnected()
  447. if err != nil {
  448. voice.Close()
  449. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  450. delete(s.VoiceConnections, gID)
  451. return
  452. }
  453. return
  454. }
  455. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  456. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  457. // If we don't have a connection for the channel, don't bother
  458. if st.ChannelID == "" {
  459. return
  460. }
  461. // Check if we have a voice connection to update
  462. voice, exists := s.VoiceConnections[st.GuildID]
  463. if !exists {
  464. return
  465. }
  466. // Need to have this happen at login and store it in the Session
  467. // TODO : This should be done upon connecting to Discord, or
  468. // be moved to a small helper function
  469. self, err := s.User("@me") // TODO: move to Login/New
  470. if err != nil {
  471. log.Println(err)
  472. return
  473. }
  474. // We only care about events that are about us
  475. if st.UserID != self.ID {
  476. return
  477. }
  478. // Store the SessionID for later use.
  479. voice.UserID = self.ID // TODO: Review
  480. voice.sessionID = st.SessionID
  481. }
  482. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  483. //
  484. // This is also fired if the Guild's voice region changes while connected
  485. // to a voice channel. In that case, need to re-establish connection to
  486. // the new region endpoint.
  487. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  488. voice, exists := s.VoiceConnections[st.GuildID]
  489. // If no VoiceConnection exists, just skip this
  490. if !exists {
  491. return
  492. }
  493. // If currently connected to voice ws/udp, then disconnect.
  494. // Has no effect if not connected.
  495. voice.Close()
  496. // Store values for later use
  497. voice.token = st.Token
  498. voice.endpoint = st.Endpoint
  499. voice.GuildID = st.GuildID
  500. // Open a conenction to the voice server
  501. err := voice.open()
  502. if err != nil {
  503. s.log(LogError, "onVoiceServerUpdate voice.open, ", err)
  504. }
  505. }