-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
452 lines (378 loc) · 14.8 KB
/
Copy pathserver.py
File metadata and controls
452 lines (378 loc) · 14.8 KB
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
import os
import db
import uuid
import io
from flask import Flask, render_template, redirect, url_for, current_app, session, request, jsonify
from authlib.integrations.flask_client import OAuth
from urllib.parse import quote_plus, urlencode, unquote_plus
from dotenv import load_dotenv
from functools import wraps
from PIL import Image
import re
load_dotenv()
oauth = None
def normalize_display_name(name):
# Trim and collapse multiple spaces to one
normalized = " ".join(name.strip().split())
if not (3 <= len(normalized) <= 13):
return None
if not re.compile(r"^[A-Za-z]+(?: [A-Za-z]+)*$").fullmatch(normalized):
return None
return normalized
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if not session.get("userinfo"):
next_url = request.path
if request.full_path:
next_url = request.full_path
return redirect(url_for("login", next=next_url))
return f(*args, **kwargs)
return decorated
def setup():
global oauth
app.secret_key = os.environ.get("APP_SECRET_KEY")
current_app.config["GOOGLE_MAPS_API_KEY"] = os.environ.get(
"GOOGLE_MAPS_API_KEY")
current_app.config["MAPBOX_ACCESS_TOKEN"] = os.environ.get(
"MAPBOX_ACCESS_TOKEN")
current_app.config["DB_POOL"] = db.init_pool(
os.environ.get("DATABASE_URL"))
oauth = OAuth(app)
oauth.register(
"auth0",
client_id=os.environ.get("AUTH0_CLIENT_ID"),
client_secret=os.environ.get("AUTH0_CLIENT_SECRET"),
client_kwargs={
"scope": "openid profile email",
},
server_metadata_url=f'https://{os.environ.get("AUTH0_DOMAIN")}/.well-known/openid-configuration'
)
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
CLIENT_DIR = os.path.join(BASE_DIR, "client")
app = Flask(
__name__,
template_folder=os.path.join(CLIENT_DIR, "templates"),
static_folder=os.path.join(CLIENT_DIR, "static"),
)
def ensure_logged_in_user():
userinfo = session.get("userinfo")
if not userinfo:
return None
pool = current_app.config["DB_POOL"]
user_id = userinfo.get("sub")
email = userinfo.get("email") or None
picture = userinfo.get("picture") or None
db.upsert_user(pool, user_id, email, picture)
return user_id
with app.app_context():
setup()
@app.context_processor
def inject_google_maps_key():
return {"google_maps_api_key": current_app.config.get("GOOGLE_MAPS_API_KEY")}
@app.context_processor
def inject_mapbox_access_token():
return {"mapbox_access_token": current_app.config.get("MAPBOX_ACCESS_TOKEN")}
@app.route("/login")
def login():
next_url = request.args.get("next")
if next_url:
session["post_login_redirect"] = next_url
return oauth.auth0.authorize_redirect(
redirect_uri=url_for("callback", _external=True)
)
@app.route("/logout")
def logout():
if not session:
return redirect("/")
session.clear()
domain = os.environ.get("AUTH0_DOMAIN")
client_id = os.environ.get("AUTH0_CLIENT_ID")
return_to = url_for("index", _external=True)
params = urlencode(
{
"returnTo": return_to,
"client_id": client_id,
},
quote_via=quote_plus,
)
logout_url = f"https://{domain}/v2/logout?{params}"
return redirect(logout_url)
@app.route("/callback", methods=["GET", "POST"])
def callback():
token = oauth.auth0.authorize_access_token()
try:
userinfo = oauth.auth0.userinfo()
session["userinfo"] = userinfo
except Exception:
session["userinfo"] = None
session["user"] = token
pool = current_app.config["DB_POOL"]
user_id = userinfo.get("sub")
profile_data = db.check_profile_complete(pool, user_id)
session.update(profile_data)
ensure_logged_in_user()
next_url = session.pop("post_login_redirect", None)
if next_url:
return redirect(next_url)
return redirect(url_for("index"))
@app.route("/api/check-profile-status")
def get_profile_status():
logged_in = session.get("user") is not None
profile_complete = session.get('profile_complete', False)
return jsonify({
'logged_in': logged_in,
'profile_complete': profile_complete
})
# TODO: This needs
@app.route("/complete_profile", methods=["GET", "POST"])
@requires_auth
def complete_profile():
if request.method == 'POST':
userinfo = session.get("userinfo")
pool = current_app.config["DB_POOL"]
user_id = userinfo.get("sub")
display_name = request.form.get('display_name')
normalized_name = normalize_display_name(display_name)
if not normalized_name:
return "Invalid display name. Must be 3-13 letters with single spaces.", 400
privacy_settings = (request.form.get('privacy_settings') == "public")
db.update_profile_settings(pool, user_id, normalized_name, privacy_settings)
session['profile_complete'] = True
session['display_name'] = normalized_name
session['public'] = privacy_settings
return redirect(url_for("index"))
return render_template("complete_profile.html")
@app.route("/api/posts")
def get_posts():
pool = current_app.config["DB_POOL"]
userinfo = session.get("userinfo")
viewer_id = userinfo.get("sub") if userinfo else None
return jsonify(db.fetch_posts(pool, viewer_id))
@app.route("/api/posts/<user_id>")
def get_posts_by_user_id(user_id):
pool = current_app.config["DB_POOL"]
userinfo = session.get("userinfo")
viewer_id = userinfo.get("sub") if userinfo else None
return jsonify(db.fetch_posts_by_user_id(pool, user_id, viewer_id))
@app.route("/api/<post_id>/comment", methods=["POST"])
@requires_auth
def add_comment(post_id):
user_id = ensure_logged_in_user()
comment = request.form.get("comment", "").strip()
if not comment:
return redirect(url_for("post", post_id=post_id))
pool = current_app.config["DB_POOL"]
comment_id = str(uuid.uuid4())
db.insert_comment(pool, comment_id, comment, post_id, user_id)
return redirect(url_for("post", post_id=post_id))
@app.route("/")
def index():
return render_template("index.html")
@app.route("/post/<post_id>")
def post(post_id):
pool = current_app.config["DB_POOL"]
userinfo = session.get("userinfo")
viewer_id = userinfo.get("sub") if userinfo else None
post = db.fetch_single_post(pool, post_id, viewer_id)
if not post:
return redirect(url_for("index"))
comments = db.fetch_comments(pool, post_id)
recommended_posts = db.fetch_nearest_posts(pool, post_id, k=5)
is_self = False
if (userinfo and post) and (post["user_id"] == userinfo["sub"]):
is_self = True
return render_template("post.html", post=post, comments=comments, recommended_posts=recommended_posts, is_self=is_self)
def optimize_image(file_storage, quality=80):
file_storage.stream.seek(0)
img = Image.open(file_storage.stream)
if img.mode not in ("RGB", "L"):
img = img.convert("RGB")
img.thumbnail(img.size, Image.Resampling.LANCZOS)
out = io.BytesIO()
img.save(out, format="JPEG", quality=quality, optimize=True, progressive=True)
return out.getvalue()
def create_thumbnail(file_storage, max_size=320, quality=70):
file_storage.stream.seek(0)
img = Image.open(file_storage.stream)
if img.mode not in ("RGB", "L"):
img = img.convert("RGB")
img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
out = io.BytesIO()
img.save(out, format="JPEG", quality=quality, optimize=True, progressive=True)
return out.getvalue()
@app.route("/create/post", methods=["GET", "POST"])
@requires_auth
def create_post():
if request.method == "GET":
return render_template("create_post.html", google_maps_api_key=os.environ.get("GOOGLE_MAPS_API_KEY"))
user_id = ensure_logged_in_user()
if not user_id:
return redirect(url_for("login"))
file = request.files.get("image")
caption = request.form.get("caption", "").strip()
lat = request.form.get("latitude")
lng = request.form.get("longitude")
if not file or not caption or not lat or not lng:
return "Missing required fields", 400
try:
lat_f = float(lat)
lng_f = float(lng)
except ValueError:
return "Invalid coordinates", 400
post_id = str(uuid.uuid4())
media_id = str(uuid.uuid4())
file_bytes = optimize_image(file, quality=80)
thumb_bytes = create_thumbnail(file, max_size=320, quality=70)
base, _ = os.path.splitext(file.filename or "upload")
file_name = f"{base}.jpg"
pool = current_app.config["DB_POOL"]
db.insert_post_with_media(
pool, post_id, caption, user_id, lng_f, lat_f, media_id, file_name, file_bytes, thumb_bytes)
return redirect(url_for("post", post_id=post_id))
@app.route("/profile")
@requires_auth
def profile_root():
userinfo = session["userinfo"]
return redirect(url_for("profile", user_id=userinfo.get("sub")))
@app.route("/profile/<user_id>")
def profile(user_id):
pool = current_app.config["DB_POOL"]
userinfo = session.get("userinfo")
profile_user = db.fetch_user_by_id(pool, user_id)
if not profile_user:
return redirect(url_for("index"))
viewer_id = userinfo.get('sub') if userinfo else None
followers_data = db.fetch_followers(pool, user_id)
display_name = profile_user.get('display_name')
profile_picture = db.fetch_user_profile_image_by_user_id(pool, user_id)
can_view_profile = db.can_view_user(pool, user_id, viewer_id)
is_self = (userinfo and (userinfo.get('sub') == user_id))
posts = None
if can_view_profile or is_self:
posts = db.fetch_users_post_images_by_user_id(pool, user_id, viewer_id)
relation = None
if userinfo:
for follower_by in followers_data['followed_by']:
if follower_by['follower_id'] == userinfo['sub']:
relation = "pending" if not follower_by['is_accepted'] else "following"
break
is_logged_in = True if userinfo else False
return render_template("profile.html",
username=user_id,
display_name=display_name,
is_self=is_self,
followers_data=followers_data,
relation=relation,
profile_picture=profile_picture,
posts=posts,
is_logged_in=is_logged_in,
can_view_profile=can_view_profile)
@app.route("/settings")
@requires_auth
def settings_root():
userinfo = session["userinfo"]
return redirect(url_for("profile_settings", user_id=userinfo.get("sub")))
@app.route("/profile/settings/<user_id>")
@requires_auth
def profile_settings(user_id):
pool = current_app.config["DB_POOL"]
userinfo = session["userinfo"]
user_id = userinfo.get("sub")
current_settings = db.fetch_user_settings(pool, user_id)
profile_picture = db.fetch_user_profile_image_by_user_id(pool, user_id)
return render_template("profile_settings.html",
display_name=current_settings["display_name"],
public=current_settings["public"],
picture=profile_picture["picture"],
user_id=user_id)
@app.route("/update_profile_settings", methods=["POST"])
def handle_update_profile_settings():
pool = current_app.config["DB_POOL"]
userinfo = session["userinfo"]
user_id = userinfo.get("sub")
print(user_id)
display_name = request.form.get('display_name')
normalized_name = normalize_display_name(display_name)
if not normalized_name:
return "Invalid display name. Must be 3-13 letters with single spaces.", 400
privacy_settings = (request.form.get('privacy_settings') == "public")
db.update_profile_settings(pool, user_id, normalized_name, privacy_settings)
session['display_name'] = normalized_name
session['public'] = privacy_settings
return redirect(url_for("profile_root"))
@app.route("/api/search_users")
def search():
name = request.args.get('name')
pool = current_app.config["DB_POOL"]
matching_users = db.fetch_users(pool, name)
return jsonify(matching_users)
@app.route("/follower_request_create", methods=['POST'])
def follower_request_creation():
followee = unquote_plus(request.args.get('followee', ''))
info = get_request_info(followee)
if info['followee_id'] is None:
return jsonify({"success": False, "error": "User not found"}), 404
db.follow_request(info['pool'], info['follower_id'], info["followee_id"])
return jsonify({"success": True})
@app.route("/follower_request_handler", methods=["POST"])
def follower_request_handler():
data = request.get_json()
follower = data.get('follower', '')
followee = data.get('followee', '')
action = data.get('action', '')
info = get_request_info(followee,follower)
db.handle_follow_request(info['pool'], info['follower_id'], info['followee_id'], action)
return jsonify({"success": True})
@app.route("/unfollow", methods=["POST"])
@requires_auth
def unfollow():
data = request.get_json()
followee = data.get('followee')
info = get_request_info(followee)
if not info['follower_id'] or not info['followee_id']:
return jsonify({"success": False, "error": "Invalid request"}), 400
# accept=false will delete the row
db.handle_follow_request(info['pool'], info['follower_id'], info['followee_id'], accept=False)
return jsonify({"success": True})
def get_request_info(followee, follower=None):
followee = (followee or "").strip()
pool = current_app.config["DB_POOL"]
userinfo = session.get("userinfo")
result = {
"follower_id": None,
"followee_id": None,
"pool": pool
}
if follower:
result["follower_id"] = follower.strip()
elif userinfo:
result["follower_id"] = userinfo.get("sub")
if followee:
result["followee_id"] = followee
return result
@app.route("/update_post/<post_id>", methods=["POST"])
def update_post(post_id):
data = request.get_json()
caption = data.get("caption")
lng = data.get("lng")
lat = data.get("lat")
if not caption or not lat or not lng:
return "Missing required fields", 400
try:
lat_f = float(lat)
lng_f = float(lng)
except ValueError:
return "Invalid coordinates", 400
userinfo = session["userinfo"]
user_id = userinfo["sub"]
pool = current_app.config["DB_POOL"]
db.update_post(pool, user_id, post_id, caption, lng_f, lat_f )
return "success", 200
@app.route("/delete_post/<post_id>")
def delete_post(post_id):
userinfo = session["userinfo"]
user_id = userinfo["sub"]
pool = current_app.config["DB_POOL"]
db.delete_post(pool, user_id, post_id)
return redirect(url_for('profile', user_id=user_id))