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,
71 locked: user.info["locked"] || false
75 @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])?)*$/
76 def remote_user_creation(params) do
79 |> cast(params, [:bio, :name, :ap_id, :nickname, :info, :avatar])
80 |> validate_required([:name, :ap_id, :nickname])
81 |> unique_constraint(:nickname)
82 |> validate_format(:nickname, @email_regex)
83 |> validate_length(:bio, max: 5000)
84 |> validate_length(:name, max: 100)
85 |> put_change(:local, false)
88 case changes.changes[:info]["source_data"] do
89 %{"followers" => followers} ->
91 |> put_change(:follower_address, followers)
94 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
97 |> put_change(:follower_address, followers)
104 def update_changeset(struct, params \\ %{}) do
106 |> cast(params, [:bio, :name])
107 |> unique_constraint(:nickname)
108 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
109 |> validate_length(:bio, max: 5000)
110 |> validate_length(:name, min: 1, max: 100)
113 def upgrade_changeset(struct, params \\ %{}) do
115 |> cast(params, [:bio, :name, :info, :follower_address, :avatar])
116 |> unique_constraint(:nickname)
117 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
118 |> validate_length(:bio, max: 5000)
119 |> validate_length(:name, max: 100)
122 def password_update_changeset(struct, params) do
125 |> cast(params, [:password, :password_confirmation])
126 |> validate_required([:password, :password_confirmation])
127 |> validate_confirmation(:password)
129 if changeset.valid? do
130 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
133 |> put_change(:password_hash, hashed)
139 def reset_password(user, data) do
140 update_and_set_cache(password_update_changeset(user, data))
143 def register_changeset(struct, params \\ %{}) do
146 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
147 |> validate_required([:email, :name, :nickname, :password, :password_confirmation])
148 |> validate_confirmation(:password)
149 |> unique_constraint(:email)
150 |> unique_constraint(:nickname)
151 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
152 |> validate_format(:email, @email_regex)
153 |> validate_length(:bio, max: 1000)
154 |> validate_length(:name, min: 1, max: 100)
156 if changeset.valid? do
157 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
158 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
159 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
162 |> put_change(:password_hash, hashed)
163 |> put_change(:ap_id, ap_id)
164 |> put_change(:following, [followers])
165 |> put_change(:follower_address, followers)
171 def maybe_direct_follow(%User{} = follower, %User{info: info} = followed) do
172 user_info = user_info(followed)
174 should_direct_follow =
176 # if the account is locked, don't pre-create the relationship
177 user_info[:locked] == true ->
180 # if the users are blocking each other, we shouldn't even be here, but check for it anyway
181 User.blocks?(follower, followed) == true or User.blocks?(followed, follower) == true ->
184 # if OStatus, then there is no three-way handshake to follow
185 User.ap_enabled?(followed) != true ->
188 # if there are no other reasons not to, just pre-create the relationship
193 if should_direct_follow do
194 follow(follower, followed)
200 def follow(%User{} = follower, %User{info: info} = followed) do
201 ap_followers = followed.follower_address
204 following?(follower, followed) or info["deactivated"] ->
205 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
207 blocks?(followed, follower) ->
208 {:error, "Could not follow user: #{followed.nickname} blocked you."}
211 if !followed.local && follower.local && !ap_enabled?(followed) do
212 Websub.subscribe(follower, followed)
216 [ap_followers | follower.following]
221 |> follow_changeset(%{following: following})
222 |> update_and_set_cache
224 {:ok, _} = update_follower_count(followed)
230 def unfollow(%User{} = follower, %User{} = followed) do
231 ap_followers = followed.follower_address
233 if following?(follower, followed) and follower.ap_id != followed.ap_id do
236 |> List.delete(ap_followers)
240 |> follow_changeset(%{following: following})
241 |> update_and_set_cache
243 {:ok, followed} = update_follower_count(followed)
245 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
247 {:error, "Not subscribed!"}
251 def following?(%User{} = follower, %User{} = followed) do
252 Enum.member?(follower.following, followed.follower_address)
255 def locked?(%User{} = user) do
256 user.info["locked"] || false
259 def get_by_ap_id(ap_id) do
260 Repo.get_by(User, ap_id: ap_id)
263 def update_and_set_cache(changeset) do
264 with {:ok, user} <- Repo.update(changeset) do
265 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
266 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
267 Cachex.put(:user_cache, "user_info:#{user.id}", user_info(user))
274 def invalidate_cache(user) do
275 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
276 Cachex.del(:user_cache, "nickname:#{user.nickname}")
279 def get_cached_by_ap_id(ap_id) do
280 key = "ap_id:#{ap_id}"
281 Cachex.fetch!(:user_cache, key, fn _ -> get_by_ap_id(ap_id) end)
284 def get_cached_by_nickname(nickname) do
285 key = "nickname:#{nickname}"
286 Cachex.fetch!(:user_cache, key, fn _ -> get_or_fetch_by_nickname(nickname) end)
289 def get_by_nickname(nickname) do
290 Repo.get_by(User, nickname: nickname)
293 def get_by_nickname_or_email(nickname_or_email) do
294 case user = Repo.get_by(User, nickname: nickname_or_email) do
296 nil -> Repo.get_by(User, email: nickname_or_email)
300 def get_cached_user_info(user) do
301 key = "user_info:#{user.id}"
302 Cachex.fetch!(:user_cache, key, fn _ -> user_info(user) end)
305 def fetch_by_nickname(nickname) do
306 ap_try = ActivityPub.make_user_from_nickname(nickname)
309 {:ok, user} -> {:ok, user}
310 _ -> OStatus.make_user(nickname)
314 def get_or_fetch_by_nickname(nickname) do
315 with %User{} = user <- get_by_nickname(nickname) do
319 with [_nick, _domain] <- String.split(nickname, "@"),
320 {:ok, user} <- fetch_by_nickname(nickname) do
328 def get_followers_query(%User{id: id, follower_address: follower_address}) do
331 where: fragment("? <@ ?", ^[follower_address], u.following),
336 def get_followers(user) do
337 q = get_followers_query(user)
342 def get_friends_query(%User{id: id, following: following}) do
345 where: u.follower_address in ^following,
350 def get_friends(user) do
351 q = get_friends_query(user)
356 def get_follow_requests_query(%User{} = user) do
360 "? ->> 'type' = 'Follow'",
364 "? ->> 'state' = 'pending'",
370 ^%{"object" => user.ap_id}
375 def get_follow_requests(%User{} = user) do
376 q = get_follow_requests_query(user)
380 Enum.map(reqs, fn (req) -> req.actor end)
381 |> Enum.map(fn (ap_id) -> get_by_ap_id(ap_id) end)
386 def increase_note_count(%User{} = user) do
387 note_count = (user.info["note_count"] || 0) + 1
388 new_info = Map.put(user.info, "note_count", note_count)
390 cs = info_changeset(user, %{info: new_info})
392 update_and_set_cache(cs)
395 def decrease_note_count(%User{} = user) do
396 note_count = user.info["note_count"] || 0
397 note_count = if note_count <= 0, do: 0, else: note_count - 1
398 new_info = Map.put(user.info, "note_count", note_count)
400 cs = info_changeset(user, %{info: new_info})
402 update_and_set_cache(cs)
405 def update_note_count(%User{} = user) do
409 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
413 note_count = Repo.one(note_count_query)
415 new_info = Map.put(user.info, "note_count", note_count)
417 cs = info_changeset(user, %{info: new_info})
419 update_and_set_cache(cs)
422 def update_follower_count(%User{} = user) do
423 follower_count_query =
426 where: ^user.follower_address in u.following,
427 where: u.id != ^user.id,
431 follower_count = Repo.one(follower_count_query)
433 new_info = Map.put(user.info, "follower_count", follower_count)
435 cs = info_changeset(user, %{info: new_info})
437 update_and_set_cache(cs)
440 def get_notified_from_activity(%Activity{recipients: to}) do
444 where: u.ap_id in ^to,
445 where: u.local == true
451 def get_recipients_from_activity(%Activity{recipients: to}) do
455 where: u.ap_id in ^to,
456 or_where: fragment("? && ?", u.following, ^to)
459 query = from(u in query, where: u.local == true)
464 def search(query, resolve) do
465 # strip the beginning @ off if there is a query
466 query = String.trim_leading(query, "@")
469 User.get_or_fetch_by_nickname(query)
488 s in subquery(inner),
489 order_by: s.search_distance,
496 def block(user, %{ap_id: ap_id}) do
497 blocks = user.info["blocks"] || []
498 new_blocks = Enum.uniq([ap_id | blocks])
499 new_info = Map.put(user.info, "blocks", new_blocks)
501 cs = User.info_changeset(user, %{info: new_info})
502 update_and_set_cache(cs)
505 def unblock(user, %{ap_id: ap_id}) do
506 blocks = user.info["blocks"] || []
507 new_blocks = List.delete(blocks, ap_id)
508 new_info = Map.put(user.info, "blocks", new_blocks)
510 cs = User.info_changeset(user, %{info: new_info})
511 update_and_set_cache(cs)
514 def blocks?(user, %{ap_id: ap_id}) do
515 blocks = user.info["blocks"] || []
516 domain_blocks = user.info["domain_blocks"] || []
517 %{host: host} = URI.parse(ap_id)
519 Enum.member?(blocks, ap_id) ||
520 Enum.any?(domain_blocks, fn domain ->
525 def block_domain(user, domain) do
526 domain_blocks = user.info["domain_blocks"] || []
527 new_blocks = Enum.uniq([domain | domain_blocks])
528 new_info = Map.put(user.info, "domain_blocks", new_blocks)
530 cs = User.info_changeset(user, %{info: new_info})
531 update_and_set_cache(cs)
534 def unblock_domain(user, domain) do
535 blocks = user.info["domain_blocks"] || []
536 new_blocks = List.delete(blocks, domain)
537 new_info = Map.put(user.info, "domain_blocks", new_blocks)
539 cs = User.info_changeset(user, %{info: new_info})
540 update_and_set_cache(cs)
543 def local_user_query() do
544 from(u in User, where: u.local == true)
547 def deactivate(%User{} = user) do
548 new_info = Map.put(user.info, "deactivated", true)
549 cs = User.info_changeset(user, %{info: new_info})
550 update_and_set_cache(cs)
553 def delete(%User{} = user) do
554 {:ok, user} = User.deactivate(user)
556 # Remove all relationships
557 {:ok, followers} = User.get_followers(user)
560 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
562 {:ok, friends} = User.get_friends(user)
565 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
567 query = from(a in Activity, where: a.actor == ^user.ap_id)
570 |> Enum.each(fn activity ->
571 case activity.data["type"] do
573 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
575 # TODO: Do something with likes, follows, repeats.
584 def get_or_fetch_by_ap_id(ap_id) do
585 if user = get_by_ap_id(ap_id) do
588 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
595 case OStatus.make_user(ap_id) do
597 _ -> {:error, "Could not fetch by AP id"}
604 def public_key_from_info(%{
605 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
608 :public_key.pem_decode(public_key_pem)
610 |> :public_key.pem_entry_decode()
616 def public_key_from_info(%{"magic_key" => magic_key}) do
617 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
620 def get_public_key_for_ap_id(ap_id) do
621 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
622 {:ok, public_key} <- public_key_from_info(user.info) do
629 defp blank?(""), do: nil
630 defp blank?(n), do: n
632 def insert_or_update_user(data) do
635 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
637 cs = User.remote_user_creation(data)
638 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
641 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
642 def ap_enabled?(_), do: false
644 def get_or_fetch(uri_or_nickname) do
645 if String.starts_with?(uri_or_nickname, "http") do
646 get_or_fetch_by_ap_id(uri_or_nickname)
648 get_or_fetch_by_nickname(uri_or_nickname)