-
Notifications
You must be signed in to change notification settings - Fork 1
/
devfest.py
235 lines (197 loc) · 7.93 KB
/
devfest.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
from flask import Flask, request, render_template, g, redirect, Response, session, escape, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
import os
import hashlib
from helper import populate
import urllib
from markupsafe import Markup
import sys
import time
import requests
from nlp import parser
import string
reload(sys)
sys.setdefaultencoding("utf-8")
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./app.db'#/home/prokingsley/devfest/app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
salt = 'cdea050d7d604afea194572ef22d5297'
class User(db.Model):
username = db.Column(db.String(80), primary_key=True, nullable=False)
fullname = db.Column(db.String(80), nullable=False)
password = db.Column(db.String(120), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
phone = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
class Event(db.Model):
eid = db.Column(db.String(80), primary_key=True, nullable=False)
host = db.Column(db.String(80), nullable=False)
message = db.Column(db.String(300), nullable=False)
time = db.Column(db.String(80), nullable=False)
location = db.Column(db.String(80), nullable=False)
lon = db.Column(db.String(80), nullable=False)
lat = db.Column(db.String(80), nullable=False)
def __repr__(self):
return '<Event %r>' % self.message
class Attend(db.Model):
eid = db.Column(db.String(80), db.ForeignKey('event.eid'), primary_key=True)
username = db.Column(db.String(80), primary_key=True, nullable=False)
def __repr__(self):
return '<eid %r>' % self.eid
@app.template_filter('urlencode')
def urlencode_filter(s):
if type(s) == 'Markup':
s = s.unescape()
s = s.encode('utf8')
s = urllib.quote_plus(s)
return Markup(s)
def get_all_events():
event_list = []
events = Event.query.all()
for e in events:
attendee_db = db.session.query(Attend, User).filter(
Attend.username == User.username).filter(Attend.eid == e.eid).all()
attendee = []
for p in attendee_db:
attendee.append(p.User.fullname)
# res = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + e.location.replace(" ", "%20"))
# res = res.json()
event_list.append(
{'host': {'username': e.host, 'fullname': User.query.filter_by(username=e.host).first().fullname},
'location': e.location, 'get_location': {"lat":e.lat, "lng":e.lon}, 'message': e.message,
'time': e.time, 'eid': e.eid, 'attendee': attendee})
return event_list
def get_events(keywords):
event_list = []
events = Event.query.all()
for e in events:
relevant = False
for k in keywords:
if k.lower() in e.message.lower():
relevant = True
break
if relevant:
attendee_db = db.session.query(Attend, User).filter(
Attend.username == User.username).filter(Attend.eid == e.eid).all()
attendee = []
for p in attendee_db:
attendee.append(p.User.fullname)
# res = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + e.location.replace(" ", "%20"))
# res = res.json()
event_list.append(
{'host': {'username': e.host, 'fullname': User.query.filter_by(username=e.host).first().fullname},
'location': e.location, 'get_location': {"lat":e.lat, "lng":e.lon}, 'message': e.message,
'time': e.time, 'eid': e.eid, 'attendee': attendee})
return event_list
@app.route('/')
def index():
# DEBUG: this is debugging code to see what request looks like
print (request.args)
search_arg = request.args.get('q')
if search_arg is not None:
keywords = search_arg.strip().translate(string.punctuation).split(' ')
context = {'events': get_events(keywords)}
else:
context = {'events': get_all_events()}
session['createEvent'] = False
return render_template("index.html", **context)
@app.route('/login', methods=['POST'])
def login():
uname = request.form['username']
pwd = hashlib.sha512(request.form['password'] + salt).hexdigest()
try:
temp = User.query.filter_by(username=uname).first()
if temp == None or temp.password != pwd:
err_msg = "incorrect username or password"
context = dict(data = err_msg)
print ("no such user")
return render_template("index.html", **context)
else:
populate(session, temp)
return redirect(url_for('index'))
except:
err_msg = "connection to DB failed"
context = dict(data = err_msg)
return render_template("index.html", **context)
@app.route('/signup', methods=['POST'])
def signup():
if request.method == 'POST':
print ("hello world!")
uname = request.form['username']
pwd = hashlib.sha512(request.form['password'] + salt).hexdigest()
fname = request.form['fullname']
email = request.form['email']
phone = request.form['phone']
app.logger.info('%s logged in successfully', uname)
user_created = User(username = uname, fullname = fname, password = pwd, phone = phone, email = email)
try:
db.session.add(user_created)
db.session.commit()
except:
err_msg = "Signing up failed!"
context = dict(data = err_msg)
return render_template("index.html", **context)
populate(session, user_created)
return redirect(url_for('index'))
err_msg = "HTTP Request not supported!"
context = dict(data = err_msg)
return render_template("index.html", **context)
@app.route('/event', methods=['POST'])
def createEvent():
eid = "%.3f" % (time.time())
host = request.form['host']
message = request.form['message']
event_time = request.form['time']
location = request.form['location']
key = "&key=AIzaSyAOd0yLa2PRCmldYBjXYLF5eZXhzaCv8jE"
res = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + location.replace(" ", "+") + key)
res = res.json()
lat = "40.8075355"
lon = "-73.9625727"
if len(res["results"]) != 0:
lat = res["results"][0]["geometry"]["location"]["lat"]
lon = res["results"][0]["geometry"]["location"]["lng"]
(tokens, actions_list) = parser(message)
if len(actions_list) == 0:
actions_list.append(message)
event_created = Event(eid = eid, host = host, message = actions_list[0] , time = event_time, location = location, lat=lat , lon=lon)
try:
db.session.add(event_created)
db.session.commit()
except:
err_msg = "Create Event Failed!"
context = dict(data = err_msg)
return render_template("index.html", **context)
print ("Create Event Succeeded!")
return redirect(url_for('index'))
@app.route('/events', methods=['GET'])
def renderJSON():
return jsonify(get_all_events())
@app.route('/attend/<eid>/<username>', methods=['GET'])
def attendEvent(eid, username):
attend_event = Attend(eid=eid, username=username)
try:
db.session.add(attend_event)
db.session.commit()
except:
err_msg = "Join Event Failed!"
context = dict(data = err_msg)
return render_template("index.html", **context)
print ("Attend Event Succeeded!")
return redirect(url_for('index'))
@app.route('/logout')
def logout():
for key in session.keys():
session.pop(key)
return redirect(url_for('index'))
@app.route('/create')
def create_event():
session['createEvent'] = True
context = dict()
return render_template("index.html", **context)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
if __name__ == '__main__':
db.create_all()
app.run(host='0.0.0.0', port = 80)