From 60081a88181e7af9b6110e9b7456e56f33c16f6b Mon Sep 17 00:00:00 2001 From: Tusooa Zhu Date: Sun, 12 Sep 2021 09:40:20 -0400 Subject: [PATCH] Add User.add_alias/2 and User.alias_users/1 Ref: emit-move --- lib/pleroma/user.ex | 19 ++++++++++++++ test/pleroma/user_test.exs | 52 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/lib/pleroma/user.ex b/lib/pleroma/user.ex index 390de1e2d..ff56927de 100644 --- a/lib/pleroma/user.ex +++ b/lib/pleroma/user.ex @@ -2270,6 +2270,25 @@ defmodule Pleroma.User do |> update_and_set_cache() end + def alias_users(user) do + user.also_known_as + |> Enum.map(&User.get_cached_by_ap_id/1) + |> Enum.filter(fn user -> user != nil end) + end + + def add_alias(user, new_alias_user) do + current_aliases = user.also_known_as || [] + new_alias_ap_id = new_alias_user.ap_id + + if new_alias_ap_id in current_aliases do + {:ok, user} + else + user + |> cast(%{also_known_as: current_aliases ++ [new_alias_ap_id]}, [:also_known_as]) + |> update_and_set_cache() + end + end + # Internal function; public one is `deactivate/2` defp set_activation_status(user, status) do user diff --git a/test/pleroma/user_test.exs b/test/pleroma/user_test.exs index 6cd93c34c..9971aba66 100644 --- a/test/pleroma/user_test.exs +++ b/test/pleroma/user_test.exs @@ -2498,4 +2498,56 @@ defmodule Pleroma.UserTest do %{object: %{data: %{"id" => object_id}}} = Activity.get_by_id_with_object(id) object_id end + + describe "add_alias/2" do + test "should add alias for another user" do + user = insert(:user) + user2 = insert(:user) + + assert {:ok, user_updated} = user |> User.add_alias(user2) + + assert user_updated.also_known_as |> length() == 1 + assert user2.ap_id in user_updated.also_known_as + end + + test "should add multiple aliases" do + user = insert(:user) + user2 = insert(:user) + user3 = insert(:user) + + assert {:ok, user} = user |> User.add_alias(user2) + assert {:ok, user_updated} = user |> User.add_alias(user3) + + assert user_updated.also_known_as |> length() == 2 + assert user2.ap_id in user_updated.also_known_as + assert user3.ap_id in user_updated.also_known_as + end + + test "should not add duplicate aliases" do + user = insert(:user) + user2 = insert(:user) + + assert {:ok, user} = user |> User.add_alias(user2) + + assert {:ok, user_updated} = user |> User.add_alias(user2) + + assert user_updated.also_known_as |> length() == 1 + assert user2.ap_id in user_updated.also_known_as + end + end + + describe "alias_users/1" do + test "should get aliases for a user" do + user = insert(:user) + user2 = insert(:user, also_known_as: [user.ap_id]) + + aliases = user2 |> User.alias_users() + + assert aliases |> length() == 1 + + alias_user = aliases |> Enum.at(0) + + assert alias_user.ap_id == user.ap_id + end + end end