wsapi.go 22 KB

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