wsapi.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. "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. }
  36. type handshakeOp struct {
  37. Op int `json:"op"`
  38. Data handshakeData `json:"d"`
  39. }
  40. // Open opens a websocket connection to Discord.
  41. func (s *Session) Open() (err error) {
  42. s.Lock()
  43. defer func() {
  44. if err != nil {
  45. s.Unlock()
  46. }
  47. }()
  48. if s.wsConn != nil {
  49. err = errors.New("Web socket already opened.")
  50. return
  51. }
  52. // Get the gateway to use for the Websocket connection
  53. g, err := s.Gateway()
  54. if err != nil {
  55. return
  56. }
  57. header := http.Header{}
  58. header.Add("accept-encoding", "zlib")
  59. // TODO: See if there's a use for the http response.
  60. // conn, response, err := websocket.DefaultDialer.Dial(session.Gateway, nil)
  61. s.wsConn, _, err = websocket.DefaultDialer.Dial(g, header)
  62. if err != nil {
  63. return
  64. }
  65. err = s.wsConn.WriteJSON(handshakeOp{2, handshakeData{3, s.Token, handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""}, 250, s.Compress}})
  66. if err != nil {
  67. return
  68. }
  69. // Create listening outside of listen, as it needs to happen inside the mutex
  70. // lock.
  71. s.listening = make(chan interface{})
  72. go s.listen(s.wsConn, s.listening)
  73. s.Unlock()
  74. s.handle(&Connect{})
  75. return
  76. }
  77. // Close closes a websocket and stops all listening/heartbeat goroutines.
  78. // TODO: Add support for Voice WS/UDP connections
  79. func (s *Session) Close() (err error) {
  80. s.Lock()
  81. s.DataReady = false
  82. if s.listening != nil {
  83. close(s.listening)
  84. s.listening = nil
  85. }
  86. if s.wsConn != nil {
  87. err = s.wsConn.Close()
  88. s.wsConn = nil
  89. }
  90. s.Unlock()
  91. s.handle(&Disconnect{})
  92. return
  93. }
  94. // listen polls the websocket connection for events, it will stop when
  95. // the listening channel is closed, or an error occurs.
  96. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  97. for {
  98. messageType, message, err := wsConn.ReadMessage()
  99. if err != nil {
  100. // Detect if we have been closed manually. If a Close() has already
  101. // happened, the websocket we are listening on will be different to the
  102. // current session.
  103. s.RLock()
  104. sameConnection := s.wsConn == wsConn
  105. s.RUnlock()
  106. if sameConnection {
  107. // There has been an error reading, Close() the websocket so that
  108. // OnDisconnect is fired.
  109. err := s.Close()
  110. if err != nil {
  111. fmt.Println("error closing session connection: ", err)
  112. }
  113. // Attempt to reconnect, with expenonential backoff up to 10 minutes.
  114. if s.ShouldReconnectOnError {
  115. wait := time.Duration(1)
  116. for {
  117. if s.Open() == nil {
  118. return
  119. }
  120. <-time.After(wait * time.Second)
  121. wait *= 2
  122. if wait > 600 {
  123. wait = 600
  124. }
  125. }
  126. }
  127. }
  128. return
  129. }
  130. select {
  131. case <-listening:
  132. return
  133. default:
  134. go s.event(messageType, message)
  135. }
  136. }
  137. }
  138. type heartbeatOp struct {
  139. Op int `json:"op"`
  140. Data int `json:"d"`
  141. }
  142. func (s *Session) sendHeartbeat(wsConn *websocket.Conn) error {
  143. return wsConn.WriteJSON(heartbeatOp{1, int(time.Now().Unix())})
  144. }
  145. // heartbeat sends regular heartbeats to Discord so it knows the client
  146. // is still connected. If you do not send these heartbeats Discord will
  147. // disconnect the websocket connection after a few seconds.
  148. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
  149. if listening == nil || wsConn == nil {
  150. return
  151. }
  152. s.Lock()
  153. s.DataReady = true
  154. s.Unlock()
  155. // Send first heartbeat immediately because lag could put the
  156. // first heartbeat outside the required heartbeat interval window.
  157. err := s.sendHeartbeat(wsConn)
  158. if err != nil {
  159. fmt.Println("Error sending initial heartbeat:", err)
  160. return
  161. }
  162. ticker := time.NewTicker(i * time.Millisecond)
  163. for {
  164. select {
  165. case <-ticker.C:
  166. err := s.sendHeartbeat(wsConn)
  167. if err != nil {
  168. fmt.Println("Error sending heartbeat:", err)
  169. return
  170. }
  171. case <-listening:
  172. return
  173. }
  174. }
  175. }
  176. type updateStatusGame struct {
  177. Name string `json:"name"`
  178. }
  179. type updateStatusData struct {
  180. IdleSince *int `json:"idle_since"`
  181. Game *updateStatusGame `json:"game"`
  182. }
  183. type updateStatusOp struct {
  184. Op int `json:"op"`
  185. Data updateStatusData `json:"d"`
  186. }
  187. // UpdateStatus is used to update the authenticated user's status.
  188. // If idle>0 then set status to idle. If game>0 then set game.
  189. // if otherwise, set status to active, and no game.
  190. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  191. s.RLock()
  192. defer s.RUnlock()
  193. if s.wsConn == nil {
  194. return errors.New("No websocket connection exists.")
  195. }
  196. var usd updateStatusData
  197. if idle > 0 {
  198. usd.IdleSince = &idle
  199. }
  200. if game != "" {
  201. usd.Game = &updateStatusGame{game}
  202. }
  203. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  204. return
  205. }
  206. // eventToInterface is a mapping of Discord WSAPI events to their
  207. // DiscordGo event container.
  208. var eventToInterface = map[string]interface{}{
  209. "CHANNEL_CREATE": ChannelCreate{},
  210. "CHANNEL_UPDATE": ChannelUpdate{},
  211. "CHANNEL_DELETE": ChannelDelete{},
  212. "GUILD_CREATE": GuildCreate{},
  213. "GUILD_UPDATE": GuildUpdate{},
  214. "GUILD_DELETE": GuildDelete{},
  215. "GUILD_BAN_ADD": GuildBanAdd{},
  216. "GUILD_BAN_REMOVE": GuildBanRemove{},
  217. "GUILD_MEMBER_ADD": GuildMemberAdd{},
  218. "GUILD_MEMBER_UPDATE": GuildMemberUpdate{},
  219. "GUILD_MEMBER_REMOVE": GuildMemberRemove{},
  220. "GUILD_ROLE_CREATE": GuildRoleCreate{},
  221. "GUILD_ROLE_UPDATE": GuildRoleUpdate{},
  222. "GUILD_ROLE_DELETE": GuildRoleDelete{},
  223. "GUILD_INTEGRATIONS_UPDATE": GuildIntegrationsUpdate{},
  224. "GUILD_EMOJIS_UPDATE": GuildEmojisUpdate{},
  225. "MESSAGE_ACK": MessageAck{},
  226. "MESSAGE_CREATE": MessageCreate{},
  227. "MESSAGE_UPDATE": MessageUpdate{},
  228. "MESSAGE_DELETE": MessageDelete{},
  229. "PRESENCE_UPDATE": PresenceUpdate{},
  230. "READY": Ready{},
  231. "USER_UPDATE": UserUpdate{},
  232. "USER_SETTINGS_UPDATE": UserSettingsUpdate{},
  233. "TYPING_START": TypingStart{},
  234. "VOICE_SERVER_UPDATE": VoiceServerUpdate{},
  235. "VOICE_STATE_UPDATE": VoiceStateUpdate{},
  236. }
  237. // Front line handler for all Websocket Events. Determines the
  238. // event type and passes the message along to the next handler.
  239. // event is the front line handler for all events. This needs to be
  240. // broken up into smaller functions to be more idiomatic Go.
  241. // Events will be handled by any implemented handler in Session.
  242. // All unhandled events will then be handled by OnEvent.
  243. func (s *Session) event(messageType int, message []byte) {
  244. var err error
  245. var reader io.Reader
  246. reader = bytes.NewBuffer(message)
  247. if messageType == 2 {
  248. z, err1 := zlib.NewReader(reader)
  249. if err1 != nil {
  250. fmt.Println(err1)
  251. return
  252. }
  253. defer func() {
  254. err := z.Close()
  255. if err != nil {
  256. fmt.Println("error closing zlib:", err)
  257. }
  258. }()
  259. reader = z
  260. }
  261. var e *Event
  262. decoder := json.NewDecoder(reader)
  263. if err = decoder.Decode(&e); err != nil {
  264. fmt.Println(err)
  265. return
  266. }
  267. if s.Debug {
  268. printEvent(e)
  269. }
  270. i := eventToInterface[e.Type]
  271. if i != nil {
  272. // Create a new instance of the event type.
  273. i = reflect.New(reflect.TypeOf(i)).Interface()
  274. // Attempt to unmarshal our event.
  275. // If there is an error we should handle the event itself.
  276. if err = unmarshal(e.RawData, i); err != nil {
  277. fmt.Println("Unable to unmarshal event data.")
  278. i = e
  279. }
  280. } else {
  281. fmt.Println("Unknown event.")
  282. i = e
  283. }
  284. s.handle(i)
  285. return
  286. }
  287. // ------------------------------------------------------------------------------------------------
  288. // Code related to voice connections that initiate over the data websocket
  289. // ------------------------------------------------------------------------------------------------
  290. // A VoiceServerUpdate stores the data received during the Voice Server Update
  291. // data websocket event. This data is used during the initial Voice Channel
  292. // join handshaking.
  293. type VoiceServerUpdate struct {
  294. Token string `json:"token"`
  295. GuildID string `json:"guild_id"`
  296. Endpoint string `json:"endpoint"`
  297. }
  298. type voiceChannelJoinData struct {
  299. GuildID *string `json:"guild_id"`
  300. ChannelID *string `json:"channel_id"`
  301. SelfMute bool `json:"self_mute"`
  302. SelfDeaf bool `json:"self_deaf"`
  303. }
  304. type voiceChannelJoinOp struct {
  305. Op int `json:"op"`
  306. Data voiceChannelJoinData `json:"d"`
  307. }
  308. // ChannelVoiceJoin joins the session user to a voice channel. After calling
  309. // this func please monitor the Session.Voice.Ready bool to determine when
  310. // it is ready and able to send/receive audio, that should happen quickly.
  311. //
  312. // gID : Guild ID of the channel to join.
  313. // cID : Channel ID of the channel to join.
  314. // mute : If true, you will be set to muted upon joining.
  315. // deaf : If true, you will be set to deafened upon joining.
  316. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (err error) {
  317. // Create new voice{} struct if one does not exist.
  318. // If you create this prior to calling this func then you can manually
  319. // set some variables if needed, such as to enable debugging.
  320. if s.Voice == nil {
  321. s.Voice = &Voice{}
  322. }
  323. // Send the request to Discord that we want to join the voice channel
  324. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  325. err = s.wsConn.WriteJSON(data)
  326. if err != nil {
  327. return
  328. }
  329. // Store gID and cID for later use
  330. s.Voice.guildID = gID
  331. s.Voice.channelID = cID
  332. return
  333. }
  334. // ChannelVoiceLeave disconnects from the currently connected
  335. // voice channel.
  336. func (s *Session) ChannelVoiceLeave() (err error) {
  337. if s.Voice == nil {
  338. return
  339. }
  340. // Send the request to Discord that we want to leave voice
  341. data := voiceChannelJoinOp{4, voiceChannelJoinData{nil, nil, true, true}}
  342. err = s.wsConn.WriteJSON(data)
  343. if err != nil {
  344. return
  345. }
  346. // Close voice and nil data struct
  347. s.Voice.Close()
  348. s.Voice = nil
  349. return
  350. }
  351. // onVoiceStateUpdate handles Voice State Update events on the data
  352. // websocket. This comes immediately after the call to VoiceChannelJoin
  353. // for the session user.
  354. func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
  355. // Ignore if Voice is nil
  356. if s.Voice == nil {
  357. return
  358. }
  359. // Need to have this happen at login and store it in the Session
  360. // TODO : This should be done upon connecting to Discord, or
  361. // be moved to a small helper function
  362. self, err := s.User("@me") // TODO: move to Login/New
  363. if err != nil {
  364. fmt.Println(err)
  365. return
  366. }
  367. // This event comes for all users, if it's not for the session
  368. // user just ignore it.
  369. // TODO Move this IF to the event() func
  370. if st.UserID != self.ID {
  371. return
  372. }
  373. // Store the SessionID for later use.
  374. s.Voice.userID = self.ID // TODO: Review
  375. s.Voice.sessionID = st.SessionID
  376. }
  377. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  378. // This event tells us the information needed to open a voice websocket
  379. // connection and should happen after the VOICE_STATE event.
  380. //
  381. // This is also fired if the Guild's voice region changes while connected
  382. // to a voice channel. In that case, need to re-establish connection to
  383. // the new region endpoint.
  384. func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
  385. // Store values for later use
  386. s.Voice.token = st.Token
  387. s.Voice.endpoint = st.Endpoint
  388. s.Voice.guildID = st.GuildID
  389. // If currently connected to voice ws/udp, then disconnect.
  390. // Has no effect if not connected.
  391. s.Voice.Close()
  392. // We now have enough information to open a voice websocket conenction
  393. // so, that's what the next call does.
  394. err := s.Voice.Open()
  395. if err != nil {
  396. fmt.Println("onVoiceServerUpdate Voice.Open error: ", err)
  397. // TODO better logging
  398. }
  399. }