wsapi.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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. GuildIDs []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 : Single Guild ID 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 string, query string, limit int) (err error) {
  345. data := requestGuildMembersData{
  346. GuildID: guildID,
  347. Query: query,
  348. Limit: limit,
  349. }
  350. err = s.requestGuildMember(&data)
  351. return err
  352. }
  353. // RequestGuildMembersBatch requests guild members from the gateway
  354. // The gateway responds with GuildMembersChunk events
  355. // guildID : Slice of guild IDs to request members of
  356. // query : String that username starts with, leave empty to return all members
  357. // limit : Max number of items to return, or 0 to request all members matched
  358. func (s *Session) RequestGuildMembersBatch(guildIDs []string, query string, limit int) (err error) {
  359. data := requestGuildMembersData{
  360. GuildIDs: guildIDs,
  361. Query: query,
  362. Limit: limit,
  363. }
  364. err = s.requestGuildMember(&data)
  365. return err
  366. }
  367. func (s *Session) requestGuildMember(data *requestGuildMembersData) (err error) {
  368. s.log(LogInformational, "called")
  369. s.RLock()
  370. defer s.RUnlock()
  371. if s.wsConn == nil {
  372. return ErrWSNotFound
  373. }
  374. s.wsMutex.Lock()
  375. err = s.wsConn.WriteJSON(requestGuildMembersOp{8, *data})
  376. s.wsMutex.Unlock()
  377. return err
  378. }
  379. // onEvent is the "event handler" for all messages received on the
  380. // Discord Gateway API websocket connection.
  381. //
  382. // If you use the AddHandler() function to register a handler for a
  383. // specific event this function will pass the event along to that handler.
  384. //
  385. // If you use the AddHandler() function to register a handler for the
  386. // "OnEvent" event then all events will be passed to that handler.
  387. func (s *Session) onEvent(messageType int, message []byte) (*Event, error) {
  388. var err error
  389. var reader io.Reader
  390. reader = bytes.NewBuffer(message)
  391. // If this is a compressed message, uncompress it.
  392. if messageType == websocket.BinaryMessage {
  393. z, err2 := zlib.NewReader(reader)
  394. if err2 != nil {
  395. s.log(LogError, "error uncompressing websocket message, %s", err)
  396. return nil, err2
  397. }
  398. defer func() {
  399. err3 := z.Close()
  400. if err3 != nil {
  401. s.log(LogWarning, "error closing zlib, %s", err)
  402. }
  403. }()
  404. reader = z
  405. }
  406. // Decode the event into an Event struct.
  407. var e *Event
  408. decoder := json.NewDecoder(reader)
  409. if err = decoder.Decode(&e); err != nil {
  410. s.log(LogError, "error decoding websocket message, %s", err)
  411. return e, err
  412. }
  413. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  414. // Ping request.
  415. // Must respond with a heartbeat packet within 5 seconds
  416. if e.Operation == 1 {
  417. s.log(LogInformational, "sending heartbeat in response to Op1")
  418. s.wsMutex.Lock()
  419. err = s.wsConn.WriteJSON(heartbeatOp{1, atomic.LoadInt64(s.sequence)})
  420. s.wsMutex.Unlock()
  421. if err != nil {
  422. s.log(LogError, "error sending heartbeat in response to Op1")
  423. return e, err
  424. }
  425. return e, nil
  426. }
  427. // Reconnect
  428. // Must immediately disconnect from gateway and reconnect to new gateway.
  429. if e.Operation == 7 {
  430. s.log(LogInformational, "Closing and reconnecting in response to Op7")
  431. s.Close()
  432. s.reconnect()
  433. return e, nil
  434. }
  435. // Invalid Session
  436. // Must respond with a Identify packet.
  437. if e.Operation == 9 {
  438. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  439. err = s.identify()
  440. if err != nil {
  441. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  442. return e, err
  443. }
  444. return e, nil
  445. }
  446. if e.Operation == 10 {
  447. // Op10 is handled by Open()
  448. return e, nil
  449. }
  450. if e.Operation == 11 {
  451. s.Lock()
  452. s.LastHeartbeatAck = time.Now().UTC()
  453. s.Unlock()
  454. s.log(LogDebug, "got heartbeat ACK")
  455. return e, nil
  456. }
  457. // Do not try to Dispatch a non-Dispatch Message
  458. if e.Operation != 0 {
  459. // But we probably should be doing something with them.
  460. // TEMP
  461. 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))
  462. return e, nil
  463. }
  464. // Store the message sequence
  465. atomic.StoreInt64(s.sequence, e.Sequence)
  466. // Map event to registered event handlers and pass it along to any registered handlers.
  467. if eh, ok := registeredInterfaceProviders[e.Type]; ok {
  468. e.Struct = eh.New()
  469. // Attempt to unmarshal our event.
  470. if err = json.Unmarshal(e.RawData, e.Struct); err != nil {
  471. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  472. }
  473. // Send event to any registered event handlers for it's type.
  474. // Because the above doesn't cancel this, in case of an error
  475. // the struct could be partially populated or at default values.
  476. // However, most errors are due to a single field and I feel
  477. // it's better to pass along what we received than nothing at all.
  478. // TODO: Think about that decision :)
  479. // Either way, READY events must fire, even with errors.
  480. s.handleEvent(e.Type, e.Struct)
  481. } else {
  482. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  483. }
  484. // For legacy reasons, we send the raw event also, this could be useful for handling unknown events.
  485. s.handleEvent(eventEventType, e)
  486. return e, nil
  487. }
  488. // ------------------------------------------------------------------------------------------------
  489. // Code related to voice connections that initiate over the data websocket
  490. // ------------------------------------------------------------------------------------------------
  491. type voiceChannelJoinData struct {
  492. GuildID *string `json:"guild_id"`
  493. ChannelID *string `json:"channel_id"`
  494. SelfMute bool `json:"self_mute"`
  495. SelfDeaf bool `json:"self_deaf"`
  496. }
  497. type voiceChannelJoinOp struct {
  498. Op int `json:"op"`
  499. Data voiceChannelJoinData `json:"d"`
  500. }
  501. // ChannelVoiceJoin joins the session user to a voice channel.
  502. //
  503. // gID : Guild ID of the channel to join.
  504. // cID : Channel ID of the channel to join.
  505. // mute : If true, you will be set to muted upon joining.
  506. // deaf : If true, you will be set to deafened upon joining.
  507. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  508. s.log(LogInformational, "called")
  509. s.RLock()
  510. voice, _ = s.VoiceConnections[gID]
  511. s.RUnlock()
  512. if voice == nil {
  513. voice = &VoiceConnection{}
  514. s.Lock()
  515. s.VoiceConnections[gID] = voice
  516. s.Unlock()
  517. }
  518. voice.Lock()
  519. voice.GuildID = gID
  520. voice.ChannelID = cID
  521. voice.deaf = deaf
  522. voice.mute = mute
  523. voice.session = s
  524. voice.Unlock()
  525. err = s.ChannelVoiceJoinManual(gID, cID, mute, deaf)
  526. if err != nil {
  527. return
  528. }
  529. // doesn't exactly work perfect yet.. TODO
  530. err = voice.waitUntilConnected()
  531. if err != nil {
  532. s.log(LogWarning, "error waiting for voice to connect, %s", err)
  533. voice.Close()
  534. return
  535. }
  536. return
  537. }
  538. // ChannelVoiceJoinManual initiates a voice session to a voice channel, but does not complete it.
  539. //
  540. // This should only be used when the VoiceServerUpdate will be intercepted and used elsewhere.
  541. //
  542. // gID : Guild ID of the channel to join.
  543. // cID : Channel ID of the channel to join, leave empty to disconnect.
  544. // mute : If true, you will be set to muted upon joining.
  545. // deaf : If true, you will be set to deafened upon joining.
  546. func (s *Session) ChannelVoiceJoinManual(gID, cID string, mute, deaf bool) (err error) {
  547. s.log(LogInformational, "called")
  548. var channelID *string
  549. if cID == "" {
  550. channelID = nil
  551. } else {
  552. channelID = &cID
  553. }
  554. // Send the request to Discord that we want to join the voice channel
  555. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, channelID, mute, deaf}}
  556. s.wsMutex.Lock()
  557. err = s.wsConn.WriteJSON(data)
  558. s.wsMutex.Unlock()
  559. return
  560. }
  561. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  562. func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) {
  563. // If we don't have a connection for the channel, don't bother
  564. if st.ChannelID == "" {
  565. return
  566. }
  567. // Check if we have a voice connection to update
  568. s.RLock()
  569. voice, exists := s.VoiceConnections[st.GuildID]
  570. s.RUnlock()
  571. if !exists {
  572. return
  573. }
  574. // We only care about events that are about us.
  575. if s.State.User.ID != st.UserID {
  576. return
  577. }
  578. // Store the SessionID for later use.
  579. voice.Lock()
  580. voice.UserID = st.UserID
  581. voice.sessionID = st.SessionID
  582. voice.ChannelID = st.ChannelID
  583. voice.Unlock()
  584. }
  585. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  586. //
  587. // This is also fired if the Guild's voice region changes while connected
  588. // to a voice channel. In that case, need to re-establish connection to
  589. // the new region endpoint.
  590. func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) {
  591. s.log(LogInformational, "called")
  592. s.RLock()
  593. voice, exists := s.VoiceConnections[st.GuildID]
  594. s.RUnlock()
  595. // If no VoiceConnection exists, just skip this
  596. if !exists {
  597. return
  598. }
  599. // If currently connected to voice ws/udp, then disconnect.
  600. // Has no effect if not connected.
  601. voice.Close()
  602. // Store values for later use
  603. voice.Lock()
  604. voice.token = st.Token
  605. voice.endpoint = st.Endpoint
  606. voice.GuildID = st.GuildID
  607. voice.Unlock()
  608. // Open a connection to the voice server
  609. err := voice.open()
  610. if err != nil {
  611. s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
  612. }
  613. }
  614. type identifyProperties struct {
  615. OS string `json:"$os"`
  616. Browser string `json:"$browser"`
  617. Device string `json:"$device"`
  618. Referer string `json:"$referer"`
  619. ReferringDomain string `json:"$referring_domain"`
  620. }
  621. type identifyData struct {
  622. Token string `json:"token"`
  623. Properties identifyProperties `json:"properties"`
  624. LargeThreshold int `json:"large_threshold"`
  625. Compress bool `json:"compress"`
  626. Shard *[2]int `json:"shard,omitempty"`
  627. }
  628. type identifyOp struct {
  629. Op int `json:"op"`
  630. Data identifyData `json:"d"`
  631. }
  632. // identify sends the identify packet to the gateway
  633. func (s *Session) identify() error {
  634. properties := identifyProperties{runtime.GOOS,
  635. "Discordgo v" + VERSION,
  636. "",
  637. "",
  638. "",
  639. }
  640. data := identifyData{s.Token,
  641. properties,
  642. 250,
  643. s.Compress,
  644. nil,
  645. }
  646. if s.ShardCount > 1 {
  647. if s.ShardID >= s.ShardCount {
  648. return ErrWSShardBounds
  649. }
  650. data.Shard = &[2]int{s.ShardID, s.ShardCount}
  651. }
  652. op := identifyOp{2, data}
  653. s.wsMutex.Lock()
  654. err := s.wsConn.WriteJSON(op)
  655. s.wsMutex.Unlock()
  656. return err
  657. }
  658. func (s *Session) reconnect() {
  659. s.log(LogInformational, "called")
  660. var err error
  661. if s.ShouldReconnectOnError {
  662. wait := time.Duration(1)
  663. for {
  664. s.log(LogInformational, "trying to reconnect to gateway")
  665. err = s.Open()
  666. if err == nil {
  667. s.log(LogInformational, "successfully reconnected to gateway")
  668. // I'm not sure if this is actually needed.
  669. // if the gw reconnect works properly, voice should stay alive
  670. // However, there seems to be cases where something "weird"
  671. // happens. So we're doing this for now just to improve
  672. // stability in those edge cases.
  673. s.RLock()
  674. defer s.RUnlock()
  675. for _, v := range s.VoiceConnections {
  676. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  677. go v.reconnect()
  678. // This is here just to prevent violently spamming the
  679. // voice reconnects
  680. time.Sleep(1 * time.Second)
  681. }
  682. return
  683. }
  684. // Certain race conditions can call reconnect() twice. If this happens, we
  685. // just break out of the reconnect loop
  686. if err == ErrWSAlreadyOpen {
  687. s.log(LogInformational, "Websocket already exists, no need to reconnect")
  688. return
  689. }
  690. s.log(LogError, "error reconnecting to gateway, %s", err)
  691. <-time.After(wait * time.Second)
  692. wait *= 2
  693. if wait > 600 {
  694. wait = 600
  695. }
  696. }
  697. }
  698. }
  699. // Close closes a websocket and stops all listening/heartbeat goroutines.
  700. // TODO: Add support for Voice WS/UDP connections
  701. func (s *Session) Close() (err error) {
  702. s.log(LogInformational, "called")
  703. s.Lock()
  704. s.DataReady = false
  705. if s.listening != nil {
  706. s.log(LogInformational, "closing listening channel")
  707. close(s.listening)
  708. s.listening = nil
  709. }
  710. // TODO: Close all active Voice Connections too
  711. // this should force stop any reconnecting voice channels too
  712. if s.wsConn != nil {
  713. s.log(LogInformational, "sending close frame")
  714. // To cleanly close a connection, a client should send a close
  715. // frame and wait for the server to close the connection.
  716. s.wsMutex.Lock()
  717. err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  718. s.wsMutex.Unlock()
  719. if err != nil {
  720. s.log(LogInformational, "error closing websocket, %s", err)
  721. }
  722. // TODO: Wait for Discord to actually close the connection.
  723. time.Sleep(1 * time.Second)
  724. s.log(LogInformational, "closing gateway websocket")
  725. err = s.wsConn.Close()
  726. if err != nil {
  727. s.log(LogInformational, "error closing websocket, %s", err)
  728. }
  729. s.wsConn = nil
  730. }
  731. s.Unlock()
  732. s.log(LogInformational, "emit disconnect event")
  733. s.handleEvent(disconnectEventType, &Disconnect{})
  734. return
  735. }