Move friends flows to server-rendered Flask/Jinja routes
This commit is contained in:
+3
-1
@@ -26,9 +26,11 @@ def create_app():
|
||||
|
||||
from .routes.auth import auth_bp
|
||||
from .routes.main import main_bp
|
||||
from .routes.friends import friends_bp
|
||||
|
||||
app.register_blueprint(auth_bp)
|
||||
app.register_blueprint(main_bp)
|
||||
app.register_blueprint(auth_bp)
|
||||
app.register_blueprint(friends_bp)
|
||||
|
||||
init_db(app)
|
||||
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
from flask import Blueprint, flash, jsonify, redirect, request, url_for
|
||||
from flask_login import current_user, login_required
|
||||
|
||||
from app.db import get_db
|
||||
|
||||
|
||||
friends_bp = Blueprint("friends", __name__)
|
||||
|
||||
|
||||
def _get_friendship_row(user_a_id: int, user_b_id: int):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
"""
|
||||
SELECT requester_id, addressee_id, status
|
||||
FROM friendships
|
||||
WHERE (requester_id = ? AND addressee_id = ?)
|
||||
OR (requester_id = ? AND addressee_id = ?)
|
||||
LIMIT 1
|
||||
""",
|
||||
(user_a_id, user_b_id, user_b_id, user_a_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _send_friend_request_or_accept(addressee_id: int):
|
||||
if addressee_id == current_user.id:
|
||||
return {"error": "cannot send a request to yourself"}, 400
|
||||
|
||||
db = get_db()
|
||||
user_exists = db.execute(
|
||||
"SELECT id FROM users WHERE id = ?",
|
||||
(addressee_id,),
|
||||
).fetchone()
|
||||
if not user_exists:
|
||||
return {"error": "user not found"}, 404
|
||||
|
||||
friendship = _get_friendship_row(current_user.id, addressee_id)
|
||||
if friendship:
|
||||
if friendship["status"] == "accepted":
|
||||
return {"error": "already friends"}, 409
|
||||
if friendship["status"] == "blocked":
|
||||
return {"error": "cannot send request"}, 403
|
||||
if friendship["status"] == "pending":
|
||||
if friendship["addressee_id"] == current_user.id:
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE friendships
|
||||
SET status = 'accepted'
|
||||
WHERE requester_id = ? AND addressee_id = ?
|
||||
""",
|
||||
(addressee_id, current_user.id),
|
||||
)
|
||||
db.commit()
|
||||
return {"status": "accepted"}, 200
|
||||
return {"error": "request already sent"}, 409
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO friendships (requester_id, addressee_id, status)
|
||||
VALUES (?, ?, 'pending')
|
||||
""",
|
||||
(current_user.id, addressee_id),
|
||||
)
|
||||
db.commit()
|
||||
return {"status": "pending"}, 201
|
||||
|
||||
|
||||
def _accept_friend_request(requester_id: int):
|
||||
db = get_db()
|
||||
updated = db.execute(
|
||||
"""
|
||||
UPDATE friendships
|
||||
SET status = 'accepted'
|
||||
WHERE requester_id = ?
|
||||
AND addressee_id = ?
|
||||
AND status = 'pending'
|
||||
""",
|
||||
(requester_id, current_user.id),
|
||||
).rowcount
|
||||
|
||||
if updated == 0:
|
||||
return {"error": "request not found"}, 404
|
||||
|
||||
db.commit()
|
||||
return {"status": "accepted"}, 200
|
||||
|
||||
|
||||
def _decline_friend_request(requester_id: int):
|
||||
db = get_db()
|
||||
deleted = db.execute(
|
||||
"""
|
||||
DELETE FROM friendships
|
||||
WHERE requester_id = ?
|
||||
AND addressee_id = ?
|
||||
AND status = 'pending'
|
||||
""",
|
||||
(requester_id, current_user.id),
|
||||
).rowcount
|
||||
|
||||
if deleted == 0:
|
||||
return {"error": "request not found"}, 404
|
||||
|
||||
db.commit()
|
||||
return {"status": "declined"}, 200
|
||||
|
||||
|
||||
def _cancel_outgoing_friend_request(addressee_id: int):
|
||||
db = get_db()
|
||||
deleted = db.execute(
|
||||
"""
|
||||
DELETE FROM friendships
|
||||
WHERE requester_id = ?
|
||||
AND addressee_id = ?
|
||||
AND status = 'pending'
|
||||
""",
|
||||
(current_user.id, addressee_id),
|
||||
).rowcount
|
||||
|
||||
if deleted == 0:
|
||||
return {"error": "request not found"}, 404
|
||||
|
||||
db.commit()
|
||||
return {"status": "canceled"}, 200
|
||||
|
||||
|
||||
def _friends_page_data(search_query: str = ""):
|
||||
db = get_db()
|
||||
|
||||
friends = db.execute(
|
||||
"""
|
||||
SELECT DISTINCT u.id, u.username,
|
||||
CASE
|
||||
WHEN u.last_seen_at IS NOT NULL
|
||||
AND u.last_seen_at >= datetime('now', '-35 seconds')
|
||||
THEN 1 ELSE 0
|
||||
END AS is_online
|
||||
FROM friendships f
|
||||
JOIN users u
|
||||
ON (
|
||||
(f.requester_id = ? AND f.addressee_id = u.id)
|
||||
OR
|
||||
(f.addressee_id = ? AND f.requester_id = u.id)
|
||||
)
|
||||
WHERE f.status = 'accepted'
|
||||
ORDER BY u.username COLLATE NOCASE ASC
|
||||
""",
|
||||
(current_user.id, current_user.id),
|
||||
).fetchall()
|
||||
|
||||
incoming = db.execute(
|
||||
"""
|
||||
SELECT f.requester_id AS id, u.username
|
||||
FROM friendships f
|
||||
JOIN users u ON u.id = f.requester_id
|
||||
WHERE f.addressee_id = ?
|
||||
AND f.status = 'pending'
|
||||
ORDER BY u.username COLLATE NOCASE ASC
|
||||
""",
|
||||
(current_user.id,),
|
||||
).fetchall()
|
||||
|
||||
outgoing = db.execute(
|
||||
"""
|
||||
SELECT f.addressee_id AS id, u.username
|
||||
FROM friendships f
|
||||
JOIN users u ON u.id = f.addressee_id
|
||||
WHERE f.requester_id = ?
|
||||
AND f.status = 'pending'
|
||||
ORDER BY u.username COLLATE NOCASE ASC
|
||||
""",
|
||||
(current_user.id,),
|
||||
).fetchall()
|
||||
|
||||
search_results = []
|
||||
normalized_query = search_query.strip()
|
||||
if len(normalized_query) >= 2:
|
||||
like_query = f"%{normalized_query}%"
|
||||
rows = db.execute(
|
||||
"""
|
||||
SELECT u.id, u.username
|
||||
FROM users u
|
||||
WHERE u.id != ?
|
||||
AND u.username LIKE ?
|
||||
ORDER BY u.username COLLATE NOCASE ASC
|
||||
LIMIT 20
|
||||
""",
|
||||
(current_user.id, like_query),
|
||||
).fetchall()
|
||||
|
||||
for row in rows:
|
||||
relation = "none"
|
||||
friendship = _get_friendship_row(current_user.id, row["id"])
|
||||
if friendship:
|
||||
if friendship["status"] == "accepted":
|
||||
relation = "accepted"
|
||||
elif friendship["status"] == "pending":
|
||||
relation = (
|
||||
"incoming"
|
||||
if friendship["addressee_id"] == current_user.id
|
||||
else "outgoing"
|
||||
)
|
||||
else:
|
||||
relation = friendship["status"]
|
||||
|
||||
search_results.append(
|
||||
{
|
||||
"id": row["id"],
|
||||
"username": row["username"],
|
||||
"relation": relation,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"friends": friends,
|
||||
"incoming_requests": incoming,
|
||||
"outgoing_requests": outgoing,
|
||||
"search_results": search_results,
|
||||
"search_query": normalized_query,
|
||||
}
|
||||
|
||||
|
||||
@friends_bp.route("/friends/request", methods=["POST"])
|
||||
@login_required
|
||||
def request_page_action():
|
||||
try:
|
||||
addressee_id = int(request.form.get("addressee_id", ""))
|
||||
except ValueError:
|
||||
flash("Invalid user id", "error")
|
||||
return redirect(url_for("main.friends", q=request.form.get("q", "")))
|
||||
|
||||
payload, status = _send_friend_request_or_accept(addressee_id)
|
||||
if status in (200, 201):
|
||||
flash("Friend request updated", "success")
|
||||
else:
|
||||
flash(payload["error"], "error")
|
||||
|
||||
return redirect(url_for("main.friends", q=request.form.get("q", "")))
|
||||
|
||||
|
||||
@friends_bp.route("/friends/requests/<int:requester_id>/accept", methods=["POST"])
|
||||
@login_required
|
||||
def accept_page_action(requester_id: int):
|
||||
payload, status = _accept_friend_request(requester_id)
|
||||
if status == 200:
|
||||
flash("Friend request accepted", "success")
|
||||
else:
|
||||
flash(payload["error"], "error")
|
||||
|
||||
return redirect(url_for("main.friends", q=request.form.get("q", "")))
|
||||
|
||||
|
||||
@friends_bp.route("/friends/requests/<int:requester_id>/decline", methods=["POST"])
|
||||
@login_required
|
||||
def decline_page_action(requester_id: int):
|
||||
payload, status = _decline_friend_request(requester_id)
|
||||
if status == 200:
|
||||
flash("Friend request declined", "success")
|
||||
else:
|
||||
flash(payload["error"], "error")
|
||||
|
||||
return redirect(url_for("main.friends", q=request.form.get("q", "")))
|
||||
|
||||
|
||||
@friends_bp.route("/friends/requests/<int:addressee_id>/cancel", methods=["POST"])
|
||||
@login_required
|
||||
def cancel_page_action(addressee_id: int):
|
||||
payload, status = _cancel_outgoing_friend_request(addressee_id)
|
||||
if status == 200:
|
||||
flash("Outgoing request canceled", "success")
|
||||
else:
|
||||
flash(payload["error"], "error")
|
||||
|
||||
return redirect(url_for("main.friends", q=request.form.get("q", "")))
|
||||
|
||||
|
||||
@friends_bp.route("/api/friends", methods=["GET"])
|
||||
@login_required
|
||||
def list_friends():
|
||||
data = _friends_page_data("")
|
||||
return jsonify({"friends": [dict(row) for row in data["friends"]]})
|
||||
|
||||
|
||||
@friends_bp.route("/api/friends/search", methods=["GET"])
|
||||
@login_required
|
||||
def search_people():
|
||||
data = _friends_page_data(request.args.get("q", ""))
|
||||
return jsonify({"results": data["search_results"]})
|
||||
|
||||
|
||||
@friends_bp.route("/api/friends/requests/incoming", methods=["GET"])
|
||||
@login_required
|
||||
def incoming_friend_requests():
|
||||
data = _friends_page_data("")
|
||||
return jsonify({"requests": [dict(row) for row in data["incoming_requests"]]})
|
||||
|
||||
|
||||
@friends_bp.route("/api/friends/requests/outgoing", methods=["GET"])
|
||||
@login_required
|
||||
def outgoing_friend_requests():
|
||||
data = _friends_page_data("")
|
||||
return jsonify({"requests": [dict(row) for row in data["outgoing_requests"]]})
|
||||
|
||||
|
||||
@friends_bp.route("/api/friends/requests", methods=["POST"])
|
||||
@login_required
|
||||
def send_friend_request():
|
||||
payload = request.get_json(silent=True) or {}
|
||||
addressee_id = payload.get("addressee_id")
|
||||
|
||||
if not isinstance(addressee_id, int):
|
||||
return jsonify({"error": "addressee_id must be an integer"}), 400
|
||||
|
||||
response_payload, status = _send_friend_request_or_accept(addressee_id)
|
||||
return jsonify(response_payload), status
|
||||
|
||||
|
||||
@friends_bp.route("/api/friends/requests/<int:requester_id>/accept", methods=["POST"])
|
||||
@login_required
|
||||
def accept_friend_request(requester_id: int):
|
||||
payload, status = _accept_friend_request(requester_id)
|
||||
return jsonify(payload), status
|
||||
|
||||
|
||||
@friends_bp.route("/api/friends/requests/<int:requester_id>/decline", methods=["POST"])
|
||||
@login_required
|
||||
def decline_friend_request(requester_id: int):
|
||||
payload, status = _decline_friend_request(requester_id)
|
||||
return jsonify(payload), status
|
||||
+7
-11
@@ -1,16 +1,10 @@
|
||||
from flask import Blueprint, render_template, redirect, url_for
|
||||
from flask import Blueprint, render_template, redirect, url_for, request
|
||||
from flask_login import login_required, current_user
|
||||
from app.routes.friends import _friends_page_data
|
||||
|
||||
main_bp = Blueprint("main", __name__)
|
||||
|
||||
""" def login_required(view):
|
||||
@wraps(view)
|
||||
def wrapped_view(**kwargs):
|
||||
if "user_id" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return view(**kwargs)
|
||||
return wrapped_view
|
||||
"""
|
||||
|
||||
|
||||
@main_bp.route("/", methods=["GET", "POST"])
|
||||
def index():
|
||||
@@ -18,10 +12,10 @@ def index():
|
||||
return redirect(url_for("main.home"))
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
@main_bp.route("/home", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def home():
|
||||
print(f"Current user: {current_user.username}")
|
||||
return render_template("home.html")
|
||||
|
||||
|
||||
@@ -31,7 +25,9 @@ def play():
|
||||
return render_template("play.html")
|
||||
|
||||
|
||||
#todo: decide if this should get moved to the friends.py file
|
||||
@main_bp.route("/friends", methods=["GET"])
|
||||
@login_required
|
||||
def friends():
|
||||
return render_template("friends.html")
|
||||
data = _friends_page_data(request.args.get("q", ""))
|
||||
return render_template("friends.html", **data)
|
||||
+149
-44
@@ -1,48 +1,153 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Friends</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='app.css') }}" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="site-shell">
|
||||
<header class="topbar">
|
||||
<a href="{{ url_for('main.home') }}" class="brand">Chess</a>
|
||||
<nav class="topnav">
|
||||
<a href="{{ url_for('main.home') }}">Home</a>
|
||||
<a href="{{ url_for('main.play') }}">Play</a>
|
||||
<a href="{{ url_for('main.friends') }}" class="active">Friends</a>
|
||||
</nav>
|
||||
<div class="profile-pill">{{ current_user.username }}</div>
|
||||
</header>
|
||||
|
||||
{% extends "base_app.html" %} {% set active_page = 'friends' %} {% block title
|
||||
%}Friends{% endblock %} {% block content %}
|
||||
<h1>Friends</h1>
|
||||
|
||||
<section class="panel-grid">
|
||||
<article class="panel">
|
||||
<h2>Online now</h2>
|
||||
<ul class="friend-list">
|
||||
<li><span class="dot"></span>name1</li>
|
||||
<li><span class="dot"></span>friend2</li>
|
||||
<li><span class="dot"></span>bro has a lot of friends</li>
|
||||
</ul>
|
||||
</article>
|
||||
<section class="panel friends-search-panel">
|
||||
<h2>Find people</h2>
|
||||
<form method="GET" action="{{ url_for('main.friends') }}" class="search-form">
|
||||
<input
|
||||
type="search"
|
||||
name="q"
|
||||
minlength="2"
|
||||
value="{{ search_query }}"
|
||||
placeholder="Search by username"
|
||||
/>
|
||||
<button type="submit" class="btn btn-primary">Search</button>
|
||||
</form>
|
||||
|
||||
<article class="panel">
|
||||
<h2>Incoming invites</h2>
|
||||
<p>No pending invitations
|
||||
</p>
|
||||
</article>
|
||||
</section>
|
||||
</main>
|
||||
{% if search_query %}
|
||||
<div class="friends-list">
|
||||
{% if search_results %} {% for person in search_results %}
|
||||
<div class="friend-card">
|
||||
<div class="friend-main">
|
||||
<div class="friend-username">{{ person.username }}</div>
|
||||
<div class="friend-status">{{ person.relation|capitalize }}</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
<div class="friend-actions">
|
||||
{% if person.relation == 'none' %}
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ url_for('friends.request_page_action') }}"
|
||||
>
|
||||
<input type="hidden" name="addressee_id" value="{{ person.id }}" />
|
||||
<input type="hidden" name="q" value="{{ search_query }}" />
|
||||
<button class="btn btn-secondary" type="submit">Add Friend</button>
|
||||
</form>
|
||||
{% elif person.relation == 'incoming' %}
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ url_for('friends.accept_page_action', requester_id=person.id) }}"
|
||||
>
|
||||
<input type="hidden" name="q" value="{{ search_query }}" />
|
||||
<button class="btn btn-primary" type="submit">Accept</button>
|
||||
</form>
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ url_for('friends.decline_page_action', requester_id=person.id) }}"
|
||||
>
|
||||
<input type="hidden" name="q" value="{{ search_query }}" />
|
||||
<button class="btn btn-secondary" type="submit">Decline</button>
|
||||
</form>
|
||||
{% elif person.relation == 'outgoing' %}
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ url_for('friends.cancel_page_action', addressee_id=person.id) }}"
|
||||
>
|
||||
<input type="hidden" name="q" value="{{ search_query }}" />
|
||||
<button class="btn btn-secondary" type="submit">
|
||||
Cancel Request
|
||||
</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<span class="friend-note">No action available</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %} {% else %}
|
||||
<p class="muted">No users found for "{{ search_query }}".</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="panel friends-section">
|
||||
<!-- todo: update presence -->
|
||||
<h2>Your friends</h2>
|
||||
{% if friends %}
|
||||
<div class="friends-list">
|
||||
{% for friend in friends %}
|
||||
<div class="friend-card">
|
||||
<div class="friend-main">
|
||||
<div class="friend-username">{{ friend.username }}</div>
|
||||
<div
|
||||
class="friend-status {{ 'status-online' if friend.is_online else 'status-offline' }}"
|
||||
>
|
||||
{{ 'Online' if friend.is_online else 'Offline' }}
|
||||
</div>
|
||||
</div>
|
||||
<!-- todo: implement button -->
|
||||
<button class="btn btn-secondary" type="button">Challenge</button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="muted">No friends yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="panel friends-section">
|
||||
<h2>Requests</h2>
|
||||
|
||||
<h3>Incoming</h3>
|
||||
{% if incoming_requests %}
|
||||
<div class="friends-list">
|
||||
{% for req in incoming_requests %}
|
||||
<div class="friend-card">
|
||||
<div class="friend-main">
|
||||
<div class="friend-username">{{ req.username }}</div>
|
||||
<div class="friend-status">Pending</div>
|
||||
</div>
|
||||
<div class="friend-actions">
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ url_for('friends.accept_page_action', requester_id=req.id) }}"
|
||||
>
|
||||
<button class="btn btn-primary" type="submit">Accept</button>
|
||||
</form>
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ url_for('friends.decline_page_action', requester_id=req.id) }}"
|
||||
>
|
||||
<button class="btn btn-secondary" type="submit">Decline</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="muted">No incoming requests.</p>
|
||||
{% endif %}
|
||||
|
||||
<h3>Outgoing</h3>
|
||||
{% if outgoing_requests %}
|
||||
<div class="friends-list">
|
||||
{% for req in outgoing_requests %}
|
||||
<div class="friend-card">
|
||||
<div class="friend-main">
|
||||
<div class="friend-username">{{ req.username }}</div>
|
||||
<div class="friend-status">Pending</div>
|
||||
</div>
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ url_for('friends.cancel_page_action', addressee_id=req.id) }}"
|
||||
>
|
||||
<button class="btn btn-secondary" type="submit">Cancel Request</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="muted">No outgoing requests.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user