wsapi.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. // UpdateStreamingStatus is used to update the user's streaming status.
  270. // If idle>0 then set status to idle.
  271. // If game!="" then set game.
  272. // If game!="" and url!="" then set the status type to streaming with the URL set.
  273. // if otherwise, set status to active, and no game.
  274. func (s *Session) UpdateStreamingStatus(idle int, game string, url string) (err error) {
  275. s.log(LogInformational, "called")
  276. usd := UpdateStatusData{
  277. Status: "online",
  278. }
  279. if idle > 0 {
  280. usd.IdleSince = &idle
  281. }
  282. if game != "" {
  283. gameType := GameTypeGame
  284. if url != "" {
  285. gameType = GameTypeStreaming
  286. }
  287. usd.Game = &Game{
  288. Name: game,
  289. Type: gameType,
  290. URL: url,
  291. }
  292. }
  293. return s.UpdateStatusComplex(usd)
  294. }
  295. // UpdateStatusComplex allows for sending the raw status update data untouched by discordgo.
  296. func (s *Session) UpdateStatusComplex(usd UpdateStatusData) (err error) {
  297. s.RLock()
  298. defer s.RUnlock()
  299. if s.wsConn == nil {
  300. return ErrWSNotFound
  301. }
  302. s.wsMutex.Lock()
  303. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  304. s.wsMutex.Unlock()
  305. return
  306. }
  307. // UpdateStatus is used to update the user's status.
  308. // If idle>0 then set status to idle.
  309. // If game!="" then set game.
  310. // if otherwise, set status to active, and no game.
  311. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  312. return s.UpdateStreamingStatus(idle, game, "")
  313. }
  314. // UpdateListeningStatus is used to set the user to "Listening to..."
  315. // If game!="" then set to what user is listening to
  316. // Else, set user to active and no game.
  317. func (s *Session) UpdateListeningStatus(game string) (err error) {
  318. usd := UpdateStatusData{
  319. Status: "online",
  320. }
  321. if game != "" {
  322. usd.Game = &Game{
  323. Name: game,
  324. Type: GameTypeListening,
  325. URL: "",
  326. }
  327. }
  328. return s.UpdateStatusComplex(usd)
  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(LogInformational, "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. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  525. func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) {
  526. // If we don't have a connection for the channel, don't bother
  527. if st.ChannelID == "" {
  528. return
  529. }
  530. // Check if we have a voice connection to update
  531. s.RLock()
  532. voice, exists := s.VoiceConnections[st.GuildID]
  533. s.RUnlock()
  534. if !exists {
  535. return
  536. }
  537. // We only care about events that are about us.
  538. if s.State.User.ID != st.UserID {
  539. return
  540. }
  541. // Store the SessionID for later use.
  542. voice.Lock()
  543. voice.UserID = st.UserID
  544. voice.sessionID = st.SessionID
  545. voice.ChannelID = st.ChannelID
  546. voice.Unlock()
  547. }
  548. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  549. //
  550. // This is also fired if the Guild's voice region changes while connected
  551. // to a voice channel. In that case, need to re-establish connection to
  552. // the new region endpoint.
  553. func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) {
  554. s.log(LogInformational, "called")
  555. s.RLock()
  556. voice, exists := s.VoiceConnections[st.GuildID]
  557. s.RUnlock()
  558. // If no VoiceConnection exists, just skip this
  559. if !exists {
  560. return
  561. }
  562. // If currently connected to voice ws/udp, then disconnect.
  563. // Has no effect if not connected.
  564. voice.Close()
  565. // Store values for later use
  566. voice.Lock()
  567. voice.token = st.Token
  568. voice.endpoint = st.Endpoint
  569. voice.GuildID = st.GuildID
  570. voice.Unlock()
  571. // Open a connection to the voice server
  572. err := voice.open()
  573. if err != nil {
  574. s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
  575. }
  576. }
  577. type identifyProperties struct {
  578. OS string `json:"$os"`
  579. Browser string `json:"$browser"`
  580. Device string `json:"$device"`
  581. Referer string `json:"$referer"`
  582. ReferringDomain string `json:"$referring_domain"`
  583. }
  584. type identifyData struct {
  585. Token string `json:"token"`
  586. Properties identifyProperties `json:"properties"`
  587. LargeThreshold int `json:"large_threshold"`
  588. Compress bool `json:"compress"`
  589. Shard *[2]int `json:"shard,omitempty"`
  590. }
  591. type identifyOp struct {
  592. Op int `json:"op"`
  593. Data identifyData `json:"d"`
  594. }
  595. // identify sends the identify packet to the gateway
  596. func (s *Session) identify() error {
  597. properties := identifyProperties{runtime.GOOS,
  598. "Discordgo v" + VERSION,
  599. "",
  600. "",
  601. "",
  602. }
  603. data := identifyData{s.Token,
  604. properties,
  605. 250,
  606. s.Compress,
  607. nil,
  608. }
  609. if s.ShardCount > 1 {
  610. if s.ShardID >= s.ShardCount {
  611. return ErrWSShardBounds
  612. }
  613. data.Shard = &[2]int{s.ShardID, s.ShardCount}
  614. }
  615. op := identifyOp{2, data}
  616. s.wsMutex.Lock()
  617. err := s.wsConn.WriteJSON(op)
  618. s.wsMutex.Unlock()
  619. return err
  620. }
  621. func (s *Session) reconnect() {
  622. s.log(LogInformational, "called")
  623. var err error
  624. if s.ShouldReconnectOnError {
  625. wait := time.Duration(1)
  626. for {
  627. s.log(LogInformational, "trying to reconnect to gateway")
  628. err = s.Open()
  629. if err == nil {
  630. s.log(LogInformational, "successfully reconnected to gateway")
  631. // I'm not sure if this is actually needed.
  632. // if the gw reconnect works properly, voice should stay alive
  633. // However, there seems to be cases where something "weird"
  634. // happens. So we're doing this for now just to improve
  635. // stability in those edge cases.
  636. s.RLock()
  637. defer s.RUnlock()
  638. for _, v := range s.VoiceConnections {
  639. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  640. go v.reconnect()
  641. // This is here just to prevent violently spamming the
  642. // voice reconnects
  643. time.Sleep(1 * time.Second)
  644. }
  645. return
  646. }
  647. // Certain race conditions can call reconnect() twice. If this happens, we
  648. // just break out of the reconnect loop
  649. if err == ErrWSAlreadyOpen {
  650. s.log(LogInformational, "Websocket already exists, no need to reconnect")
  651. return
  652. }
  653. s.log(LogError, "error reconnecting to gateway, %s", err)
  654. <-time.After(wait * time.Second)
  655. wait *= 2
  656. if wait > 600 {
  657. wait = 600
  658. }
  659. }
  660. }
  661. }
  662. // Close closes a websocket and stops all listening/heartbeat goroutines.
  663. // TODO: Add support for Voice WS/UDP connections
  664. func (s *Session) Close() (err error) {
  665. s.log(LogInformational, "called")
  666. s.Lock()
  667. s.DataReady = false
  668. if s.listening != nil {
  669. s.log(LogInformational, "closing listening channel")
  670. close(s.listening)
  671. s.listening = nil
  672. }
  673. // TODO: Close all active Voice Connections too
  674. // this should force stop any reconnecting voice channels too
  675. if s.wsConn != nil {
  676. s.log(LogInformational, "sending close frame")
  677. // To cleanly close a connection, a client should send a close
  678. // frame and wait for the server to close the connection.
  679. s.wsMutex.Lock()
  680. err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  681. s.wsMutex.Unlock()
  682. if err != nil {
  683. s.log(LogInformational, "error closing websocket, %s", err)
  684. }
  685. // TODO: Wait for Discord to actually close the connection.
  686. time.Sleep(1 * time.Second)
  687. s.log(LogInformational, "closing gateway websocket")
  688. err = s.wsConn.Close()
  689. if err != nil {
  690. s.log(LogInformational, "error closing websocket, %s", err)
  691. }
  692. s.wsConn = nil
  693. }
  694. s.Unlock()
  695. s.log(LogInformational, "emit disconnect event")
  696. s.handleEvent(disconnectEventType, &Disconnect{})
  697. return
  698. }