1 defmodule Pleroma.User do
5 alias Pleroma.{Repo, User, Object}
6 alias Pleroma.Web.ActivityPub.ActivityPub
12 field :nickname, :string
13 field :password_hash, :string
14 field :password, :string, virtual: true
15 field :password_confirmation, :string, virtual: true
16 field :following, { :array, :string }, default: []
23 def ap_id(%User{nickname: nickname}) do
24 "#{Pleroma.Web.base_url}/users/#{nickname}"
27 def ap_followers(%User{} = user) do
28 "#{ap_id(user)}/followers"
31 def follow_changeset(struct, params \\ %{}) do
33 |> cast(params, [:following])
34 |> validate_required([:following])
37 def user_info(%User{} = user) do
38 note_count_query = from a in Object,
39 where: fragment("? @> ?", a.data, ^%{actor: user.ap_id, type: "Note"}),
42 follower_count_query = from u in User,
43 where: fragment("? @> ?", u.following, ^User.ap_followers(user)),
47 following_count: length(user.following),
48 note_count: Repo.one(note_count_query),
49 follower_count: Repo.one(follower_count_query)
53 def register_changeset(struct, params \\ %{}) do
55 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
56 |> validate_required([:bio, :email, :name, :nickname, :password, :password_confirmation])
57 |> validate_confirmation(:password)
58 |> unique_constraint(:email)
59 |> unique_constraint(:nickname)
61 if changeset.valid? do
62 hashed = Comeonin.Pbkdf2.hashpwsalt(changeset.changes[:password])
63 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
64 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
66 |> put_change(:password_hash, hashed)
67 |> put_change(:ap_id, ap_id)
68 |> put_change(:following, [followers])
74 def follow(%User{} = follower, %User{} = followed) do
75 ap_followers = User.ap_followers(followed)
76 if following?(follower, followed) do
78 "Could not follow user: #{followed.nickname} is already on your list." }
80 following = [ap_followers | follower.following]
84 |> follow_changeset(%{following: following})
89 def unfollow(%User{} = follower, %User{} = followed) do
90 ap_followers = User.ap_followers(followed)
91 if following?(follower, followed) do
92 following = follower.following
93 |> List.delete(ap_followers)
95 { :ok, follower } = follower
96 |> follow_changeset(%{following: following})
98 { :ok, follower, ActivityPub.fetch_latest_follow(follower, followed)}
100 { :error, "Not subscribed!" }
104 def following?(%User{} = follower, %User{} = followed) do
105 Enum.member?(follower.following, User.ap_followers(followed))
108 def get_cached_by_ap_id(ap_id) do
109 key = "ap_id:#{ap_id}"
110 Cachex.get!(:user_cache, key, fallback: fn(_) -> Repo.get_by(User, ap_id: ap_id) end)
113 def get_cached_by_nickname(nickname) do
114 key = "nickname:#{nickname}"
115 Cachex.get!(:user_cache, key, fallback: fn(_) -> Repo.get_by(User, nickname: nickname) end)