-
Notifications
You must be signed in to change notification settings - Fork 3
/
views.py
executable file
·377 lines (288 loc) · 11.7 KB
/
views.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
from __init__ import app, cur, conn
from flask import render_template, redirect, request
import requests
import datetime
import sys
from bs4 import BeautifulSoup
import urllib2
url = 'http://fa16-cs411-47.cs.illinois.edu'
@app.route('/', methods=['GET', 'POST'])
def welcome_user():
if request.method == 'GET':
return render_template('webpage2/welcome-form/welcome.html')
else:
username = request.form.get('username', None)
password = request.form.get('password', None)
if request.args.get("login", None):
valid_login = username and password and authenticated(username, password)
if valid_login:
return redirect(url + "/{}/search".format(username))
else:
return render_template('webpage2/welcome-form/welcome.html', login_failed=True)
elif request.args.get("signup", None):
name = request.form.get('name', None)
valid_signup = username and password and name and create_user(username, password, name)
if valid_signup:
return redirect(url + "/{}/search".format(username))
else:
return render_template('webpage2/welcome-form/welcome.html', login_failed=True)
@app.route('/<username>/logout')
def logout_user(username):
change_user_logged_in(username, False)
return redirect(url)
@app.route('/<username>/search')
def search(username):
if not authenticated(username):
return redirect(url)
return render_template('webpage2/search.html', username=username)
@app.route('/example_query')
def example_query():
cur.execute("SELECT page_title FROM page WHERE page_title LIKE '%Republic%'")
query_name = "SELECT page_title FROM page WHERE page_title LIKE '%Republic%'"
query = str(cur.fetchall())
return render_template('example_query.html', query_name=query_name, query=query)
@app.route('/<username>/search/<keyword>/<lpnum>', methods=['GET'])
def get_trip(username, keyword, lpnum):
if not authenticated(username):
return render_templated('webpage2/welcome-form/welcome.html', login_failed=True)
possible_locations = get_best_locations(keyword)
lpnum = min(int(lpnum), len(possible_locations))
has_go_nexts = False
for location in possible_locations[lpnum:]:
go_nexts = get_location_go_nexts(location)
if go_nexts and go_nexts[0][0] != 'EMPTY':
has_go_nexts = True
break
lpnum += 1
if not has_go_nexts:
return redirect(url + "/{}/search".format(username))
trip_exists = get_trip_by_keyword(keyword, lpnum) != None
if not trip_exists:
best_location = possible_locations[lpnum]
best_location = best_location.replace(" ", "_")
create_trip(keyword, best_location, username, lpnum)
create_trip_user(keyword, username, lpnum)
trip = get_trip_locations(keyword, lpnum)
trip = [loc for loc in trip if loc]
coords = []
for location in trip:
coords.append(get_location_coords(location['name']))
liked = get_trip_user(keyword, username, lpnum)[3]
return render_template('webpage2/trip.html', trip=trip, coords=coords, keyword=keyword, liked=liked, username=username, lpnum=lpnum)
@app.route('/<username>/search/<keyword>/<lpnum>/<like>')
def like_trip(username, keyword, lpnum, like):
like = like == 'True'
cur.execute('''
UPDATE TripUser
SET Assessment={}
WHERE TripKeyword='{}' AND Username='{}' AND LPNum={}
'''.format(like, keyword, username, lpnum))
conn.commit()
return redirect("{}/{}/search/{}/{}".format(url, username, keyword, lpnum))
@app.route('/<username>/search/<keyword>/<lpnum>/delete')
def delete_past_trip(username, keyword, lpnum):
cur.execute('''
DELETE FROM TripUser
WHERE Username='{}' AND TripKeyword='{}' AND LPNum={}
'''.format(username, keyword, lpnum))
conn.commit()
profile_url = "{}/{}".format(url, username)
return redirect(profile_url)
@app.route('/<username>')
def get_user_profile(username):
return render_template('webpage2/profile.html', username=username, recommended=recommend_trip(username), past=past_trips(username))
def authenticated(username, password=None):
user = get_user_by_username(username)
if not user:
return False
user_password = user[1]
logged_in = user[3]
if not password and logged_in:
return True
elif user_password == password:
change_user_logged_in(username, True)
return True
else:
return False
def get_best_locations(keyword):
'''
Make requests to LostVoyager API with the user inputted keyword
Choose most popular locations from request
Return information needed to make trip and location AND IMAGE URL
'''
destinations = []
keyword = urllib2.quote(keyword)
url = "https://www.viator.com/search/"+keyword
response = urllib2.urlopen(url)
soup=BeautifulSoup(response.read(), "lxml")
content = soup.find_all("p", class_="man mts note xsmall")
for c in content:
result = str(c)
split = result.split(',')
if len(split) > 1:
result = split[-1]
else:
result = split[0]
result = result.split('<')[0]
result = result.strip()
destinations.append(result)
dests = set()
unique_destinations = []
for location in destinations:
if location not in dests:
unique_destinations.append(location)
dests.add(location)
return unique_destinations
def get_trip_locations(keyword, lpnum):
cur.execute('''
SELECT LocationName
FROM TripLocation
WHERE TripKeyword='{}' AND LPNum={}
'''.format(keyword, lpnum))
trip_locations = cur.fetchall()
locations = [get_location_by_name(loc[0]) for loc in trip_locations]
return locations
def get_trip_by_keyword(keyword, lpnum):
cur.execute("SELECT * FROM Trip WHERE Keyword='{}' AND LPNum='{}'".format(keyword, lpnum))
trip = cur.fetchone()
return trip
def get_location_coords(location_name):
rv = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={}&key=AIzaSyCoIJcakxVen5qGdu_PsV_ajdl33qwGskI'.format(location_name))
data = rv.json()
coords = data['results'][0]['geometry']['location']
return (coords['lat'], coords['lng'])
def create_location_image(location_name):
cur.execute("SELECT * FROM Photo WHERE LocationName='{}'".format(location_name))
photo = cur.fetchone()
if photo:
return
key = 'AIzaSyCoIJcakxVen5qGdu_PsV_ajdl33qwGskI'
rv = requests.get('https://maps.googleapis.com/maps/api/place/autocomplete/json?key={}&input={}&type=geocode&'.format(key, location_name))
data = rv.json()
if data['status'] != 'OK':
return
location = data['predictions'][0]
place_id = location['place_id']
rv = requests.get('https://maps.googleapis.com/maps/api/place/details/json?key={}&placeid={}'.format(key, place_id))
data = rv.json()['result']
if 'photos' not in data:
url = None
else:
photo_ref = data['photos'][0]['photo_reference']
url = 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference={}&key={}'.format(photo_ref, key)
cur.execute("INSERT INTO Photo VALUES ('{}', '{}')".format(url, location_name))
conn.commit()
def get_location_by_name(name):
cur.execute('''
SELECT l.Description, l.Eat, l.See, l.Do, l.Name, p.URL
FROM Location l, Photo p
WHERE l.Name='{}' AND p.LocationName = '{}'
'''.format(name, name))
location = cur.fetchone()
if location:
return location_to_dict(location)
return None
def get_location_by_coords(coords):
cur.execute("SELECT * FROM Location WHERE Coordinates='{}'".format(coords))
location = cur.fetchone()
return location
def create_trip_location(keyword, location_name, lpnum):
cur.execute("INSERT INTO TripLocation VALUES ('{}','{}', {})".format(keyword, location_name, lpnum))
conn.commit()
def create_trip_user(keyword, username, lpnum):
trip_user = get_trip_user(keyword, username, lpnum)
if not trip_user:
cur.execute("INSERT INTO TripUser VALUES ('{}','{}', {}, 0)".format(keyword, username, lpnum))
conn.commit()
def get_trip_user(keyword, username, lpnum):
cur.execute("SELECT * FROM TripUser WHERE TripKeyword='{}' AND Username='{}' AND LPNum={}".format(keyword, username, lpnum))
trip_user = cur.fetchone()
return trip_user
def create_user(username, password, name):
user = get_user_by_username(username)
if user:
return False
else:
cur.execute("INSERT INTO User VALUES ('{}', '{}', '{}', {})".format(username, password, name, True))
conn.commit()
return True
def get_user_by_username(username):
cur.execute("SELECT * FROM `User` WHERE Username='{}'".format(username))
return cur.fetchone()
def change_user_logged_in(username, logged_in):
cur.execute("UPDATE User SET LoggedIn={} WHERE Username='{}'".format(logged_in, username))
conn.commit()
def get_location_go_nexts(location_name):
# Get all associated go nexts with location
db_location_name = location_name.replace(" ", "_")
cur.execute('''
SELECT NextName, NextCoords
FROM LocationGoNext
WHERE SourceName LIKE '{}%'
'''.format(db_location_name))
rv = cur.fetchall()
return rv
def create_trip(keyword, location_name, user, lpnum):
'''
Create trip from location's go next
'''
go_nexts = get_location_go_nexts(location_name)
if not go_nexts:
raise ValueError('Location {} does not exist'.format(location_name))
create_trip_location(keyword, location_name, lpnum)
create_location_image(location_name)
# Get info and create location for all go nexts
num_go_nexts = min(len(go_nexts), 5)
for location in go_nexts[:num_go_nexts]:
name = location[0]
coords = location[1]
if name:
create_trip_location(keyword, name, lpnum)
create_location_image(name)
# Create trip
cur.execute('''
INSERT INTO Trip
VALUES ('{}', '{}', {})
'''.format(keyword, location_name, lpnum))
conn.commit()
def location_to_dict(location):
location_dict = {'description':location[0],'eat':location[1],
'see':location[2], 'do':location[3],
'name':location[4].replace("_", " "), 'photo':location[5]}
return location_dict
def recommend_trip(username):
query = '''
SELECT u.TripKeyword, MAX(u.LPNum)
FROM TripUser u
WHERE u.Assessment = 1 AND u.Username = '{}'
GROUP BY u.TripKeyword
'''.format(username)
cur.execute(query)
rv = cur.fetchall()
recommended = [[], []];
if not rv:
return []
else:
for trip_info in rv:
keyword = trip_info[0]
lpnum = trip_info[1]
recommended[0].append("http://fa16-cs411-47.cs.illinois.edu/{}/search/{}/{}".format(username, keyword, lpnum + 1))
recommended[1].append(keyword + " {}".format(lpnum+1))
return recommended
def past_trips(username):
cur.execute('''
SELECT TripKeyword, LPNum
FROM TripUser
WHERE Username = '{}'
'''.format(username))
rv = cur.fetchall()
past = [[], []];
if not rv:
return []
else:
for trip_info in rv:
keyword = trip_info[0]
lpnum = trip_info[1]
past[0].append("http://fa16-cs411-47.cs.illinois.edu/{}/search/{}/{}".format(username, keyword, lpnum))
past[1].append(keyword + " {}".format(lpnum))
return past