From bed0b398139897ebe9f839d1263acf6934c4a42f Mon Sep 17 00:00:00 2001 From: Roger Braun Date: Sun, 30 Apr 2017 18:48:48 +0200 Subject: [PATCH] Add function to fetch users from fqn. --- lib/pleroma/user.ex | 12 ++++++++++++ test/user_test.exs | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/lib/pleroma/user.ex b/lib/pleroma/user.ex index 58f89a915..c264d7e90 100644 --- a/lib/pleroma/user.ex +++ b/lib/pleroma/user.ex @@ -3,6 +3,7 @@ defmodule Pleroma.User do import Ecto.Changeset import Ecto.Query alias Pleroma.{Repo, User, Activity, Object} + alias Pleroma.Web.OStatus schema "users" do field :bio, :string @@ -131,4 +132,15 @@ defmodule Pleroma.User do key = "user_info:#{user.id}" Cachex.get!(:user_cache, key, fallback: fn(_) -> user_info(user) end) end + + def get_or_fetch_by_nickname(nickname) do + with %User{} = user <- get_by_nickname(nickname) do + user + else _e -> + with {:ok, user} <- OStatus.make_user(nickname) do + user + else _e -> nil + end + end + end end diff --git a/test/user_test.exs b/test/user_test.exs index d711adb9d..6684aa434 100644 --- a/test/user_test.exs +++ b/test/user_test.exs @@ -86,4 +86,24 @@ defmodule Pleroma.UserTest do assert changeset.changes[:following] == [User.ap_followers(%User{nickname: @full_user_data.nickname})] end end + + describe "fetching a user from nickname or trying to build one" do + test "gets an existing user" do + user = insert(:user) + fetched_user = User.get_or_fetch_by_nickname(user.nickname) + + assert user == fetched_user + end + + test "fetches an external user via ostatus if no user exists" do + fetched_user = User.get_or_fetch_by_nickname("shp@social.heldscal.la") + assert fetched_user.nickname == "shp@social.heldscal.la" + end + + test "returns nil if no user could be fetched" do + fetched_user = User.get_or_fetch_by_nickname("nonexistant@social.heldscal.la") + assert fetched_user == nil + end + end end +