wsapi.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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. }
  217. // FailedHeartbeatAcks is the Number of heartbeat intervals to wait until forcing a connection restart.
  218. const FailedHeartbeatAcks time.Duration = 5 * time.Millisecond
  219. // HeartbeatLatency returns the latency between heartbeat acknowledgement and heartbeat send.
  220. func (s *Session) HeartbeatLatency() time.Duration {
  221. return s.LastHeartbeatAck.Sub(s.LastHeartbeatSent)
  222. }
  223. // heartbeat sends regular heartbeats to Discord so it knows the client
  224. // is still connected. If you do not send these heartbeats Discord will
  225. // disconnect the websocket connection after a few seconds.
  226. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, heartbeatIntervalMsec time.Duration) {
  227. s.log(LogInformational, "called")
  228. if listening == nil || wsConn == nil {
  229. return
  230. }
  231. var err error
  232. ticker := time.NewTicker(heartbeatIntervalMsec * time.Millisecond)
  233. defer ticker.Stop()
  234. for {
  235. s.RLock()
  236. last := s.LastHeartbeatAck
  237. s.RUnlock()
  238. sequence := atomic.LoadInt64(s.sequence)
  239. s.log(LogDebug, "sending gateway websocket heartbeat seq %d", sequence)
  240. s.wsMutex.Lock()
  241. s.LastHeartbeatSent = time.Now().UTC()
  242. err = wsConn.WriteJSON(heartbeatOp{1, sequence})
  243. s.wsMutex.Unlock()
  244. if err != nil || time.Now().UTC().Sub(last) > (heartbeatIntervalMsec*FailedHeartbeatAcks) {
  245. if err != nil {
  246. s.log(LogError, "error sending heartbeat to gateway %s, %s", s.gateway, err)
  247. } else {
  248. s.log(LogError, "haven't gotten a heartbeat ACK in %v, triggering a reconnection", time.Now().UTC().Sub(last))
  249. }
  250. s.Close()
  251. s.reconnect()
  252. return
  253. }
  254. s.Lock()
  255. s.DataReady = true
  256. s.Unlock()
  257. select {
  258. case <-ticker.C:
  259. // continue loop and send heartbeat
  260. case <-listening:
  261. return
  262. }
  263. }
  264. }
  265. // UpdateStatusData ia provided to UpdateStatusComplex()
  266. type UpdateStatusData struct {
  267. IdleSince *int `json:"since"`
  268. Game *Game `json:"game"`
  269. AFK bool `json:"afk"`
  270. Status string `json:"status"`
  271. }
  272. type updateStatusOp struct {
  273. Op int `json:"op"`
  274. Data UpdateStatusData `json:"d"`
  275. }
  276. func newUpdateStatusData(idle int, gameType GameType, game, url string) *UpdateStatusData {
  277. usd := &UpdateStatusData{
  278. Status: "online",
  279. }
  280. if idle > 0 {
  281. usd.IdleSince = &idle
  282. }
  283. if game != "" {
  284. usd.Game = &Game{
  285. Name: game,
  286. Type: gameType,
  287. URL: url,
  288. }
  289. }
  290. return usd
  291. }
  292. // UpdateStatus is used to update the user's status.
  293. // If idle>0 then set status to idle.
  294. // If game!="" then set game.
  295. // if otherwise, set status to active, and no game.
  296. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  297. return s.UpdateStatusComplex(*newUpdateStatusData(idle, GameTypeGame, game, ""))
  298. }
  299. // UpdateStreamingStatus is used to update the user's streaming status.
  300. // If idle>0 then set status to idle.
  301. // If game!="" then set game.
  302. // If game!="" and url!="" then set the status type to streaming with the URL set.
  303. // if otherwise, set status to active, and no game.
  304. func (s *Session) UpdateStreamingStatus(idle int, game string, url string) (err error) {
  305. gameType := GameTypeGame
  306. if url != "" {
  307. gameType = GameTypeStreaming
  308. }
  309. return s.UpdateStatusComplex(*newUpdateStatusData(idle, gameType, game, url))
  310. }
  311. // UpdateListeningStatus is used to set the user to "Listening to..."
  312. // If game!="" then set to what user is listening to
  313. // Else, set user to active and no game.
  314. func (s *Session) UpdateListeningStatus(game string) (err error) {
  315. return s.UpdateStatusComplex(*newUpdateStatusData(0, GameTypeListening, game, ""))
  316. }
  317. // UpdateStatusComplex allows for sending the raw status update data untouched by discordgo.
  318. func (s *Session) UpdateStatusComplex(usd UpdateStatusData) (err error) {
  319. s.RLock()
  320. defer s.RUnlock()
  321. if s.wsConn == nil {
  322. return ErrWSNotFound
  323. }
  324. s.wsMutex.Lock()
  325. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  326. s.wsMutex.Unlock()
  327. return
  328. }
  329. type requestGuildMembersData struct {
  330. GuildID string `json:"guild_id"`
  331. Query string `json:"query"`
  332. Limit int `json:"limit"`
  333. }
  334. type requestGuildMembersOp struct {
  335. Op int `json:"op"`
  336. Data requestGuildMembersData `json:"d"`
  337. }
  338. // RequestGuildMembers requests guild members from the gateway
  339. // The gateway responds with GuildMembersChunk events
  340. // guildID : The ID of the guild to request members of
  341. // query : String that username starts with, leave empty to return all members
  342. // limit : Max number of items to return, or 0 to request all members matched
  343. func (s *Session) RequestGuildMembers(guildID, query string, limit int) (err error) {
  344. s.log(LogInformational, "called")
  345. s.RLock()
  346. defer s.RUnlock()
  347. if s.wsConn == nil {
  348. return ErrWSNotFound
  349. }
  350. data := requestGuildMembersData{
  351. GuildID: guildID,
  352. Query: query,
  353. Limit: limit,
  354. }
  355. s.wsMutex.Lock()
  356. err = s.wsConn.WriteJSON(requestGuildMembersOp{8, data})
  357. s.wsMutex.Unlock()
  358. return
  359. }
  360. // onEvent is the "event handler" for all messages received on the
  361. // Discord Gateway API websocket connection.
  362. //
  363. // If you use the AddHandler() function to register a handler for a
  364. // specific event this function will pass the event along to that handler.
  365. //
  366. // If you use the AddHandler() function to register a handler for the
  367. // "OnEvent" event then all events will be passed to that handler.
  368. func (s *Session) onEvent(messageType int, message []byte) (*Event, error) {
  369. var err error
  370. var reader io.Reader
  371. reader = bytes.NewBuffer(message)
  372. // If this is a compressed message, uncompress it.
  373. if messageType == websocket.BinaryMessage {
  374. z, err2 := zlib.NewReader(reader)
  375. if err2 != nil {
  376. s.log(LogError, "error uncompressing websocket message, %s", err)
  377. return nil, err2
  378. }
  379. defer func() {
  380. err3 := z.Close()
  381. if err3 != nil {
  382. s.log(LogWarning, "error closing zlib, %s", err)
  383. }
  384. }()
  385. reader = z
  386. }
  387. // Decode the event into an Event struct.
  388. var e *Event
  389. decoder := json.NewDecoder(reader)
  390. if err = decoder.Decode(&e); err != nil {
  391. s.log(LogError, "error decoding websocket message, %s", err)
  392. return e, err
  393. }
  394. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  395. // Ping request.
  396. // Must respond with a heartbeat packet within 5 seconds
  397. if e.Operation == 1 {
  398. s.log(LogInformational, "sending heartbeat in response to Op1")
  399. s.wsMutex.Lock()
  400. err = s.wsConn.WriteJSON(heartbeatOp{1, atomic.LoadInt64(s.sequence)})
  401. s.wsMutex.Unlock()
  402. if err != nil {
  403. s.log(LogError, "error sending heartbeat in response to Op1")
  404. return e, err
  405. }
  406. return e, nil
  407. }
  408. // Reconnect
  409. // Must immediately disconnect from gateway and reconnect to new gateway.
  410. if e.Operation == 7 {
  411. s.log(LogInformational, "Closing and reconnecting in response to Op7")
  412. s.Close()
  413. s.reconnect()
  414. return e, nil
  415. }
  416. // Invalid Session
  417. // Must respond with a Identify packet.
  418. if e.Operation == 9 {
  419. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  420. err = s.identify()
  421. if err != nil {
  422. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  423. return e, err
  424. }
  425. return e, nil
  426. }
  427. if e.Operation == 10 {
  428. // Op10 is handled by Open()
  429. return e, nil
  430. }
  431. if e.Operation == 11 {
  432. s.Lock()
  433. s.LastHeartbeatAck = time.Now().UTC()
  434. s.Unlock()
  435. s.log(LogDebug, "got heartbeat ACK")
  436. return e, nil
  437. }
  438. // Do not try to Dispatch a non-Dispatch Message
  439. if e.Operation != 0 {
  440. // But we probably should be doing something with them.
  441. // TEMP
  442. 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))
  443. return e, nil
  444. }
  445. // Store the message sequence
  446. atomic.StoreInt64(s.sequence, e.Sequence)
  447. // Map event to registered event handlers and pass it along to any registered handlers.
  448. if eh, ok := registeredInterfaceProviders[e.Type]; ok {
  449. e.Struct = eh.New()
  450. // Attempt to unmarshal our event.
  451. if err = json.Unmarshal(e.RawData, e.Struct); err != nil {
  452. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  453. }
  454. // Send event to any registered event handlers for it's type.
  455. // Because the above doesn't cancel this, in case of an error
  456. // the struct could be partially populated or at default values.
  457. // However, most errors are due to a single field and I feel
  458. // it's better to pass along what we received than nothing at all.
  459. // TODO: Think about that decision :)
  460. // Either way, READY events must fire, even with errors.
  461. s.handleEvent(e.Type, e.Struct)
  462. } else {
  463. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  464. }
  465. // For legacy reasons, we send the raw event also, this could be useful for handling unknown events.
  466. s.handleEvent(eventEventType, e)
  467. return e, nil
  468. }
  469. // ------------------------------------------------------------------------------------------------
  470. // Code related to voice connections that initiate over the data websocket
  471. // ------------------------------------------------------------------------------------------------
  472. type voiceChannelJoinData struct {
  473. GuildID *string `json:"guild_id"`
  474. ChannelID *string `json:"channel_id"`
  475. SelfMute bool `json:"self_mute"`
  476. SelfDeaf bool `json:"self_deaf"`
  477. }
  478. type voiceChannelJoinOp struct {
  479. Op int `json:"op"`
  480. Data voiceChannelJoinData `json:"d"`
  481. }
  482. // ChannelVoiceJoin joins the session user to a voice channel.
  483. //
  484. // gID : Guild ID of the channel to join.
  485. // cID : Channel ID of the channel to join.
  486. // mute : If true, you will be set to muted upon joining.
  487. // deaf : If true, you will be set to deafened upon joining.
  488. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  489. s.log(LogInformational, "called")
  490. s.RLock()
  491. voice, _ = s.VoiceConnections[gID]
  492. s.RUnlock()
  493. if voice == nil {
  494. voice = &VoiceConnection{}
  495. s.Lock()
  496. s.VoiceConnections[gID] = voice
  497. s.Unlock()
  498. }
  499. voice.Lock()
  500. voice.GuildID = gID
  501. voice.ChannelID = cID
  502. voice.deaf = deaf
  503. voice.mute = mute
  504. voice.session = s
  505. voice.Unlock()
  506. err = s.ChannelVoiceJoinManual(gID, cID, mute, deaf)
  507. if err != nil {
  508. return
  509. }
  510. // doesn't exactly work perfect yet.. TODO
  511. err = voice.waitUntilConnected()
  512. if err != nil {
  513. s.log(LogWarning, "error waiting for voice to connect, %s", err)
  514. voice.Close()
  515. return
  516. }
  517. return
  518. }
  519. // ChannelVoiceJoinManual initiates a voice session to a voice channel, but does not complete it.
  520. //
  521. // This should only be used when the VoiceServerUpdate will be intercepted and used elsewhere.
  522. //
  523. // gID : Guild ID of the channel to join.
  524. // cID : Channel ID of the channel to join, leave empty to disconnect.
  525. // mute : If true, you will be set to muted upon joining.
  526. // deaf : If true, you will be set to deafened upon joining.
  527. func (s *Session) ChannelVoiceJoinManual(gID, cID string, mute, deaf bool) (err error) {
  528. s.log(LogInformational, "called")
  529. var channelID *string
  530. if cID == "" {
  531. channelID = nil
  532. } else {
  533. channelID = &cID
  534. }
  535. // Send the request to Discord that we want to join the voice channel
  536. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, channelID, mute, deaf}}
  537. s.wsMutex.Lock()
  538. err = s.wsConn.WriteJSON(data)
  539. s.wsMutex.Unlock()
  540. return
  541. }
  542. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  543. func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) {
  544. // If we don't have a connection for the channel, don't bother
  545. if st.ChannelID == "" {
  546. return
  547. }
  548. // Check if we have a voice connection to update
  549. s.RLock()
  550. voice, exists := s.VoiceConnections[st.GuildID]
  551. s.RUnlock()
  552. if !exists {
  553. return
  554. }
  555. // We only care about events that are about us.
  556. if s.State.User.ID != st.UserID {
  557. return
  558. }
  559. // Store the SessionID for later use.
  560. voice.Lock()
  561. voice.UserID = st.UserID
  562. voice.sessionID = st.SessionID
  563. voice.ChannelID = st.ChannelID
  564. voice.Unlock()
  565. }
  566. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  567. //
  568. // This is also fired if the Guild's voice region changes while connected
  569. // to a voice channel. In that case, need to re-establish connection to
  570. // the new region endpoint.
  571. func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) {
  572. s.log(LogInformational, "called")
  573. s.RLock()
  574. voice, exists := s.VoiceConnections[st.GuildID]
  575. s.RUnlock()
  576. // If no VoiceConnection exists, just skip this
  577. if !exists {
  578. return
  579. }
  580. // If currently connected to voice ws/udp, then disconnect.
  581. // Has no effect if not connected.
  582. voice.Close()
  583. // Store values for later use
  584. voice.Lock()
  585. voice.token = st.Token
  586. voice.endpoint = st.Endpoint
  587. voice.GuildID = st.GuildID
  588. voice.Unlock()
  589. // Open a connection to the voice server
  590. err := voice.open()
  591. if err != nil {
  592. s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
  593. }
  594. }
  595. type identifyProperties struct {
  596. OS string `json:"$os"`
  597. Browser string `json:"$browser"`
  598. Device string `json:"$device"`
  599. Referer string `json:"$referer"`
  600. ReferringDomain string `json:"$referring_domain"`
  601. }
  602. type identifyData struct {
  603. Token string `json:"token"`
  604. Properties identifyProperties `json:"properties"`
  605. LargeThreshold int `json:"large_threshold"`
  606. Compress bool `json:"compress"`
  607. Shard *[2]int `json:"shard,omitempty"`
  608. }
  609. type identifyOp struct {
  610. Op int `json:"op"`
  611. Data identifyData `json:"d"`
  612. }
  613. // identify sends the identify packet to the gateway
  614. func (s *Session) identify() error {
  615. properties := identifyProperties{runtime.GOOS,
  616. "Discordgo v" + VERSION,
  617. "",
  618. "",
  619. "",
  620. }
  621. data := identifyData{s.Token,
  622. properties,
  623. 250,
  624. s.Compress,
  625. nil,
  626. }
  627. if s.ShardCount > 1 {
  628. if s.ShardID >= s.ShardCount {
  629. return ErrWSShardBounds
  630. }
  631. data.Shard = &[2]int{s.ShardID, s.ShardCount}
  632. }
  633. op := identifyOp{2, data}
  634. s.wsMutex.Lock()
  635. err := s.wsConn.WriteJSON(op)
  636. s.wsMutex.Unlock()
  637. return err
  638. }
  639. func (s *Session) reconnect() {
  640. s.log(LogInformational, "called")
  641. var err error
  642. if s.ShouldReconnectOnError {
  643. wait := time.Duration(1)
  644. for {
  645. s.log(LogInformational, "trying to reconnect to gateway")
  646. err = s.Open()
  647. if err == nil {
  648. s.log(LogInformational, "successfully reconnected to gateway")
  649. // I'm not sure if this is actually needed.
  650. // if the gw reconnect works properly, voice should stay alive
  651. // However, there seems to be cases where something "weird"
  652. // happens. So we're doing this for now just to improve
  653. // stability in those edge cases.
  654. s.RLock()
  655. defer s.RUnlock()
  656. for _, v := range s.VoiceConnections {
  657. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  658. go v.reconnect()
  659. // This is here just to prevent violently spamming the
  660. // voice reconnects
  661. time.Sleep(1 * time.Second)
  662. }
  663. return
  664. }
  665. // Certain race conditions can call reconnect() twice. If this happens, we
  666. // just break out of the reconnect loop
  667. if err == ErrWSAlreadyOpen {
  668. s.log(LogInformational, "Websocket already exists, no need to reconnect")
  669. return
  670. }
  671. s.log(LogError, "error reconnecting to gateway, %s", err)
  672. <-time.After(wait * time.Second)
  673. wait *= 2
  674. if wait > 600 {
  675. wait = 600
  676. }
  677. }
  678. }
  679. }
  680. // Close closes a websocket and stops all listening/heartbeat goroutines.
  681. // TODO: Add support for Voice WS/UDP connections
  682. func (s *Session) Close() (err error) {
  683. s.log(LogInformational, "called")
  684. s.Lock()
  685. s.DataReady = false
  686. if s.listening != nil {
  687. s.log(LogInformational, "closing listening channel")
  688. close(s.listening)
  689. s.listening = nil
  690. }
  691. // TODO: Close all active Voice Connections too
  692. // this should force stop any reconnecting voice channels too
  693. if s.wsConn != nil {
  694. s.log(LogInformational, "sending close frame")
  695. // To cleanly close a connection, a client should send a close
  696. // frame and wait for the server to close the connection.
  697. s.wsMutex.Lock()
  698. err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  699. s.wsMutex.Unlock()
  700. if err != nil {
  701. s.log(LogInformational, "error closing websocket, %s", err)
  702. }
  703. // TODO: Wait for Discord to actually close the connection.
  704. time.Sleep(1 * time.Second)
  705. s.log(LogInformational, "closing gateway websocket")
  706. err = s.wsConn.Close()
  707. if err != nil {
  708. s.log(LogInformational, "error closing websocket, %s", err)
  709. }
  710. s.wsConn = nil
  711. }
  712. s.Unlock()
  713. s.log(LogInformational, "emit disconnect event")
  714. s.handleEvent(disconnectEventType, &Disconnect{})
  715. return
  716. }