wsapi.go 15 KB

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