wsapi.go 16 KB

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