-
Notifications
You must be signed in to change notification settings - Fork 0
/
banner_update.go
82 lines (61 loc) · 1.88 KB
/
banner_update.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
package main
import (
"bytes"
"errors"
"fmt"
"image"
"image/png"
"mime/multipart"
"net/http"
"github.com/dghubble/oauth1"
)
func getTwitterOauth1Client(consumerKey string, consumerSecret string, accessToken string, accessSecret string) *http.Client {
config := oauth1.NewConfig(consumerKey, consumerSecret)
token := oauth1.NewToken(accessToken, accessSecret)
return config.Client(oauth1.NoContext, token)
}
func writeBannerForm(body *bytes.Buffer, drawable *image.RGBA) (*multipart.Writer, error) {
multipartWriter := multipart.NewWriter(body)
fwriter, err := multipartWriter.CreateFormField("banner")
if err != nil {
return multipartWriter, err
}
err = png.Encode(fwriter, drawable)
if err != nil {
return multipartWriter, err
}
multipartWriter.Close()
return multipartWriter, nil
}
func doTwitterUploadRequest(client *http.Client, multipartWriter *multipart.Writer, body *bytes.Buffer, debug bool) error {
const apiUrl = "https://api.twitter.com/1.1/account/update_profile_banner.json"
req, err := http.NewRequest("POST", apiUrl, body)
if err != nil {
return err
}
req.Header.Set("Content-Type", multipartWriter.FormDataContentType())
res, err := client.Do(req)
if err != nil {
return err
}
if res.StatusCode != 201 {
return errors.New(fmt.Sprintf("Failed upload request. Status: %s", res.Status))
}
if debug {
fmt.Printf("Upload request returned: %s\n", res.Status)
}
return nil
}
func UpdateTwitterBanner(consumerKey string, consumerSecret string, accessToken string, accessSecret string, drawable *image.RGBA, debug bool) error {
var body bytes.Buffer
client := getTwitterOauth1Client(consumerKey, consumerSecret, accessToken, accessSecret)
multipartWriter, err := writeBannerForm(&body, drawable)
if err != nil {
return err
}
err = doTwitterUploadRequest(client, multipartWriter, &body, debug)
if err != nil {
return err
}
return nil
}