Websub controller beginnings.
[akkoma] / lib / pleroma / user.ex
1 defmodule Pleroma.User do
2 use Ecto.Schema
3 import Ecto.Changeset
4 alias Pleroma.{Repo, User}
5
6 schema "users" do
7 field :bio, :string
8 field :email, :string
9 field :name, :string
10 field :nickname, :string
11 field :password_hash, :string
12 field :password, :string, virtual: true
13 field :password_confirmation, :string, virtual: true
14 field :following, { :array, :string }, default: []
15 field :ap_id, :string
16 field :avatar, :map
17
18 timestamps()
19 end
20
21 def avatar_url(user) do
22 case user.avatar do
23 %{"url" => [%{"href" => href} | _]} -> href
24 _ -> "https://placehold.it/48x48"
25 end
26 end
27
28 def ap_id(%User{nickname: nickname}) do
29 "#{Pleroma.Web.base_url}/users/#{nickname}"
30 end
31
32 def ap_followers(%User{} = user) do
33 "#{ap_id(user)}/followers"
34 end
35
36 def follow_changeset(struct, params \\ %{}) do
37 struct
38 |> cast(params, [:following])
39 |> validate_required([:following])
40 end
41
42 def register_changeset(struct, params \\ %{}) do
43 changeset = struct
44 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
45 |> validate_required([:bio, :email, :name, :nickname, :password, :password_confirmation])
46 |> validate_confirmation(:password)
47 |> unique_constraint(:email)
48 |> unique_constraint(:nickname)
49
50 if changeset.valid? do
51 hashed = Comeonin.Pbkdf2.hashpwsalt(changeset.changes[:password])
52 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
53 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
54 changeset
55 |> put_change(:password_hash, hashed)
56 |> put_change(:ap_id, ap_id)
57 |> put_change(:following, [followers])
58 else
59 changeset
60 end
61 end
62
63 def follow(%User{} = follower, %User{} = followed) do
64 ap_followers = User.ap_followers(followed)
65 following = [ap_followers | follower.following]
66 |> Enum.uniq
67
68 follower
69 |> follow_changeset(%{following: following})
70 |> Repo.update
71 end
72
73 def unfollow(%User{} = follower, %User{} = followed) do
74 ap_followers = User.ap_followers(followed)
75 following = follower.following
76 |> List.delete(ap_followers)
77
78 follower
79 |> follow_changeset(%{following: following})
80 |> Repo.update
81 end
82
83 def following?(%User{} = follower, %User{} = followed) do
84 Enum.member?(follower.following, User.ap_followers(followed))
85 end
86
87 def get_cached_by_ap_id(ap_id) do
88 key = "ap_id:#{ap_id}"
89 Cachex.get!(:user_cache, key, fallback: fn(_) -> Repo.get_by(User, ap_id: ap_id) end)
90 end
91
92 def get_cached_by_nickname(nickname) do
93 key = "nickname:#{nickname}"
94 Cachex.get!(:user_cache, key, fallback: fn(_) -> Repo.get_by(User, nickname: nickname) end)
95 end
96 end