wsapi.go 15 KB

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