This repository has been archived by the owner on Apr 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·257 lines (216 loc) · 7.52 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
"""
main module that contains all the url handlers
"""
import os, re, base64, logging
from django.utils import simplejson as json
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
from google.appengine.api import users as google_users
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from xml.dom import minidom
from incoming_email import IncomingEmailHandler
from models import Users
from models import Comments
from util import StringUtil
from util import ModelsUtil
class MainHandler(webapp.RequestHandler):
""" handler for / """
def get(self):
""" this handler supports http get """
data = {}
if google_users.get_current_user():
google_user = google_users.get_current_user()
user = db.Query(Users).filter('user_id =', google_user.user_id()).get()
if user is not None:
data['token'] = user.pt_token
data['havetoken'] = user.pt_token is not None
data['has_signature'] = len(user.signatures) > 0
data['has_email'] = user.pt_emails is not None and len(user.pt_emails) > 0
if user.pt_emails is not None:
data['emails'] = user.pt_emails
if len(user.signatures) > 0:
# convert \n to br so they display correctly
sigs = []
count = 0
for signature in user.signatures:
sig = {}
sig['index'] = count
sig['text'] = StringUtil.nl2br(signature)
sig['is_html'] = re.search('<.*>', signature) is not None
sigs.append(sig)
count = count + 1
data['signatures'] = sigs
comment = db.Query(Comments).filter('user_id =', google_user.user_id()).get()
data['has_comments'] = comment
data['url'] = google_users.create_logout_url(self.request.uri)
data['user'] = google_users.get_current_user()
else:
data['url'] = google_users.create_login_url(self.request.uri)
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, data))
class GetToken(webapp.RequestHandler):
"""
Pulls the user's Pivotal Tracker Token from the API.
url: /get-token
"""
def post(self):
""" this handler supports http post """
google_user = google_users.get_current_user()
user = db.Query(Users).filter('user_id =', google_user.user_id()).get()
if user is None:
user = Users(user_id = google_user.user_id(), email = google_user.email())
username = self.request.get('username')
password = self.request.get('password')
token = self.request.get('token', None)
if token == None:
url = 'https://www.pivotaltracker.com/services/v3/tokens/active'
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
result = urlfetch.fetch(url=url,
headers={"Authorization": authheader})
if result.status_code == 200:
token_dom = minidom.parseString(result.content)
for node in token_dom.getElementsByTagName('token'):
token = node.getElementsByTagName('guid')[0].firstChild.data
elif result.status_code == 401:
self.response.out.write("Invalid Username or Password")
self.response.set_status(401)
return
else:
self.response.out.write("Error getting token. Please try again later")
self.response.set_status(400)
return
elif token.strip() == '':
self.response.out.write("Token is required.")
self.response.set_status(400)
return
user.pt_username = username
user.pt_token = token
db.put(user)
self.response.out.write(token)
class RemoveToken(webapp.RequestHandler):
"""
Removes a Pivotal Tracker token for the user.
url: /remove-token
"""
def post(self):
""" this handler supports http post """
google_user = google_users.get_current_user()
user = db.Query(Users).filter('user_id =', google_user.user_id()).get()
if user is not None:
user.pt_token = None
db.put(user)
else:
self.response.out.write("Error getting user.")
self.response.set_status(400)
class SaveEmail(webapp.RequestHandler):
"""
Saves a new email for a user. HTTP400 if no email provided or email already exists.
url: /save-email
"""
def post(self):
""" this handler supports http post """
google_user = google_users.get_current_user()
user = db.Query(Users).filter('user_id =', google_user.user_id()).get()
if user is None:
user = Users(user_id = google_user.user_id(), email = google_user.email())
emails = self.request.get('email').lower()
emails = emails.split(',')
if len(emails) == 0:
self.response.set_status(400)
self.response.out.write('Email is required.')
return
added_one = False
for email in emails:
if email.strip() == '':
continue
try:
user.pt_emails.index(email)
except ValueError:
added_one = True
user.pt_emails.append(email)
if added_one == False:
self.response.set_status(400)
self.response.out.write('Email is required.')
return
db.put(user)
self.response.out.write(json.dumps(user.pt_emails))
class RemoveEmail(webapp.RequestHandler):
"""
Removes an email.
url: /remove-email
"""
def post(self):
""" this handler supports http post """
google_user = google_users.get_current_user()
user = db.Query(Users).filter('user_id =', google_user.user_id()).get()
if user is None:
user = Users(user_id = google_user.user_id(), email = google_user.email())
email = self.request.get('email')
email = email.lower()
user.pt_emails.remove(email)
db.put(user)
self.response.out.write(json.dumps(user.pt_emails))
class SaveSignature(webapp.RequestHandler):
"""
Saves a new signature for a user. HTTP400 if the signature already exists.
Returns all signatures on success.
url: /save-signature
"""
def post(self):
""" this handler supports http post """
signature = self.request.get('signature').strip()
if signature == '':
self.response.set_status(400)
self.response.out.write('Signature is required.')
else:
google_user = google_users.get_current_user()
user = db.Query(Users).filter('user_id =', google_user.user_id()).get()
if user is None:
user = Users(user_id = google_user.user_id(), email = google_user.email())
(code, message) = ModelsUtil.add_signature(user, signature)
self.response.set_status(code)
self.response.out.write(message)
class RemoveSignature(webapp.RequestHandler):
"""
Removes a signature.
url: /remove-signature
"""
def post(self):
""" this handler supports http post """
google_user = google_users.get_current_user()
user = db.Query(Users).filter('user_id =', google_user.user_id()).get()
if user is None:
user = Users(user_id = google_user.user_id(), email = google_user.email())
index = self.request.get('signature')
user.signatures.pop(int(index))
db.put(user)
sigs = []
for signature in user.signatures:
sigs.append(StringUtil.nl2br(signature))
self.response.out.write(json.dumps(sigs))
class UpdateSchema(webapp.RequestHandler):
"""
Ensures that the schema of DataStore elements has all the necessary fields.
url: /update-schema
"""
def get(self):
""" this handler supports http get """
def main():
""" Sets up the url handler mapping. """
application = webapp.WSGIApplication([('/', MainHandler),
('/get-token', GetToken),
('/remove-token', RemoveToken),
('/save-email', SaveEmail),
('/remove-email', RemoveEmail),
('/save-signature', SaveSignature),
('/remove-signature', RemoveSignature),
('/update-schema', UpdateSchema),
IncomingEmailHandler.mapping()
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()