-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·309 lines (266 loc) · 12.6 KB
/
main.py
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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.
#
import datetime
import httplib
import sys
import logging
import oauth
import random
import time
from apiclient.discovery import build
import os
import hashlib
from weibopy.api import API
from weibopy.auth import OAuthHandler
from weibopy.error import WeibopError
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp import util
from google.appengine.api import memcache
from abstract import BaseHandler
# fake urls for the test server (matches ones in server.py)
SERVER = 'api.t.sina.com.cn'
ACCESS_TOKEN_URL = 'http://'+SERVER+'/oauth/access_token'
AUTHORIZATION_URL = 'http://'+SERVER+'/oauth/authorize'
CALLBACK_URL = os.environ['HTTP_HOST']
CONSUMER_KEY = '811259784'
CONSUMER_SECRET = 'bb501362af3d370773d5dba442cf773e'
PORT = 80
REQUEST_TOKEN_URL = 'http://'+SERVER+'/oauth/request_token'
RESOURCE_URL = os.environ['HTTP_HOST']
PAGE_SIZE=10
# Set cookie. Expiration is 2 days long.
expires = datetime.datetime.now() + datetime.timedelta(days=2)
expires_rfc822 = expires.strftime('%a, %d %b %Y %H:%M:%S GMT')
cookie = "; expires=%s; path=/" % expires_rfc822
class SimpleOAuthClient(oauth.OAuthClient):
def __init__(self, server, port=httplib.HTTP_PORT, request_token_url='',
access_token_url='', authorization_url=''):
self.server = server
self.port = port
self.request_token_url = request_token_url
self.access_token_url = access_token_url
self.authorization_url = authorization_url
self.connection = httplib.HTTPConnection("%s:%d" % (self.server,
self.port))
def fetch_request_token(self, oauth_request):
# via headers
# -> OAuthToken
self.connection.request(oauth_request.http_method,
self.request_token_url,
headers=oauth_request.to_header())
response = self.connection.getresponse()
return oauth.OAuthToken.from_string(response.read())
def fetch_access_token(self, oauth_request):
# via headers
# -> OAuthToken
self.connection.request(oauth_request.http_method,
self.access_token_url,
headers=oauth_request.to_header())
response = self.connection.getresponse()
return oauth.OAuthToken.from_string(response.read())
def authorize_token(self, oauth_request):
# via url
# -> typically just some okay response
self.connection.request(oauth_request.http_method,
oauth_request.to_url())
response = self.connection.getresponse()
return response.read()
class SinaOauthPhaseOne(webapp.RequestHandler):
def get(self):
# setup/initial
client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
ACCESS_TOKEN_URL, AUTHORIZATION_URL)
consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT()
signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
# get request token
# print '* Obtain a request token ...'
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer,
callback=CALLBACK_URL,
http_url=client.request_token_url)
oauth_request.sign_request(signature_method_plaintext, consumer, None)
#print 'REQUEST (via headers)'
#print 'parameters: %s' % str(oauth_request.parameters)
cid = str(int(random.uniform(0,sys.maxint)))
token = client.fetch_request_token(oauth_request)
memcache.set("PK_"+cid, token.to_string())
PHASETWO_CALLBACK_URL = 'http://'+os.environ['HTTP_HOST']+'/oauth_authorized?id=' + cid
#print '* Authorize the request token ...'
oauth_request = oauth.OAuthRequest.from_token_and_callback(
token=token,
callback=PHASETWO_CALLBACK_URL,
http_url=client.authorization_url)
#??? response = client.authorize_token(oauth_request)
#??? self.redirect(response)
# OR USING BELOW LINES instead ?
oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
self.redirect(oauth_request.to_url())
class SinaOauthPhaseTwo(webapp.RequestHandler):
# get access token
def get(self):
verifier = self.request.get('oauth_verifier')
logging.info('verify id = %s' % verifier)
signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
# Get token - key and secret from memcache that we set on SinaOauthPhaseOne
tokenstr = memcache.get("PK_"+self.request.get('id'))
memcache.delete("PK_"+self.request.get('id'))
token = oauth.OAuthToken.from_string(tokenstr)
consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
ACCESS_TOKEN_URL, AUTHORIZATION_URL)
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer,
token=token, verifier=verifier,
http_url=client.access_token_url)
oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
# Finally get access_token after verifier is matched.
access_token = client.fetch_access_token(oauth_request)
logging.info('Sina Authorized access_token = %s' % access_token)
# Set cookie into browser in case for further use.
self.response.headers.add_header('Set-Cookie',
'oauth_key=' + access_token.key + cookie)
self.response.headers.add_header('Set-Cookie',
'oauth_secret=' + access_token.secret + cookie)
# Call Sina weibopy API auth.OAuthHandler() and set access_token to
# fetch access_resource aka:user resource.
auth_access_resource = OAuthHandler(
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET)
auth_access_resource.set_access_token(access_token.key,
access_token.secret)
# API() inherits auth_access_resource return.
api = API(auth_access_resource)
# I call api.verify_credentials instead of use auth.OAuthHandler.get_username
username = api.verify_credentials()
if username:
self.username = username.screen_name
self.response.headers.add_header('Set-Cookie',
'sina_username=' + self.username + cookie)
logging.info('Sina username: %s' % self.username)
else:
logging.info('NO SINA USER')
self.redirect('/')
class LogoutHandler(webapp.RequestHandler):
def get(self):
expires_rfc822 = time.time() - 86400
cookie = "; expires=%s; path=/" % expires_rfc822
self.response.headers.add_header('Set-Cookie',
'sina_username=' + "" + cookie)
self.redirect("/")
class Translator(object):
@classmethod
def translate(clz,text,source='zh',target='en'):
ahash = hashlib.sha224(text.encode('utf-8')).hexdigest()
trans = memcache.get(ahash)
if trans is None:
logging.info('MISS %s',ahash)
service = build('translate', 'v2',
developerKey='AIzaSyDBy_hjgHTqJhILOrlTfb_3rTYYgM6Pypc')
data = (service.translations().list(
source=source,
target=target,
q=[text]
).execute())
trans = data['translations'][0]['translatedText']
memcache.add(ahash,trans,60*60*24*7)
else:
logging.info('HIT %s',ahash)
return trans
class TranslateHandler(BaseHandler):
def post(self):
text = self.request.get('text')
source,target = self.request.get('lang').split("|")
self.response.out.write(Translator.translate(text,source=source,target=target))
class SinaHandler(BaseHandler):
api = None
sina_username = None
def auth(self):
# Check Sina user logged in or not.
self.sina_username = self.request.cookies.get("sina_username")
if self.sina_username:
oauth_key = self.request.cookies.get("oauth_key")
oauth_secret = self.request.cookies.get("oauth_secret")
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.setToken(oauth_key, oauth_secret)
self.api = API(auth)
return True
return False
class MainPage(SinaHandler):
def get(self):
if self.auth():
api = self.api
view = self.request.get('view')
timeline = None
if view=='mine':
timeline = api.user_timeline(count=PAGE_SIZE, page=1)
elif view=='mentions':
timeline = api.mentions(count=PAGE_SIZE, page=1)
elif view=='comments':
timeline = api.comments_timeline(count=PAGE_SIZE, page=1)
else:
timeline = api.friends_timeline(count=PAGE_SIZE, page=1)
friendids = api.friends_ids().ids
for status in timeline:
status.me = status.user.screen_name==self.sina_username
status.text_en = Translator.translate(status.text)
status.following_author = status.user.id in friendids
status.created_at_iso = "%s+0800" % (str(status.created_at).replace(" ","T"))
if hasattr(status,'retweeted_status'):
status.retweeted_text_en = Translator.translate(status.retweeted_status.text)
self.render_template("index.html",{"timeline":timeline,"username":self.sina_username})
else:
self.response.out.write("<a href='/oauth/sina_login'>Login with Sina</a>")
class FollowHandler(SinaHandler):
def get(self):
id = int(self.request.get("id"))
if self.auth():
try:
self.api.create_friendship(user_id=id)
self.response.out.write('{"status":"ok"}')
except WeibopError:
self.response.out.write('{"status":"error", "message":"already following this user"}')
else:
self.response.out.write('{"status":"error", "message":"not signed in"}')
class ComposeHandler(SinaHandler):
def post(self):
tweet = self.request.get("text")
sina_username = self.request.cookies.get("sina_username")
if self.auth():
self.api.update_status(tweet)
self.redirect("/sent")
else:
self.response.out.write("<a href='/oauth/sina_login'>Login with Sina</a>")
class SentHandler(BaseHandler):
def get(self):
self.render_template("sent.html",{})
def main():
application = webapp.WSGIApplication(
[('/', MainPage),
('/follow',FollowHandler),
('/oauth/sina_login', SinaOauthPhaseOne),
('/oauth_authorized', SinaOauthPhaseTwo),
('/oauth/sina_logout', LogoutHandler),
('/translate',TranslateHandler),
('/compose',ComposeHandler),
('/sent',SentHandler),
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()