summaryrefslogtreecommitdiff
path: root/sw/users.py
diff options
context:
space:
mode:
authorTom Harley2021-07-30 18:35:08 +0000
committerTom Harley2021-07-30 18:35:08 +0000
commitc77d6a4d4a1d628788be73491aa7fa4e4fdcff05 (patch)
tree90f92c373b085818243835c323fa6e1884854ce9 /sw/users.py
parentAdd more inbox/outbox tests (diff)
downloadswap-c77d6a4d4a1d628788be73491aa7fa4e4fdcff05.tar.gz
swap-c77d6a4d4a1d628788be73491aa7fa4e4fdcff05.zip

Add templates

Rather than using jsonify on a dict, the system now uses render_template on json documents. This gives the ability to extend previous files (which might be useful for activitypub features), and also enables using different templates for different filetypes.

Supplied are templates for accessing inboxes and outboxes in JSON-LD and HTML.

The “items” field in get_user_inbox_page.json and get_user_outbox_page.json might be currently borked.

Diffstat (limited to 'sw/users.py')
-rw-r--r--sw/users.py157
1 files changed, 74 insertions, 83 deletions
diff --git a/sw/users.py b/sw/users.py
index 71258c1..573b58f 100644
--- a/sw/users.py
+++ b/sw/users.py
@@ -1,4 +1,13 @@
-from flask import Blueprint, jsonify, url_for, request, abort, g, Response
+from flask import (
+ Blueprint,
+ jsonify,
+ url_for,
+ request,
+ abort,
+ g,
+ Response,
+ render_template,
+)
import json
@@ -24,6 +33,39 @@ def ap(r):
return res
+def decide_response_filetype():
+ res = request.accept_mimetypes.best_match(
+ [
+ "text/html",
+ "application/ld+json",
+ "application/json",
+ ]
+ )
+
+ if not request.accept_mimetypes:
+ return (".json", "application/ld+json")
+
+ elif res == "text/html":
+ return (".html", "text/html")
+
+ elif res == "application/json":
+ return (".json", "application/json")
+
+ elif res == "application/ld+json":
+ return (".json", "application/ld+json")
+
+ else: # res is None
+ abort(406)
+
+
+def prepared_output(filename, **kwargs):
+ ext, mime = decide_response_filetype()
+
+ body = render_template(f"{filename}{ext}", **kwargs)
+
+ return Response(body, content_type=mime)
+
+
@bp.route("/<username>")
def get_user_info(username):
db = get_db()
@@ -33,82 +75,62 @@ def get_user_info(username):
if user is None:
abort(404, "User not found")
- return jsonify(ap(user))
+ return prepared_output("user_info", user=user)
@bp.route("/<username>/inbox")
@specific_user_required
def get_user_inbox(username):
- db = get_db()
-
- inbox_size = db.execute(
- "select inbox_size from users where username=?", (username,)
- ).fetchone()[0]
-
# since a logged-in user is required to access this endpoint, there
# is no way that a non-existant user can be queried (in other
# words, the user will not have the clearance to see an unreal
# user's inbox)
- return jsonify(
- {
- "id": url_for(".get_user_inbox", username=username),
- "type": "OrderedCollection",
- "totalItems": inbox_size,
- "first": url_for(
- ".get_user_inbox_page", username=username, page_index=now()
- ),
- # "last": url_for(".get_user_inbox_page", username=username, page=1),
- }
- )
+ return prepared_output("get_user_inbox", user=g.user)
-@bp.route("/<username>/inbox/<page_index>")
+@bp.route("/<username>/inbox/items")
@specific_user_required
-def get_user_inbox_page(username, page_index):
+def get_user_inbox_page(username):
db = get_db()
inbox_fetch_limit = 10 # TODO: give this variable a home
- if page_index == "latest":
- page_index = now()
+ max_id = request.args.get("max_id")
res = db.execute(
"select * from inbox "
"where recipient=? "
- "and received<? "
- "order by received desc "
+ "and (id <= ? or ? is null) "
+ "order by id desc "
"limit ? "
";",
- (username, page_index, inbox_fetch_limit),
+ (username, max_id, max_id, inbox_fetch_limit),
).fetchall()
def ap(r):
def f(k):
return k.startswith("ap_") and r[k] is not None
- res = {k: r[k] for k in filter(f, r.keys())}
- # res["id"] = url_for("items.get_item", item_id=r["id"])
+ res = {k[3:]: r[k] for k in filter(f, r.keys())}
+
return json.dumps(res)
- earliest_received = res[-1]["received"]
+ ids = [x["id"] for x in res]
- return jsonify(
- {
- "id": url_for(
- ".get_user_inbox_page", username=username, page_index=page_index
- ),
- "type": "OrderedCollectionPage",
- "next": url_for(
- ".get_user_inbox_page", username=username, page_index=earliest_received
- ),
- "partOf": url_for(".get_user_inbox", username=username),
- "items": [ap(x) for x in res],
- }
+ return prepared_output(
+ "get_user_inbox_page",
+ user=g.user,
+ items=json.dumps([ap(x) for x in res]),
+ max_id=max(ids, default=None),
+ min_id=min(ids, default=None),
)
def is_ap_activity(obj):
+ # TODO: use actual JSON-LD logic to check this
+ # (so that it's extension-proof
+
return obj["type"] in [
"Activity",
"Create",
@@ -157,37 +179,16 @@ def post_user_inbox_item(username):
@bp.route("/<username>/outbox")
def get_user_outbox(username):
- db = get_db()
+ return prepared_output("get_user_outbox", user=g.user)
- outbox_size = db.execute(
- "select outbox_size from users where username=?", (username,)
- ).fetchone()["outbox_size"]
- if outbox_size is None:
- abort(404, "User not found")
-
- # TODO: outbox contents not filtered by recipient data
-
- return jsonify(
- {
- "id": url_for(".get_user_inbox", username=username),
- "type": "OrderedCollection",
- "totalItems": outbox_size,
- "first": url_for(
- ".get_user_outbox_page", username=username, page_index=now()
- ),
- }
- )
-
-
-@bp.route("/username/outbox/<page_index>")
+@bp.route("/username/outbox/items")
def get_user_outbox_page(username, page_index):
db = get_db()
outbox_fetch_limit = 10 # TODO: give this variable a home
- if page_index == "latest":
- page_index = now()
+ max_id = request.args.get("max_id")
res = db.execute(
"select * from outbox "
@@ -203,26 +204,16 @@ def get_user_outbox_page(username, page_index):
def f(k):
return k.startswith("ap_") and r[k] is not None
- res = {k: r[k] for k in filter(f, r.keys())}
- # res["id"] = url_for("items.get_item", item_id=r["id"])
- return json.dumps(res)
-
- earliest_sent = res[-1]["sent"]
+ res = {k[3:]: r[k] for k in filter(f, r.keys())}
- # TODO: the final page of the collection should have a null/missing `next` property
+ return res
- return jsonify(
- {
- "id": url_for(
- ".get_user_outbox_page", username=username, page_index=page_index
- ),
- "type": "OrderedCollectionPage",
- "next": url_for(
- ".get_user_outbox_page", username=username, page_index=earliest_sent
- ),
- "partOf": url_for(".get_user_outbox", username=username),
- "items": [ap(x) for x in res],
- }
+ return prepared_output(
+ "get_user_outbox_page",
+ user=g.user,
+ items=[ap(x) for x in res],
+ max_id=max(ids, default=None),
+ min_id=min(ids, default=None),
)