wsapi.go 22 KB

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