This repository was archived by the owner on Oct 31, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.py
211 lines (169 loc) · 7.18 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
import base64
import cgi
import logging
from django.utils import simplejson as json
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import oauthlib.oauth
import yahoo.application
import yahoo.oauth
from bookmarks import parse_bookmarks_xml
import oauthkeys
CALLBACK_URL = 'http://delicious-export.appspot.com/oauth-callback'
class StoredToken(db.Model):
token_key = db.StringProperty(required=True)
token = db.StringProperty(required=True)
class BaseHandler(webapp.RequestHandler):
def _handle_error(self, url_fetch_result):
def debug(str):
self.response.out.write(str + '\n')
logging.debug(str)
self.response.set_status(500)
self.response.headers['Content-Type'] = 'text/html'
debug('<h1>Received an error from the Delicious API</h1>')
debug('<b>Status code:</b> %d<br>' %
url_fetch_result.status_code)
debug('<b>Headers:</b><ul>')
for header, value in url_fetch_result.headers.items():
debug('<li><b>%s:</b> %s</li>' %
(cgi.escape(header), cgi.escape(value)))
debug('</ul>')
debug('<b>Body:</b> <pre>%s</pre>' %
cgi.escape(url_fetch_result.content))
def _output_export_form(self, bookmarks):
self.response.headers['Content-Type'] = 'text/html'
out = self.response.out
out.write('<script type="text/javascript" src="/main.js"></script>')
out.write('''
<h1>Uploading...</h1>
<form id="upload-form"
action="https://www.google.com/bookmarks/mark?op=upload"
method="POST"
accept-charset="utf-8">
<input type="hidden" name="" id="data">
</form>
''')
out.write('<script type="text/javascript">jsonCallback(')
# Mimic the "raw" JSON output produced by the Delicious PAI
bookmarks_json = []
for bookmark in bookmarks:
tags = list(bookmark.tags)
if bookmark.is_private:
tags.append('delicious-private')
tags.append('delicious-export')
bookmark_json = {
'u': bookmark.href,
'd': bookmark.description,
'e': bookmark.extended,
't': tags
}
bookmarks_json.append(bookmark_json)
out.write(json.dumps(bookmarks_json, indent=2, ensure_ascii=True))
out.write(')</script>')
class OAuthHandler(BaseHandler):
def _create_oauthapp(self):
return yahoo.application.OAuthApplication(
oauthkeys.CONSUMER_KEY,
oauthkeys.CONSUMER_SECRET,
oauthkeys.APPLICATION_ID,
CALLBACK_URL)
def _handle_xml_export(self, oauthapp):
url = 'http://api.del.icio.us/v2/posts/all'
signing_request = oauthlib.oauth.OAuthRequest.from_consumer_and_token(
oauthapp.consumer,
token=oauthapp.token,
http_method='GET',
http_url=url)
signing_request.sign_request(
oauthapp.signature_method_hmac_sha1, oauthapp.consumer, oauthapp.token)
headers = signing_request.to_header('yahooapis.com')
result = urlfetch.fetch(
url=url,
method=urlfetch.GET,
deadline=60,
headers=headers)
if result.status_code != 200:
self._handle_error(result)
return
bookmarks = parse_bookmarks_xml(result.content)
self._output_export_form(bookmarks)
class RequestAuthorizationHandler(OAuthHandler):
def get(self):
oauthapp = self._create_oauthapp()
request_token = oauthapp.get_request_token(CALLBACK_URL)
stored_token = StoredToken(
token_key=request_token.key, token=request_token.to_string())
stored_token.put()
self.redirect(oauthapp.get_authorization_url(request_token))
class OAuthCallbackHandler(OAuthHandler):
def get(self):
oauthapp = self._create_oauthapp()
stored_tokens = db.GqlQuery(
'SELECT * FROM StoredToken WHERE token_key = :1',
self.request.get('oauth_token')).fetch(2)
if len(stored_tokens) != 1:
self.error(400)
return
stored_token = stored_tokens[0]
request_token = yahoo.oauth.RequestToken.from_string(stored_token.token)
verifier = self.request.get('oauth_verifier')
access_token = oauthapp.get_access_token(request_token, verifier)
logging.debug('access_token: %s' % access_token.to_string())
oauthapp.token = access_token
self._handle_xml_export(oauthapp)
class BasicAuthUploadHandler(BaseHandler):
def post(self):
username = self.request.get('username')
password = self.request.get('password')
logging.debug('Exporting bookmarks using Basic Auth for %s' % username)
encoded_credentials = base64.encodestring(
'%s:%s' % (username, password))[:-1]
# The v1 API seems to be more prone to taking longer to respond (or is
# it that v1 users tend to have more bookmarks?), so to avoid hitting
# the 10 second HTTP urlfetch timeout limit, we chunk the data that is
# requested
chunk_start = 0
chunk_size = 500
bookmarks = []
while True:
logging.debug(' Fetching chunk from %d' % chunk_start)
result = urlfetch.fetch(
url='https://api.del.icio.us/v1/posts/all?results=%d&start=%d' %
(chunk_size, chunk_start),
method=urlfetch.GET,
deadline=60,
headers={'Authorization': 'Basic %s' % encoded_credentials})
if result.status_code != 200:
self._handle_error(result)
return
chunk_bookmarks = parse_bookmarks_xml(result.content)
bookmarks.extend(chunk_bookmarks)
logging.debug(' Got %d bookmarks in chunk' % len(chunk_bookmarks))
if len(chunk_bookmarks) != chunk_size:
break
chunk_start += chunk_size
self._output_export_form(bookmarks)
class DebugTokenHandler(OAuthHandler):
def post(self):
oauthapp = self._create_oauthapp()
access_token = yahoo.oauth.AccessToken.from_string(
self.request.get('access-token'))
oauthapp.token = access_token
self._handle_xml_export(oauthapp)
class FaviconHandler(webapp.RequestHandler):
def get(self):
self.redirect('http://persistent.info/favicon.ico')
def main():
application = webapp.WSGIApplication([
('/request-authorization', RequestAuthorizationHandler),
('/oauth-callback', OAuthCallbackHandler),
('/debug-token', DebugTokenHandler),
('/basic-auth', BasicAuthUploadHandler),
('/favicon.ico', FaviconHandler),
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()