This repository has been archived by the owner on May 3, 2018. It is now read-only.
/
rest.go
242 lines (205 loc) · 7.88 KB
/
rest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package disgo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"unicode/utf8"
"mime/multipart"
"github.com/slf4go/logger"
)
type EndPoint struct {
Url string
bucket string
resetTime int
}
var (
BaseUrl = "https://discordapp.com/api/v" + gatewayVersion
EndPointGateway = makeEndPoint("/gateway")
EndPointBotGateway = makeEndPoint("/gateway/bot")
EndPointVoiceRegions = makeEndPoint("/voice/regions")
EndPointChannel = makeEndPoint("/channels/:channel_id")
EndPointMessages = makeEndPoint("/channels/:channel_id/messages")
EndPointMessage = makeEndPoint("/channels/:channel_id/messages/:message_id")
EndPointMessageBulkDelete = makeEndPoint("/channels/:channel_id/messages/bulk-delete")
EndPointReactions = makeEndPoint("/channels/:channel_id/messages/:mesasge_id/reactions")
EndPointReaction = makeEndPoint("/channels/:channel_id/messages/:mesasge_id/reactions/%%s/:user_id")
EndPointOwnReaction = makeEndPoint("/channels/:channel_id/messages/:message_id/reactions/%%s/@me")
EndPointChannelPermissions = makeEndPoint("/channels/:channel_id/permissions/:overwrite_id")
EndPointChannelInvites = makeEndPoint("/channels/:channel_id/invites")
EndPointChannelTyping = makeEndPoint("/channels/:channel_id/typing")
EndPointChannelPins = makeEndPoint("/channels/:channel_id/pins")
EndPointChannelPin = makeEndPoint("/channels/:channel_id/pins/:message_id")
EndPointChannelRecipient = makeEndPoint("/channels/:channel_id/recipients/:user_id")
EndPointGuilds = makeEndPoint("/guilds")
EndPointGuild = makeEndPoint("/guilds/:guild_id")
EndPointGuildChannels = makeEndPoint("/guilds/:guild_id/channels")
EndPointGuildMembers = makeEndPoint("/guilds/:guild_id/members")
EndPointGuildMember = makeEndPoint("/guilds/:guild_id/members/:user_id")
EndPointGuildOwnNick = makeEndPoint("/guilds/:guild_id/members/@me/nick")
EndPointGuildMemberRoles = makeEndPoint("/guilds/:guild_id/members/:user_id/roles/:role_id")
EndPointGuildBans = makeEndPoint("/guilds/:guild_id/bans")
EndPointGuildMemberBan = makeEndPoint("/guilds/:guild_id/bans/:user_id")
EndPointGuildRoles = makeEndPoint("/guilds/:guild_id/roles")
EndPointGuildRole = makeEndPoint("/guilds/:guild_id/roles/:role_id")
EndPointGuildPrune = makeEndPoint("/guilds/:guild_id/prune")
EndPointGuildRegions = makeEndPoint("/guilds/:guild_id/regions")
EndPointGuildInvites = makeEndPoint("/guilds/:guild_id/invites")
EndPointGuildIntegrations = makeEndPoint("/guilds/:guild_id/integrations")
EndPointGuildIntegration = makeEndPoint("/guilds/:guild_id/integrations/:integration_id")
EndPointGuildIntegrationSync = makeEndPoint("/guilds/:guild_id/integrations/:integration_id/sync")
EndPointGuildEmbed = makeEndPoint("/guilds/:guild_id/embed")
EndPointOwnUser = makeEndPoint("/users/@me")
EndPointUser = makeEndPoint("/users/:user_id")
EndPointUserAvatar = BaseUrl + "/users/%d/avatars/%s.jpg"
EndPointOwnGuilds = makeEndPoint("/users/@me/guilds")
EndPointOwnGuild = makeEndPoint("/users/@me/guilds/:guild_id")
EndPointDMChannels = makeEndPoint("/users/@me/channels")
)
func makeEndPoint(path string) func(ids ...Snowflake) EndPoint {
parts := strings.Split(path, "/")
capacity := strings.Count(path, ":")
snowflakes := make([]Snowflake, 0, capacity)
endPoint := BaseUrl
endPointIDs := make([]interface{}, 0, capacity)
bucketID := ""
bucketIDs := make([]interface{}, 0, capacity)
for _, part := range parts {
if utf8.RuneCountInString(part) != 0 {
// For every variable in the path
if part[:1] == ":" {
snowflakes = append(snowflakes, Snowflake(42))
// Add a format
endPoint += "/%s"
endPointIDs = append(endPointIDs, &snowflakes[len(snowflakes)-1])
// If we're dealing with one of the "major" IDs, we can consider this part of the bucket
switch part[1:] {
case "guild_id":
fallthrough
case "channel_id":
bucketID += "/%s"
bucketIDs = append(bucketIDs, &snowflakes[len(snowflakes)-1])
default:
// Otherwise, generalize it with a simple zero, an ID that *should* never occur
bucketID += "/0"
}
} else if part == "@me" {
endPoint += "/" + part
bucketID += "/0"
} else {
// And well, if we're not dealing with a variable, just append it
extension := "/" + part
endPoint += extension
bucketID += extension
}
}
}
// The idea is that any part of the library can create an EndPoint with their snowflakes
return func(ids ...Snowflake) EndPoint {
for i, snowflake := range ids {
snowflakes[i] = snowflake
}
// But only the rest api functions themselves should decide whether they need the bucket ID or the Url
return EndPoint{fmt.Sprintf(endPoint, endPointIDs...), fmt.Sprintf(bucketID, bucketIDs...), -1}
}
}
func (s *Session) doHttpGet(endPoint EndPoint, target interface{}) (err error) {
err = s.rateLimit(endPoint, func() (*http.Response, error) {
return s.doRequest("GET", endPoint.Url, "", nil, target)
})
return
}
func (s *Session) doHttpDelete(endPoint EndPoint, target interface{}) (err error) {
err = s.rateLimit(endPoint, func() (*http.Response, error) {
return s.doRequest("DELETE", endPoint.Url, "", nil, target)
})
return
}
func (s *Session) doHttpPut(endPoint EndPoint, target interface{}) (err error) {
err = s.rateLimit(endPoint, func() (*http.Response, error) {
return s.doRequest("PUT", endPoint.Url, "", nil, target)
})
return
}
func (s *Session) doHttpPost(endPoint EndPoint, body, target interface{}) (err error) {
jsonBody, err := json.Marshal(body)
if err == nil {
byteBuf := bytes.NewReader(jsonBody)
err = s.rateLimit(endPoint, func() (*http.Response, error) {
return s.doRequest("POST", endPoint.Url, "application/json", byteBuf, target)
})
}
return
}
func (s *Session) doHttMultipartPost(endPoint EndPoint, bodyWriter func(writer *multipart.Writer) error, target interface{}) (err error) {
var buffer bytes.Buffer
mpW := multipart.NewWriter(&buffer)
err = bodyWriter(mpW)
if err != nil {
return
}
mpW.Close()
err = s.rateLimit(endPoint, func() (*http.Response, error) {
return s.doRequest("POST", endPoint.Url, mpW.FormDataContentType(), &buffer, target)
})
return
}
func (s *Session) doHttpPatch(endPoint EndPoint, body, target interface{}) (err error) {
jsonBody, err := json.Marshal(body)
if err == nil {
byteBuf := bytes.NewReader(jsonBody)
err = s.rateLimit(endPoint, func() (*http.Response, error) {
return s.doRequest("PATCH", endPoint.Url, "application/json", byteBuf, target)
})
}
return
}
func (s *Session) doRequest(method, url string, contentType string, body io.Reader, target interface{}) (response *http.Response, err error) {
logger.Debugf("HTTP %s %s", method, strings.Replace(url, BaseUrl, "", 1))
var (
req *http.Request
client = http.Client{
Timeout: 10 * time.Second,
}
)
if req, err = http.NewRequest(method, url, body); err != nil {
return
}
if contentType != "" {
req.Header.Add("Content-Type", contentType)
}
req.Header.Add("Authorization", s.tokenType+s.token)
req.Header.Add("User-Agent", "DiscordBot (https://github.com/ikkerens/disgo, 1.0.0)")
if response, err = client.Do(req); err != nil {
logger.ErrorE(err)
return
}
defer response.Body.Close()
switch response.StatusCode {
case http.StatusOK:
fallthrough
case http.StatusCreated:
if target != nil {
body := response.Body
if err = json.NewDecoder(body).Decode(target); err != nil {
return
}
}
case http.StatusNoContent:
fallthrough
case http.StatusNotModified:
return
default:
var bodyBuf []byte
bodyBuf, err = ioutil.ReadAll(response.Body)
if err != nil {
return
}
return response, fmt.Errorf("Discord replied with status code %d: %s", response.StatusCode, string(bodyBuf))
}
return
}