1 defmodule Pleroma.User do
4 import Ecto.{Changeset, Query}
5 alias Pleroma.{Repo, User, Object, Web, Activity, Notification}
7 alias Pleroma.Web.{OStatus, Websub}
8 alias Pleroma.Web.ActivityPub.{Utils, ActivityPub}
12 field(:email, :string)
14 field(:nickname, :string)
15 field(:password_hash, :string)
16 field(:password, :string, virtual: true)
17 field(:password_confirmation, :string, virtual: true)
18 field(:following, {:array, :string}, default: [])
19 field(:ap_id, :string)
21 field(:local, :boolean, default: true)
22 field(:info, :map, default: %{})
23 field(:follower_address, :string)
24 field(:search_distance, :float, virtual: true)
25 has_many(:notifications, Notification)
30 def avatar_url(user) do
32 %{"url" => [%{"href" => href} | _]} -> href
33 _ -> "#{Web.base_url()}/images/avi.png"
37 def banner_url(user) do
38 case user.info["banner"] do
39 %{"url" => [%{"href" => href} | _]} -> href
40 _ -> "#{Web.base_url()}/images/banner.png"
44 def ap_id(%User{nickname: nickname}) do
45 "#{Web.base_url()}/users/#{nickname}"
48 def ap_followers(%User{} = user) do
49 "#{ap_id(user)}/followers"
52 def follow_changeset(struct, params \\ %{}) do
54 |> cast(params, [:following])
55 |> validate_required([:following])
58 def info_changeset(struct, params \\ %{}) do
60 |> cast(params, [:info])
61 |> validate_required([:info])
64 def user_info(%User{} = user) do
65 oneself = if user.local, do: 1, else: 0
68 following_count: length(user.following) - oneself,
69 note_count: user.info["note_count"] || 0,
70 follower_count: user.info["follower_count"] || 0
74 @email_regex ~r/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
75 def remote_user_creation(params) do
78 |> cast(params, [:bio, :name, :ap_id, :nickname, :info, :avatar])
79 |> validate_required([:name, :ap_id, :nickname])
80 |> unique_constraint(:nickname)
81 |> validate_format(:nickname, @email_regex)
82 |> validate_length(:bio, max: 5000)
83 |> validate_length(:name, max: 100)
84 |> put_change(:local, false)
87 case changes.changes[:info]["source_data"] do
88 %{"followers" => followers} ->
90 |> put_change(:follower_address, followers)
93 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
96 |> put_change(:follower_address, followers)
103 def update_changeset(struct, params \\ %{}) do
105 |> cast(params, [:bio, :name])
106 |> unique_constraint(:nickname)
107 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
108 |> validate_length(:bio, max: 5000)
109 |> validate_length(:name, min: 1, max: 100)
112 def upgrade_changeset(struct, params \\ %{}) do
114 |> cast(params, [:bio, :name, :info, :follower_address, :avatar])
115 |> unique_constraint(:nickname)
116 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
117 |> validate_length(:bio, max: 5000)
118 |> validate_length(:name, max: 100)
121 def password_update_changeset(struct, params) do
124 |> cast(params, [:password, :password_confirmation])
125 |> validate_required([:password, :password_confirmation])
126 |> validate_confirmation(:password)
128 if changeset.valid? do
129 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
132 |> put_change(:password_hash, hashed)
138 def reset_password(user, data) do
139 update_and_set_cache(password_update_changeset(user, data))
142 def register_changeset(struct, params \\ %{}) do
145 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
146 |> validate_required([:email, :name, :nickname, :password, :password_confirmation])
147 |> validate_confirmation(:password)
148 |> unique_constraint(:email)
149 |> unique_constraint(:nickname)
150 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
151 |> validate_format(:email, @email_regex)
152 |> validate_length(:bio, max: 1000)
153 |> validate_length(:name, min: 1, max: 100)
155 if changeset.valid? do
156 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
157 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
158 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
161 |> put_change(:password_hash, hashed)
162 |> put_change(:ap_id, ap_id)
163 |> put_change(:following, [followers])
164 |> put_change(:follower_address, followers)
170 def follow(%User{} = follower, %User{info: info} = followed) do
171 ap_followers = followed.follower_address
173 if following?(follower, followed) or info["deactivated"] do
174 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
176 if !followed.local && follower.local && !ap_enabled?(followed) do
177 Websub.subscribe(follower, followed)
181 [ap_followers | follower.following]
186 |> follow_changeset(%{following: following})
187 |> update_and_set_cache
189 {:ok, _} = update_follower_count(followed)
195 def unfollow(%User{} = follower, %User{} = followed) do
196 ap_followers = followed.follower_address
198 if following?(follower, followed) and follower.ap_id != followed.ap_id do
201 |> List.delete(ap_followers)
205 |> follow_changeset(%{following: following})
206 |> update_and_set_cache
208 {:ok, followed} = update_follower_count(followed)
210 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
212 {:error, "Not subscribed!"}
216 def following?(%User{} = follower, %User{} = followed) do
217 Enum.member?(follower.following, followed.follower_address)
220 def get_by_ap_id(ap_id) do
221 Repo.get_by(User, ap_id: ap_id)
224 def update_and_set_cache(changeset) do
225 with {:ok, user} <- Repo.update(changeset) do
226 Cachex.set(:user_cache, "ap_id:#{user.ap_id}", user)
227 Cachex.set(:user_cache, "nickname:#{user.nickname}", user)
228 Cachex.set(:user_cache, "user_info:#{user.id}", user_info(user))
235 def invalidate_cache(user) do
236 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
237 Cachex.del(:user_cache, "nickname:#{user.nickname}")
240 def get_cached_by_ap_id(ap_id) do
241 key = "ap_id:#{ap_id}"
242 Cachex.get!(:user_cache, key, fallback: fn _ -> get_by_ap_id(ap_id) end)
245 def get_cached_by_nickname(nickname) do
246 key = "nickname:#{nickname}"
247 Cachex.get!(:user_cache, key, fallback: fn _ -> get_or_fetch_by_nickname(nickname) end)
250 def get_by_nickname(nickname) do
251 Repo.get_by(User, nickname: nickname)
254 def get_by_nickname_or_email(nickname_or_email) do
255 case user = Repo.get_by(User, nickname: nickname_or_email) do
257 nil -> Repo.get_by(User, email: nickname_or_email)
261 def get_cached_user_info(user) do
262 key = "user_info:#{user.id}"
263 Cachex.get!(:user_cache, key, fallback: fn _ -> user_info(user) end)
266 def fetch_by_nickname(nickname) do
267 ap_try = ActivityPub.make_user_from_nickname(nickname)
270 {:ok, user} -> {:ok, user}
271 _ -> OStatus.make_user(nickname)
275 def get_or_fetch_by_nickname(nickname) do
276 with %User{} = user <- get_by_nickname(nickname) do
280 with [_nick, _domain] <- String.split(nickname, "@"),
281 {:ok, user} <- fetch_by_nickname(nickname) do
289 def get_followers_query(%User{id: id, follower_address: follower_address}) do
292 where: fragment("? <@ ?", ^[follower_address], u.following),
297 def get_followers(user) do
298 q = get_followers_query(user)
303 def get_friends_query(%User{id: id, following: following}) do
306 where: u.follower_address in ^following,
311 def get_friends(user) do
312 q = get_friends_query(user)
317 def increase_note_count(%User{} = user) do
318 note_count = (user.info["note_count"] || 0) + 1
319 new_info = Map.put(user.info, "note_count", note_count)
321 cs = info_changeset(user, %{info: new_info})
323 update_and_set_cache(cs)
326 def decrease_note_count(%User{} = user) do
327 note_count = user.info["note_count"] || 0
328 note_count = if note_count <= 0, do: 0, else: note_count - 1
329 new_info = Map.put(user.info, "note_count", note_count)
331 cs = info_changeset(user, %{info: new_info})
333 update_and_set_cache(cs)
336 def update_note_count(%User{} = user) do
340 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
344 note_count = Repo.one(note_count_query)
346 new_info = Map.put(user.info, "note_count", note_count)
348 cs = info_changeset(user, %{info: new_info})
350 update_and_set_cache(cs)
353 def update_follower_count(%User{} = user) do
354 follower_count_query =
357 where: ^user.follower_address in u.following,
358 where: u.id != ^user.id,
362 follower_count = Repo.one(follower_count_query)
364 new_info = Map.put(user.info, "follower_count", follower_count)
366 cs = info_changeset(user, %{info: new_info})
368 update_and_set_cache(cs)
371 def get_notified_from_activity(%Activity{recipients: to}) do
375 where: u.ap_id in ^to,
376 where: u.local == true
382 def get_recipients_from_activity(%Activity{recipients: to}) do
386 where: u.ap_id in ^to,
387 or_where: fragment("? && ?", u.following, ^to)
390 query = from(u in query, where: u.local == true)
395 def search(query, resolve) do
396 # strip the beginning @ off if there is a query
397 query = String.trim_leading(query, "@")
400 User.get_or_fetch_by_nickname(query)
407 search_distance: fragment(
415 q = from(s in subquery(inner),
416 order_by: s.search_distance,
423 def block(user, %{ap_id: ap_id}) do
424 blocks = user.info["blocks"] || []
425 new_blocks = Enum.uniq([ap_id | blocks])
426 new_info = Map.put(user.info, "blocks", new_blocks)
428 cs = User.info_changeset(user, %{info: new_info})
429 update_and_set_cache(cs)
432 def unblock(user, %{ap_id: ap_id}) do
433 blocks = user.info["blocks"] || []
434 new_blocks = List.delete(blocks, ap_id)
435 new_info = Map.put(user.info, "blocks", new_blocks)
437 cs = User.info_changeset(user, %{info: new_info})
438 update_and_set_cache(cs)
441 def blocks?(user, %{ap_id: ap_id}) do
442 blocks = user.info["blocks"] || []
443 Enum.member?(blocks, ap_id)
446 def local_user_query() do
447 from(u in User, where: u.local == true)
450 def deactivate(%User{} = user) do
451 new_info = Map.put(user.info, "deactivated", true)
452 cs = User.info_changeset(user, %{info: new_info})
453 update_and_set_cache(cs)
456 def delete(%User{} = user) do
457 {:ok, user} = User.deactivate(user)
459 # Remove all relationships
460 {:ok, followers} = User.get_followers(user)
463 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
465 {:ok, friends} = User.get_friends(user)
468 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
470 query = from(a in Activity, where: a.actor == ^user.ap_id)
473 |> Enum.each(fn activity ->
474 case activity.data["type"] do
476 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
478 # TODO: Do something with likes, follows, repeats.
487 def get_or_fetch_by_ap_id(ap_id) do
488 if user = get_by_ap_id(ap_id) do
491 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
498 case OStatus.make_user(ap_id) do
500 _ -> {:error, "Could not fetch by AP id"}
507 def public_key_from_info(%{
508 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
511 :public_key.pem_decode(public_key_pem)
513 |> :public_key.pem_entry_decode()
519 def public_key_from_info(%{"magic_key" => magic_key}) do
520 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
523 def get_public_key_for_ap_id(ap_id) do
524 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
525 {:ok, public_key} <- public_key_from_info(user.info) do
532 defp blank?(""), do: nil
533 defp blank?(n), do: n
535 def insert_or_update_user(data) do
538 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
540 cs = User.remote_user_creation(data)
541 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
544 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
545 def ap_enabled?(_), do: false
547 def get_or_fetch(uri_or_nickname) do
548 if String.starts_with?(uri_or_nickname, "http") do
549 get_or_fetch_by_ap_id(uri_or_nickname)
551 get_or_fetch_by_nickname(uri_or_nickname)