wsapi.go 12 KB

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