Add basic user caching.
[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 :following, { :array, :string }, default: []
13 field :ap_id, :string
14
15 timestamps()
16 end
17
18 def ap_id(%User{nickname: nickname}) do
19 "#{Pleroma.Web.base_url}/users/#{nickname}"
20 end
21
22 def ap_followers(%User{} = user) do
23 "#{ap_id(user)}/followers"
24 end
25
26 def follow_changeset(struct, params \\ %{}) do
27 struct
28 |> cast(params, [:following])
29 |> validate_required([:following])
30 end
31
32 def follow(%User{} = follower, %User{} = followed) do
33 ap_followers = User.ap_followers(followed)
34 following = [ap_followers | follower.following]
35 |> Enum.uniq
36
37 follower
38 |> follow_changeset(%{following: following})
39 |> Repo.update
40 end
41
42 def unfollow(%User{} = follower, %User{} = followed) do
43 ap_followers = User.ap_followers(followed)
44 following = follower.following
45 |> List.delete(ap_followers)
46
47 follower
48 |> follow_changeset(%{following: following})
49 |> Repo.update
50 end
51
52 def following?(%User{} = follower, %User{} = followed) do
53 Enum.member?(follower.following, User.ap_followers(followed))
54 end
55
56 def get_cached_by_ap_id(ap_id) do
57 ConCache.get_or_store(:users, "ap_id:#{ap_id}", fn() ->
58 # Return false so the cache will store it.
59 Repo.get_by(User, ap_id: ap_id) || false
60 end)
61 end
62
63 def get_cached_by_nickname(nickname) do
64 ConCache.get_or_store(:users, "nickname:#{nickname}", fn() ->
65 Repo.get_by(User, nickname: nickname) || false
66 end)
67 end
68 end