wsapi.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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. "net/http"
  17. "runtime"
  18. "sync/atomic"
  19. "time"
  20. "github.com/gorilla/websocket"
  21. )
  22. // ErrWSAlreadyOpen is thrown when you attempt to open
  23. // a websocket that already is open.
  24. var ErrWSAlreadyOpen = errors.New("web socket already opened")
  25. // ErrWSNotFound is thrown when you attempt to use a websocket
  26. // that doesn't exist
  27. var ErrWSNotFound = errors.New("no websocket connection exists")
  28. // ErrWSShardBounds is thrown when you try to use a shard ID that is
  29. // less than the total shard count
  30. var ErrWSShardBounds = errors.New("ShardID must be less than ShardCount")
  31. type resumePacket struct {
  32. Op int `json:"op"`
  33. Data struct {
  34. Token string `json:"token"`
  35. SessionID string `json:"session_id"`
  36. Sequence int64 `json:"seq"`
  37. } `json:"d"`
  38. }
  39. // Open creates a websocket connection to Discord.
  40. // See: https://discordapp.com/developers/docs/topics/gateway#connecting
  41. func (s *Session) Open() error {
  42. s.log(LogInformational, "called")
  43. var err error
  44. // Prevent Open or other major Session functions from
  45. // being called while Open is still running.
  46. s.Lock()
  47. defer s.Unlock()
  48. // If the websock is already open, bail out here.
  49. if s.wsConn != nil {
  50. return ErrWSAlreadyOpen
  51. }
  52. // Get the gateway to use for the Websocket connection
  53. if s.gateway == "" {
  54. s.gateway, err = s.Gateway()
  55. if err != nil {
  56. return err
  57. }
  58. // Add the version and encoding to the URL
  59. s.gateway = s.gateway + "?v=" + APIVersion + "&encoding=json"
  60. }
  61. // Connect to the Gateway
  62. s.log(LogInformational, "connecting to gateway %s", s.gateway)
  63. header := http.Header{}
  64. header.Add("accept-encoding", "zlib")
  65. s.wsConn, _, err = websocket.DefaultDialer.Dial(s.gateway, header)
  66. if err != nil {
  67. s.log(LogWarning, "error connecting to gateway %s, %s", s.gateway, err)
  68. s.gateway = "" // clear cached gateway
  69. s.wsConn = nil // Just to be safe.
  70. return err
  71. }
  72. s.wsConn.SetCloseHandler(func(code int, text string) error {
  73. return nil
  74. })
  75. defer func() {
  76. // because of this, all code below must set err to the error
  77. // when exiting with an error :) Maybe someone has a better
  78. // way :)
  79. if err != nil {
  80. s.wsConn.Close()
  81. s.wsConn = nil
  82. }
  83. }()
  84. // The first response from Discord should be an Op 10 (Hello) Packet.
  85. // When processed by onEvent the heartbeat goroutine will be started.
  86. mt, m, err := s.wsConn.ReadMessage()
  87. if err != nil {
  88. return err
  89. }
  90. e, err := s.onEvent(mt, m)
  91. if err != nil {
  92. return err
  93. }
  94. if e.Operation != 10 {
  95. err = fmt.Errorf("expecting Op 10, got Op %d instead", e.Operation)
  96. return err
  97. }
  98. s.log(LogInformational, "Op 10 Hello Packet received from Discord")
  99. s.LastHeartbeatAck = time.Now().UTC()
  100. var h helloOp
  101. if err = json.Unmarshal(e.RawData, &h); err != nil {
  102. err = fmt.Errorf("error unmarshalling helloOp, %s", err)
  103. return err
  104. }
  105. // Now we send either an Op 2 Identity if this is a brand new
  106. // connection or Op 6 Resume if we are resuming an existing connection.
  107. sequence := atomic.LoadInt64(s.sequence)
  108. if s.sessionID == "" && sequence == 0 {
  109. // Send Op 2 Identity Packet
  110. err = s.identify()
  111. if err != nil {
  112. err = fmt.Errorf("error sending identify packet to gateway, %s, %s", s.gateway, err)
  113. return err
  114. }
  115. } else {
  116. // Send Op 6 Resume Packet
  117. p := resumePacket{}
  118. p.Op = 6
  119. p.Data.Token = s.Token
  120. p.Data.SessionID = s.sessionID
  121. p.Data.Sequence = sequence
  122. s.log(LogInformational, "sending resume packet to gateway")
  123. s.wsMutex.Lock()
  124. err = s.wsConn.WriteJSON(p)
  125. s.wsMutex.Unlock()
  126. if err != nil {
  127. err = fmt.Errorf("error sending gateway resume packet, %s, %s", s.gateway, err)
  128. return err
  129. }
  130. }
  131. // A basic state is a hard requirement for Voice.
  132. // We create it here so the below READY/RESUMED packet can populate
  133. // the state :)
  134. // XXX: Move to New() func?
  135. if s.State == nil {
  136. state := NewState()
  137. state.TrackChannels = false
  138. state.TrackEmojis = false
  139. state.TrackMembers = false
  140. state.TrackRoles = false
  141. state.TrackVoice = false
  142. s.State = state
  143. }
  144. // Now Discord should send us a READY or RESUMED packet.
  145. mt, m, err = s.wsConn.ReadMessage()
  146. if err != nil {
  147. return err
  148. }
  149. e, err = s.onEvent(mt, m)
  150. if err != nil {
  151. return err
  152. }
  153. if e.Type != `READY` && e.Type != `RESUMED` {
  154. // This is not fatal, but it does not follow their API documentation.
  155. s.log(LogWarning, "Expected READY/RESUMED, instead got:\n%#v\n", e)
  156. }
  157. s.log(LogInformational, "First Packet:\n%#v\n", e)
  158. s.log(LogInformational, "We are now connected to Discord, emitting connect event")
  159. s.handleEvent(connectEventType, &Connect{})
  160. // A VoiceConnections map is a hard requirement for Voice.
  161. // XXX: can this be moved to when opening a voice connection?
  162. if s.VoiceConnections == nil {
  163. s.log(LogInformational, "creating new VoiceConnections map")
  164. s.VoiceConnections = make(map[string]*VoiceConnection)
  165. }
  166. // Create listening chan outside of listen, as it needs to happen inside the
  167. // mutex lock and needs to exist before calling heartbeat and listen
  168. // go rountines.
  169. s.listening = make(chan interface{})
  170. // Start sending heartbeats and reading messages from Discord.
  171. go s.heartbeat(s.wsConn, s.listening, h.HeartbeatInterval)
  172. go s.listen(s.wsConn, s.listening)
  173. s.log(LogInformational, "exiting")
  174. return nil
  175. }
  176. // listen polls the websocket connection for events, it will stop when the
  177. // listening channel is closed, or an error occurs.
  178. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  179. s.log(LogInformational, "called")
  180. for {
  181. messageType, message, err := wsConn.ReadMessage()
  182. if err != nil {
  183. // Detect if we have been closed manually. If a Close() has already
  184. // happened, the websocket we are listening on will be different to
  185. // the current session.
  186. s.RLock()
  187. sameConnection := s.wsConn == wsConn
  188. s.RUnlock()
  189. if sameConnection {
  190. s.log(LogWarning, "error reading from gateway %s websocket, %s", s.gateway, err)
  191. // There has been an error reading, close the websocket so that
  192. // OnDisconnect event is emitted.
  193. err := s.Close()
  194. if err != nil {
  195. s.log(LogWarning, "error closing session connection, %s", err)
  196. }
  197. s.log(LogInformational, "calling reconnect() now")
  198. s.reconnect()
  199. }
  200. return
  201. }
  202. select {
  203. case <-listening:
  204. return
  205. default:
  206. s.onEvent(messageType, message)
  207. }
  208. }
  209. }
  210. type heartbeatOp struct {
  211. Op int `json:"op"`
  212. Data int64 `json:"d"`
  213. }
  214. type helloOp struct {
  215. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  216. Trace []string `json:"_trace"`
  217. }
  218. // FailedHeartbeatAcks is the Number of heartbeat intervals to wait until forcing a connection restart.
  219. const FailedHeartbeatAcks time.Duration = 5 * time.Millisecond
  220. // HeartbeatLatency returns the latency between heartbeat acknowledgement and heartbeat send.
  221. func (s *Session) HeartbeatLatency() time.Duration {
  222. return s.LastHeartbeatAck.Sub(s.LastHeartbeatSent)
  223. }
  224. // heartbeat sends regular heartbeats to Discord so it knows the client
  225. // is still connected. If you do not send these heartbeats Discord will
  226. // disconnect the websocket connection after a few seconds.
  227. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, heartbeatIntervalMsec time.Duration) {
  228. s.log(LogInformational, "called")
  229. if listening == nil || wsConn == nil {
  230. return
  231. }
  232. var err error
  233. ticker := time.NewTicker(heartbeatIntervalMsec * time.Millisecond)
  234. defer ticker.Stop()
  235. for {
  236. s.RLock()
  237. last := s.LastHeartbeatAck
  238. s.RUnlock()
  239. sequence := atomic.LoadInt64(s.sequence)
  240. s.log(LogDebug, "sending gateway websocket heartbeat seq %d", sequence)
  241. s.wsMutex.Lock()
  242. s.LastHeartbeatSent = time.Now().UTC()
  243. err = wsConn.WriteJSON(heartbeatOp{1, sequence})
  244. s.wsMutex.Unlock()
  245. if err != nil || time.Now().UTC().Sub(last) > (heartbeatIntervalMsec*FailedHeartbeatAcks) {
  246. if err != nil {
  247. s.log(LogError, "error sending heartbeat to gateway %s, %s", s.gateway, err)
  248. } else {
  249. s.log(LogError, "haven't gotten a heartbeat ACK in %v, triggering a reconnection", time.Now().UTC().Sub(last))
  250. }
  251. s.Close()
  252. s.reconnect()
  253. return
  254. }
  255. s.Lock()
  256. s.DataReady = true
  257. s.Unlock()
  258. select {
  259. case <-ticker.C:
  260. // continue loop and send heartbeat
  261. case <-listening:
  262. return
  263. }
  264. }
  265. }
  266. // UpdateStatusData ia provided to UpdateStatusComplex()
  267. type UpdateStatusData struct {
  268. IdleSince *int `json:"since"`
  269. Game *Game `json:"game"`
  270. AFK bool `json:"afk"`
  271. Status string `json:"status"`
  272. }
  273. type updateStatusOp struct {
  274. Op int `json:"op"`
  275. Data UpdateStatusData `json:"d"`
  276. }
  277. func newUpdateStatusData(idle int, gameType GameType, game, url string) *UpdateStatusData {
  278. usd := &UpdateStatusData{
  279. Status: "online",
  280. }
  281. if idle > 0 {
  282. usd.IdleSince = &idle
  283. }
  284. if game != "" {
  285. usd.Game = &Game{
  286. Name: game,
  287. Type: gameType,
  288. URL: url,
  289. }
  290. }
  291. return usd
  292. }
  293. // UpdateStatus is used to update the user's status.
  294. // If idle>0 then set status to idle.
  295. // If game!="" then set game.
  296. // if otherwise, set status to active, and no game.
  297. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  298. return s.UpdateStatusComplex(*newUpdateStatusData(idle, GameTypeGame, game, ""))
  299. }
  300. // UpdateStreamingStatus is used to update the user's streaming status.
  301. // If idle>0 then set status to idle.
  302. // If game!="" then set game.
  303. // If game!="" and url!="" then set the status type to streaming with the URL set.
  304. // if otherwise, set status to active, and no game.
  305. func (s *Session) UpdateStreamingStatus(idle int, game string, url string) (err error) {
  306. gameType := GameTypeGame
  307. if url != "" {
  308. gameType = GameTypeStreaming
  309. }
  310. return s.UpdateStatusComplex(*newUpdateStatusData(idle, gameType, game, url))
  311. }
  312. // UpdateListeningStatus is used to set the user to "Listening to..."
  313. // If game!="" then set to what user is listening to
  314. // Else, set user to active and no game.
  315. func (s *Session) UpdateListeningStatus(game string) (err error) {
  316. return s.UpdateStatusComplex(*newUpdateStatusData(0, GameTypeListening, game, ""))
  317. }
  318. // UpdateStatusComplex allows for sending the raw status update data untouched by discordgo.
  319. func (s *Session) UpdateStatusComplex(usd UpdateStatusData) (err error) {
  320. s.RLock()
  321. defer s.RUnlock()
  322. if s.wsConn == nil {
  323. return ErrWSNotFound
  324. }
  325. s.wsMutex.Lock()
  326. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  327. s.wsMutex.Unlock()
  328. return
  329. }
  330. type requestGuildMembersData struct {
  331. GuildID string `json:"guild_id"`
  332. Query string `json:"query"`
  333. Limit int `json:"limit"`
  334. }
  335. type requestGuildMembersOp struct {
  336. Op int `json:"op"`
  337. Data requestGuildMembersData `json:"d"`
  338. }
  339. // RequestGuildMembers requests guild members from the gateway
  340. // The gateway responds with GuildMembersChunk events
  341. // guildID : The ID of the guild to request members of
  342. // query : String that username starts with, leave empty to return all members
  343. // limit : Max number of items to return, or 0 to request all members matched
  344. func (s *Session) RequestGuildMembers(guildID, query string, limit int) (err error) {
  345. s.log(LogInformational, "called")
  346. s.RLock()
  347. defer s.RUnlock()
  348. if s.wsConn == nil {
  349. return ErrWSNotFound
  350. }
  351. data := requestGuildMembersData{
  352. GuildID: guildID,
  353. Query: query,
  354. Limit: limit,
  355. }
  356. s.wsMutex.Lock()
  357. err = s.wsConn.WriteJSON(requestGuildMembersOp{8, data})
  358. s.wsMutex.Unlock()
  359. return
  360. }
  361. // onEvent is the "event handler" for all messages received on the
  362. // Discord Gateway API websocket connection.
  363. //
  364. // If you use the AddHandler() function to register a handler for a
  365. // specific event this function will pass the event along to that handler.
  366. //
  367. // If you use the AddHandler() function to register a handler for the
  368. // "OnEvent" event then all events will be passed to that handler.
  369. func (s *Session) onEvent(messageType int, message []byte) (*Event, error) {
  370. var err error
  371. var reader io.Reader
  372. reader = bytes.NewBuffer(message)
  373. // If this is a compressed message, uncompress it.
  374. if messageType == websocket.BinaryMessage {
  375. z, err2 := zlib.NewReader(reader)
  376. if err2 != nil {
  377. s.log(LogError, "error uncompressing websocket message, %s", err)
  378. return nil, err2
  379. }
  380. defer func() {
  381. err3 := z.Close()
  382. if err3 != nil {
  383. s.log(LogWarning, "error closing zlib, %s", err)
  384. }
  385. }()
  386. reader = z
  387. }
  388. // Decode the event into an Event struct.
  389. var e *Event
  390. decoder := json.NewDecoder(reader)
  391. if err = decoder.Decode(&e); err != nil {
  392. s.log(LogError, "error decoding websocket message, %s", err)
  393. return e, err
  394. }
  395. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  396. // Ping request.
  397. // Must respond with a heartbeat packet within 5 seconds
  398. if e.Operation == 1 {
  399. s.log(LogInformational, "sending heartbeat in response to Op1")
  400. s.wsMutex.Lock()
  401. err = s.wsConn.WriteJSON(heartbeatOp{1, atomic.LoadInt64(s.sequence)})
  402. s.wsMutex.Unlock()
  403. if err != nil {
  404. s.log(LogError, "error sending heartbeat in response to Op1")
  405. return e, err
  406. }
  407. return e, nil
  408. }
  409. // Reconnect
  410. // Must immediately disconnect from gateway and reconnect to new gateway.
  411. if e.Operation == 7 {
  412. s.log(LogInformational, "Closing and reconnecting in response to Op7")
  413. s.Close()
  414. s.reconnect()
  415. return e, nil
  416. }
  417. // Invalid Session
  418. // Must respond with a Identify packet.
  419. if e.Operation == 9 {
  420. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  421. err = s.identify()
  422. if err != nil {
  423. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  424. return e, err
  425. }
  426. return e, nil
  427. }
  428. if e.Operation == 10 {
  429. // Op10 is handled by Open()
  430. return e, nil
  431. }
  432. if e.Operation == 11 {
  433. s.Lock()
  434. s.LastHeartbeatAck = time.Now().UTC()
  435. s.Unlock()
  436. s.log(LogDebug, "got heartbeat ACK")
  437. return e, nil
  438. }
  439. // Do not try to Dispatch a non-Dispatch Message
  440. if e.Operation != 0 {
  441. // But we probably should be doing something with them.
  442. // TEMP
  443. 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))
  444. return e, nil
  445. }
  446. // Store the message sequence
  447. atomic.StoreInt64(s.sequence, e.Sequence)
  448. // Map event to registered event handlers and pass it along to any registered handlers.
  449. if eh, ok := registeredInterfaceProviders[e.Type]; ok {
  450. e.Struct = eh.New()
  451. // Attempt to unmarshal our event.
  452. if err = json.Unmarshal(e.RawData, e.Struct); err != nil {
  453. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  454. }
  455. // Send event to any registered event handlers for it's type.
  456. // Because the above doesn't cancel this, in case of an error
  457. // the struct could be partially populated or at default values.
  458. // However, most errors are due to a single field and I feel
  459. // it's better to pass along what we received than nothing at all.
  460. // TODO: Think about that decision :)
  461. // Either way, READY events must fire, even with errors.
  462. s.handleEvent(e.Type, e.Struct)
  463. } else {
  464. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  465. }
  466. // For legacy reasons, we send the raw event also, this could be useful for handling unknown events.
  467. s.handleEvent(eventEventType, e)
  468. return e, nil
  469. }
  470. // ------------------------------------------------------------------------------------------------
  471. // Code related to voice connections that initiate over the data websocket
  472. // ------------------------------------------------------------------------------------------------
  473. type voiceChannelJoinData struct {
  474. GuildID *string `json:"guild_id"`
  475. ChannelID *string `json:"channel_id"`
  476. SelfMute bool `json:"self_mute"`
  477. SelfDeaf bool `json:"self_deaf"`
  478. }
  479. type voiceChannelJoinOp struct {
  480. Op int `json:"op"`
  481. Data voiceChannelJoinData `json:"d"`
  482. }
  483. // ChannelVoiceJoin joins the session user to a voice channel.
  484. //
  485. // gID : Guild ID of the channel to join.
  486. // cID : Channel ID of the channel to join.
  487. // mute : If true, you will be set to muted upon joining.
  488. // deaf : If true, you will be set to deafened upon joining.
  489. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  490. s.log(LogInformational, "called")
  491. s.RLock()
  492. voice, _ = s.VoiceConnections[gID]
  493. s.RUnlock()
  494. if voice == nil {
  495. voice = &VoiceConnection{}
  496. s.Lock()
  497. s.VoiceConnections[gID] = voice
  498. s.Unlock()
  499. }
  500. voice.Lock()
  501. voice.GuildID = gID
  502. voice.ChannelID = cID
  503. voice.deaf = deaf
  504. voice.mute = mute
  505. voice.session = s
  506. voice.Unlock()
  507. // Send the request to Discord that we want to join the voice channel
  508. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  509. s.wsMutex.Lock()
  510. err = s.wsConn.WriteJSON(data)
  511. s.wsMutex.Unlock()
  512. if err != nil {
  513. return
  514. }
  515. // doesn't exactly work perfect yet.. TODO
  516. err = voice.waitUntilConnected()
  517. if err != nil {
  518. s.log(LogWarning, "error waiting for voice to connect, %s", err)
  519. voice.Close()
  520. return
  521. }
  522. return
  523. }
  524. // ChannelVoiceJoinManual initiates a voice session to a voice channel, but does not complete it.
  525. //
  526. // This should only be used when the VoiceServerUpdate will be intercepted and used elsewhere.
  527. //
  528. // gID : Guild ID of the channel to join.
  529. // cID : Channel ID of the channel to join.
  530. // mute : If true, you will be set to muted upon joining.
  531. // deaf : If true, you will be set to deafened upon joining.
  532. func (s *Session) ChannelVoiceJoinManual(gID, cID string, mute, deaf bool) (err error) {
  533. s.log(LogInformational, "called")
  534. // Send the request to Discord that we want to join the voice channel
  535. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  536. s.wsMutex.Lock()
  537. err = s.wsConn.WriteJSON(data)
  538. s.wsMutex.Unlock()
  539. if err != nil {
  540. return
  541. }
  542. return
  543. }
  544. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  545. func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) {
  546. // If we don't have a connection for the channel, don't bother
  547. if st.ChannelID == "" {
  548. return
  549. }
  550. // Check if we have a voice connection to update
  551. s.RLock()
  552. voice, exists := s.VoiceConnections[st.GuildID]
  553. s.RUnlock()
  554. if !exists {
  555. return
  556. }
  557. // We only care about events that are about us.
  558. if s.State.User.ID != st.UserID {
  559. return
  560. }
  561. // Store the SessionID for later use.
  562. voice.Lock()
  563. voice.UserID = st.UserID
  564. voice.sessionID = st.SessionID
  565. voice.ChannelID = st.ChannelID
  566. voice.Unlock()
  567. }
  568. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  569. //
  570. // This is also fired if the Guild's voice region changes while connected
  571. // to a voice channel. In that case, need to re-establish connection to
  572. // the new region endpoint.
  573. func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) {
  574. s.log(LogInformational, "called")
  575. s.RLock()
  576. voice, exists := s.VoiceConnections[st.GuildID]
  577. s.RUnlock()
  578. // If no VoiceConnection exists, just skip this
  579. if !exists {
  580. return
  581. }
  582. // If currently connected to voice ws/udp, then disconnect.
  583. // Has no effect if not connected.
  584. voice.Close()
  585. // Store values for later use
  586. voice.Lock()
  587. voice.token = st.Token
  588. voice.endpoint = st.Endpoint
  589. voice.GuildID = st.GuildID
  590. voice.Unlock()
  591. // Open a connection to the voice server
  592. err := voice.open()
  593. if err != nil {
  594. s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
  595. }
  596. }
  597. type identifyProperties struct {
  598. OS string `json:"$os"`
  599. Browser string `json:"$browser"`
  600. Device string `json:"$device"`
  601. Referer string `json:"$referer"`
  602. ReferringDomain string `json:"$referring_domain"`
  603. }
  604. type identifyData struct {
  605. Token string `json:"token"`
  606. Properties identifyProperties `json:"properties"`
  607. LargeThreshold int `json:"large_threshold"`
  608. Compress bool `json:"compress"`
  609. Shard *[2]int `json:"shard,omitempty"`
  610. }
  611. type identifyOp struct {
  612. Op int `json:"op"`
  613. Data identifyData `json:"d"`
  614. }
  615. // identify sends the identify packet to the gateway
  616. func (s *Session) identify() error {
  617. properties := identifyProperties{runtime.GOOS,
  618. "Discordgo v" + VERSION,
  619. "",
  620. "",
  621. "",
  622. }
  623. data := identifyData{s.Token,
  624. properties,
  625. 250,
  626. s.Compress,
  627. nil,
  628. }
  629. if s.ShardCount > 1 {
  630. if s.ShardID >= s.ShardCount {
  631. return ErrWSShardBounds
  632. }
  633. data.Shard = &[2]int{s.ShardID, s.ShardCount}
  634. }
  635. op := identifyOp{2, data}
  636. s.wsMutex.Lock()
  637. err := s.wsConn.WriteJSON(op)
  638. s.wsMutex.Unlock()
  639. return err
  640. }
  641. func (s *Session) reconnect() {
  642. s.log(LogInformational, "called")
  643. var err error
  644. if s.ShouldReconnectOnError {
  645. wait := time.Duration(1)
  646. for {
  647. s.log(LogInformational, "trying to reconnect to gateway")
  648. err = s.Open()
  649. if err == nil {
  650. s.log(LogInformational, "successfully reconnected to gateway")
  651. // I'm not sure if this is actually needed.
  652. // if the gw reconnect works properly, voice should stay alive
  653. // However, there seems to be cases where something "weird"
  654. // happens. So we're doing this for now just to improve
  655. // stability in those edge cases.
  656. s.RLock()
  657. defer s.RUnlock()
  658. for _, v := range s.VoiceConnections {
  659. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  660. go v.reconnect()
  661. // This is here just to prevent violently spamming the
  662. // voice reconnects
  663. time.Sleep(1 * time.Second)
  664. }
  665. return
  666. }
  667. // Certain race conditions can call reconnect() twice. If this happens, we
  668. // just break out of the reconnect loop
  669. if err == ErrWSAlreadyOpen {
  670. s.log(LogInformational, "Websocket already exists, no need to reconnect")
  671. return
  672. }
  673. s.log(LogError, "error reconnecting to gateway, %s", err)
  674. <-time.After(wait * time.Second)
  675. wait *= 2
  676. if wait > 600 {
  677. wait = 600
  678. }
  679. }
  680. }
  681. }
  682. // Close closes a websocket and stops all listening/heartbeat goroutines.
  683. // TODO: Add support for Voice WS/UDP connections
  684. func (s *Session) Close() (err error) {
  685. s.log(LogInformational, "called")
  686. s.Lock()
  687. s.DataReady = false
  688. if s.listening != nil {
  689. s.log(LogInformational, "closing listening channel")
  690. close(s.listening)
  691. s.listening = nil
  692. }
  693. // TODO: Close all active Voice Connections too
  694. // this should force stop any reconnecting voice channels too
  695. if s.wsConn != nil {
  696. s.log(LogInformational, "sending close frame")
  697. // To cleanly close a connection, a client should send a close
  698. // frame and wait for the server to close the connection.
  699. s.wsMutex.Lock()
  700. err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  701. s.wsMutex.Unlock()
  702. if err != nil {
  703. s.log(LogInformational, "error closing websocket, %s", err)
  704. }
  705. // TODO: Wait for Discord to actually close the connection.
  706. time.Sleep(1 * time.Second)
  707. s.log(LogInformational, "closing gateway websocket")
  708. err = s.wsConn.Close()
  709. if err != nil {
  710. s.log(LogInformational, "error closing websocket, %s", err)
  711. }
  712. s.wsConn = nil
  713. }
  714. s.Unlock()
  715. s.log(LogInformational, "emit disconnect event")
  716. s.handleEvent(disconnectEventType, &Disconnect{})
  717. return
  718. }