From 2cca9fab2d880b6f16ae13d2923de89abe239270 Mon Sep 17 00:00:00 2001 From: Mouse Reeve Date: Sat, 8 Jan 2022 12:05:42 -0800 Subject: [PATCH] Cache user relationship for follow buttons --- .../templates/snippets/follow_button.html | 16 +++++++++---- bookwyrm/templatetags/interaction.py | 24 +++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/bookwyrm/templates/snippets/follow_button.html b/bookwyrm/templates/snippets/follow_button.html index f7025bba..0482bde0 100644 --- a/bookwyrm/templates/snippets/follow_button.html +++ b/bookwyrm/templates/snippets/follow_button.html @@ -1,13 +1,18 @@ {% load i18n %} +{% load interaction %} {% if request.user == user or not request.user.is_authenticated %} -{% elif user in request.user.blocks.all %} +{# nothing to see here -- either it's yourself or your logged out #} +{% else %} + +{% get_relationship user as relationship %} +{% if relationship.is_blocked %} {% include 'snippets/block_button.html' with blocks=True %} {% else %}
- -
{% endif %}
+ +{% endif %} + {% endif %} diff --git a/bookwyrm/templatetags/interaction.py b/bookwyrm/templatetags/interaction.py index 90309aaf..7aaaaca7 100644 --- a/bookwyrm/templatetags/interaction.py +++ b/bookwyrm/templatetags/interaction.py @@ -32,3 +32,27 @@ def get_user_boosted(user, status): def get_user_saved_lists(user, book_list): """did the user save a list""" return user.saved_lists.filter(id=book_list.id).exists() + +@register.simple_tag(takes_context=True) +def get_relationship(context, user_object): + """caches the relationship between the logged in user and another user""" + user = context["request"].user + return cache.get(f"relationship-{user.id}-{user_object.id}") or cache.set( + get_relationship_name(user, user_object), + timeout=259200, + ) + +def get_relationship_name(user, user_object): + """returns the relationship type""" + types = { + "is_following": False, + "is_follow_pending": False, + "is_blocked": False, + } + if user_object in user.blocks.all(): + types["is_blocked"] = True + elif user_object in user.following.all(): + types["is_following"] = True + elif user_object in user.follower_requests.all(): + types["is_follow_pending"] = True + return types