forked from ekyoung/fbmessenger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
216 lines (169 loc) · 5.3 KB
/
client.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
package fbmessenger
import (
"bytes"
"encoding/json"
"fmt"
"golang.org/x/net/context"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
)
const apiURL = "https://graph.facebook.com/v2.6"
type httpDoer interface {
Do(req *http.Request) (*http.Response, error)
}
/*
Client is used to send messages and get user profiles. Use the empty value in most cases.
The URL field can be overridden to allow for writing integration tests that use a different
endpoint (not Facebook).
*/
type Client struct {
URL string
httpDoer httpDoer
}
/*
Send POSTs a request to and returns a response from the Send API. A response from
Facebook indicating an error does not return an error. Be sure to check for errors
in sending, and errors in the response from Facebook.
response, err := client.Send(request, "YOUR_PAGE_ACCESS_TOKEN")
if err != nil {
//Got an error. Request never got to Facebook.
} else if response.Error != nil {
//Request got to Facebook. Facebook returned an error.
} else {
//Hooray!
}
*/
func (c *Client) Send(sendRequest *SendRequest, pageAccessToken string) (*SendResponse, error) {
return c.SendWithContext(context.Background(), sendRequest, pageAccessToken)
}
// SendWithContext is like Send but allows you to timeout or cancel the request using context.Context.
func (c *Client) SendWithContext(ctx context.Context, sendRequest *SendRequest, pageAccessToken string) (*SendResponse, error) {
var req *http.Request
var err error
if isDataMessage(sendRequest) {
req, err = c.newFormDataRequest(sendRequest, pageAccessToken)
} else {
req, err = c.newJSONRequest(sendRequest, pageAccessToken)
}
if err != nil {
return nil, err
}
response := &SendResponse{}
err = c.doRequest(ctx, req, response)
if err != nil {
return nil, err
}
return response, nil
}
func isDataMessage(sendRequest *SendRequest) bool {
if sendRequest.Message.Attachment == nil {
return false
}
_, ok := sendRequest.Message.Attachment.Payload.(DataPayload)
return ok
}
func (c *Client) newJSONRequest(sendRequest *SendRequest, pageAccessToken string) (*http.Request, error) {
requestBytes, err := json.Marshal(sendRequest)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.buildURL("/me/messages?access_token="+pageAccessToken), bytes.NewBuffer(requestBytes))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return req, nil
}
func (c *Client) newFormDataRequest(sendRequest *SendRequest, pageAccessToken string) (*http.Request, error) {
payload, _ := sendRequest.Message.Attachment.Payload.(DataPayload)
var reqBuffer bytes.Buffer
w := multipart.NewWriter(&reqBuffer)
err := writeFormField(w, "recipient", sendRequest.Recipient)
if err != nil {
return nil, err
}
err = writeFormField(w, "message", sendRequest.Message)
if err != nil {
return nil, err
}
if sendRequest.NotificationType != "" {
err = w.WriteField("notification_type", sendRequest.NotificationType)
if err != nil {
return nil, err
}
}
header := make(textproto.MIMEHeader)
header.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, "filedata", payload.FileName))
header.Set("Content-Type", payload.ContentType)
fileWriter, err := w.CreatePart(header)
if err != nil {
return nil, err
}
_, err = fileWriter.Write(payload.Data)
if err != nil {
return nil, err
}
w.Close()
req, err := http.NewRequest("POST", c.buildURL("/me/messages?access_token="+pageAccessToken), &reqBuffer)
//req, err := http.NewRequest("POST", "http://httpbin.org/post", &reqBuffer)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", w.FormDataContentType())
return req, nil
}
func writeFormField(w *multipart.Writer, fieldName string, value interface{}) error {
valueBytes, err := json.Marshal(value)
if err != nil {
return fmt.Errorf("error marshaling value for field %v: %v", fieldName, err)
}
return w.WriteField(fieldName, string(valueBytes))
}
// GetUserProfile GETs a profile with more information about the user.
func (c *Client) GetUserProfile(userId, pageAccessToken string) (*UserProfile, error) {
return c.GetUserProfileWithContext(context.Background(), userId, pageAccessToken)
}
// GetUserProfileWithContext is like GetUserProfile but allows you to timeout or cancel the request using context.Context.
func (c *Client) GetUserProfileWithContext(ctx context.Context, userId, pageAccessToken string) (*UserProfile, error) {
url := c.buildURL(fmt.Sprintf("/%v?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=%v", userId, pageAccessToken))
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
userProfile := &UserProfile{}
err = c.doRequest(ctx, req, userProfile)
if err != nil {
return nil, err
}
return userProfile, nil
}
func (c *Client) buildURL(path string) string {
url := c.URL
if url == "" {
url = apiURL
}
return url + path
}
func (c *Client) doRequest(ctx context.Context, req *http.Request, responseStruct interface{}) error {
req.Cancel = ctx.Done()
doer := c.httpDoer
if doer == nil {
doer = &http.Client{}
}
resp, err := doer.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, responseStruct)
if err != nil {
return err
}
return nil
}