| 1 | package slack |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "io/ioutil" |
| 11 | "mime" |
| 12 | "mime/multipart" |
| 13 | "net/http" |
| 14 | "net/http/httputil" |
| 15 | "net/url" |
| 16 | "os" |
| 17 | "path/filepath" |
| 18 | "strconv" |
| 19 | "strings" |
| 20 | "time" |
| 21 | ) |
| 22 | |
| 23 | // SlackResponse handles parsing out errors from the web api. |
| 24 | type SlackResponse struct { |
| 25 | Ok bool `json:"ok"` |
| 26 | Error string `json:"error"` |
| 27 | ResponseMetadata ResponseMetadata `json:"response_metadata"` |
| 28 | } |
| 29 | |
| 30 | func (t SlackResponse) Err() error { |
| 31 | if t.Ok { |
| 32 | return nil |
| 33 | } |
| 34 | |
| 35 | // handle pure text based responses like chat.post |
| 36 | // which while they have a slack response in their data structure |
| 37 | // it doesn't actually get set during parsing. |
| 38 | if strings.TrimSpace(t.Error) == "" { |
| 39 | return nil |
| 40 | } |
| 41 | |
| 42 | return SlackErrorResponse{Err: t.Error, ResponseMetadata: t.ResponseMetadata} |
| 43 | } |
| 44 | |
| 45 | // SlackErrorResponse brings along the metadata of errors returned by the Slack API. |
| 46 | type SlackErrorResponse struct { |
| 47 | Err string |
| 48 | ResponseMetadata ResponseMetadata |
| 49 | } |
| 50 | |
| 51 | func (r SlackErrorResponse) Error() string { return r.Err } |
| 52 | |
| 53 | // RateLimitedError represents the rate limit response from slack |
| 54 | type RateLimitedError struct { |
| 55 | RetryAfter time.Duration |
| 56 | } |
| 57 | |
| 58 | func (e *RateLimitedError) Error() string { |
| 59 | return fmt.Sprintf("slack rate limit exceeded, retry after %s", e.RetryAfter) |
| 60 | } |
| 61 | |
| 62 | func (e *RateLimitedError) Retryable() bool { |
| 63 | return true |
| 64 | } |
| 65 | |
| 66 | func fileUploadReq(ctx context.Context, path string, values url.Values, r io.Reader) (*http.Request, error) { |
| 67 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, path, r) |
| 68 | if err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | |
| 72 | req.URL.RawQuery = values.Encode() |
| 73 | return req, nil |
| 74 | } |
| 75 | |
| 76 | func downloadFile(ctx context.Context, client httpClient, token string, downloadURL string, writer io.Writer, d Debug) error { |
| 77 | if downloadURL == "" { |
| 78 | return fmt.Errorf("received empty download URL") |
| 79 | } |
| 80 | |
| 81 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, &bytes.Buffer{}) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | |
| 86 | var bearer = "Bearer " + token |
| 87 | req.Header.Add("Authorization", bearer) |
| 88 | |
| 89 | resp, err := client.Do(req) |
| 90 | if err != nil { |
| 91 | return err |
| 92 | } |
| 93 | |
| 94 | defer resp.Body.Close() |
| 95 | |
| 96 | err = checkStatusCode(resp, d) |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | |
| 101 | _, err = io.Copy(writer, resp.Body) |
| 102 | |
| 103 | return err |
| 104 | } |
| 105 | |
| 106 | func formReq(ctx context.Context, endpoint string, values url.Values) (req *http.Request, err error) { |
| 107 | if req, err = http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(values.Encode())); err != nil { |
| 108 | return nil, err |
| 109 | } |
| 110 | |
| 111 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 112 | return req, nil |
| 113 | } |
| 114 | |
| 115 | func jsonReq(ctx context.Context, endpoint string, body interface{}) (req *http.Request, err error) { |
| 116 | buffer := bytes.NewBuffer([]byte{}) |
| 117 | if err = json.NewEncoder(buffer).Encode(body); err != nil { |
| 118 | return nil, err |
| 119 | } |
| 120 | |
| 121 | if req, err = http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer); err != nil { |
| 122 | return nil, err |
| 123 | } |
| 124 | |
| 125 | req.Header.Set("Content-Type", "application/json; charset=utf-8") |
| 126 | return req, nil |
| 127 | } |
| 128 | |
| 129 | func parseResponseBody(body io.ReadCloser, intf interface{}, d Debug) error { |
| 130 | response, err := ioutil.ReadAll(body) |
| 131 | if err != nil { |
| 132 | return err |
| 133 | } |
| 134 | |
| 135 | if d.Debug() { |
| 136 | d.Debugln("parseResponseBody", string(response)) |
| 137 | } |
| 138 | |
| 139 | return json.Unmarshal(response, intf) |
| 140 | } |
| 141 | |
| 142 | func postLocalWithMultipartResponse(ctx context.Context, client httpClient, method, fpath, fieldname, token string, values url.Values, intf interface{}, d Debug) error { |
| 143 | fullpath, err := filepath.Abs(fpath) |
| 144 | if err != nil { |
| 145 | return err |
| 146 | } |
| 147 | file, err := os.Open(fullpath) |
| 148 | if err != nil { |
| 149 | return err |
| 150 | } |
| 151 | defer file.Close() |
| 152 | |
| 153 | return postWithMultipartResponse(ctx, client, method, filepath.Base(fpath), fieldname, token, values, file, intf, d) |
| 154 | } |
| 155 | |
| 156 | func postWithMultipartResponse(ctx context.Context, client httpClient, path, name, fieldname, token string, values url.Values, r io.Reader, intf interface{}, d Debug) error { |
| 157 | pipeReader, pipeWriter := io.Pipe() |
| 158 | wr := multipart.NewWriter(pipeWriter) |
| 159 | errc := make(chan error) |
| 160 | go func() { |
| 161 | defer pipeWriter.Close() |
| 162 | ioWriter, err := wr.CreateFormFile(fieldname, name) |
| 163 | if err != nil { |
| 164 | errc <- err |
| 165 | return |
| 166 | } |
| 167 | _, err = io.Copy(ioWriter, r) |
| 168 | if err != nil { |
| 169 | errc <- err |
| 170 | return |
| 171 | } |
| 172 | if err = wr.Close(); err != nil { |
| 173 | errc <- err |
| 174 | return |
| 175 | } |
| 176 | }() |
| 177 | req, err := fileUploadReq(ctx, path, values, pipeReader) |
| 178 | if err != nil { |
| 179 | return err |
| 180 | } |
| 181 | req.Header.Add("Content-Type", wr.FormDataContentType()) |
| 182 | req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) |
| 183 | resp, err := client.Do(req) |
| 184 | |
| 185 | if err != nil { |
| 186 | return err |
| 187 | } |
| 188 | defer resp.Body.Close() |
| 189 | |
| 190 | err = checkStatusCode(resp, d) |
| 191 | if err != nil { |
| 192 | return err |
| 193 | } |
| 194 | |
| 195 | select { |
| 196 | case err = <-errc: |
| 197 | return err |
| 198 | default: |
| 199 | return newJSONParser(intf)(resp) |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | func doPost(ctx context.Context, client httpClient, req *http.Request, parser responseParser, d Debug) error { |
| 204 | resp, err := client.Do(req) |
| 205 | if err != nil { |
| 206 | return err |
| 207 | } |
| 208 | defer resp.Body.Close() |
| 209 | |
| 210 | err = checkStatusCode(resp, d) |
| 211 | if err != nil { |
| 212 | return err |
| 213 | } |
| 214 | |
| 215 | return parser(resp) |
| 216 | } |
| 217 | |
| 218 | // post JSON. |
| 219 | func postJSON(ctx context.Context, client httpClient, endpoint, token string, json []byte, intf interface{}, d Debug) error { |
| 220 | reqBody := bytes.NewBuffer(json) |
| 221 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, reqBody) |
| 222 | if err != nil { |
| 223 | return err |
| 224 | } |
| 225 | req.Header.Set("Content-Type", "application/json") |
| 226 | req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) |
| 227 | |
| 228 | return doPost(ctx, client, req, newJSONParser(intf), d) |
| 229 | } |
| 230 | |
| 231 | // post a url encoded form. |
| 232 | func postForm(ctx context.Context, client httpClient, endpoint string, values url.Values, intf interface{}, d Debug) error { |
| 233 | reqBody := strings.NewReader(values.Encode()) |
| 234 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, reqBody) |
| 235 | if err != nil { |
| 236 | return err |
| 237 | } |
| 238 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 239 | return doPost(ctx, client, req, newJSONParser(intf), d) |
| 240 | } |
| 241 | |
| 242 | func getResource(ctx context.Context, client httpClient, endpoint, token string, values url.Values, intf interface{}, d Debug) error { |
| 243 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) |
| 244 | if err != nil { |
| 245 | return err |
| 246 | } |
| 247 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 248 | req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) |
| 249 | |
| 250 | req.URL.RawQuery = values.Encode() |
| 251 | |
| 252 | return doPost(ctx, client, req, newJSONParser(intf), d) |
| 253 | } |
| 254 | |
| 255 | func parseAdminResponse(ctx context.Context, client httpClient, method string, teamName string, values url.Values, intf interface{}, d Debug) error { |
| 256 | endpoint := fmt.Sprintf(WEBAPIURLFormat, teamName, method, time.Now().Unix()) |
| 257 | return postForm(ctx, client, endpoint, values, intf, d) |
| 258 | } |
| 259 | |
| 260 | func logResponse(resp *http.Response, d Debug) error { |
| 261 | if d.Debug() { |
| 262 | text, err := httputil.DumpResponse(resp, true) |
| 263 | if err != nil { |
| 264 | return err |
| 265 | } |
| 266 | d.Debugln(string(text)) |
| 267 | } |
| 268 | |
| 269 | return nil |
| 270 | } |
| 271 | |
| 272 | func okJSONHandler(rw http.ResponseWriter, r *http.Request) { |
| 273 | rw.Header().Set("Content-Type", "application/json") |
| 274 | response, _ := json.Marshal(SlackResponse{ |
| 275 | Ok: true, |
| 276 | }) |
| 277 | rw.Write(response) |
| 278 | } |
| 279 | |
| 280 | // timerReset safely reset a timer, see time.Timer.Reset for details. |
| 281 | func timerReset(t *time.Timer, d time.Duration) { |
| 282 | if !t.Stop() { |
| 283 | <-t.C |
| 284 | } |
| 285 | t.Reset(d) |
| 286 | } |
| 287 | |
| 288 | func checkStatusCode(resp *http.Response, d Debug) error { |
| 289 | if resp.StatusCode == http.StatusTooManyRequests { |
| 290 | retry, err := strconv.ParseInt(resp.Header.Get("Retry-After"), 10, 64) |
| 291 | if err != nil { |
| 292 | return err |
| 293 | } |
| 294 | return &RateLimitedError{time.Duration(retry) * time.Second} |
| 295 | } |
| 296 | |
| 297 | // Slack seems to send an HTML body along with 5xx error codes. Don't parse it. |
| 298 | if resp.StatusCode != http.StatusOK { |
| 299 | logResponse(resp, d) |
| 300 | return StatusCodeError{Code: resp.StatusCode, Status: resp.Status} |
| 301 | } |
| 302 | |
| 303 | return nil |
| 304 | } |
| 305 | |
| 306 | type responseParser func(*http.Response) error |
| 307 | |
| 308 | func newJSONParser(dst interface{}) responseParser { |
| 309 | return func(resp *http.Response) error { |
| 310 | return json.NewDecoder(resp.Body).Decode(dst) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | func newTextParser(dst interface{}) responseParser { |
| 315 | return func(resp *http.Response) error { |
| 316 | b, err := ioutil.ReadAll(resp.Body) |
| 317 | if err != nil { |
| 318 | return err |
| 319 | } |
| 320 | |
| 321 | if !bytes.Equal(b, []byte("ok")) { |
| 322 | return errors.New(string(b)) |
| 323 | } |
| 324 | |
| 325 | return nil |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | func newContentTypeParser(dst interface{}) responseParser { |
| 330 | return func(req *http.Response) (err error) { |
| 331 | var ( |
| 332 | ctype string |
| 333 | ) |
| 334 | |
| 335 | if ctype, _, err = mime.ParseMediaType(req.Header.Get("Content-Type")); err != nil { |
| 336 | return err |
| 337 | } |
| 338 | |
| 339 | switch ctype { |
| 340 | case "application/json": |
| 341 | return newJSONParser(dst)(req) |
| 342 | default: |
| 343 | return newTextParser(dst)(req) |
| 344 | } |
| 345 | } |
| 346 | } |