wsapi.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. "io"
  15. "log"
  16. "net/http"
  17. "reflect"
  18. "runtime"
  19. "time"
  20. "github.com/gorilla/websocket"
  21. )
  22. type handshakeProperties struct {
  23. OS string `json:"$os"`
  24. Browser string `json:"$browser"`
  25. Device string `json:"$device"`
  26. Referer string `json:"$referer"`
  27. ReferringDomain string `json:"$referring_domain"`
  28. }
  29. type handshakeData struct {
  30. Version int `json:"v"`
  31. Token string `json:"token"`
  32. Properties handshakeProperties `json:"properties"`
  33. LargeThreshold int `json:"large_threshold"`
  34. Compress bool `json:"compress"`
  35. Shard [2]int `json:"shard"`
  36. }
  37. type handshakeOp struct {
  38. Op int `json:"op"`
  39. Data handshakeData `json:"d"`
  40. }
  41. // Open opens a websocket connection to Discord.
  42. func (s *Session) Open() (err error) {
  43. s.Lock()
  44. defer func() {
  45. if err != nil {
  46. s.Unlock()
  47. }
  48. }()
  49. s.VoiceConnections = make(map[string]*VoiceConnection)
  50. if s.wsConn != nil {
  51. err = errors.New("Web socket already opened.")
  52. return
  53. }
  54. // Get the gateway to use for the Websocket connection
  55. g, err := s.Gateway()
  56. if err != nil {
  57. return
  58. }
  59. header := http.Header{}
  60. header.Add("accept-encoding", "zlib")
  61. // TODO: See if there's a use for the http response.
  62. // conn, response, err := websocket.DefaultDialer.Dial(session.Gateway, nil)
  63. s.wsConn, _, err = websocket.DefaultDialer.Dial(g, header)
  64. if err != nil {
  65. return
  66. }
  67. handshake := handshakeData{
  68. Version: 4,
  69. Token: s.Token,
  70. Properties: handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""},
  71. LargeThreshold: 250,
  72. Compress: s.Compress,
  73. }
  74. // If we've set NumShards, add the shard information to the handshake
  75. if s.NumShards > 0 {
  76. handshake.Shard = [2]int{s.ShardID, s.NumShards}
  77. }
  78. err = s.wsConn.WriteJSON(handshakeOp{2, handshake})
  79. if err != nil {
  80. return
  81. }
  82. // Create listening outside of listen, as it needs to happen inside the mutex
  83. // lock.
  84. s.listening = make(chan interface{})
  85. go s.listen(s.wsConn, s.listening)
  86. s.Unlock()
  87. s.initialize()
  88. s.handle(&Connect{})
  89. return
  90. }
  91. // Close closes a websocket and stops all listening/heartbeat goroutines.
  92. // TODO: Add support for Voice WS/UDP connections
  93. func (s *Session) Close() (err error) {
  94. s.Lock()
  95. s.DataReady = false
  96. if s.listening != nil {
  97. close(s.listening)
  98. s.listening = nil
  99. }
  100. if s.wsConn != nil {
  101. err = s.wsConn.Close()
  102. s.wsConn = nil
  103. }
  104. s.Unlock()
  105. s.handle(&Disconnect{})
  106. return
  107. }
  108. // listen polls the websocket connection for events, it will stop when
  109. // the listening channel is closed, or an error occurs.
  110. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  111. for {
  112. messageType, message, err := wsConn.ReadMessage()
  113. if err != nil {
  114. // Detect if we have been closed manually. If a Close() has already
  115. // happened, the websocket we are listening on will be different to the
  116. // current session.
  117. s.RLock()
  118. sameConnection := s.wsConn == wsConn
  119. s.RUnlock()
  120. if sameConnection {
  121. // There has been an error reading, Close() the websocket so that
  122. // OnDisconnect is fired.
  123. err := s.Close()
  124. if err != nil {
  125. log.Println("error closing session connection: ", err)
  126. }
  127. // Attempt to reconnect, with expenonential backoff up to 10 minutes.
  128. if s.ShouldReconnectOnError {
  129. wait := time.Duration(1)
  130. for {
  131. if s.Open() == nil {
  132. return
  133. }
  134. <-time.After(wait * time.Second)
  135. wait *= 2
  136. if wait > 600 {
  137. wait = 600
  138. }
  139. }
  140. }
  141. }
  142. return
  143. }
  144. select {
  145. case <-listening:
  146. return
  147. default:
  148. go s.event(messageType, message)
  149. }
  150. }
  151. }
  152. type heartbeatOp struct {
  153. Op int `json:"op"`
  154. Data int `json:"d"`
  155. }
  156. // heartbeat sends regular heartbeats to Discord so it knows the client
  157. // is still connected. If you do not send these heartbeats Discord will
  158. // disconnect the websocket connection after a few seconds.
  159. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  160. if listening == nil || wsConn == nil {
  161. return
  162. }
  163. s.Lock()
  164. s.DataReady = true
  165. s.Unlock()
  166. var err error
  167. ticker := time.NewTicker(i * time.Millisecond)
  168. for {
  169. err = wsConn.WriteJSON(heartbeatOp{1, int(time.Now().Unix())})
  170. if err != nil {
  171. log.Println("Error sending heartbeat:", err)
  172. return
  173. }
  174. select {
  175. case <-ticker.C:
  176. // continue loop and send heartbeat
  177. case <-listening:
  178. return
  179. }
  180. }
  181. }
  182. type updateStatusGame struct {
  183. Name string `json:"name"`
  184. }
  185. type updateStatusData struct {
  186. IdleSince *int `json:"idle_since"`
  187. Game *updateStatusGame `json:"game"`
  188. }
  189. type updateStatusOp struct {
  190. Op int `json:"op"`
  191. Data updateStatusData `json:"d"`
  192. }
  193. // UpdateStatus is used to update the authenticated user's status.
  194. // If idle>0 then set status to idle. If game>0 then set game.
  195. // if otherwise, set status to active, and no game.
  196. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  197. s.RLock()
  198. defer s.RUnlock()
  199. if s.wsConn == nil {
  200. return errors.New("No websocket connection exists.")
  201. }
  202. var usd updateStatusData
  203. if idle > 0 {
  204. usd.IdleSince = &idle
  205. }
  206. if game != "" {
  207. usd.Game = &updateStatusGame{game}
  208. }
  209. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  210. return
  211. }
  212. // Front line handler for all Websocket Events. Determines the
  213. // event type and passes the message along to the next handler.
  214. // event is the front line handler for all events. This needs to be
  215. // broken up into smaller functions to be more idiomatic Go.
  216. // Events will be handled by any implemented handler in Session.
  217. // All unhandled events will then be handled by OnEvent.
  218. func (s *Session) event(messageType int, message []byte) {
  219. var err error
  220. var reader io.Reader
  221. reader = bytes.NewBuffer(message)
  222. if messageType == 2 {
  223. z, err1 := zlib.NewReader(reader)
  224. if err1 != nil {
  225. log.Println(err1)
  226. return
  227. }
  228. defer func() {
  229. err := z.Close()
  230. if err != nil {
  231. log.Println("error closing zlib:", err)
  232. }
  233. }()
  234. reader = z
  235. }
  236. var e *Event
  237. decoder := json.NewDecoder(reader)
  238. if err = decoder.Decode(&e); err != nil {
  239. log.Println(err)
  240. return
  241. }
  242. if s.Debug {
  243. printEvent(e)
  244. }
  245. i := eventToInterface[e.Type]
  246. if i != nil {
  247. // Create a new instance of the event type.
  248. i = reflect.New(reflect.TypeOf(i)).Interface()
  249. // Attempt to unmarshal our event.
  250. // If there is an error we should handle the event itself.
  251. if err = unmarshal(e.RawData, i); err != nil {
  252. log.Println("Unable to unmarshal event data.", err)
  253. // Ready events must fire, even if they are empty.
  254. if e.Type != "READY" {
  255. i = nil
  256. }
  257. }
  258. } else {
  259. log.Println("Unknown event.")
  260. i = nil
  261. }
  262. if i != nil {
  263. s.handle(i)
  264. }
  265. e.Struct = i
  266. s.handle(e)
  267. return
  268. }
  269. // ------------------------------------------------------------------------------------------------
  270. // Code related to voice connections that initiate over the data websocket
  271. // ------------------------------------------------------------------------------------------------
  272. // A VoiceServerUpdate stores the data received during the Voice Server Update
  273. // data websocket event. This data is used during the initial Voice Channel
  274. // join handshaking.
  275. type VoiceServerUpdate struct {
  276. Token string `json:"token"`
  277. GuildID string `json:"guild_id"`
  278. Endpoint string `json:"endpoint"`
  279. }
  280. type voiceChannelJoinData struct {
  281. GuildID *string `json:"guild_id"`
  282. ChannelID *string `json:"channel_id"`
  283. SelfMute bool `json:"self_mute"`
  284. SelfDeaf bool `json:"self_deaf"`
  285. }
  286. type voiceChannelJoinOp struct {
  287. Op int `json:"op"`
  288. Data voiceChannelJoinData `json:"d"`
  289. }
  290. // ChannelVoiceJoin joins the session user to a voice channel.
  291. //
  292. // gID : Guild ID of the channel to join.
  293. // cID : Channel ID of the channel to join.
  294. // mute : If true, you will be set to muted upon joining.
  295. // deaf : If true, you will be set to deafened upon joining.
  296. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  297. // If a voice connection already exists for this guild then
  298. // return that connection. If the channel differs, also change channels.
  299. var ok bool
  300. if voice, ok = s.VoiceConnections[gID]; ok && voice.GuildID != "" {
  301. //TODO: consider a better variable than GuildID in the above check
  302. // to verify if this connection is valid or not.
  303. if voice.ChannelID != cID {
  304. err = voice.ChangeChannel(cID, mute, deaf)
  305. }
  306. return
  307. }
  308. // Create a new voice session
  309. // TODO review what all these things are for....
  310. voice = &VoiceConnection{
  311. GuildID: gID,
  312. ChannelID: cID,
  313. session: s,
  314. connected: make(chan bool),
  315. sessionRecv: make(chan string),
  316. }
  317. // Store voice in VoiceConnections map for this GuildID
  318. s.VoiceConnections[gID] = voice
  319. // Send the request to Discord that we want to join the voice channel
  320. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  321. err = s.wsConn.WriteJSON(data)
  322. if err != nil {
  323. delete(s.VoiceConnections, gID)
  324. return
  325. }
  326. // doesn't exactly work perfect yet.. TODO
  327. err = voice.waitUntilConnected()
  328. if err != nil {
  329. voice.Close()
  330. delete(s.VoiceConnections, gID)
  331. return
  332. }
  333. return
  334. }
  335. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  336. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  337. // If we don't have a connection for the channel, don't bother
  338. if st.ChannelID == "" {
  339. return
  340. }
  341. // Check if we have a voice connection to update
  342. voice, exists := s.VoiceConnections[st.GuildID]
  343. if !exists {
  344. return
  345. }
  346. // Need to have this happen at login and store it in the Session
  347. // TODO : This should be done upon connecting to Discord, or
  348. // be moved to a small helper function
  349. self, err := s.User("@me") // TODO: move to Login/New
  350. if err != nil {
  351. log.Println(err)
  352. return
  353. }
  354. // We only care about events that are about us
  355. if st.UserID != self.ID {
  356. return
  357. }
  358. // Store the SessionID for later use.
  359. voice.UserID = self.ID // TODO: Review
  360. voice.sessionID = st.SessionID
  361. // TODO: Consider this...
  362. // voice.sessionRecv <- st.SessionID
  363. }
  364. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  365. //
  366. // This is also fired if the Guild's voice region changes while connected
  367. // to a voice channel. In that case, need to re-establish connection to
  368. // the new region endpoint.
  369. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  370. voice, exists := s.VoiceConnections[st.GuildID]
  371. // If no VoiceConnection exists, just skip this
  372. if !exists {
  373. return
  374. }
  375. // Store values for later use
  376. voice.token = st.Token
  377. voice.endpoint = st.Endpoint
  378. voice.GuildID = st.GuildID
  379. // If currently connected to voice ws/udp, then disconnect.
  380. // Has no effect if not connected.
  381. // voice.Close()
  382. // Wait for the sessionID from onVoiceStateUpdate
  383. // voice.sessionID = <-voice.sessionRecv
  384. // TODO review above
  385. // wouldn't this cause a huge problem, if it's just a guild server
  386. // update.. ?
  387. // I could add a timeout loop of some sort and also check if the
  388. // sessionID doesn't or does exist already...
  389. // something.. a bit smarter.
  390. // We now have enough information to open a voice websocket conenction
  391. // so, that's what the next call does.
  392. err := voice.open()
  393. if err != nil {
  394. log.Println("onVoiceServerUpdate Voice.Open error: ", err)
  395. // TODO better logging
  396. }
  397. }