forked from trhura/chaparty
/
app.go
225 lines (175 loc) · 5.12 KB
/
app.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
package app
import (
"bytes"
"image"
"io"
"io/ioutil"
"math/rand"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
_ "image/jpeg"
_ "image/png"
fb "github.com/huandu/facebook"
"appengine"
"appengine/datastore"
"appengine/urlfetch"
)
//var APPSECRET = os.Getenv("APPSECRET")
var clientID = "526791527487217"
var FbApp = fb.New(clientID, APPSECRET)
var aboutParams = fb.Params{
"method": fb.GET,
"relative_url": "me?fields=name,email,gender,age_range,address,location",
}
var photoParams = fb.Params{
"method": fb.GET,
"relative_url": "me/picture?width=320&height=320&redirect=false",
}
func init() {
http.HandleFunc("/static/", StaticHandler)
http.HandleFunc("/", MainHandler)
http.HandleFunc("/web/", WebHandler)
fb.Debug = fb.DEBUG_ALL
FbApp.EnableAppsecretProof = true
rand.Seed(time.Now().UTC().UnixNano())
}
func WebHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
code := query.Get("code")
if code == "" {
http.Error(w, "Cannot get code from facebook.", 505)
return
}
context := appengine.NewContext(r)
client := urlfetch.Client(context)
fb.SetHttpClient(client)
redirectURL := "http://" + r.Host + r.URL.Path
accessResp, err := fb.Get("/v2.4/oauth/access_token", fb.Params{
"code": code,
"redirect_uri": redirectURL,
"client_id": clientID,
"client_secret": APPSECRET,
})
check(err, context)
var accessToken string
accessResp.DecodeField("access_token", &accessToken)
paths := strings.Split(r.URL.Path, "/")
party := paths[len(paths)-1]
photoID := UploadPhoto(accessToken, party, context)
redirectUrl := "https://facebook.com/photo.php?fbid=" + photoID + "&makeprofile=1&prof"
http.Redirect(w, r, redirectUrl, 303)
}
func UploadPhoto(accessToken string, party string, context appengine.Context) string {
session := FbApp.Session(accessToken)
session.HttpClient = urlfetch.Client(context)
err := session.Validate()
check(err, context)
results, err := session.BatchApi(aboutParams, photoParams)
check(err, context)
aboutBatch, err := results[0].Batch()
check(err, context)
photoBatch, err := results[1].Batch()
check(err, context)
aboutResp := aboutBatch.Result
photoResp := photoBatch.Result
SaveAboutUser(&aboutResp, party, context)
profilePicture := GetUserPhoto(&photoResp, context)
imagebytes := addLogo(profilePicture, party, context)
form, mime := CreateImageForm(&imagebytes, context)
url := "https://graph.facebook.com/v2.4/me/photos" +
"?access_token=" + accessToken +
"&no_story=true" +
"&appsecret_proof=" + session.AppsecretProof()
uploadResquest, _ := http.NewRequest("POST", url, form)
uploadResquest.Header.Set("Content-Type", mime)
uploadResp, _ := session.Request(uploadResquest)
check(err, context)
var photoID string
uploadResp.DecodeField("id", &photoID)
return photoID
}
func StaticHandler(w http.ResponseWriter, r *http.Request) {
path := "." + r.URL.Path
if f, err := os.Stat(path); err == nil && !f.IsDir() {
http.ServeFile(w, r, path)
return
}
http.NotFound(w, r)
}
func MainHandler(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/privacy":
context := appengine.NewContext(r)
data, err := ioutil.ReadFile("privacy.html")
check(err, context)
w.Write(data)
case r.URL.Path == "/tcp":
context := appengine.NewContext(r)
data, err := ioutil.ReadFile("tcp.html")
check(err, context)
w.Write(data)
case r.URL.Path != "/":
http.NotFound(w, r)
default:
handleMain(w, r)
}
return
}
func handleMain(w http.ResponseWriter, r *http.Request) {
context := appengine.NewContext(r)
data, err := ioutil.ReadFile("index.html")
check(err, context)
w.Write(data)
}
type Log struct {
Name string
Gender string
Party string
Email string
AgeRange int
Location string
}
func SaveAboutUser(aboutResp *fb.Result, party string, context appengine.Context) {
var log Log
aboutResp.Decode(&log)
var ageRange map[string]int
var location map[string]string
aboutResp.DecodeField("location", &location)
aboutResp.DecodeField("age_range", &ageRange)
log.AgeRange = ageRange["min"]
log.Location = location["name"]
log.Party = party
_, err := datastore.Put(context,
datastore.NewIncompleteKey(context, "log", nil),
&log)
check(err, context)
}
func GetUserPhoto(photoResp *fb.Result, context appengine.Context) *image.Image {
var dataField fb.Result
photoResp.DecodeField("data", &dataField)
var url string
dataField.DecodeField("url", &url)
client := urlfetch.Client(context)
resp, err := client.Get(url)
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
check(err, context)
reader := bytes.NewReader(data)
profilePicture, _, err := image.Decode(reader)
check(err, context)
return &profilePicture
}
func CreateImageForm(imageBytes *[]byte, context appengine.Context) (*bytes.Buffer, string) {
var formBuffer bytes.Buffer
multiWriter := multipart.NewWriter(&formBuffer)
imageField, err := multiWriter.CreateFormFile("source", "election.png")
check(err, context)
imageBuffer := bytes.NewBuffer(*imageBytes)
_, err = io.Copy(imageField, imageBuffer)
check(err, context)
multiWriter.Close()
return &formBuffer, multiWriter.FormDataContentType()
}