wsapi.go 16 KB

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