1 defmodule Pleroma.User do
4 import Ecto.{Changeset, Query}
5 alias Pleroma.{Repo, User, Object, Web, Activity, Notification}
7 alias Pleroma.Formatter
8 alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils
9 alias Pleroma.Web.{OStatus, Websub, OAuth}
10 alias Pleroma.Web.ActivityPub.{Utils, ActivityPub}
12 @type t :: %__MODULE__{}
14 @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])?)*$/
16 @strict_local_nickname_regex ~r/^[a-zA-Z\d]+$/
17 @extended_local_nickname_regex ~r/^[a-zA-Z\d_-]+$/
21 field(:email, :string)
23 field(:nickname, :string)
24 field(:password_hash, :string)
25 field(:password, :string, virtual: true)
26 field(:password_confirmation, :string, virtual: true)
27 field(:following, {:array, :string}, default: [])
28 field(:ap_id, :string)
30 field(:local, :boolean, default: true)
31 field(:follower_address, :string)
32 field(:search_distance, :float, virtual: true)
33 field(:tags, {:array, :string}, default: [])
34 field(:last_refreshed_at, :naive_datetime)
35 has_many(:notifications, Notification)
36 embeds_one(:info, Pleroma.User.Info)
41 def avatar_url(user) do
43 %{"url" => [%{"href" => href} | _]} -> href
44 _ -> "#{Web.base_url()}/images/avi.png"
48 def banner_url(user) do
49 case user.info.banner do
50 %{"url" => [%{"href" => href} | _]} -> href
51 _ -> "#{Web.base_url()}/images/banner.png"
55 def profile_url(%User{info: %{source_data: %{"url" => url}}}), do: url
56 def profile_url(%User{ap_id: ap_id}), do: ap_id
57 def profile_url(_), do: nil
59 def ap_id(%User{nickname: nickname}) do
60 "#{Web.base_url()}/users/#{nickname}"
63 def ap_followers(%User{} = user) do
64 "#{ap_id(user)}/followers"
67 def follow_changeset(struct, params \\ %{}) do
69 |> cast(params, [:following])
70 |> validate_required([:following])
73 def user_info(%User{} = user) do
74 oneself = if user.local, do: 1, else: 0
77 following_count: length(user.following) - oneself,
78 note_count: user.info.note_count,
79 follower_count: user.info.follower_count,
80 locked: user.info.locked,
81 default_scope: user.info.default_scope
85 def remote_user_creation(params) do
88 |> Map.put(:info, params[:info] || %{})
90 info_cng = User.Info.remote_user_creation(%User.Info{}, params[:info])
94 |> cast(params, [:bio, :name, :ap_id, :nickname, :avatar])
95 |> validate_required([:name, :ap_id])
96 |> unique_constraint(:nickname)
97 |> validate_format(:nickname, @email_regex)
98 |> validate_length(:bio, max: 5000)
99 |> validate_length(:name, max: 100)
100 |> put_change(:local, false)
101 |> put_embed(:info, info_cng)
104 case info_cng.changes[:source_data] do
105 %{"followers" => followers} ->
107 |> put_change(:follower_address, followers)
110 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
113 |> put_change(:follower_address, followers)
120 def update_changeset(struct, params \\ %{}) do
122 |> cast(params, [:bio, :name, :avatar])
123 |> unique_constraint(:nickname)
124 |> validate_format(:nickname, local_nickname_regex())
125 |> validate_length(:bio, max: 5000)
126 |> validate_length(:name, min: 1, max: 100)
129 def upgrade_changeset(struct, params \\ %{}) do
132 |> Map.put(:last_refreshed_at, NaiveDateTime.utc_now())
136 |> User.Info.user_upgrade(params[:info])
139 |> cast(params, [:bio, :name, :follower_address, :avatar, :last_refreshed_at])
140 |> unique_constraint(:nickname)
141 |> validate_format(:nickname, local_nickname_regex())
142 |> validate_length(:bio, max: 5000)
143 |> validate_length(:name, max: 100)
144 |> put_embed(:info, info_cng)
147 def password_update_changeset(struct, params) do
150 |> cast(params, [:password, :password_confirmation])
151 |> validate_required([:password, :password_confirmation])
152 |> validate_confirmation(:password)
154 OAuth.Token.delete_user_tokens(struct)
155 OAuth.Authorization.delete_user_authorizations(struct)
157 if changeset.valid? do
158 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
161 |> put_change(:password_hash, hashed)
167 def reset_password(user, data) do
168 update_and_set_cache(password_update_changeset(user, data))
171 def register_changeset(struct, params \\ %{}) do
174 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
175 |> validate_required([:email, :name, :nickname, :password, :password_confirmation])
176 |> validate_confirmation(:password)
177 |> unique_constraint(:email)
178 |> unique_constraint(:nickname)
179 |> validate_format(:nickname, local_nickname_regex())
180 |> validate_format(:email, @email_regex)
181 |> validate_length(:bio, max: 1000)
182 |> validate_length(:name, min: 1, max: 100)
183 |> put_change(:info, %Pleroma.User.Info{})
185 if changeset.valid? do
186 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
187 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
188 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
191 |> put_change(:password_hash, hashed)
192 |> put_change(:ap_id, ap_id)
193 |> put_change(:following, [followers])
194 |> put_change(:follower_address, followers)
200 def needs_update?(%User{local: true}), do: false
202 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
204 def needs_update?(%User{local: false} = user) do
205 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86400
208 def needs_update?(_), do: true
210 def maybe_direct_follow(%User{} = follower, %User{local: true, info: %{locked: true}}) do
214 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
215 follow(follower, followed)
218 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
219 if not User.ap_enabled?(followed) do
220 follow(follower, followed)
226 def maybe_follow(%User{} = follower, %User{info: _info} = followed) do
227 if not following?(follower, followed) do
228 follow(follower, followed)
234 def follow(%User{} = follower, %User{info: info} = followed) do
235 user_config = Application.get_env(:pleroma, :user)
236 deny_follow_blocked = Keyword.get(user_config, :deny_follow_blocked)
238 ap_followers = followed.follower_address
241 following?(follower, followed) or info.deactivated ->
242 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
244 deny_follow_blocked and blocks?(followed, follower) ->
245 {:error, "Could not follow user: #{followed.nickname} blocked you."}
248 if !followed.local && follower.local && !ap_enabled?(followed) do
249 Websub.subscribe(follower, followed)
253 [ap_followers | follower.following]
258 |> follow_changeset(%{following: following})
259 |> update_and_set_cache
261 {:ok, _} = update_follower_count(followed)
267 def unfollow(%User{} = follower, %User{} = followed) do
268 ap_followers = followed.follower_address
270 if following?(follower, followed) and follower.ap_id != followed.ap_id do
273 |> List.delete(ap_followers)
277 |> follow_changeset(%{following: following})
278 |> update_and_set_cache
280 {:ok, followed} = update_follower_count(followed)
282 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
284 {:error, "Not subscribed!"}
288 @spec following?(User.t(), User.t()) :: boolean
289 def following?(%User{} = follower, %User{} = followed) do
290 Enum.member?(follower.following, followed.follower_address)
293 def locked?(%User{} = user) do
294 user.info.locked || false
297 def get_by_ap_id(ap_id) do
298 Repo.get_by(User, ap_id: ap_id)
301 def update_and_set_cache(changeset) do
302 with {:ok, user} <- Repo.update(changeset) do
303 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
304 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
305 Cachex.put(:user_cache, "user_info:#{user.id}", user_info(user))
312 def invalidate_cache(user) do
313 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
314 Cachex.del(:user_cache, "nickname:#{user.nickname}")
315 Cachex.del(:user_cache, "user_info:#{user.id}")
318 def get_cached_by_ap_id(ap_id) do
319 key = "ap_id:#{ap_id}"
320 Cachex.fetch!(:user_cache, key, fn _ -> get_by_ap_id(ap_id) end)
323 def get_cached_by_nickname(nickname) do
324 key = "nickname:#{nickname}"
325 Cachex.fetch!(:user_cache, key, fn _ -> get_or_fetch_by_nickname(nickname) end)
328 def get_by_nickname(nickname) do
329 Repo.get_by(User, nickname: nickname)
332 def get_by_nickname_or_email(nickname_or_email) do
333 case user = Repo.get_by(User, nickname: nickname_or_email) do
335 nil -> Repo.get_by(User, email: nickname_or_email)
339 def get_cached_user_info(user) do
340 key = "user_info:#{user.id}"
341 Cachex.fetch!(:user_cache, key, fn _ -> user_info(user) end)
344 def fetch_by_nickname(nickname) do
345 ap_try = ActivityPub.make_user_from_nickname(nickname)
348 {:ok, user} -> {:ok, user}
349 _ -> OStatus.make_user(nickname)
353 def get_or_fetch_by_nickname(nickname) do
354 with %User{} = user <- get_by_nickname(nickname) do
358 with [_nick, _domain] <- String.split(nickname, "@"),
359 {:ok, user} <- fetch_by_nickname(nickname) do
367 def get_followers_query(%User{id: id, follower_address: follower_address}) do
370 where: fragment("? <@ ?", ^[follower_address], u.following),
375 def get_followers(user) do
376 q = get_followers_query(user)
381 def get_friends_query(%User{id: id, following: following}) do
384 where: u.follower_address in ^following,
389 def get_friends(user) do
390 q = get_friends_query(user)
395 def get_follow_requests_query(%User{} = user) do
400 "? ->> 'type' = 'Follow'",
405 "? ->> 'state' = 'pending'",
412 ^%{"object" => user.ap_id}
417 def get_follow_requests(%User{} = user) do
418 q = get_follow_requests_query(user)
422 Enum.map(reqs, fn req -> req.actor end)
424 |> Enum.map(fn ap_id -> get_by_ap_id(ap_id) end)
425 |> Enum.filter(fn u -> !following?(u, user) end)
430 def increase_note_count(%User{} = user) do
431 info_cng = User.Info.add_to_note_count(user.info, 1)
435 |> put_embed(:info, info_cng)
437 update_and_set_cache(cng)
440 def decrease_note_count(%User{} = user) do
441 info_cng = User.Info.add_to_note_count(user.info, -1)
445 |> put_embed(:info, info_cng)
447 update_and_set_cache(cng)
450 def update_note_count(%User{} = user) do
454 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
458 note_count = Repo.one(note_count_query)
460 info_cng = User.Info.set_note_count(user.info, note_count)
464 |> put_embed(:info, info_cng)
466 update_and_set_cache(cng)
469 def update_follower_count(%User{} = user) do
470 follower_count_query =
473 where: ^user.follower_address in u.following,
474 where: u.id != ^user.id,
478 follower_count = Repo.one(follower_count_query)
482 |> User.Info.set_follower_count(follower_count)
486 |> put_embed(:info, info_cng)
488 update_and_set_cache(cng)
491 def get_users_from_set_query(ap_ids, false) do
494 where: u.ap_id in ^ap_ids
498 def get_users_from_set_query(ap_ids, true) do
499 query = get_users_from_set_query(ap_ids, false)
503 where: u.local == true
507 def get_users_from_set(ap_ids, local_only \\ true) do
508 get_users_from_set_query(ap_ids, local_only)
512 def get_recipients_from_activity(%Activity{recipients: to}) do
516 where: u.ap_id in ^to,
517 or_where: fragment("? && ?", u.following, ^to)
520 query = from(u in query, where: u.local == true)
525 def search(query, resolve \\ false) do
526 # strip the beginning @ off if there is a query
527 query = String.trim_leading(query, "@")
530 User.get_or_fetch_by_nickname(query)
545 where: not is_nil(u.nickname)
550 s in subquery(inner),
551 order_by: s.search_distance,
558 def block(blocker, %User{ap_id: ap_id} = blocked) do
559 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
561 if following?(blocker, blocked) do
562 {:ok, blocker, _} = unfollow(blocker, blocked)
568 if following?(blocked, blocker) do
569 unfollow(blocked, blocker)
574 |> User.Info.add_to_block(ap_id)
578 |> put_embed(:info, info_cng)
580 update_and_set_cache(cng)
583 # helper to handle the block given only an actor's AP id
584 def block(blocker, %{ap_id: ap_id}) do
585 block(blocker, User.get_by_ap_id(ap_id))
588 def unblock(blocker, %{ap_id: ap_id}) do
591 |> User.Info.remove_from_block(ap_id)
595 |> put_embed(:info, info_cng)
597 update_and_set_cache(cng)
600 def blocks?(user, %{ap_id: ap_id}) do
601 blocks = user.info.blocks
602 domain_blocks = user.info.domain_blocks
603 %{host: host} = URI.parse(ap_id)
605 Enum.member?(blocks, ap_id) ||
606 Enum.any?(domain_blocks, fn domain ->
611 def block_domain(user, domain) do
614 |> User.Info.add_to_domain_block(domain)
618 |> put_embed(:info, info_cng)
620 update_and_set_cache(cng)
623 def unblock_domain(user, domain) do
626 |> User.Info.remove_from_domain_block(domain)
630 |> put_embed(:info, info_cng)
632 update_and_set_cache(cng)
635 def local_user_query() do
638 where: u.local == true,
639 where: not is_nil(u.nickname)
643 def moderator_user_query() do
646 where: u.local == true,
647 where: fragment("?->'is_moderator' @> 'true'", u.info)
651 def deactivate(%User{} = user, status \\ true) do
652 info_cng = User.Info.set_activation_status(user.info, status)
656 |> put_embed(:info, info_cng)
658 update_and_set_cache(cng)
661 def delete(%User{} = user) do
662 {:ok, user} = User.deactivate(user)
664 # Remove all relationships
665 {:ok, followers} = User.get_followers(user)
668 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
670 {:ok, friends} = User.get_friends(user)
673 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
675 query = from(a in Activity, where: a.actor == ^user.ap_id)
678 |> Enum.each(fn activity ->
679 case activity.data["type"] do
681 ActivityPub.delete(Object.normalize(activity.data["object"]))
683 # TODO: Do something with likes, follows, repeats.
692 def html_filter_policy(%User{info: %{no_rich_text: true}}) do
693 Pleroma.HTML.Scrubber.TwitterText
696 def html_filter_policy(_), do: nil
698 def get_or_fetch_by_ap_id(ap_id) do
699 user = get_by_ap_id(ap_id)
701 if !is_nil(user) and !User.needs_update?(user) do
704 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
711 case OStatus.make_user(ap_id) do
713 _ -> {:error, "Could not fetch by AP id"}
719 def get_or_create_instance_user do
720 relay_uri = "#{Pleroma.Web.Endpoint.url()}/relay"
722 if user = get_by_ap_id(relay_uri) do
726 %User{info: %User.Info{}}
727 |> cast(%{}, [:ap_id, :nickname, :local])
728 |> put_change(:ap_id, relay_uri)
729 |> put_change(:nickname, nil)
730 |> put_change(:local, true)
731 |> put_change(:follower_address, relay_uri <> "/followers")
733 {:ok, user} = Repo.insert(changes)
739 def public_key_from_info(%{
740 source_data: %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
744 |> :public_key.pem_decode()
746 |> :public_key.pem_entry_decode()
752 def public_key_from_info(%{magic_key: magic_key}) do
753 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
756 def get_public_key_for_ap_id(ap_id) do
757 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
758 {:ok, public_key} <- public_key_from_info(user.info) do
765 defp blank?(""), do: nil
766 defp blank?(n), do: n
768 def insert_or_update_user(data) do
771 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
773 cs = User.remote_user_creation(data)
775 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
778 def ap_enabled?(%User{local: true}), do: true
779 def ap_enabled?(%User{info: info}), do: info.ap_enabled
780 def ap_enabled?(_), do: false
782 @doc "Gets or fetch a user by uri or nickname."
783 @spec get_or_fetch(String.t()) :: User.t()
784 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
785 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
787 # wait a period of time and return newest version of the User structs
788 # this is because we have synchronous follow APIs and need to simulate them
789 # with an async handshake
790 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
791 with %User{} = a <- Repo.get(User, a.id),
792 %User{} = b <- Repo.get(User, b.id) do
800 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
801 with :ok <- :timer.sleep(timeout),
802 %User{} = a <- Repo.get(User, a.id),
803 %User{} = b <- Repo.get(User, b.id) do
811 def parse_bio(bio, user \\ %User{info: %{source_data: %{}}})
812 def parse_bio(nil, _user), do: ""
813 def parse_bio(bio, _user) when bio == "", do: bio
815 def parse_bio(bio, user) do
816 mentions = Formatter.parse_mentions(bio)
817 tags = Formatter.parse_tags(bio)
820 (user.info.source_data["tag"] || [])
821 |> Enum.filter(fn %{"type" => t} -> t == "Emoji" end)
822 |> Enum.map(fn %{"icon" => %{"url" => url}, "name" => name} ->
823 {String.trim(name, ":"), url}
827 |> CommonUtils.format_input(mentions, tags, "text/plain")
828 |> Formatter.emojify(emoji)
831 def tag(user_identifiers, tags) when is_list(user_identifiers) do
832 Repo.transaction(fn ->
833 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
837 def tag(nickname, tags) when is_binary(nickname),
838 do: tag(User.get_by_nickname(nickname), tags)
840 def tag(%User{} = user, tags),
841 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
843 def untag(user_identifiers, tags) when is_list(user_identifiers) do
844 Repo.transaction(fn ->
845 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
849 def untag(nickname, tags) when is_binary(nickname),
850 do: untag(User.get_by_nickname(nickname), tags)
852 def untag(%User{} = user, tags),
853 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
855 defp update_tags(%User{} = user, new_tags) do
856 {:ok, updated_user} =
858 |> change(%{tags: new_tags})
864 defp normalize_tags(tags) do
867 |> Enum.map(&String.downcase(&1))
870 defp local_nickname_regex() do
871 if Pleroma.Config.get([:instance, :extended_nickname_format]) do
872 @extended_local_nickname_regex
874 @strict_local_nickname_regex