wsapi.go 24 KB

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