From 44aef2183e0f44dbb8619ad3438e80cca67fb5cb Mon Sep 17 00:00:00 2001 From: Roger Braun Date: Thu, 20 Jul 2017 19:37:41 +0200 Subject: [PATCH] Add follower / friend fetching to user. --- lib/pleroma/user.ex | 17 +++++++++++++++++ test/user_test.exs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/lib/pleroma/user.ex b/lib/pleroma/user.ex index af0e569a4..d5befa67b 100644 --- a/lib/pleroma/user.ex +++ b/lib/pleroma/user.ex @@ -186,4 +186,21 @@ def get_or_fetch_by_nickname(nickname) do end end end + + # TODO: these queries could be more efficient if the type in postgresql wasn't map, but array. + def get_followers(%User{id: id, follower_address: follower_address}) do + q = from u in User, + where: fragment("? @> ?", u.following, ^follower_address ), + where: u.id != ^id + + {:ok, Repo.all(q)} + end + + def get_friends(%User{id: id, following: following}) do + q = from u in User, + where: u.follower_address in ^following, + where: u.id != ^id + + {:ok, Repo.all(q)} + end end diff --git a/test/user_test.exs b/test/user_test.exs index 0f42e9b51..81827afa3 100644 --- a/test/user_test.exs +++ b/test/user_test.exs @@ -197,5 +197,35 @@ test "it restricts some sizes" do end) end end + + describe "followers and friends" do + test "gets all followers for a given user" do + user = insert(:user) + follower_one = insert(:user) + follower_two = insert(:user) + not_follower = insert(:user) + + {:ok, follower_one} = User.follow(follower_one, user) + {:ok, follower_two} = User.follow(follower_two, user) + + {:ok, res} = User.get_followers(user) + + assert res == [follower_one, follower_two] + end + + test "gets all friends (followed users) for a given user" do + user = insert(:user) + followed_one = insert(:user) + followed_two = insert(:user) + not_followed = insert(:user) + + {:ok, user} = User.follow(user, followed_one) + {:ok, user} = User.follow(user, followed_two) + + {:ok, res} = User.get_friends(user) + + assert res == [followed_one, followed_two] + end + end end