-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparley.py
443 lines (376 loc) · 15.3 KB
/
parley.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import tornado.httpserver
import tornado.ioloop
import tornado.web
import datetime
import pymongo
import json
import logging
import urllib
logging.basicConfig(level="INFO")
from tornado.web import HTTPError
from dictshield.document import Document
from dictshield.fields.mongo import ObjectIdField
from dictshield.fields import (StringField,
BooleanField,
EmailField,
DateTimeField)
#config = json.load(open("config.json"))
class Signature(Document):
first_name = StringField(max_length=200, required=True)
last_name = StringField(max_length=200, required=True)
organisation = StringField(max_length=200)
email = EmailField(max_length=200, required=True)
comment = StringField(max_length=140)
is_australian = BooleanField(required=True)
pid = ObjectIdField(required=True)
signed_on = DateTimeField(required=True)
class Petition(Document):
sid = StringField(max_length=4096)
title = StringField(max_length=4096)
message = StringField(max_length=4096)
disabled = BooleanField()
hashtag = StringField(max_length=20)
url = StringField(max_length=4096)
twitter_msg = StringField(max_length=140)
def get_fields(shield):
x = shield.to_python()
for k in shield._fields.keys():
if k not in x:
x[k] = ""
del x["_types"]
del x["_cls"]
return x
def create_html5_page(title, head=[], body=[]):
doc = """<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>{title}</title>{head}
</head>
<body>{body}</body>
</html>"""
return doc.format(
title=title,
head="\n" + "\n".join(head),
body="\n".join(body)
)
def create_table(table, headers=None):
x = []
for row in table:
x.append("<td>" + "</td><td>".join(row) + "</td>")
tbody = "<tbody><tr>" + "</tr><tr>".join(x) + "</tr></tbody>"
thead = ""
if headers:
thead = "<thead><th>" + "</th><th>".join(headers) + "</th></thead>"
return "<table>" + thead + tbody + "</table>"
def create_css():
return """<style type="text/css">
body {
font-family: sans-serif;
background-color: #ccc;
}
td {
vertical-align: top;
}
.signature-form, .share-box {
float: right;
clear: right;
border: 1px solid gray;
background-color: #eee;
margin-left: 6px;
margin-bottom: 6px;
padding: 6px;
width: 280px;
}
.share-box iframe {
float: left;
padding-bottom: 4px;
}
.header {
background-color: white;
border: 1px solid gray;
max-width: 800px;
padding: 6px;
}
.header td {
vertical-align: middle;
}
.header h1 {
text-align: center;
}
.header li {
margin-bottom: 0.2em;
}
.signature-form h2 {
text-align: center;
}
.signature-form .error {
color: red;
}
.signature-form .error > input {
background-color: pink;
}
.signature-form label {
display: block;
}
.signature-form input[type='text'],
.signature-form input[type='email'],
.signature-form input[type='submit'],
.signature-form textarea {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
margin-bottom: 6px;
}
.signature-form table {
width: 100%;
}
.signature-form textarea {
resize: vertical;
min-height: 60px;
}
.signature-form .radio {
display: inline-block; *display: inline; zoom: 1;
width: 52px;
padding-left: 10px;
}
</style>"""
def create_share_box(sid, msg, hashtag, url):
return """<div class='share-box'>
<a href="https://twitter.com/piratepartyau" class="twitter-follow-button" data-show-count="false">Follow @piratepartyau</a>
<script>!function(d,s,id){{var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){{js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}}}(document,"script","twitter-wjs");</script>
<a href="https://twitter.com/intent/tweet?button_hashtag={hashtag}&text={msg}" class="twitter-hashtag-button" data-related="piratepartyau" data-url="{url}">Tweet #{hashtag}</a>
<script>!function(d,s,id){{var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){{js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}}}(document,"script","twitter-wjs");</script>
<div id="fb-root"></div>
<script>(function(d, s, id) {{
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="{url}" data-send="true" data-width="250" data-show-faces="false"></div>
</div>""".format(sid=sid, msg=urllib.quote(msg), hashtag=hashtag, url=url)
def create_signature_form(values={}, invalid=[], error_msg=""):
form = """<form class='signature-form' method="post">
<h2>Sign the petition!</h2>
{error_msg}
<table role='presentation'>
<tbody>
<tr>
<td class="{first_name_label}" style="width: 50%">
<label for='first_name'>First name</label>
<input type='text' id='first_name' name="first_name" value="{first_name}">
</td>
<td class="{last_name_label}" style="width: 50%">
<label for='last_name'>Last name</label>
<input type='text' id='last_name' name="last_name" value="{last_name}">
</td>
</tr>
<tr>
<td colspan='2'>
<label for='organisation'>Organisation <small>(optional)</small></label>
<input type='text' id='organisation' name='organisation' value="{organisation}">
</td>
</tr>
<tr>
<td class="{email_label}" colspan='2'>
<label for='email'>Email address</label>
<input type='email' id='email' name='email' value="{email}">
</td>
</tr>
<tr>
<td colspan='2'>
<label for='comment'>Comment <small>(optional, max 140 chars)</small></label>
<textarea id='comment' name='comment'>{comment}</textarea>
</td>
</tr>
<tr>
<td class="{is_australian_label}" colspan='2'>
<span>Are you Australian?</span>
<div class='radio'>
<input type='radio' id="is_australian_true" name="is_australian" {is_australian_true} value="true"> Yes
</div>
<div class='radio'>
<input type='radio' id="is_australian_false" name="is_australian" {is_australian_false} value="false"> No
</div>
</td>
</tr>
<tr>
<td colspan='2'>
<input type='submit' value='Submit'>
</td>
</tr>
</tbody>
</table>
</form>
"""
o = values
missing = False
for name in ['first_name', 'last_name', 'email', 'is_australian']:
if name in invalid:
o[name + "_label"] = "error"
missing = True
else:
o[name + "_label"] = ""
o['is_australian_false'] = ""
o['is_australian_true'] = ""
if o.get('is_australian') == True:
o['is_australian_true'] = "checked"
elif o.get('is_australian') == False:
o['is_australian_false'] = "checked"
if missing:
error_msg = "<div class='error'>There are incomplete fields.</div>"
return form.format(error_msg=error_msg, **o)
class SignatureHandler(tornado.web.RequestHandler):
def get(self, petition_id):
petition = db.petitions.find_one({"sid": petition_id})
if petition is None:
raise HTTPError(404)
signatures = db.signatures.find({"pid": petition['_id']})
signatures = [Signature(**signature) for signature in signatures]
headers = ['First Name', 'Last Name', 'Organisation', 'Email', 'Is Australian?', 'Comments']
table = []
for s in signatures:
row = []
row.append(s.first_name)
row.append(s.last_name)
row.append(s.organisation or "")
row.append(s.email)
row.append(str(s.is_australian))
row.append(s.comment or "")
table.append(row)
table = create_table(table, headers)
chunk = "<div class='header'>\n<h1>%s</h1>\n<p>%s</p>\n</div>\n" % (petition['title'], petition['message'])
body = [chunk, "<hr>", table]
self.write(create_html5_page(petition_id, [create_css()], body))
class JSONPPetitionHandler(tornado.web.RequestHandler):
def get(self, petition_id):
jsonp_method = self.get_argument("jsonp", "jsonp")
self.set_header("Content-Type", "application/javascript")
petition = db.petitions.find_one({"sid": petition_id})
if petition is None:
raise HTTPError(404)
del petition['_id']
self.write(jsonp_method + "(" + json.dumps(petition) + ")")
class JSONPetitionHandler(tornado.web.RequestHandler):
def get(self, petition_id):
self.set_header("Content-Type", "application/json")
petition = db.petitions.find_one({"sid": petition_id})
if petition is None:
raise HTTPError(404)
del petition['_id']
self.write(json.dumps(petition))
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.redirect("/natsecinquiry")
class FaviconHandler(tornado.web.RequestHandler):
def get(self):
pass
class RobotsHandler(tornado.web.RequestHandler):
def get(self):
self.write("User-agent: *\nDisallow:\n")
class PetitionHandler(tornado.web.RequestHandler):
def get(self, petition_id):
petition = db.petitions.find_one({"sid": petition_id, "disabled": {"$ne": True}})
if petition is None:
raise HTTPError(404)
logo = """<a href='http://pirateparty.org.au/'>
<img src='https://join.pirateparty.org.au/logo.png' class='logo' alt='Pirate Party Australia logo'>
</a>"""
chunk = """<div class='header'>
<table role='presentation'>
<tr>
<td>
%s
</td>
<td>
<h1>%s</h1>
</td>
</tr>
</table>
<div>%s</div>
</div>
""" % (logo, petition['title'], petition['message'])
head = [create_css()]
share_box = create_share_box(petition_id, petition['twitter_msg'], petition['hashtag'], petition['url'])
body = [create_signature_form(get_fields(Signature())), share_box, chunk]
self.write(create_html5_page(petition['title'], head, body))
def post(self, petition_id):
petition = db.petitions.find_one({"sid": petition_id, "disabled": {"$ne": True}})
if petition is None:
raise HTTPError(404)
sig = Signature()
sig.pid = petition['_id']
petition = Petition(**petition)
sig.first_name = self.get_argument("first_name", None)
sig.last_name = self.get_argument("last_name", None)
sig.organisation = self.get_argument("organisation", None)
sig.email = self.get_argument("email", None)
sig.comment = self.get_argument("comment", None)
is_australian = self.get_argument("is_australian", None)
if is_australian is not None:
is_australian = is_australian == "true"
sig.is_australian = is_australian
sig.signed_on = datetime.datetime.utcnow()
error_fields = []
try:
sig.validate(True)
except Exception as e:
error_fields = [error.field_name for error in e.error_list]
logo = """<a href='http://pirateparty.org.au/'>
<img src='https://join.pirateparty.org.au/logo.png' class='logo' alt='Pirate Party Australia logo'>
</a>"""
chunk = """<div class='header'>
<table role='presentation'>
<tr>
<td>
%s
</td>
<td>
<h1>%s</h1>
</td>
</tr>
</table>
<div>%s</div>
</div>
""" % (logo, petition['title'], petition['message'])
head = [create_css()]
body = []
share_box = create_share_box(petition_id, petition['twitter_msg'], petition['hashtag'], petition['url'])
if len(error_fields) > 0:
body += [create_signature_form(get_fields(sig), error_fields), share_box, chunk]
else:
signature = db.signatures.find_one({"pid": sig.pid, "email": sig.email})
if signature is not None:
body.append("<div class='signature-form'>A submission from this email address has previously been received. Thank you for your support.</div>")
logging.warn("[%s] Email '%s' attempted to sign again." % (self.request.remote_ip, sig.email))
else:
db.signatures.insert(sig.to_python())
body.append("<div class='signature-form'>Submission received. Thank you for your support.</div>")
logging.info("[%s] Email '%s' signed." % (self.request.remote_ip, sig.email))
body += [share_box, chunk]
self.write(create_html5_page(petition['title'], head, body))
'''
class TestHandler(tornado.web.RequestHandler):
def get(self, petition_id):
petition = db.petitions.find_one({"sid": petition_id})
head = []
body = ["<iframe height='500' width='300' src='/" + petition_id + "'></iframe>"]
self.write(create_html5_page(petition_id, head, body))
'''
db = pymongo.Connection().petitions
application = tornado.web.Application([
#(r"/signatures/(.*)", SignatureHandler),
(r"/robots.txt", RobotsHandler),
(r"/favicon.ico", FaviconHandler),
(r"/", IndexHandler),
(r"/(.*).jsonp", JSONPPetitionHandler),
(r"/(.*).json", JSONPetitionHandler),
(r"/(.*)", PetitionHandler),
], db=db)
if __name__ == "__main__":
httpserv = tornado.httpserver.HTTPServer(application, xheaders=True)
httpserv.listen(8888)
tornado.ioloop.IOLoop.instance().start()