5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-11-10 14:30:26 +00:00
matterbridge/vendor/github.com/slack-go/slack/misc.go

347 lines
8.5 KiB
Go
Raw Normal View History

2016-09-05 14:34:37 +00:00
package slack
import (
"bytes"
2017-07-16 12:29:46 +00:00
"context"
2016-09-05 14:34:37 +00:00
"encoding/json"
2018-08-09 22:38:19 +00:00
"errors"
2016-09-05 14:34:37 +00:00
"fmt"
"io"
"io/ioutil"
2019-09-07 20:46:58 +00:00
"mime"
2016-09-05 14:34:37 +00:00
"mime/multipart"
"net/http"
2016-11-05 23:07:24 +00:00
"net/http/httputil"
2016-09-05 14:34:37 +00:00
"net/url"
"os"
"path/filepath"
2018-01-08 21:41:38 +00:00
"strconv"
2017-07-16 12:29:46 +00:00
"strings"
2016-09-05 14:34:37 +00:00
"time"
)
2018-12-01 18:55:35 +00:00
// SlackResponse handles parsing out errors from the web api.
2018-08-09 22:38:19 +00:00
type SlackResponse struct {
2020-10-11 21:07:00 +00:00
Ok bool `json:"ok"`
Error string `json:"error"`
ResponseMetadata ResponseMetadata `json:"response_metadata"`
2017-07-16 12:29:46 +00:00
}
2018-08-09 22:38:19 +00:00
func (t SlackResponse) Err() error {
if t.Ok {
return nil
}
// handle pure text based responses like chat.post
// which while they have a slack response in their data structure
// it doesn't actually get set during parsing.
if strings.TrimSpace(t.Error) == "" {
return nil
}
2017-07-16 12:29:46 +00:00
2021-12-11 23:05:15 +00:00
return SlackErrorResponse{Err: t.Error, ResponseMetadata: t.ResponseMetadata}
2018-08-09 22:38:19 +00:00
}
2016-09-05 14:34:37 +00:00
2021-12-11 23:05:15 +00:00
// SlackErrorResponse brings along the metadata of errors returned by the Slack API.
type SlackErrorResponse struct {
Err string
ResponseMetadata ResponseMetadata
}
func (r SlackErrorResponse) Error() string { return r.Err }
2019-09-07 20:46:58 +00:00
// RateLimitedError represents the rate limit respond from slack
2018-01-08 21:41:38 +00:00
type RateLimitedError struct {
RetryAfter time.Duration
}
func (e *RateLimitedError) Error() string {
2019-09-07 20:46:58 +00:00
return fmt.Sprintf("slack rate limit exceeded, retry after %s", e.RetryAfter)
}
func (e *RateLimitedError) Retryable() bool {
return true
2018-01-08 21:41:38 +00:00
}
2018-12-01 18:55:35 +00:00
func fileUploadReq(ctx context.Context, path string, values url.Values, r io.Reader) (*http.Request, error) {
2022-04-25 21:50:10 +00:00
req, err := http.NewRequestWithContext(ctx, http.MethodPost, path, r)
2019-09-07 20:46:58 +00:00
if err != nil {
return nil, err
}
2016-09-05 14:34:37 +00:00
2022-04-25 21:50:10 +00:00
req.URL.RawQuery = values.Encode()
2019-09-07 20:46:58 +00:00
return req, nil
}
2022-04-25 21:50:10 +00:00
func downloadFile(ctx context.Context, client httpClient, token string, downloadURL string, writer io.Writer, d Debug) error {
2019-09-07 20:46:58 +00:00
if downloadURL == "" {
return fmt.Errorf("received empty download URL")
}
2022-04-25 21:50:10 +00:00
req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, &bytes.Buffer{})
2019-09-07 20:46:58 +00:00
if err != nil {
return err
}
var bearer = "Bearer " + token
req.Header.Add("Authorization", bearer)
resp, err := client.Do(req)
2016-09-05 14:34:37 +00:00
if err != nil {
2019-09-07 20:46:58 +00:00
return err
}
defer resp.Body.Close()
err = checkStatusCode(resp, d)
if err != nil {
return err
}
_, err = io.Copy(writer, resp.Body)
return err
}
2022-04-25 21:50:10 +00:00
func formReq(ctx context.Context, endpoint string, values url.Values) (req *http.Request, err error) {
if req, err = http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(values.Encode())); err != nil {
2016-09-05 14:34:37 +00:00
return nil, err
}
2019-09-07 20:46:58 +00:00
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req, nil
}
2022-04-25 21:50:10 +00:00
func jsonReq(ctx context.Context, endpoint string, body interface{}) (req *http.Request, err error) {
2019-09-07 20:46:58 +00:00
buffer := bytes.NewBuffer([]byte{})
if err = json.NewEncoder(buffer).Encode(body); err != nil {
return nil, err
}
2022-04-25 21:50:10 +00:00
if req, err = http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer); err != nil {
2019-09-07 20:46:58 +00:00
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
2016-09-05 14:34:37 +00:00
return req, nil
}
2020-12-31 13:48:12 +00:00
func parseResponseBody(body io.ReadCloser, intf interface{}, d Debug) error {
2016-09-05 14:34:37 +00:00
response, err := ioutil.ReadAll(body)
if err != nil {
return err
}
2018-12-01 18:55:35 +00:00
if d.Debug() {
d.Debugln("parseResponseBody", string(response))
2016-09-05 14:34:37 +00:00
}
2018-08-09 22:38:19 +00:00
return json.Unmarshal(response, intf)
2016-09-05 14:34:37 +00:00
}
func postLocalWithMultipartResponse(ctx context.Context, client httpClient, method, fpath, fieldname, token string, values url.Values, intf interface{}, d Debug) error {
2017-07-16 12:29:46 +00:00
fullpath, err := filepath.Abs(fpath)
if err != nil {
return err
}
file, err := os.Open(fullpath)
if err != nil {
return err
}
defer file.Close()
2019-09-07 20:46:58 +00:00
return postWithMultipartResponse(ctx, client, method, filepath.Base(fpath), fieldname, token, values, file, intf, d)
2017-07-16 12:29:46 +00:00
}
func postWithMultipartResponse(ctx context.Context, client httpClient, path, name, fieldname, token string, values url.Values, r io.Reader, intf interface{}, d Debug) error {
2018-12-01 18:55:35 +00:00
pipeReader, pipeWriter := io.Pipe()
wr := multipart.NewWriter(pipeWriter)
errc := make(chan error)
go func() {
defer pipeWriter.Close()
ioWriter, err := wr.CreateFormFile(fieldname, name)
if err != nil {
errc <- err
return
}
_, err = io.Copy(ioWriter, r)
if err != nil {
errc <- err
return
}
if err = wr.Close(); err != nil {
errc <- err
return
}
}()
2019-09-07 20:46:58 +00:00
req, err := fileUploadReq(ctx, path, values, pipeReader)
2017-07-16 12:29:46 +00:00
if err != nil {
return err
}
2018-12-01 18:55:35 +00:00
req.Header.Add("Content-Type", wr.FormDataContentType())
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
2018-08-09 22:38:19 +00:00
resp, err := client.Do(req)
2018-12-01 18:55:35 +00:00
2016-09-05 14:34:37 +00:00
if err != nil {
return err
}
defer resp.Body.Close()
2016-11-05 23:07:24 +00:00
2019-09-07 20:46:58 +00:00
err = checkStatusCode(resp, d)
if err != nil {
return err
2018-01-08 21:41:38 +00:00
}
2018-12-01 18:55:35 +00:00
select {
case err = <-errc:
return err
default:
2019-09-07 20:46:58 +00:00
return newJSONParser(intf)(resp)
2018-12-01 18:55:35 +00:00
}
2016-09-05 14:34:37 +00:00
}
2020-12-31 13:48:12 +00:00
func doPost(ctx context.Context, client httpClient, req *http.Request, parser responseParser, d Debug) error {
2018-08-09 22:38:19 +00:00
resp, err := client.Do(req)
2016-09-05 14:34:37 +00:00
if err != nil {
return err
}
defer resp.Body.Close()
2019-09-07 20:46:58 +00:00
err = checkStatusCode(resp, d)
if err != nil {
return err
2018-08-09 22:38:19 +00:00
}
2019-09-07 20:46:58 +00:00
return parser(resp)
2018-08-09 22:38:19 +00:00
}
// post JSON.
2020-12-31 13:48:12 +00:00
func postJSON(ctx context.Context, client httpClient, endpoint, token string, json []byte, intf interface{}, d Debug) error {
2018-08-09 22:38:19 +00:00
reqBody := bytes.NewBuffer(json)
2022-04-25 21:50:10 +00:00
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, reqBody)
2018-08-09 22:38:19 +00:00
if err != nil {
return err
2017-07-16 12:29:46 +00:00
}
2018-08-09 22:38:19 +00:00
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
2019-09-07 20:46:58 +00:00
return doPost(ctx, client, req, newJSONParser(intf), d)
2018-08-09 22:38:19 +00:00
}
2017-07-16 12:29:46 +00:00
2018-08-09 22:38:19 +00:00
// post a url encoded form.
2020-12-31 13:48:12 +00:00
func postForm(ctx context.Context, client httpClient, endpoint string, values url.Values, intf interface{}, d Debug) error {
2018-08-09 22:38:19 +00:00
reqBody := strings.NewReader(values.Encode())
2022-04-25 21:50:10 +00:00
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, reqBody)
2018-08-09 22:38:19 +00:00
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
2019-09-07 20:46:58 +00:00
return doPost(ctx, client, req, newJSONParser(intf), d)
2016-09-05 14:34:37 +00:00
}
2016-11-05 23:07:24 +00:00
func getResource(ctx context.Context, client httpClient, endpoint, token string, values url.Values, intf interface{}, d Debug) error {
2022-04-25 21:50:10 +00:00
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
2018-12-01 18:55:35 +00:00
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
2018-12-01 18:55:35 +00:00
req.URL.RawQuery = values.Encode()
2019-09-07 20:46:58 +00:00
return doPost(ctx, client, req, newJSONParser(intf), d)
2018-12-01 18:55:35 +00:00
}
2020-12-31 13:48:12 +00:00
func parseAdminResponse(ctx context.Context, client httpClient, method string, teamName string, values url.Values, intf interface{}, d Debug) error {
2018-12-01 18:55:35 +00:00
endpoint := fmt.Sprintf(WEBAPIURLFormat, teamName, method, time.Now().Unix())
return postForm(ctx, client, endpoint, values, intf, d)
}
2020-12-31 13:48:12 +00:00
func logResponse(resp *http.Response, d Debug) error {
2018-12-01 18:55:35 +00:00
if d.Debug() {
2016-11-05 23:07:24 +00:00
text, err := httputil.DumpResponse(resp, true)
if err != nil {
return err
}
2018-12-01 18:55:35 +00:00
d.Debugln(string(text))
2016-11-05 23:07:24 +00:00
}
return nil
}
2017-07-16 12:29:46 +00:00
2018-08-09 22:38:19 +00:00
func okJSONHandler(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
response, _ := json.Marshal(SlackResponse{
Ok: true,
})
rw.Write(response)
}
// timerReset safely reset a timer, see time.Timer.Reset for details.
func timerReset(t *time.Timer, d time.Duration) {
if !t.Stop() {
<-t.C
}
t.Reset(d)
2017-07-16 12:29:46 +00:00
}
2019-09-07 20:46:58 +00:00
2020-12-31 13:48:12 +00:00
func checkStatusCode(resp *http.Response, d Debug) error {
2019-09-07 20:46:58 +00:00
if resp.StatusCode == http.StatusTooManyRequests {
retry, err := strconv.ParseInt(resp.Header.Get("Retry-After"), 10, 64)
if err != nil {
return err
}
return &RateLimitedError{time.Duration(retry) * time.Second}
}
// Slack seems to send an HTML body along with 5xx error codes. Don't parse it.
if resp.StatusCode != http.StatusOK {
logResponse(resp, d)
2022-06-24 22:36:16 +00:00
return StatusCodeError{Code: resp.StatusCode, Status: resp.Status}
2019-09-07 20:46:58 +00:00
}
return nil
}
type responseParser func(*http.Response) error
func newJSONParser(dst interface{}) responseParser {
return func(resp *http.Response) error {
return json.NewDecoder(resp.Body).Decode(dst)
}
}
func newTextParser(dst interface{}) responseParser {
return func(resp *http.Response) error {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if !bytes.Equal(b, []byte("ok")) {
return errors.New(string(b))
}
return nil
}
}
func newContentTypeParser(dst interface{}) responseParser {
return func(req *http.Response) (err error) {
var (
ctype string
)
if ctype, _, err = mime.ParseMediaType(req.Header.Get("Content-Type")); err != nil {
return err
}
switch ctype {
case "application/json":
return newJSONParser(dst)(req)
default:
return newTextParser(dst)(req)
}
}
}