wsapi.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. "log"
  17. "net/http"
  18. "reflect"
  19. "runtime"
  20. "time"
  21. "github.com/gorilla/websocket"
  22. )
  23. var GATEWAY_VERSION int = 4
  24. type handshakeProperties struct {
  25. OS string `json:"$os"`
  26. Browser string `json:"$browser"`
  27. Device string `json:"$device"`
  28. Referer string `json:"$referer"`
  29. ReferringDomain string `json:"$referring_domain"`
  30. }
  31. type handshakeData struct {
  32. Token string `json:"token"`
  33. Properties handshakeProperties `json:"properties"`
  34. LargeThreshold int `json:"large_threshold"`
  35. Compress bool `json:"compress"`
  36. }
  37. type handshakeOp struct {
  38. Op int `json:"op"`
  39. Data handshakeData `json:"d"`
  40. }
  41. type ResumePacket struct {
  42. Op int `json:"op"`
  43. Data struct {
  44. Token string `json:"token"`
  45. SessionID string `json:"session_id"`
  46. Sequence int `json:"seq"`
  47. } `json:"d"`
  48. }
  49. // Open opens a websocket connection to Discord.
  50. func (s *Session) Open() (err error) {
  51. s.log(LogInformational, "called")
  52. s.Lock()
  53. defer func() {
  54. if err != nil {
  55. s.Unlock()
  56. }
  57. }()
  58. if s.wsConn != nil {
  59. err = errors.New("Web socket already opened.")
  60. return
  61. }
  62. if s.VoiceConnections == nil {
  63. s.log(LogInformational, "creating new VoiceConnections map")
  64. s.VoiceConnections = make(map[string]*VoiceConnection)
  65. }
  66. // Get the gateway to use for the Websocket connection
  67. if s.gateway == "" {
  68. s.gateway, err = s.Gateway()
  69. if err != nil {
  70. return
  71. }
  72. // Add the version and encoding to the URL
  73. s.gateway = fmt.Sprintf("%s?v=%v&encoding=json", s.gateway, GATEWAY_VERSION)
  74. }
  75. header := http.Header{}
  76. header.Add("accept-encoding", "zlib")
  77. s.log(LogInformational, "connecting to gateway %s", s.gateway)
  78. s.wsConn, _, err = websocket.DefaultDialer.Dial(s.gateway, header)
  79. if err != nil {
  80. s.log(LogWarning, "error connecting to gateway %s, %s", s.gateway, err)
  81. s.gateway = "" // clear cached gateway
  82. // TODO: should we add a retry block here?
  83. return
  84. }
  85. if s.sessionID != "" && s.sequence > 0 {
  86. p := ResumePacket{}
  87. p.Op = 6
  88. p.Data.Token = s.Token
  89. p.Data.SessionID = s.sessionID
  90. p.Data.Sequence = s.sequence
  91. s.log(LogInformational, "sending resume packet to gateway")
  92. err = s.wsConn.WriteJSON(p)
  93. if err != nil {
  94. s.log(LogWarning, "error sending gateway resume packet, %s, %s", s.gateway, err)
  95. return
  96. }
  97. } else {
  98. data := handshakeOp{
  99. 2,
  100. handshakeData{
  101. s.Token,
  102. handshakeProperties{
  103. runtime.GOOS,
  104. "Discordgo v" + VERSION,
  105. "",
  106. "",
  107. "",
  108. },
  109. 250,
  110. s.Compress,
  111. },
  112. }
  113. s.log(LogInformational, "sending identify packet to gateway")
  114. err = s.wsConn.WriteJSON(data)
  115. if err != nil {
  116. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  117. return
  118. }
  119. }
  120. // Create listening outside of listen, as it needs to happen inside the mutex
  121. // lock.
  122. s.listening = make(chan interface{})
  123. go s.listen(s.wsConn, s.listening)
  124. s.Unlock()
  125. s.initialize()
  126. s.handle(&Connect{})
  127. return
  128. }
  129. // Close closes a websocket and stops all listening/heartbeat goroutines.
  130. // TODO: Add support for Voice WS/UDP connections
  131. func (s *Session) Close() (err error) {
  132. s.log(LogInformational, "called")
  133. s.Lock()
  134. s.DataReady = false
  135. if s.listening != nil {
  136. s.log(LogInformational, "closing listening channel")
  137. close(s.listening)
  138. s.listening = nil
  139. }
  140. if s.wsConn != nil {
  141. s.log(LogInformational, "closing gateway websocket")
  142. err = s.wsConn.Close()
  143. s.wsConn = nil
  144. }
  145. s.Unlock()
  146. s.handle(&Disconnect{})
  147. return
  148. }
  149. // listen polls the websocket connection for events, it will stop when the
  150. // listening channel is closed, or an error occurs.
  151. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  152. s.log(LogInformational, "called")
  153. for {
  154. messageType, message, err := wsConn.ReadMessage()
  155. if err != nil {
  156. // Detect if we have been closed manually. If a Close() has already
  157. // happened, the websocket we are listening on will be different to
  158. // the current session.
  159. s.RLock()
  160. sameConnection := s.wsConn == wsConn
  161. s.RUnlock()
  162. if sameConnection {
  163. neterr, ok := err.(net.Error)
  164. if ok {
  165. if neterr.Timeout() {
  166. v.log(LogDebug, "neterr udp timeout error")
  167. }
  168. if neterr.Temporary() {
  169. v.log(LogDebug, "neterr udp tempoary error")
  170. }
  171. v.log(LogDebug, "neterr udp error %s", neterr.Error())
  172. }
  173. s.log(LogWarning, "error reading from gateway %s websocket, %s", s.gateway, err)
  174. // There has been an error reading, close the websocket so that
  175. // OnDisconnect event is emitted.
  176. err := s.Close()
  177. if err != nil {
  178. s.log(LogWarning, "error closing session connection, %s", err)
  179. }
  180. // Attempt to reconnect, with expenonential backoff up to
  181. // 10 minutes.
  182. if s.ShouldReconnectOnError {
  183. wait := time.Duration(1)
  184. for {
  185. s.log(LogInformational, "trying to reconnect to gateway")
  186. if s.Open() == nil {
  187. s.log(LogInformational, "successfully reconnected to gateway")
  188. return
  189. }
  190. <-time.After(wait * time.Second)
  191. wait *= 2
  192. if wait > 600 {
  193. wait = 600
  194. }
  195. }
  196. }
  197. }
  198. return
  199. }
  200. select {
  201. case <-listening:
  202. return
  203. default:
  204. go s.onEvent(messageType, message)
  205. }
  206. }
  207. }
  208. type heartbeatOp struct {
  209. Op int `json:"op"`
  210. Data int `json:"d"`
  211. }
  212. // heartbeat sends regular heartbeats to Discord so it knows the client
  213. // is still connected. If you do not send these heartbeats Discord will
  214. // disconnect the websocket connection after a few seconds.
  215. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  216. s.log(LogInformational, "called")
  217. if listening == nil || wsConn == nil {
  218. return
  219. }
  220. s.Lock()
  221. s.DataReady = true
  222. s.Unlock()
  223. var err error
  224. ticker := time.NewTicker(i * time.Millisecond)
  225. for {
  226. s.log(LogDebug, "sending gateway websocket heartbeat seq %d", s.sequence)
  227. s.wsMutex.Lock()
  228. err = wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  229. s.wsMutex.Unlock()
  230. if err != nil {
  231. log.Println("Error sending heartbeat:", err)
  232. return
  233. }
  234. select {
  235. case <-ticker.C:
  236. // continue loop and send heartbeat
  237. case <-listening:
  238. return
  239. }
  240. }
  241. }
  242. type updateStatusGame struct {
  243. Name string `json:"name"`
  244. }
  245. type updateStatusData struct {
  246. IdleSince *int `json:"idle_since"`
  247. Game *updateStatusGame `json:"game"`
  248. }
  249. type updateStatusOp struct {
  250. Op int `json:"op"`
  251. Data updateStatusData `json:"d"`
  252. }
  253. // UpdateStatus is used to update the authenticated user's status.
  254. // If idle>0 then set status to idle. If game>0 then set game.
  255. // if otherwise, set status to active, and no game.
  256. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  257. s.log(LogInformational, "called")
  258. s.RLock()
  259. defer s.RUnlock()
  260. if s.wsConn == nil {
  261. return errors.New("no websocket connection exists")
  262. }
  263. var usd updateStatusData
  264. if idle > 0 {
  265. usd.IdleSince = &idle
  266. }
  267. if game != "" {
  268. usd.Game = &updateStatusGame{game}
  269. }
  270. s.wsMutex.Lock()
  271. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  272. s.wsMutex.Unlock()
  273. return
  274. }
  275. // onEvent is the "event handler" for all messages received on the
  276. // Discord Gateway API websocket connection.
  277. //
  278. // If you use the AddHandler() function to register a handler for a
  279. // specific event this function will pass the event along to that handler.
  280. //
  281. // If you use the AddHandler() function to register a handler for the
  282. // "OnEvent" event then all events will be passed to that handler.
  283. //
  284. // TODO: You may also register a custom event handler entirely using...
  285. func (s *Session) onEvent(messageType int, message []byte) {
  286. var err error
  287. var reader io.Reader
  288. reader = bytes.NewBuffer(message)
  289. // If this is a compressed message, uncompress it.
  290. if messageType == 2 {
  291. z, err := zlib.NewReader(reader)
  292. if err != nil {
  293. s.log(LogError, "error uncompressing websocket message, %s", err)
  294. return
  295. }
  296. defer func() {
  297. err := z.Close()
  298. if err != nil {
  299. s.log(LogWarning, "error closing zlib, %s", err)
  300. }
  301. }()
  302. reader = z
  303. }
  304. // Decode the event into an Event struct.
  305. var e *Event
  306. decoder := json.NewDecoder(reader)
  307. if err = decoder.Decode(&e); err != nil {
  308. s.log(LogError, "error decoding websocket message, %s", err)
  309. return
  310. }
  311. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  312. // Ping request.
  313. // Must respond with a heartbeat packet within 5 seconds
  314. if e.Operation == 1 {
  315. s.log(LogInformational, "sending heartbeat in response to Op1")
  316. s.wsMutex.Lock()
  317. err = s.wsConn.WriteJSON(heartbeatOp{1, s.sequence})
  318. s.wsMutex.Unlock()
  319. if err != nil {
  320. s.log(LogError, "error sending heartbeat in response to Op1")
  321. return
  322. }
  323. return
  324. }
  325. // Reconnect
  326. // Must immediately disconnect from gateway and reconnect to new gateway.
  327. if e.Operation == 7 {
  328. // TODO
  329. }
  330. // Invalid Session
  331. // Must respond with a Identify packet.
  332. if e.Operation == 9 {
  333. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  334. s.wsMutex.Lock()
  335. err = s.wsConn.WriteJSON(handshakeOp{2, handshakeData{s.Token, handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""}, 250, s.Compress}})
  336. s.wsMutex.Unlock()
  337. if err != nil {
  338. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  339. return
  340. }
  341. return
  342. }
  343. // Do not try to Dispatch a non-Dispatch Message
  344. if e.Operation != 0 {
  345. // But we probably should be doing something with them.
  346. // TEMP
  347. 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))
  348. return
  349. }
  350. // Store the message sequence
  351. s.sequence = e.Sequence
  352. // Map event to registered event handlers and pass it along
  353. // to any registered functions
  354. i := eventToInterface[e.Type]
  355. if i != nil {
  356. // Create a new instance of the event type.
  357. i = reflect.New(reflect.TypeOf(i)).Interface()
  358. // Attempt to unmarshal our event.
  359. if err = json.Unmarshal(e.RawData, i); err != nil {
  360. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  361. }
  362. // Send event to any registered event handlers for it's type.
  363. // Because the above doesn't cancel this, in case of an error
  364. // the struct could be partially populated or at default values.
  365. // However, most errors are due to a single field and I feel
  366. // it's better to pass along what we received than nothing at all.
  367. // TODO: Think about that decision :)
  368. // Either way, READY events must fire, even with errors.
  369. s.handle(i)
  370. } else {
  371. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  372. }
  373. // Emit event to the OnEvent handler
  374. e.Struct = i
  375. s.handle(e)
  376. }
  377. // ------------------------------------------------------------------------------------------------
  378. // Code related to voice connections that initiate over the data websocket
  379. // ------------------------------------------------------------------------------------------------
  380. // A VoiceServerUpdate stores the data received during the Voice Server Update
  381. // data websocket event. This data is used during the initial Voice Channel
  382. // join handshaking.
  383. type VoiceServerUpdate struct {
  384. Token string `json:"token"`
  385. GuildID string `json:"guild_id"`
  386. Endpoint string `json:"endpoint"`
  387. }
  388. type voiceChannelJoinData struct {
  389. GuildID *string `json:"guild_id"`
  390. ChannelID *string `json:"channel_id"`
  391. SelfMute bool `json:"self_mute"`
  392. SelfDeaf bool `json:"self_deaf"`
  393. }
  394. type voiceChannelJoinOp struct {
  395. Op int `json:"op"`
  396. Data voiceChannelJoinData `json:"d"`
  397. }
  398. // ChannelVoiceJoin joins the session user to a voice channel.
  399. //
  400. // gID : Guild ID of the channel to join.
  401. // cID : Channel ID of the channel to join.
  402. // mute : If true, you will be set to muted upon joining.
  403. // deaf : If true, you will be set to deafened upon joining.
  404. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  405. // If a voice connection already exists for this guild then
  406. // return that connection. If the channel differs, also change channels.
  407. var ok bool
  408. if voice, ok = s.VoiceConnections[gID]; ok && voice.GuildID != "" {
  409. //TODO: consider a better variable than GuildID in the above check
  410. // to verify if this connection is valid or not.
  411. if voice.ChannelID != cID {
  412. err = voice.ChangeChannel(cID, mute, deaf)
  413. }
  414. return
  415. }
  416. // Create a new voice session
  417. // TODO review what all these things are for....
  418. voice = &VoiceConnection{
  419. GuildID: gID,
  420. ChannelID: cID,
  421. deaf: deaf,
  422. mute: mute,
  423. session: s,
  424. }
  425. // Store voice in VoiceConnections map for this GuildID
  426. s.VoiceConnections[gID] = voice
  427. // Send the request to Discord that we want to join the voice channel
  428. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  429. s.wsMutex.Lock()
  430. err = s.wsConn.WriteJSON(data)
  431. s.wsMutex.Unlock()
  432. if err != nil {
  433. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  434. delete(s.VoiceConnections, gID)
  435. return
  436. }
  437. // doesn't exactly work perfect yet.. TODO
  438. err = voice.waitUntilConnected()
  439. if err != nil {
  440. voice.Close()
  441. s.log(LogInformational, "Deleting VoiceConnection %s", gID)
  442. delete(s.VoiceConnections, gID)
  443. return
  444. }
  445. return
  446. }
  447. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  448. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  449. // If we don't have a connection for the channel, don't bother
  450. if st.ChannelID == "" {
  451. return
  452. }
  453. // Check if we have a voice connection to update
  454. voice, exists := s.VoiceConnections[st.GuildID]
  455. if !exists {
  456. return
  457. }
  458. // Need to have this happen at login and store it in the Session
  459. // TODO : This should be done upon connecting to Discord, or
  460. // be moved to a small helper function
  461. self, err := s.User("@me") // TODO: move to Login/New
  462. if err != nil {
  463. log.Println(err)
  464. return
  465. }
  466. // We only care about events that are about us
  467. if st.UserID != self.ID {
  468. return
  469. }
  470. // Store the SessionID for later use.
  471. voice.UserID = self.ID // TODO: Review
  472. voice.sessionID = st.SessionID
  473. }
  474. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  475. //
  476. // This is also fired if the Guild's voice region changes while connected
  477. // to a voice channel. In that case, need to re-establish connection to
  478. // the new region endpoint.
  479. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  480. voice, exists := s.VoiceConnections[st.GuildID]
  481. // If no VoiceConnection exists, just skip this
  482. if !exists {
  483. return
  484. }
  485. // If currently connected to voice ws/udp, then disconnect.
  486. // Has no effect if not connected.
  487. voice.Close()
  488. // Store values for later use
  489. voice.token = st.Token
  490. voice.endpoint = st.Endpoint
  491. voice.GuildID = st.GuildID
  492. // Open a conenction to the voice server
  493. err := voice.open()
  494. if err != nil {
  495. s.log(LogError, "onVoiceServerUpdate voice.open, ", err)
  496. }
  497. }