-
Notifications
You must be signed in to change notification settings - Fork 2
/
gplus2others.go
279 lines (239 loc) · 7.12 KB
/
gplus2others.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// gplus2others - Send Google+ activities to other networks
//
// Copyright 2011 The gplus2others Authors. All rights reserved.
// Use of this source code is governed by the Simplified BSD
// license that can be found in the LICENSE file.
package gplus2others
import (
"appengine"
"appengine/datastore"
"appengine/memcache"
"appengine/urlfetch"
"encoding/json"
plus "google.golang.org/api/plus/v1"
"gopkg.in/tweetlib.v2"
"io/ioutil"
"net/http"
"text/template"
"time"
)
var appConfig struct {
FacebookAppId string
FacebookAppSecret string
GoogleClientId string
GoogleClientSecret string
TwitterConsumerKey string
TwitterConsumerSecret string
AppHost string
AppDomain string
SessionStoreKey string
}
var (
templates, _ = template.ParseFiles(
"templates/404.html",
"templates/home.html",
"templates/header.html",
"templates/footer.html",
"templates/error.html")
)
func init() {
// Read configuration file
content, err := ioutil.ReadFile("config.json")
if err == nil {
err = json.Unmarshal(content, &appConfig)
}
if err != nil {
panic("Can't load configuration")
}
// Make sure every conf option has been completed, except
// for AppDomain, because it is useful to test the app with
// localhost but some browsers require localhost cookies
// to have Domain as ""
if appConfig.FacebookAppId == "" || appConfig.FacebookAppSecret == "" ||
appConfig.GoogleClientId == "" || appConfig.GoogleClientSecret == "" ||
appConfig.TwitterConsumerKey == "" || appConfig.TwitterConsumerSecret == "" ||
appConfig.AppHost == "" {
panic("Invalid configuration")
}
http.HandleFunc("/", homeHandler)
http.HandleFunc("/twitter", twitterHandler)
http.HandleFunc("/loginGoogle", loginGoogle)
http.HandleFunc("/oauth2callback", googleCallbackHandler)
http.HandleFunc("/fb", fbHandler)
http.HandleFunc("/sync", syncHandler)
http.HandleFunc("/deleteAccount", deleteAccountHandler)
http.HandleFunc("/deleteFacebook", deleteFacebookHandler)
http.HandleFunc("/deleteTwitter", deleteTwitterHandler)
}
func loadUserCookie(r *http.Request) (User, error) {
userCookie, err := r.Cookie("userId")
var user User
if err == nil {
user = loadUser(r, userCookie.Value)
}
return user, err
}
// Displays the home page.
func homeHandler(w http.ResponseWriter, r *http.Request) {
if appConfig.AppHost == "" {
appConfig.AppHost = r.Host
}
c := appengine.NewContext(r)
if r.Method != "GET" || r.URL.Path != "/" {
serve404(w)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
params := make(map[string]string)
// Look for a browser cookie containing the user id
// We can use this to load the user information
var user User
user, err := loadUserCookie(r)
if err == nil {
if user.TwitterId != "" {
item := new(memcache.Item)
item, err := memcache.Get(c, "pic"+user.Id)
if err != nil {
// get the user profile pic
conf := &tweetlib.Config{
ConsumerKey: appConfig.TwitterConsumerKey,
ConsumerSecret: appConfig.TwitterConsumerSecret}
tok := &tweetlib.Token{
OAuthSecret: user.TwitterOAuthSecret,
OAuthToken: user.TwitterOAuthToken}
tr := &tweetlib.Transport{Config: conf,
Token: tok,
Transport: &urlfetch.Transport{Context: c}}
tl, _ := tweetlib.New(tr.Client())
opts := tweetlib.NewOptionals()
opts.Add("user_id", user.TwitterId)
u, err := tl.User.Show(user.TwitterScreenName, opts)
if err == nil {
params["pic"] = u.ProfileImageUrl
memcache.Add(c, &memcache.Item{Key: "pic" + user.Id, Value: []byte(u.ProfileImageUrl)})
}
} else {
params["pic"] = string(item.Value)
}
}
params["twitterid"] = user.TwitterId
params["twittername"] = user.TwitterScreenName
params["googleid"] = user.Id
params["fbid"] = user.FBId
params["fbname"] = user.FBName
mu := memUser(c, user.Id)
if mu.Name == "" {
tr := transport(user)
tr.Transport = &urlfetch.Transport{Context: c}
p, _ := plus.New(tr.Client())
person, err := p.People.Get(user.Id).Do()
if err == nil {
mu.Image = person.Image.Url
mu.Name = person.DisplayName
memUserSave(c, user.Id, mu)
}
}
params["googleimg"] = mu.Image
params["googlename"] = mu.Name
}
if err := templates.ExecuteTemplate(w, "home", params); err != nil {
serveError(c, w, err)
return
}
}
func syncHandler(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
q := datastore.NewQuery("User").
Filter("Active=", true)
for t := q.Run(c); ; {
var u User
_, err := t.Next(&u)
if err == datastore.Done {
break
}
if err != nil {
serveError(c, w, err)
return
}
syncStream(w, r, &u)
}
// schedule next run
}
func syncStream(w http.ResponseWriter, r *http.Request, user *User) {
c := appengine.NewContext(r)
tr := transport(*user)
tr.Transport = &urlfetch.Transport{Context: c}
httpClient := tr.Client()
p, err := plus.New(httpClient)
if err != nil {
serveError(c, w, err)
return
}
latest := user.GoogleLatest
c.Debugf("syncStream: fetching for %s\n", user.Id)
activityFeed, err := p.Activities.List(user.Id, "public").MaxResults(5).Do()
if err != nil {
c.Debugf("syncStream: activity fetch failed for %s. Err: %v\n", user.Id, err)
return
}
for _, act := range activityFeed.Items {
published, _ := time.Parse(time.RFC3339, act.Published)
nPub := published.UnixNano()
c.Debugf("syncStream: user: %s, nPub: %v, Latest: %v\n", user.Id, nPub, user.GoogleLatest)
baba, _ := json.Marshal(act)
c.Debugf("\n\nActivity: %s\n\n", baba)
if nPub > user.GoogleLatest {
if user.HasFacebook() {
publishActivityToFacebook(w, r, act, user)
}
if user.HasTwitter() {
publishActivityToTwitter(w, r, act, user)
}
}
if nPub > latest {
latest = nPub
}
}
if latest > user.GoogleLatest ||
user.GoogleAccessToken != tr.Token.AccessToken ||
user.GoogleRefreshToken != tr.Token.RefreshToken ||
user.GoogleTokenExpiry != tr.Token.Expiry.UnixNano() {
user.GoogleLatest = latest
user.GoogleAccessToken = tr.Token.AccessToken
user.GoogleRefreshToken = tr.Token.RefreshToken
user.GoogleTokenExpiry = tr.Token.Expiry.UnixNano()
saveUser(r, user)
}
}
func deleteAccountHandler(w http.ResponseWriter, r *http.Request) {
user, err := loadUserCookie(r)
if err != nil {
http.Redirect(w, r, "/", http.StatusNotFound)
return
}
c := appengine.NewContext(r)
key := datastore.NewKey(c, "User", user.Id, 0, nil)
datastore.Delete(c, key)
memUserDelete(c, user.Id)
memcache.Delete(c, "user"+user.Id)
http.SetCookie(w, &http.Cookie{Name: "userId", Value: "", Domain: appConfig.AppDomain, Path: "/", MaxAge: -1})
http.Redirect(w, r, "/", http.StatusFound)
}
func deleteTwitterHandler(w http.ResponseWriter, r *http.Request) {
user, err := loadUserCookie(r)
if err == nil {
user.DisableTwitter()
saveUser(r, &user)
http.Redirect(w, r, "/", http.StatusFound)
}
http.Redirect(w, r, "/", http.StatusNotFound)
}
func deleteFacebookHandler(w http.ResponseWriter, r *http.Request) {
user, err := loadUserCookie(r)
if err != nil {
http.Redirect(w, r, "/", http.StatusNotFound)
}
user.DisableFacebook()
saveUser(r, &user)
http.Redirect(w, r, "/", http.StatusFound)
}