This repository has been archived by the owner on May 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
website.py
906 lines (792 loc) · 34 KB
/
website.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Website server for doctypehtml5.in
"""
from collections import defaultdict
from datetime import datetime
from flask_migrate import Migrate
import re
from flask import Flask, abort, request, render_template, redirect, url_for
from flask import flash, session, g, Response
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.useragents import UserAgent
from flask_mail import Mail, Message
from wtforms import Form, TextField, TextAreaField, PasswordField, SelectField
from wtforms.validators import DataRequired, Email, ValidationError
from pytz import utc, timezone
from markdown import markdown
import pygooglechart
from coaster.sqlalchemy import UuidMixin
import coaster.app
from coaster.db import db
from coaster.utils import buid
try:
from greatape import MailChimp, MailChimpError
except ImportError:
MailChimp = None
app = Flask(__name__)
mail = Mail()
# ---------------------------------------------------------------------------
# Static data
USER_CATEGORIES = [
('0', 'Unclassified'),
('1', 'Student or Trainee'),
('2', 'Developer'),
('3', 'Designer'),
('4', 'Manager, Senior Developer/Designer'),
('5', 'CTO, CIO, CEO'),
('6', 'Entrepreneur'),
]
USER_CITIES = [
('', ''),
('bangalore', 'Bangalore - October 9, 2010 (over!)'),
('chennai', 'Chennai - November 27, 2010 (over!)'),
('pune', 'Pune - December 4, 2010 (over!)'),
('hyderabad', 'Hyderabad - January 23, 2011 (over!)'),
('ahmedabad', 'Ahmedabad - February 5, 2011 (over!)'),
]
TSHIRT_SIZES = [
('', ''),
('1', 'XS'),
('2', 'S'),
('3', 'M'),
('4', 'L'),
('5', 'XL'),
('6', 'XXL'),
('7', 'XXXL'),
]
REFERRERS = [
('', ''),
('1', 'Twitter'),
('2', 'Facebook'),
('3', 'LinkedIn'),
('10', 'Discussion Group or List'),
('4', 'Google/Bing Search'),
('5', 'Google Buzz'),
('6', 'Blog'),
('7', 'Email/IM from Friend'),
('8', 'Colleague at Work'),
('9', 'Other'),
]
GALLERY_SECTIONS = [
('Basics', 'basics'),
('Business', 'biz'),
('Accessibility', 'accessibility'),
('Typography', 'typography'),
('CSS3', 'css'),
('Audio', 'audio'),
('Video', 'video'),
('Canvas', 'canvas'),
('Vector Graphics', 'svg'),
('Geolocation', 'geolocation'),
('Mobile', 'mobile'),
('Websockets', 'websockets'),
('Toolkits', 'toolkit'),
('Showcase', 'showcase'),
]
hideemail = re.compile('.{1,3}@')
# -------------------------------------------------------------------------
# Utility functions
def currentuser():
"""
Get the current user, or None if user isn't logged in.
"""
if 'userid' in session and session['userid']:
return User.query.filter_by(email=session['userid']).first()
else:
return None
def getuser(f):
"""
Decorator for routes that need a logged-in user.
"""
def wrapped(*args, **kw):
g.user = currentuser()
return f(*args, **kw)
wrapped.__name__ = f.__name__
return wrapped
def request_is_xhr():
"""
True if the request was triggered via a JavaScript XMLHttpRequest. This only works
with libraries that support the `X-Requested-With` header and set it to
"XMLHttpRequest". Libraries that do that are prototype, jQuery and Mochikit and
probably some more. This function was ported from Werkzeug after being removed from
there.
"""
return request.environ.get('HTTP_X_REQUESTED_WITH', '').lower() == 'xmlhttprequest'
# ---------------------------------------------------------------------------
# Data models and forms
class Participant(db.Model):
"""
Participant data, as submitted from the registration form.
"""
__tablename__ = 'participant'
id = db.Column(db.Integer, primary_key=True)
#: User's full name
fullname = db.Column(db.Unicode(80), nullable=False)
#: User's email address
email = db.Column(db.Unicode(80), nullable=False)
#: Edition of the event they'd like to attend
edition = db.Column(db.Unicode(80), nullable=False)
#: User's company name
company = db.Column(db.Unicode(80), nullable=False)
#: User's job title
jobtitle = db.Column(db.Unicode(80), nullable=False)
#: User's twitter id (optional)
twitter = db.Column(db.Unicode(80), nullable=True)
#: T-shirt size (XS, S, M, L, XL, XXL, XXXL)
tshirtsize = db.Column(db.Integer, nullable=False, default=0)
#: How did the user hear about this event?
referrer = db.Column(db.Integer, nullable=False, default=0)
#: User's reason for wanting to attend
reason = db.Column(db.Text, nullable=False)
#: User category, defined by a reviewer
category = db.Column(db.Integer, nullable=False, default=0)
#: User agent with which the user registered
useragent = db.Column(db.Unicode(250), nullable=True)
#: Date the user registered
regdate = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
#: Submitter's IP address, for logging (45 chars to accommodate an IPv6 address)
ipaddr = db.Column(db.Unicode(45), nullable=False)
#: Has the user's application been approved?
approved = db.Column(db.Boolean, default=False, nullable=False)
#: RSVP status codes:
#: A = Awaiting Response
#: Y = Yes, Attending
#: M = Maybe Attending
#: N = Not Attending
rsvp = db.Column(db.Unicode(1), default='A', nullable=False)
#: Did the participant attend the event?
attended = db.Column(db.Boolean, default=False, nullable=False)
#: Datetime the participant showed up
attenddate = db.Column(db.DateTime, nullable=True)
#: Did the participant agree to subscribe to the newsletter?
subscribe = db.Column(db.Boolean, default=False, nullable=False)
#: User_id
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True, unique=False)
#: Link to user account
user = db.relation('User', backref='participants')
class User(UuidMixin, db.Model):
"""
User account. This is different from :class:`Participant` because the email
address here has been verified and is unique. The email address in
:class:`Participant` cannot be unique as that is unverified. Anyone may
submit using any email address. Participant objects link to user objects
"""
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
#: User's name
fullname = db.Column(db.Unicode(80), nullable=False)
#: Email id (repeated from participant.email, but unique here)
email = db.Column(db.Unicode(80), nullable=False, unique=True)
#: Private key, for first-time access without password
privatekey = db.Column(db.String(22), nullable=False, unique=True, default=buid)
#: Password hash
pw_hash = db.Column(db.String(80))
#: Is this account active?
active = db.Column(db.Boolean, nullable=False, default=False)
#: Date of creation
created_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
#: Date of first login
firstuse_date = db.Column(db.DateTime, nullable=True)
def _set_password(self, password):
if password is None:
self.pw_hash = None
else:
self.pw_hash = generate_password_hash(password)
password = property(fset=_set_password)
def check_password(self, password):
return check_password_hash(self.pw_hash, password)
def __repr__(self):
return '<User %s>' % (self.email)
class RegisterForm(Form):
fullname = TextField('Full name', validators=[DataRequired()])
email = TextField('Email address', validators=[DataRequired(), Email()])
edition = SelectField('Edition', validators=[DataRequired()], choices=USER_CITIES)
company = TextField('Company name (or school/college)', validators=[DataRequired()])
jobtitle = TextField('Job title', validators=[DataRequired()])
twitter = TextField('Twitter id (optional)')
tshirtsize = SelectField('T-shirt size', validators=[DataRequired()], choices=TSHIRT_SIZES)
referrer = SelectField('How did you hear about this event?', validators=[DataRequired()], choices=REFERRERS)
reason = TextAreaField('Your reasons for attending', validators=[DataRequired()])
def validate_edition(self, field):
if hasattr(self, '_venuereg'):
if field.data != self._venuereg:
raise ValidationError("You can't register for that")
else:
return # Register at venue even if public reg is closed
if field.data in ['bangalore', 'chennai', 'pune', 'hyderabad', 'ahmedabad']:
raise ValidationError("Registrations are closed for this edition")
class AccessKeyForm(Form):
key = PasswordField('Access Key', validators=[DataRequired()])
class LoginForm(Form):
email = TextField('Email address', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
def getuser(self, name):
return User.query.filter_by(email=name).first()
def validate_username(self, field):
existing = self.getuser(field.data)
if existing is None:
raise ValidationError("No user account for that email address")
if not existing.active:
raise ValidationError("This user account is disabled")
def validate_password(self, field):
user = self.getuser(self.email.data)
if user is None or not user.check_password(field.data):
raise ValidationError("Incorrect password")
self.user = user
# ---------------------------------------------------------------------------
# Routes
@app.route('/', methods=['GET'])
@getuser
def index(**forms):
regform = forms.get('regform', RegisterForm())
loginform = forms.get('loginform', LoginForm())
return render_template('index.html',
regform=regform,
loginform=loginform,
gallery_sections=GALLERY_SECTIONS)
@app.route('/sitemap.xml')
def sitemap():
"""
Return a sitemap. There is only one page for web crawlers.
"""
return Response("""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>%s</loc>
</url>
</urlset>""" % url_for('index', _external=True),
content_type='text/xml; charset=utf-8')
@app.route('/login')
def loginkey():
"""
Login (via access key only)
"""
key = request.args.get('key')
if key is None:
return redirect(url_for('index'), code=303)
user = User.query.filter_by(privatekey=key).first()
if user is None:
flash("Invalid access key", 'error')
return redirect(url_for('index'), code=303)
if not user.active:
flash("This account is disabled", 'error')
return redirect(url_for('index'), code=303)
if user.pw_hash != '':
# User already has a password. Can't login by key now.
flash("This access key is not valid anymore", 'error')
return redirect(url_for('index'), code=303)
if user.firstuse_date is None:
user.firstuse_date = datetime.utcnow()
db.session.commit()
g.user = user
session['userid'] = user.email
flash("You are now logged in", 'info')
return redirect(url_for('index'), code=303)
@app.route('/logout')
def logout():
g.user = None
del session['userid']
return redirect(url_for('index'), code=303)
@app.route('/rsvp/<edition>')
def rsvp(edition):
key = request.args.get('key')
choice = request.args.get('rsvp')
if key is None:
flash("You need an access key to RSVP.", 'error')
return redirect(url_for('index'), code=303)
if choice not in ['Y', 'N', 'M']:
flash("You need to RSVP with Yes, No or Maybe: Y, N or M.", 'error')
return redirect(url_for('index'), code=303)
user = User.query.filter_by(privatekey=key).first()
if user is None:
flash("Sorry, that access key is not in our records.", 'error')
return redirect(url_for('index'), code=303)
participant = Participant.query.filter_by(user=user, edition=edition).first()
if participant:
participant.rsvp = choice
else:
flash("You did not register for this edition, %s." % user.fullname, 'error')
return redirect(url_for('index'), code=303)
if choice == 'Y':
flash("Yay! So glad you will be joining us, %s." % user.fullname, 'info')
elif choice == 'N':
flash("Sorry you can't make it, %s. Hope you’ll join us next time." % user.fullname, 'error') # Fake 'error' for frowny icon
elif choice == 'M':
flash("We recorded you as Maybe Attending, %s. When you know better, could you select Yes or No?" % user.fullname, 'info')
db.session.commit()
return redirect(url_for('index'), code=303)
@app.route('/favicon.ico')
def favicon():
return redirect(url_for('static', filename='favicon.ico'), code=301)
@app.route('/robots.txt')
def robots():
# Disable support for indexing fragments, since there's no backing code
return Response("Sitemap: /sitemap.xml\n"
"Disallow: /*_escaped_fragment_\n",
content_type='text/plain; charset=utf-8')
@app.route('/adsense')
def adsense():
"""Hidden page for Google AdSense application."""
return render_template('adsense.html')
@app.route('/ads.txt')
def adstxt():
"""Render Google ads.txt"""
return Response(
"google.com, pub-7680461523383072, DIRECT, f08c47fec0942fa0\n",
content_type='text/plain; charset=utf-8')
# ---------------------------------------------------------------------------
# Form submission
@app.route('/', methods=['POST'])
def submit():
# There's only one form, so we don't need to check which one was submitted
formid = request.form.get('form.id')
if formid == 'regform':
return submit_register()
elif formid == 'login':
return submit_login()
else:
flash("Unknown form", 'error')
redirect(url_for('index'), code=303)
def submit_register():
# This function doesn't need parameters because Flask provides everything
# via thread globals.
form = RegisterForm()
if form.validate_on_submit():
participant = Participant()
form.populate_obj(participant)
participant.ipaddr = request.environ['REMOTE_ADDR']
participant.useragent = request.user_agent.string
db.session.add(participant)
db.session.commit()
return render_template('regsuccess.html')
else:
if request_is_xhr():
return render_template('regform.html',
regform=form, ajax_re_register=True)
else:
flash("Please check your details and try again.", 'error')
return index(regform=form)
def submit_login():
form = LoginForm()
if form.validate_on_submit():
user = form.user
g.user = user
session['userid'] = user.email
if user.firstuse_date is None:
user.firstuse_date = datetime.utcnow()
db.session.commit()
flash("You are now logged in", 'info')
return redirect(url_for('index'), code=303)
else:
if request_is_xhr():
return render_template('loginform.html',
loginform=form, ajax_re_register=True)
else:
flash("Please check your details and try again", 'error')
return index(loginform=form)
# ---------------------------------------------------------------------------
# Admin backend
def adminkey(keyname):
def decorator(f):
def inner(edition):
form = AccessKeyForm()
keylist = app.config[keyname]
# check for key and call f or return form
if 'key' in request.values:
if request.values.get('key') in keylist:
session[keyname] = request.values['key']
return redirect(request.base_url, code=303) # FIXME: Redirect to self URL
else:
flash("Invalid access key", 'error')
return render_template('accesskey.html', keyform=form)
elif keyname in session and session[keyname] in keylist:
return f(edition)
else:
return render_template('accesskey.html', keyform=form)
inner.__name__ = f.__name__
return inner
return decorator
@app.route('/admin/reasons/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_REASONS')
def admin_reasons(edition):
headers = [('no', 'Sl No'), ('reason', 'Reason')] # List of (key, label)
data = ({'no': i + 1, 'reason': p.reason} for i, p in
enumerate(Participant.query.filter_by(edition=edition)))
return render_template('datatable.html', headers=headers, data=data,
title='Reasons for attending')
@app.route('/admin/list/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_LIST')
def admin_list(edition):
headers = [('no', 'Sl No'), ('name', 'Name'), ('company', 'Company'),
('jobtitle', 'Job Title'), ('twitter', 'Twitter'),
('approved', 'Approved'), ('rsvp', 'RSVP'), ('attended', 'Attended')]
data = ({'no': i + 1, 'name': p.fullname, 'company': p.company,
'jobtitle': p.jobtitle,
'twitter': p.twitter,
'approved': p.approved,
'rsvp': {'Y': 'Yes', 'N': 'No', 'M': 'Maybe', 'A': 'Awaiting'}[p.rsvp],
'attended': ['No', 'Yes'][p.attended]
} for i, p in enumerate(Participant.query.order_by('fullname').filter_by(edition=edition)))
return render_template('datatable.html', headers=headers, data=data,
title='List of participants')
@app.route('/admin/rsvp/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_LIST')
def admin_rsvp(edition):
rsvp_yes = Participant.query.filter_by(edition=edition, approved=True, rsvp='Y').count()
rsvp_no = Participant.query.filter_by(edition=edition, approved=True, rsvp='N').count()
rsvp_maybe = Participant.query.filter_by(edition=edition, approved=True, rsvp='M').count()
rsvp_awaiting = Participant.query.filter_by(edition=edition, approved=True, rsvp='A').count()
return render_template('rsvp.html', yes=rsvp_yes, no=rsvp_no,
maybe=rsvp_maybe, awaiting=rsvp_awaiting,
title='RSVP Statistics')
@app.route('/admin/stats/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_LIST')
def admin_stats(edition):
# Chart sizes
CHART_X = 800
CHART_Y = 370
all_browsers = defaultdict(int)
all_brver = defaultdict(int)
all_platforms = defaultdict(int)
present_browsers = defaultdict(int)
present_brver = defaultdict(int)
present_platforms = defaultdict(int)
c_all = 0
c_present = 0
for p in Participant.query.filter_by(edition=edition):
if p.useragent:
c_all += 1
ua = UserAgent(p.useragent)
all_browsers[ua.browser] += 1
if ua.version is None:
all_brver[ua.browser] += 1
else:
all_brver['%s %s' % (ua.browser, ua.version.split('.')[0])] += 1
all_platforms[ua.platform] += 1
for p in Participant.query.filter_by(edition=edition, attended=True):
if p.useragent:
c_present += 1
ua = UserAgent(p.useragent)
present_browsers[ua.browser] += 1
present_brver['%s %s' % (ua.browser, ua.version.split('.')[0])] += 1
present_platforms[ua.platform] += 1
if c_all != 0: # Avoid divide by zero situation
f_all = 100.0 / c_all
else:
f_all = 1
if c_present != 0: # Avoid divide by zero situation
f_present = 100.0 / c_present
else:
f_present = 1
# Now make charts
# All registrations
c_all_browsers = pygooglechart.PieChart2D(CHART_X, CHART_Y)
c_all_browsers.add_data(list(all_browsers.values()))
c_all_browsers.set_pie_labels(['%s (%.2f%%)' % (key, all_browsers[key] * f_all) for key in list(all_browsers.keys())])
c_all_brver = pygooglechart.PieChart2D(CHART_X, CHART_Y)
c_all_brver.add_data(list(all_brver.values()))
c_all_brver.set_pie_labels(['%s (%.2f%%)' % (key, all_brver[key] * f_all) for key in list(all_brver.keys())])
c_all_platforms = pygooglechart.PieChart2D(CHART_X, CHART_Y)
c_all_platforms.add_data(list(all_platforms.values()))
c_all_platforms.set_pie_labels(['%s (%.2f%%)' % (key, all_platforms[key] * f_all) for key in list(all_platforms.keys())])
# Present at venue
c_present_browsers = pygooglechart.PieChart2D(CHART_X, CHART_Y)
c_present_browsers.add_data(list(present_browsers.values()))
c_present_browsers.set_pie_labels(['%s (%.2f%%)' % (key, present_browsers[key] * f_present) for key in list(present_browsers.keys())])
c_present_brver = pygooglechart.PieChart2D(CHART_X, CHART_Y)
c_present_brver.add_data(list(present_brver.values()))
c_present_brver.set_pie_labels(['%s (%.2f%%)' % (key, present_brver[key] * f_present) for key in list(present_brver.keys())])
c_present_platforms = pygooglechart.PieChart2D(CHART_X, CHART_Y)
c_present_platforms.add_data(list(present_platforms.values()))
c_present_platforms.set_pie_labels(['%s (%.2f%%)' % (key, present_platforms[key] * f_present) for key in list(present_platforms.keys())])
return render_template('stats.html',
all_browsers=c_all_browsers.get_url(),
all_brver=c_all_brver.get_url(),
all_platforms=c_all_platforms.get_url(),
present_browsers=c_present_browsers.get_url(),
present_brver=c_present_brver.get_url(),
present_platforms=c_present_platforms.get_url()
)
@app.route('/admin/data/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_DATA')
def admin_data(edition):
d_tshirt = dict(TSHIRT_SIZES)
d_referrer = dict(REFERRERS)
d_category = dict(USER_CATEGORIES)
tz = timezone(app.config['TIMEZONE'])
headers = [('no', 'Sl No'),
('regdate', 'Date'),
('name', 'Name'),
('email', 'Email'),
('company', 'Company'),
('jobtitle', 'Job Title'),
('twitter', 'Twitter'),
('tshirt', 'T-shirt Size'),
('referrer', 'Referrer'),
('category', 'Category'),
('ipaddr', 'IP Address'),
('approved', 'Approved'),
('RSVP', 'RSVP'),
('agent', 'User Agent'),
('reason', 'Reason'),
]
data = ({'no': i + 1,
'regdate': utc.localize(p.regdate).astimezone(tz).strftime('%Y-%m-%d %H:%M'),
'name': p.fullname,
'email': p.email,
'company': p.company,
'jobtitle': p.jobtitle,
'twitter': p.twitter,
'tshirt': d_tshirt.get(str(p.tshirtsize), p.tshirtsize),
'referrer': d_referrer.get(str(p.referrer), p.referrer),
'category': d_category.get(str(p.category), p.category),
'ipaddr': p.ipaddr,
'approved': {True: 'Yes', False: 'No'}[p.approved],
'rsvp': {'A': '', 'Y': 'Yes', 'M': 'Maybe', 'N': 'No'}[p.rsvp],
'agent': p.useragent,
'reason': p.reason,
} for i, p in enumerate(Participant.query.filter_by(edition=edition)))
return render_template('datatable.html', headers=headers, data=data,
title='Participant data')
@app.route('/admin/classify/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_APPROVE')
def admin_classify(edition):
if request.method == 'GET':
tz = timezone(app.config['TIMEZONE'])
return render_template('classify.html', participants=Participant.query.filter_by(edition=edition),
utc=utc, tz=tz, enumerate=enumerate, edition=edition)
elif request.method == 'POST':
p = Participant.query.get(request.form['id'])
if p:
p.category = request.form['category']
# TODO: Return status
@app.route('/admin/approve/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_APPROVE')
def admin_approve(edition):
if request.method == 'GET':
tz = timezone(app.config['TIMEZONE'])
return render_template('approve.html', participants=Participant.query.filter_by(edition=edition),
utc=utc, tz=tz, enumerate=enumerate, edition=edition)
elif request.method == 'POST':
p = Participant.query.get(request.form['id'])
if not p:
status = "No such user"
else:
if 'action.undo' in request.form:
p.approved = False
p.user = None
status = 'Undone!'
# Remove from MailChimp
if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']:
mc = MailChimp(app.config['MAILCHIMP_API_KEY'])
try:
mc.listUnsubscribe(
id=app.config['MAILCHIMP_LIST_ID'],
email_address=p.email,
send_goodbye=False,
send_notify=False,
)
pass
except MailChimpError as e:
status = e.msg
db.session.commit()
elif 'action.approve' in request.form:
if p.approved:
status = "Already approved"
else:
# Check for dupe participant (same email, same edition)
dupe = False
for other in Participant.query.filter_by(edition=p.edition, email=p.email):
if other.id != p.id:
if other.user:
dupe = True
break
if dupe is False:
p.approved = True
status = "Tada!"
# 1. Make user account and activate it
user = makeuser(p)
user.active = True
# 2. Add to MailChimp
if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']:
mc = MailChimp(app.config['MAILCHIMP_API_KEY'])
addmailchimp(mc, p)
# 3. Send notice of approval
msg = Message(subject="Your registration has been approved",
recipients=[p.email])
msg.body = render_template("approve_notice_%s.md" % edition, p=p)
msg.html = markdown(msg.body)
with app.open_resource("static/doctypehtml5-%s.ics" % edition) as ics:
msg.attach("doctypehtml5.ics", "text/calendar", ics.read())
mail.send(msg)
db.session.commit()
else:
status = "Dupe"
else:
status = 'Unknown action'
if request_is_xhr():
return status
else:
return redirect(url_for('admin_approve', edition=edition), code=303)
else:
abort(401)
@app.route('/admin/venue/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_APPROVE')
def admin_venue(edition):
if request.method == 'GET' and 'email' not in request.args:
return render_template('venuereg.html', edition=edition)
elif request.method == 'POST' or 'email' in request.args:
if 'email' in request.args:
formid = 'venueregemail'
else:
formid = request.form.get('form.id')
if formid == 'venueregemail':
email = request.values.get('email')
if email:
p = Participant.query.filter_by(edition=edition, email=email).first()
if p is not None:
if p.attended: # Already signed in
flash("You have already signed in. Next person please.")
return redirect(url_for('admin_venue', edition=edition), code=303)
else:
return render_template('venueregdetails.html', edition=edition, p=p)
# Unknown email address. Ask for new registration
regform = RegisterForm()
regform.email.data = email
regform.edition.data = edition
return render_template('venueregnew.html', edition=edition, regform=regform)
elif formid == 'venueregconfirm':
id = request.form['id']
subscribe = request.form.get('subscribe')
p = Participant.query.get(id)
if subscribe:
p.subscribe = True
else:
p.subscribe = False
p.attended = True
p.attenddate = datetime.utcnow()
db.session.commit()
flash("You have been signed in. Next person please.", 'info')
return redirect(url_for('admin_venue', edition=edition), code=303)
elif formid == 'venueregform':
# Validate form and register
regform = RegisterForm()
regform._venuereg = edition
if regform.validate_on_submit():
participant = Participant()
regform.populate_obj(participant)
participant.ipaddr = request.environ['REMOTE_ADDR']
# Do not record participant.useragent since it's a venue computer, not user's.
makeuser(participant)
db.session.add(participant)
if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']:
mc = MailChimp(app.config['MAILCHIMP_API_KEY'])
addmailchimp(mc, participant)
db.session.commit()
return render_template('venueregsuccess.html', edition=edition, p=participant)
else:
return render_template('venueregform.html', edition=edition,
regform=regform, ajax_re_register=True)
else:
flash("Unknown form submission", 'error')
return redirect(url_for('admin_venue', edition=edition), code=303)
@app.route('/admin/venuesheet/<edition>', methods=['GET', 'POST'])
@adminkey('ACCESSKEY_APPROVE')
def admin_venuesheet(edition):
if request.method == 'GET':
tz = timezone(app.config['TIMEZONE'])
return render_template('venuesheet.html', participants=Participant.query.order_by('fullname').filter_by(edition=edition),
utc=utc, tz=tz, enumerate=enumerate, hideemail=hideemail, edition=edition)
elif request.method == 'POST' and 'id' in request.form:
# Register this participant id
id = request.form['id']
p = Participant.query.get(id)
if not p.attended:
p.attended = True
p.attenddate = datetime.utcnow()
# XXX: makeuser does not add to MailChimp, to move folks along faster.
# MailChimp must be manually updated later.
makeuser(p)
db.session.commit()
return 'Signed in'
else:
return 'Already signed in'
else:
return 'Unknown form submission'
# ---------------------------------------------------------------------------
# Admin helper functions
def makeuser(participant):
"""
Convert a participant into a user. Returns User object.
"""
if participant.user:
return participant.user
else:
user = User.query.filter_by(email=participant.email).first()
if user is not None:
participant.user = user
else:
user = User(fullname=participant.fullname, email=participant.email)
participant.user = user
# These defaults don't get auto-added until the session is committed,
# but we need them before, so we have to manually assign values here.
user.privatekey = buid()
db.session.add(user)
return user
def _makeusers():
"""
Helper function to create user accounts. Meant for one-time use only.
"""
if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']:
mc = MailChimp(app.config['MAILCHIMP_API_KEY'])
else:
mc = None
for p in Participant.query.all():
if p.approved:
# Make user, but don't make account active
makeuser(p)
if mc is not None:
addmailchimp(mc, p)
db.session.commit()
def addmailchimp(mc, p):
"""
Add user to mailchimp list
"""
editions = [ap.edition for ap in p.user.participants if p.user]
groups = {'Editions': {'name': 'Editions', 'groups': ','.join(editions)}}
mc.listSubscribe(
id=app.config['MAILCHIMP_LIST_ID'],
email_address=p.email,
merge_vars={'FULLNAME': p.fullname,
'JOBTITLE': p.jobtitle,
'COMPANY': p.company,
'TWITTER': p.twitter,
'PRIVATEKEY': p.user.privatekey,
'UID': p.user.buid,
'GROUPINGS': groups},
double_optin=False,
update_existing=True
)
# ---------------------------------------------------------------------------
# Config and startup
coaster.app.init_app(app)
db.init_app(app)
db.app = app
migrate = Migrate(app, db)
app.config.from_object(__name__)
try:
app.config.from_object('settings')
except ImportError:
import sys
print("Please create a settings.py with the necessary settings. See settings-sample.py.", file=sys.stderr)
print("You may use the site without these settings, but some features may not work.", file=sys.stderr)
# Initialize mail settings
mail.init_app(app)
application = app
if __name__ == '__main__':
if MailChimp is None:
import sys
print("greatape is not installed. MailChimp support will be disabled.", file=sys.stderr)
app.run('0.0.0.0', 4001, debug=True)