-
Notifications
You must be signed in to change notification settings - Fork 0
/
facebook.go
260 lines (228 loc) · 6.61 KB
/
facebook.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// twitterlib - A simple, fully oauth-authenticated Twitter library
// Copyright (c) 2011, Roberto Teixeira <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package fblib
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"strconv"
"time"
)
var (
ErrOAuth = errors.New("OAuth authorization failure")
)
const (
tokenRequestURL = "https://www.facebook.com/dialog/oauth" // request token endpoint
accessTokenURL = "https://graph.facebook.com/oauth/access_token" // access token endpoint
apiURL = "https://graph.facebook.com"
)
type FacebookClient struct {
APIKey string
AppSecret string
AccessToken string
Transport http.RoundTripper
}
type TempToken struct {
Token string
Secret string
}
func nonce() string {
s := time.Now()
return strconv.FormatInt(s.Unix(), 10)
}
func NewFacebookClient(key, secret string) *FacebookClient {
return &FacebookClient{APIKey: key,
AppSecret: secret,
Transport: http.DefaultTransport}
}
func (fc *FacebookClient) AuthURL(redirectURI, scope string) string {
params := make(url.Values)
if scope != "" {
params.Set("scope", scope)
}
params.Set("client_id", fc.APIKey)
params.Set("redirect_uri", redirectURI)
return fmt.Sprintf("%s?%s", tokenRequestURL, params.Encode())
}
func (fc *FacebookClient) RequestAccessToken(code, redirectURI string) error {
var body io.Reader
body = bytes.NewBuffer([]byte(""))
params := make(url.Values)
params.Set("client_id", fc.APIKey)
params.Set("redirect_uri", redirectURI)
params.Set("client_secret", fc.AppSecret)
cmdStr := fmt.Sprintf("%s?%s&code=%s", accessTokenURL, params.Encode(), code)
fmt.Printf("cmdStr := %s\n", cmdStr)
req, err := http.NewRequest("GET", cmdStr, body)
if err != nil {
return err
}
resp, err := fc.Transport.RoundTrip(req)
if err != nil {
return err
}
defer resp.Body.Close()
var respBody []byte
respBody, _ = ioutil.ReadAll(resp.Body)
if resp.StatusCode == 400 {
return fc.parseError(respBody)
}
data, err := url.ParseQuery(string(respBody))
if err != nil {
return err
}
fc.AccessToken = data.Get("access_token")
return nil
}
func (fc *FacebookClient) parseError(respBody []byte) error {
var buf map[string]interface{}
json.Unmarshal(respBody, &buf)
errorMap := buf["error"]
if errorMap != nil {
error := errorMap.(map[string]interface{})
msg := error["message"].(string)
kind := error["type"].(string)
if msg != "" {
if kind == "OAuthException" {
return ErrOAuth
} else {
return errors.New(error["message"].(string))
}
}
}
return errors.New("Unknown error")
}
func (fc *FacebookClient) GetUser(id string) (*User, error) {
u := make(url.Values)
u.Set("access_token", fc.AccessToken)
body := bytes.NewBuffer([]byte(u.Encode()))
cmdStr := fmt.Sprintf("%s/%s?%s", apiURL, id, u.Encode())
req, err := http.NewRequest("GET", cmdStr, body)
if err != nil {
return nil, err
}
resp, err := fc.Transport.RoundTrip(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var respBody []byte
respBody, _ = ioutil.ReadAll(resp.Body)
if resp.StatusCode == 400 {
return nil, fc.parseError(respBody)
}
fmt.Printf("%s\n", respBody)
return nil, nil
}
// Performs API call based on httpMethod
// returns the response body as string and error/nil
func (fc *FacebookClient) Call(httpMethod, endpoint string, params url.Values) ([]byte, error) {
body := bytes.NewBuffer([]byte(params.Encode()))
cmdStr := fmt.Sprintf("%s/%s?access_token=%s", apiURL, endpoint, fc.AccessToken)
if httpMethod == "GET" {
cmdStr = cmdStr + "&" + params.Encode()
}
req, err := http.NewRequest(httpMethod, cmdStr, body)
if err != nil {
return []byte(""), err
}
resp, err := fc.Transport.RoundTrip(req)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
var respBody []byte
respBody, _ = ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return []byte(""), fc.parseError(respBody)
}
return respBody, nil
}
// Performs POST-based API call with a prepared
// body. Returns the response body as string and error/nil
func (fc *FacebookClient) PostCall(endpoint, header string, body []byte) ([]byte, error) {
cmdStr := fmt.Sprintf("%s/%s?access_token=%s", apiURL, endpoint, fc.AccessToken)
bodyReader := bytes.NewReader(body)
req, err := http.NewRequest("POST", cmdStr, bodyReader)
req.Header.Set("Content-Type", header)
if err != nil {
return []byte(""), err
}
resp, err := fc.Transport.RoundTrip(req)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
var respBody []byte
respBody, _ = ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return []byte(""), fc.parseError(respBody)
}
return respBody, nil
}
func (fc *FacebookClient) User(id string) (*User, error) {
u := new(url.Values)
resp, err := fc.Call("GET", id, *u)
if err != nil {
return nil, err
}
user := new(User)
//if err = json.Unmarshal(resp, user); err != nil {
// return nil, os.NewError(fmt.Sprintf("fc.User error -> %s (resp body: '%s')", err, resp))
//}
json.Unmarshal(resp, user)
user.Client = fc
return user, nil
}
func (fc *FacebookClient) CurrentUser() (*User, error) {
return fc.User("me")
}
func (fc *FacebookClient) PostLink(link Link) error {
u := make(url.Values)
u.Add("message", link.Text)
u.Add("link", link.Url)
u.Add("picture", link.Image)
_, err := fc.Call("POST", "me/links", u)
return err
}
func (fc *FacebookClient) PostStatus(message string) error {
u := make(url.Values)
u.Add("message", message)
_, err := fc.Call("POST", "me/feed", u)
return err
}
func (fc *FacebookClient) PostPhoto(photo Photo) error {
body := bytes.NewBufferString("")
mp := multipart.NewWriter(body)
mp.WriteField("message", photo.Message)
writer, err := mp.CreateFormFile("source", photo.FileName)
if err != nil {
return err
}
writer.Write(photo.Source)
header := fmt.Sprintf("multipart/form-data;boundary=%v", mp.Boundary())
mp.Close()
_, err = fc.PostCall("me/photos", header, body.Bytes())
//urls := fmt.Sprintf("https://upload.twitter.com/1/%s.json", "statuses/update_with_media")
//req, _ := http.NewRequest("POST", urls, body)
//req.Header.Set("Content-Type", header)
return err
}