forked from nathancrandall/cecilia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads.py
283 lines (257 loc) · 13.1 KB
/
threads.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
#!/usr/bin/env python
import database
import re
import urllib
from google.appengine.api import urlfetch
import json
cgi = database.cgi
db = database.db
class MainHandler(database.webapp2.RequestHandler):
def get(self):
user = database.users.get_current_user()
out_unread_thread = []
in_unread_thread = []
push = False
#ew, (n+1) queries
if database.get_current_li():
token = database.get_current_li().create_xsrf_token()
sent_threads = db.GqlQuery("SELECT * FROM Thread WHERE created_by_id = :1 ORDER BY created_at DESC", user.user_id())
for thread in sent_threads:
children = db.GqlQuery("SELECT * FROM Message WHERE ANCESTOR is :1", thread.key())
for child in children:
if child.recipient_id == user.user_id() and child.read == False:
push = True
break
else:
push = False
out_unread_thread.append(True) if push else out_unread_thread.append(False)
push = False
in_threads = db.GqlQuery("SELECT * FROM Thread WHERE recipient_id = :1 ORDER BY created_at DESC", user.user_id())
for thread in in_threads:
children = db.GqlQuery("SELECT * FROM Message WHERE ANCESTOR is :1", thread.key())
for child in children:
if child.recipient_id == user.user_id() and child.read == False:
push = True
break
else:
push = False
in_unread_thread.append(True) if push else in_unread_thread.append(False)
database.render_template(self, 'threads/index.html', {'sent_threads': sent_threads, 'in_threads': in_threads, 'out_unread_thread': out_unread_thread,
'in_unread_thread': in_unread_thread, 'xsrf_token': token})
else:
self.redirect('/')
class ViewHandler(database.webapp2.RequestHandler):
def get(self):
user = database.users.get_current_user()
if user and database.get_current_li().verify_xsrf_token(self):
token = database.get_current_li().create_xsrf_token()
thread_key = db.Key.from_path('Thread', int(self.request.get('thread_id')))
thread = db.get(thread_key)
if thread.recipient_id == user.user_id() or thread.created_by_id == user.user_id():
children = db.GqlQuery("SELECT * FROM Message WHERE ANCESTOR is :1", thread_key)
for child in children:
if child.recipient_id == user.user_id():
child.read = True
child.put()
database.render_template(self, 'threads/view_thread.html', {'thread': thread, 'children': children, 'xsrf_token' : token})
else:
self.redirect('/')
else:
self.redirect('/')
class NewHandler(database.webapp2.RequestHandler):
def get(self):
user = database.users.get_current_user()
if user:
lis = db.GqlQuery("SELECT * FROM LoginInformation WHERE user_id != :1", user.user_id())
token = database.get_current_li().create_xsrf_token()
item = None
if self.request.get("about"):
item = db.get(db.Key.from_path('Item', (int(cgi.escape(self.request.get('about'))))))
bad_code = ",".join(["{id:\""+str(li.user_id)+"\", name: \""+li.get_display_name()+"\"}" for li in lis if li.get_display_name()])
database.render_template(self, 'threads/new_thread.html', {'item': item, 'lis': lis, 'list':bad_code, 'xsrf_token' : token})
else:
self.redirect('/')
class NewRemoteHandler(database.webapp2.RequestHandler):
def get(self):
user = database.users.get_current_user()
if user:
token = database.get_current_li().create_xsrf_token()
about = cgi.escape(self.request.get('about'))
partner_id = cgi.escape(self.request.get('partner_id'))
remote_user_id = cgi.escape(self.request.get('remote_user_id'))
remote_username = cgi.escape(self.request.get('remote_username'))
item_title = cgi.escape(self.request.get('item_title'))
partner = database.db.get(db.Key.from_path('TrustedPartner', int(cgi.escape(self.request.get('partner_id')))))
if partner:
database.render_template(self, 'threads/new_remote_thread.html', {'about': about, 'partner_id': partner_id, 'remote_user_id':remote_user_id, 'remote_username' : remote_username, 'xsrf_token' : token, 'item_title' : item_title})
else:
self.redirect("/")
else:
self.redirect('/')
class SaveHandler(database.webapp2.RequestHandler):
def post(self):
user = database.users.get_current_user()
if user and database.get_current_li().verify_xsrf_token(self):
item = None
if self.request.get("item_id"):
item_id = int(cgi.escape(self.request.get('item_id')))
item = db.get(db.Key.from_path('Item', item_id))
recipients = [item.created_by_id]
else:
recipients = cgi.escape(self.request.get("recipients"))
#WOAH! Rejects everything but numbers, then maps to integers
recipients = [y for y in [re.sub("[^0-9]", "", x) for x in recipients.split("||")] if len(y) > 0]
recipients = db.GqlQuery("SELECT * FROM LoginInformation WHERE user_id IN :1", recipients)
recipients = [r for r in recipients if r != user]
if len(recipients) > 0:
for recipient in recipients:
database.logging.info("HERE");
thread = database.Thread(created_by_id=user.user_id())
if item:
thread.item_details = 'This is about your item: "' + item.title + '" that you posted for $' + str(item.price)
thread.title = cgi.escape(self.request.get('title'))
thread.external_conversation = False
thread.recipient_id = recipient.user_id
thread.put()
database.logging.info("Created a new thread. Info:\nThreadID: %s\nCreatedBy: %s\nTitle: %s\nSentTo: %s\nCreatedAt: %s",
thread.key().id(), thread.created_by_id, thread.title, thread.recipient_id, thread.created_at)
message = database.Message(parent=thread)
message.body = cgi.escape(self.request.get('message'))
message.created_by_id = thread.created_by_id
message.recipient_id = thread.recipient_id
message.read = False
message.put()
database.logging.info("Created a new message under thread #%s\nSentBy: %s\nSentTo: %s\nCreatedAt: %s",
message.parent().key().id(), message.created_by_id, message.recipient_id, message.created_at)
self.redirect('/threads/')
else:
self.redirect('/')
class CreateRemoteThreadHandler(database.webapp2.RequestHandler):
def post(self):
user = database.users.get_current_user()
current_li = database.get_current_li()
if user and current_li.verify_xsrf_token(self):
database.logging.info("XSRF verified")
item_title = cgi.escape(self.request.get('item_title'))
item_id = cgi.escape(self.request.get('item_id'))
message = cgi.escape(self.request.get('message'))
thread = database.Thread(created_by_id=user.user_id())
thread.item_details = 'This is about your item: "' + item_title + '" that you posted'
thread.title = cgi.escape(self.request.get('title'))
thread.external_conversation = True
thread.recipient_id = cgi.escape(self.request.get('remote_user_id'))
thread.partner_id = cgi.escape(self.request.get('partner_id'))
thread.item_id = item_id
thread.put()
partner = database.db.get(db.Key.from_path('TrustedPartner', int(cgi.escape(self.request.get('partner_id')))))
if partner:
params = {
"auth_token" : partner.foreign_auth_token,
"item_id" : item_id,
"source_user_id" : thread.created_by_id,
"source_user_name" : current_li.get_public_display_name(),
"destination_user_id" : thread.recipient_id,
"subject" : thread.title,
"message" : message,
"source_conversation_id" : thread.key().id(),
"destination_conversation_id" : "-1"
}
database.logging.info("HERE! " + str(params))
base_url = partner.base_url
url = base_url + "/webservices/send_message"
try:
database.logging.info("Making request to " + url)
result = urlfetch.fetch(url=url, payload=urllib.urlencode(params), method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'})
database.logging.info("Result : " + result.content)
j_resp = json.loads(result.content)
database.logging.info("result[success]=" + str(j_resp["success"]))
if not(j_resp["success"]):
database.logging.info("Error with result: " + result)
thread.delete()
self.redirect("/")
foreign_conversation_id = cgi.escape(j_resp["conversation_id"])
thread.external_conversation_id = foreign_conversation_id
thread.put()
message = database.Message(parent=thread)
message.body = cgi.escape(self.request.get('message'))
message.created_by_id = thread.created_by_id
message.recipient_id = thread.recipient_id
message.read = False
message.put()
database.logging.info("Created a new message under thread #%s\nSentBy: %s\nSentTo: %s\nCreatedAt: %s",
message.parent().key().id(), message.created_by_id, message.recipient_id, message.created_at)
self.redirect('/threads/')
except Exception, e:
database.logging.info("Error : %s", str(e))
thread.delete()
self.redirect("/")
else:
self.redirect("/")
else:
self.redirect('/')
class SaveMessageHandler(database.webapp2.RequestHandler):
def post(self):
user = database.users.get_current_user()
thread_key = db.Key.from_path('Thread', int(self.request.get('thread_id')))
thread = db.get(thread_key)
current_li = database.get_current_li()
if user and database.get_current_li().verify_xsrf_token(self) and (thread.recipient_id == user.user_id() or thread.created_by_id == user.user_id()):
if thread.external_conversation:
#its an external conversation, so we should send the message out to the other users API
message = database.Message(parent=thread)
message.body = cgi.escape(self.request.get('message'))
message.created_by_id = user.user_id()
message.recipient_id = thread.recipient_id if user.user_id() == thread.created_by_id else thread.created_by_id
message.read = False
partner = database.db.get(db.Key.from_path('TrustedPartner', int(thread.partner_id)))
if not(partner):
database.logging.info("No partner on external thread")
self.redirect("/")
return
destination_user_id = thread.recipient_id
if destination_user_id == user.user_id():
destination_user_id = thread.created_by_id
pass
params = {
"auth_token" : partner.foreign_auth_token,
"item_id" : thread.item_id,
"source_user_id" : user.user_id(),
"source_user_name" : current_li.get_public_display_name(),
"destination_user_id" : destination_user_id,
"subject" : thread.title,
"message" : message.body,
"source_conversation_id" : thread.key().id(),
"destination_conversation_id" : thread.external_conversation_id
}
database.logging.info("params: " + json.dumps(params))
base_url = partner.base_url
url = base_url + "/webservices/send_message"
try:
result = urlfetch.fetch(url=url, payload=urllib.urlencode(params), method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'})
database.logging.info("Result : " + result.content)
j_resp = json.loads(result.content)
database.logging.info("result[success]=" + str(j_resp["success"]))
if not(j_resp["success"]):
database.logging.info("Error with result: " + result)
self.redirect("/")
message.put()
database.logging.info("Created a new message under thread #%s\nSentBy: %s\nSentTo: %s\nCreatedAt: %s",
message.parent().key().id(), message.created_by_id, message.recipient_id, message.created_at)
except Exception, e:
database.logging.info("Error : %s", str(e))
self.redirect("/")
else:
message = database.Message(parent=thread)
message.body = cgi.escape(self.request.get('message'))
message.created_by_id = user.user_id()
message.recipient_id = thread.recipient_id if user.user_id() == thread.created_by_id else thread.created_by_id
message.read = False
message.put()
database.logging.info("Created a new message under thread #%s\nSentBy: %s\nSentTo: %s\nCreatedAt: %s",
message.parent().key().id(), message.created_by_id, message.recipient_id, message.created_at)
self.redirect('/threads/view_thread?thread_id='+self.request.get('thread_id'))
return
else:
self.redirect('/')
app = database.webapp2.WSGIApplication([('/threads/', MainHandler), ('/threads/view_thread', ViewHandler),
('/threads/new_thread', NewHandler), ('/threads/new_remote_thread', NewRemoteHandler), ('/threads/save_thread', SaveHandler), ('/threads/create_remote_thread', CreateRemoteThreadHandler), ('/threads/save_message', SaveMessageHandler)], debug=True)