1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.User do
12 alias Pleroma.Activity
13 alias Pleroma.Notification
15 alias Pleroma.Registration
19 alias Pleroma.Web.ActivityPub.ActivityPub
20 alias Pleroma.Web.ActivityPub.Utils
21 alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils
22 alias Pleroma.Web.OAuth
23 alias Pleroma.Web.OStatus
24 alias Pleroma.Web.RelMe
25 alias Pleroma.Web.Websub
29 @type t :: %__MODULE__{}
31 @primary_key {:id, Pleroma.FlakeId, autogenerate: true}
33 # credo:disable-for-next-line Credo.Check.Readability.MaxLineLength
34 @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])?)*$/
36 @strict_local_nickname_regex ~r/^[a-zA-Z\d]+$/
37 @extended_local_nickname_regex ~r/^[a-zA-Z\d_-]+$/
41 field(:email, :string)
43 field(:nickname, :string)
44 field(:password_hash, :string)
45 field(:password, :string, virtual: true)
46 field(:password_confirmation, :string, virtual: true)
47 field(:following, {:array, :string}, default: [])
48 field(:ap_id, :string)
50 field(:local, :boolean, default: true)
51 field(:follower_address, :string)
52 field(:search_rank, :float, virtual: true)
53 field(:search_type, :integer, virtual: true)
54 field(:tags, {:array, :string}, default: [])
55 field(:last_refreshed_at, :naive_datetime_usec)
56 has_many(:notifications, Notification)
57 has_many(:registrations, Registration)
58 embeds_one(:info, Pleroma.User.Info)
63 def auth_active?(%User{info: %User.Info{confirmation_pending: true}}),
64 do: !Pleroma.Config.get([:instance, :account_activation_required])
66 def auth_active?(%User{}), do: true
68 def visible_for?(user, for_user \\ nil)
70 def visible_for?(%User{id: user_id}, %User{id: for_id}) when user_id == for_id, do: true
72 def visible_for?(%User{} = user, for_user) do
73 auth_active?(user) || superuser?(for_user)
76 def visible_for?(_, _), do: false
78 def superuser?(%User{local: true, info: %User.Info{is_admin: true}}), do: true
79 def superuser?(%User{local: true, info: %User.Info{is_moderator: true}}), do: true
80 def superuser?(_), do: false
82 def avatar_url(user, options \\ []) do
84 %{"url" => [%{"href" => href} | _]} -> href
85 _ -> !options[:no_default] && "#{Web.base_url()}/images/avi.png"
89 def banner_url(user, options \\ []) do
90 case user.info.banner do
91 %{"url" => [%{"href" => href} | _]} -> href
92 _ -> !options[:no_default] && "#{Web.base_url()}/images/banner.png"
96 def profile_url(%User{info: %{source_data: %{"url" => url}}}), do: url
97 def profile_url(%User{ap_id: ap_id}), do: ap_id
98 def profile_url(_), do: nil
100 def ap_id(%User{nickname: nickname}) do
101 "#{Web.base_url()}/users/#{nickname}"
104 def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
105 def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
107 def user_info(%User{} = user) do
109 following_count: following_count(user),
110 note_count: user.info.note_count,
111 follower_count: user.info.follower_count,
112 locked: user.info.locked,
113 confirmation_pending: user.info.confirmation_pending,
114 default_scope: user.info.default_scope
118 def restrict_deactivated(query) do
120 where: not fragment("? \\? 'deactivated' AND ?->'deactivated' @> 'true'", u.info, u.info)
124 def following_count(%User{following: []}), do: 0
126 def following_count(%User{} = user) do
128 |> get_friends_query()
129 |> Repo.aggregate(:count, :id)
132 def remote_user_creation(params) do
135 |> Map.put(:info, params[:info] || %{})
137 info_cng = User.Info.remote_user_creation(%User.Info{}, params[:info])
141 |> cast(params, [:bio, :name, :ap_id, :nickname, :avatar])
142 |> validate_required([:name, :ap_id])
143 |> unique_constraint(:nickname)
144 |> validate_format(:nickname, @email_regex)
145 |> validate_length(:bio, max: 5000)
146 |> validate_length(:name, max: 100)
147 |> put_change(:local, false)
148 |> put_embed(:info, info_cng)
151 case info_cng.changes[:source_data] do
152 %{"followers" => followers} ->
154 |> put_change(:follower_address, followers)
157 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
160 |> put_change(:follower_address, followers)
167 def update_changeset(struct, params \\ %{}) do
169 |> cast(params, [:bio, :name, :avatar])
170 |> unique_constraint(:nickname)
171 |> validate_format(:nickname, local_nickname_regex())
172 |> validate_length(:bio, max: 5000)
173 |> validate_length(:name, min: 1, max: 100)
176 def upgrade_changeset(struct, params \\ %{}) do
179 |> Map.put(:last_refreshed_at, NaiveDateTime.utc_now())
183 |> User.Info.user_upgrade(params[:info])
186 |> cast(params, [:bio, :name, :follower_address, :avatar, :last_refreshed_at])
187 |> unique_constraint(:nickname)
188 |> validate_format(:nickname, local_nickname_regex())
189 |> validate_length(:bio, max: 5000)
190 |> validate_length(:name, max: 100)
191 |> put_embed(:info, info_cng)
194 def password_update_changeset(struct, params) do
197 |> cast(params, [:password, :password_confirmation])
198 |> validate_required([:password, :password_confirmation])
199 |> validate_confirmation(:password)
201 OAuth.Token.delete_user_tokens(struct)
202 OAuth.Authorization.delete_user_authorizations(struct)
204 if changeset.valid? do
205 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
208 |> put_change(:password_hash, hashed)
214 def reset_password(user, data) do
215 update_and_set_cache(password_update_changeset(user, data))
218 def register_changeset(struct, params \\ %{}, opts \\ []) do
220 if is_nil(opts[:need_confirmation]) do
221 Pleroma.Config.get([:instance, :account_activation_required])
223 opts[:need_confirmation]
227 User.Info.confirmation_changeset(%User.Info{}, need_confirmation: need_confirmation?)
231 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
232 |> validate_required([:name, :nickname, :password, :password_confirmation])
233 |> validate_confirmation(:password)
234 |> unique_constraint(:email)
235 |> unique_constraint(:nickname)
236 |> validate_exclusion(:nickname, Pleroma.Config.get([Pleroma.User, :restricted_nicknames]))
237 |> validate_format(:nickname, local_nickname_regex())
238 |> validate_format(:email, @email_regex)
239 |> validate_length(:bio, max: 1000)
240 |> validate_length(:name, min: 1, max: 100)
241 |> put_change(:info, info_change)
244 if opts[:external] do
247 validate_required(changeset, [:email])
250 if changeset.valid? do
251 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
252 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
253 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
256 |> put_change(:password_hash, hashed)
257 |> put_change(:ap_id, ap_id)
258 |> unique_constraint(:ap_id)
259 |> put_change(:following, [followers])
260 |> put_change(:follower_address, followers)
266 defp autofollow_users(user) do
267 candidates = Pleroma.Config.get([:instance, :autofollowed_nicknames])
270 User.Query.build(%{nickname: candidates, local: true, deactivated: false})
273 follow_all(user, autofollowed_users)
276 @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
277 def register(%Ecto.Changeset{} = changeset) do
278 with {:ok, user} <- Repo.insert(changeset),
279 {:ok, user} <- autofollow_users(user),
280 {:ok, user} <- set_cache(user),
281 {:ok, _} <- Pleroma.User.WelcomeMessage.post_welcome_message_to_user(user),
282 {:ok, _} <- try_send_confirmation_email(user) do
287 def try_send_confirmation_email(%User{} = user) do
288 if user.info.confirmation_pending &&
289 Pleroma.Config.get([:instance, :account_activation_required]) do
291 |> Pleroma.Emails.UserEmail.account_confirmation_email()
292 |> Pleroma.Emails.Mailer.deliver_async()
300 def needs_update?(%User{local: true}), do: false
302 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
304 def needs_update?(%User{local: false} = user) do
305 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
308 def needs_update?(_), do: true
310 def maybe_direct_follow(%User{} = follower, %User{local: true, info: %{locked: true}}) do
314 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
315 follow(follower, followed)
318 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
319 if not User.ap_enabled?(followed) do
320 follow(follower, followed)
326 def maybe_follow(%User{} = follower, %User{info: _info} = followed) do
327 if not following?(follower, followed) do
328 follow(follower, followed)
334 @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
335 @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
336 def follow_all(follower, followeds) do
339 |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
340 |> Enum.map(fn %{follower_address: fa} -> fa end)
344 where: u.id == ^follower.id,
349 "array(select distinct unnest (array_cat(?, ?)))",
358 {1, [follower]} = Repo.update_all(q, [])
360 Enum.each(followeds, fn followed ->
361 update_follower_count(followed)
367 def follow(%User{} = follower, %User{info: info} = followed) do
368 user_config = Application.get_env(:pleroma, :user)
369 deny_follow_blocked = Keyword.get(user_config, :deny_follow_blocked)
371 ap_followers = followed.follower_address
374 following?(follower, followed) or info.deactivated ->
375 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
377 deny_follow_blocked and blocks?(followed, follower) ->
378 {:error, "Could not follow user: #{followed.nickname} blocked you."}
381 if !followed.local && follower.local && !ap_enabled?(followed) do
382 Websub.subscribe(follower, followed)
387 where: u.id == ^follower.id,
388 update: [push: [following: ^ap_followers]],
392 {1, [follower]} = Repo.update_all(q, [])
394 {:ok, _} = update_follower_count(followed)
400 def unfollow(%User{} = follower, %User{} = followed) do
401 ap_followers = followed.follower_address
403 if following?(follower, followed) and follower.ap_id != followed.ap_id do
406 where: u.id == ^follower.id,
407 update: [pull: [following: ^ap_followers]],
411 {1, [follower]} = Repo.update_all(q, [])
413 {:ok, followed} = update_follower_count(followed)
417 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
419 {:error, "Not subscribed!"}
423 @spec following?(User.t(), User.t()) :: boolean
424 def following?(%User{} = follower, %User{} = followed) do
425 Enum.member?(follower.following, followed.follower_address)
428 def locked?(%User{} = user) do
429 user.info.locked || false
433 Repo.get_by(User, id: id)
436 def get_by_ap_id(ap_id) do
437 Repo.get_by(User, ap_id: ap_id)
440 # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
441 # of the ap_id and the domain and tries to get that user
442 def get_by_guessed_nickname(ap_id) do
443 domain = URI.parse(ap_id).host
444 name = List.last(String.split(ap_id, "/"))
445 nickname = "#{name}@#{domain}"
447 get_cached_by_nickname(nickname)
450 def set_cache({:ok, user}), do: set_cache(user)
451 def set_cache({:error, err}), do: {:error, err}
453 def set_cache(%User{} = user) do
454 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
455 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
456 Cachex.put(:user_cache, "user_info:#{user.id}", user_info(user))
460 def update_and_set_cache(changeset) do
461 with {:ok, user} <- Repo.update(changeset) do
468 def invalidate_cache(user) do
469 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
470 Cachex.del(:user_cache, "nickname:#{user.nickname}")
471 Cachex.del(:user_cache, "user_info:#{user.id}")
474 def get_cached_by_ap_id(ap_id) do
475 key = "ap_id:#{ap_id}"
476 Cachex.fetch!(:user_cache, key, fn _ -> get_by_ap_id(ap_id) end)
479 def get_cached_by_id(id) do
483 Cachex.fetch!(:user_cache, key, fn _ ->
487 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
488 {:commit, user.ap_id}
494 get_cached_by_ap_id(ap_id)
497 def get_cached_by_nickname(nickname) do
498 key = "nickname:#{nickname}"
500 Cachex.fetch!(:user_cache, key, fn ->
501 user_result = get_or_fetch_by_nickname(nickname)
504 {:ok, user} -> {:commit, user}
505 {:error, _error} -> {:ignore, nil}
510 def get_cached_by_nickname_or_id(nickname_or_id) do
511 get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
514 def get_by_nickname(nickname) do
515 Repo.get_by(User, nickname: nickname) ||
516 if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
517 Repo.get_by(User, nickname: local_nickname(nickname))
521 def get_by_email(email), do: Repo.get_by(User, email: email)
523 def get_by_nickname_or_email(nickname_or_email) do
524 get_by_nickname(nickname_or_email) || get_by_email(nickname_or_email)
527 def get_cached_user_info(user) do
528 key = "user_info:#{user.id}"
529 Cachex.fetch!(:user_cache, key, fn _ -> user_info(user) end)
532 def fetch_by_nickname(nickname) do
533 ap_try = ActivityPub.make_user_from_nickname(nickname)
536 {:ok, user} -> {:ok, user}
537 _ -> OStatus.make_user(nickname)
541 def get_or_fetch_by_nickname(nickname) do
542 with %User{} = user <- get_by_nickname(nickname) do
546 with [_nick, _domain] <- String.split(nickname, "@"),
547 {:ok, user} <- fetch_by_nickname(nickname) do
548 if Pleroma.Config.get([:fetch_initial_posts, :enabled]) do
549 fetch_initial_posts(user)
554 _e -> {:error, "not found " <> nickname}
559 @doc "Fetch some posts when the user has just been federated with"
560 def fetch_initial_posts(user),
561 do: PleromaJobQueue.enqueue(:background, __MODULE__, [:fetch_initial_posts, user])
563 @spec get_followers_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
564 def get_followers_query(%User{} = user, nil) do
565 User.Query.build(%{followers: user, deactivated: false})
568 def get_followers_query(user, page) do
569 from(u in get_followers_query(user, nil))
570 |> User.Query.paginate(page, 20)
573 @spec get_followers_query(User.t()) :: Ecto.Query.t()
574 def get_followers_query(user), do: get_followers_query(user, nil)
576 def get_followers(user, page \\ nil) do
577 q = get_followers_query(user, page)
582 def get_followers_ids(user, page \\ nil) do
583 q = get_followers_query(user, page)
585 Repo.all(from(u in q, select: u.id))
588 @spec get_friends_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
589 def get_friends_query(%User{} = user, nil) do
590 User.Query.build(%{friends: user, deactivated: false})
593 def get_friends_query(user, page) do
594 from(u in get_friends_query(user, nil))
595 |> User.Query.paginate(page, 20)
598 @spec get_friends_query(User.t()) :: Ecto.Query.t()
599 def get_friends_query(user), do: get_friends_query(user, nil)
601 def get_friends(user, page \\ nil) do
602 q = get_friends_query(user, page)
607 def get_friends_ids(user, page \\ nil) do
608 q = get_friends_query(user, page)
610 Repo.all(from(u in q, select: u.id))
613 @spec get_follow_requests(User.t()) :: {:ok, [User.t()]}
614 def get_follow_requests(%User{} = user) do
616 Activity.follow_requests_for_actor(user)
617 |> join(:inner, [a], u in User, on: a.actor == u.ap_id)
618 |> where([a, u], not fragment("? @> ?", u.following, ^[user.follower_address]))
619 |> group_by([a, u], u.id)
626 def increase_note_count(%User{} = user) do
628 |> where(id: ^user.id)
633 "jsonb_set(?, '{note_count}', ((?->>'note_count')::int + 1)::varchar::jsonb, true)",
640 |> Repo.update_all([])
642 {1, [user]} -> set_cache(user)
647 def decrease_note_count(%User{} = user) do
649 |> where(id: ^user.id)
654 "jsonb_set(?, '{note_count}', (greatest(0, (?->>'note_count')::int - 1))::varchar::jsonb, true)",
661 |> Repo.update_all([])
663 {1, [user]} -> set_cache(user)
668 def update_note_count(%User{} = user) do
672 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
676 note_count = Repo.one(note_count_query)
678 info_cng = User.Info.set_note_count(user.info, note_count)
682 |> put_embed(:info, info_cng)
683 |> update_and_set_cache()
686 def update_follower_count(%User{} = user) do
687 follower_count_query =
688 User.Query.build(%{followers: user, deactivated: false})
689 |> select([u], %{count: count(u.id)})
692 |> where(id: ^user.id)
693 |> join(:inner, [u], s in subquery(follower_count_query))
698 "jsonb_set(?, '{follower_count}', ?::varchar::jsonb, true)",
705 |> Repo.update_all([])
707 {1, [user]} -> set_cache(user)
712 @spec get_users_from_set([String.t()], boolean()) :: [User.t()]
713 def get_users_from_set(ap_ids, local_only \\ true) do
714 criteria = %{ap_id: ap_ids, deactivated: false}
715 criteria = if local_only, do: Map.put(criteria, :local, true), else: criteria
717 User.Query.build(criteria)
721 @spec get_recipients_from_activity(Activity.t()) :: [User.t()]
722 def get_recipients_from_activity(%Activity{recipients: to}) do
723 User.Query.build(%{recipients_from_activity: to, local: true, deactivated: false})
727 def search(query, resolve \\ false, for_user \\ nil) do
728 # Strip the beginning @ off if there is a query
729 query = String.trim_leading(query, "@")
731 if resolve, do: get_or_fetch(query)
734 Repo.transaction(fn ->
735 Ecto.Adapters.SQL.query(Repo, "select set_limit(0.25)", [])
736 Repo.all(search_query(query, for_user))
742 def search_query(query, for_user) do
743 fts_subquery = fts_search_subquery(query)
744 trigram_subquery = trigram_search_subquery(query)
745 union_query = from(s in trigram_subquery, union_all: ^fts_subquery)
746 distinct_query = from(s in subquery(union_query), order_by: s.search_type, distinct: s.id)
748 from(s in subquery(boost_search_rank_query(distinct_query, for_user)),
749 order_by: [desc: s.search_rank],
754 defp boost_search_rank_query(query, nil), do: query
756 defp boost_search_rank_query(query, for_user) do
757 friends_ids = get_friends_ids(for_user)
758 followers_ids = get_followers_ids(for_user)
760 from(u in subquery(query),
765 CASE WHEN (?) THEN (?) * 1.3
766 WHEN (?) THEN (?) * 1.2
767 WHEN (?) THEN (?) * 1.1
770 u.id in ^friends_ids and u.id in ^followers_ids,
772 u.id in ^friends_ids,
774 u.id in ^followers_ids,
782 defp fts_search_subquery(term, query \\ User) do
785 |> String.replace(~r/\W+/, " ")
788 |> Enum.map(&(&1 <> ":*"))
799 setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
800 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B'),
801 to_tsquery('simple', ?),
813 (setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
814 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B')) @@ to_tsquery('simple', ?)
821 |> restrict_deactivated()
824 defp trigram_search_subquery(term) do
828 # ^1 gives 'Postgrex expected a binary, got 1' for some weird reason
829 search_type: fragment("?", 1),
832 "similarity(?, trim(? || ' ' || coalesce(?, '')))",
838 where: fragment("trim(? || ' ' || coalesce(?, '')) % ?", u.nickname, u.name, ^term)
840 |> restrict_deactivated()
843 def mute(muter, %User{ap_id: ap_id}) do
846 |> User.Info.add_to_mutes(ap_id)
850 |> put_embed(:info, info_cng)
852 update_and_set_cache(cng)
855 def unmute(muter, %{ap_id: ap_id}) do
858 |> User.Info.remove_from_mutes(ap_id)
862 |> put_embed(:info, info_cng)
864 update_and_set_cache(cng)
867 def subscribe(subscriber, %{ap_id: ap_id}) do
868 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
870 with %User{} = subscribed <- get_cached_by_ap_id(ap_id) do
871 blocked = blocks?(subscribed, subscriber) and deny_follow_blocked
874 {:error, "Could not subscribe: #{subscribed.nickname} is blocking you"}
878 |> User.Info.add_to_subscribers(subscriber.ap_id)
881 |> put_embed(:info, info_cng)
882 |> update_and_set_cache()
887 def unsubscribe(unsubscriber, %{ap_id: ap_id}) do
888 with %User{} = user <- get_cached_by_ap_id(ap_id) do
891 |> User.Info.remove_from_subscribers(unsubscriber.ap_id)
894 |> put_embed(:info, info_cng)
895 |> update_and_set_cache()
899 def block(blocker, %User{ap_id: ap_id} = blocked) do
900 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
902 if following?(blocker, blocked) do
903 {:ok, blocker, _} = unfollow(blocker, blocked)
910 if subscribed_to?(blocked, blocker) do
911 {:ok, blocker} = unsubscribe(blocked, blocker)
917 if following?(blocked, blocker) do
918 unfollow(blocked, blocker)
921 {:ok, blocker} = update_follower_count(blocker)
925 |> User.Info.add_to_block(ap_id)
929 |> put_embed(:info, info_cng)
931 update_and_set_cache(cng)
934 # helper to handle the block given only an actor's AP id
935 def block(blocker, %{ap_id: ap_id}) do
936 block(blocker, get_cached_by_ap_id(ap_id))
939 def unblock(blocker, %{ap_id: ap_id}) do
942 |> User.Info.remove_from_block(ap_id)
946 |> put_embed(:info, info_cng)
948 update_and_set_cache(cng)
951 def mutes?(nil, _), do: false
952 def mutes?(user, %{ap_id: ap_id}), do: Enum.member?(user.info.mutes, ap_id)
954 def blocks?(user, %{ap_id: ap_id}) do
955 blocks = user.info.blocks
956 domain_blocks = user.info.domain_blocks
957 %{host: host} = URI.parse(ap_id)
959 Enum.member?(blocks, ap_id) ||
960 Enum.any?(domain_blocks, fn domain ->
965 def subscribed_to?(user, %{ap_id: ap_id}) do
966 with %User{} = target <- get_cached_by_ap_id(ap_id) do
967 Enum.member?(target.info.subscribers, user.ap_id)
971 @spec muted_users(User.t()) :: [User.t()]
972 def muted_users(user) do
973 User.Query.build(%{ap_id: user.info.mutes, deactivated: false})
977 @spec blocked_users(User.t()) :: [User.t()]
978 def blocked_users(user) do
979 User.Query.build(%{ap_id: user.info.blocks, deactivated: false})
983 @spec subscribers(User.t()) :: [User.t()]
984 def subscribers(user) do
985 User.Query.build(%{ap_id: user.info.subscribers, deactivated: false})
989 def block_domain(user, domain) do
992 |> User.Info.add_to_domain_block(domain)
996 |> put_embed(:info, info_cng)
998 update_and_set_cache(cng)
1001 def unblock_domain(user, domain) do
1004 |> User.Info.remove_from_domain_block(domain)
1008 |> put_embed(:info, info_cng)
1010 update_and_set_cache(cng)
1013 def deactivate_async(user, status \\ true) do
1014 PleromaJobQueue.enqueue(:background, __MODULE__, [:deactivate_async, user, status])
1017 def deactivate(%User{} = user, status \\ true) do
1018 info_cng = User.Info.set_activation_status(user.info, status)
1020 with {:ok, friends} <- User.get_friends(user),
1021 {:ok, followers} <- User.get_followers(user),
1025 |> put_embed(:info, info_cng)
1026 |> update_and_set_cache() do
1027 Enum.each(followers, &invalidate_cache(&1))
1028 Enum.each(friends, &update_follower_count(&1))
1034 def update_notification_settings(%User{} = user, settings \\ %{}) do
1035 info_changeset = User.Info.update_notification_settings(user.info, settings)
1038 |> put_embed(:info, info_changeset)
1039 |> update_and_set_cache()
1042 @spec delete(User.t()) :: :ok
1043 def delete(%User{} = user),
1044 do: PleromaJobQueue.enqueue(:background, __MODULE__, [:delete, user])
1046 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1047 def perform(:delete, %User{} = user) do
1048 {:ok, user} = User.deactivate(user)
1050 # Remove all relationships
1051 {:ok, followers} = User.get_followers(user)
1053 Enum.each(followers, fn follower -> User.unfollow(follower, user) end)
1055 {:ok, friends} = User.get_friends(user)
1057 Enum.each(friends, fn followed -> User.unfollow(user, followed) end)
1059 delete_user_activities(user)
1062 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1063 def perform(:fetch_initial_posts, %User{} = user) do
1064 pages = Pleroma.Config.get!([:fetch_initial_posts, :pages])
1067 # Insert all the posts in reverse order, so they're in the right order on the timeline
1068 Enum.reverse(Utils.fetch_ordered_collection(user.info.source_data["outbox"], pages)),
1069 &Pleroma.Web.Federator.incoming_ap_doc/1
1075 def perform(:deactivate_async, user, status), do: deactivate(user, status)
1077 @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
1078 def perform(:blocks_import, %User{} = blocker, blocked_identifiers)
1079 when is_list(blocked_identifiers) do
1081 blocked_identifiers,
1082 fn blocked_identifier ->
1083 with {:ok, %User{} = blocked} <- get_or_fetch(blocked_identifier),
1084 {:ok, blocker} <- block(blocker, blocked),
1085 {:ok, _} <- ActivityPub.block(blocker, blocked) do
1089 Logger.debug("blocks_import failed for #{blocked_identifier} with: #{inspect(err)}")
1096 @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
1097 def perform(:follow_import, %User{} = follower, followed_identifiers)
1098 when is_list(followed_identifiers) do
1100 followed_identifiers,
1101 fn followed_identifier ->
1102 with {:ok, %User{} = followed} <- get_or_fetch(followed_identifier),
1103 {:ok, follower} <- maybe_direct_follow(follower, followed),
1104 {:ok, _} <- ActivityPub.follow(follower, followed) do
1108 Logger.debug("follow_import failed for #{followed_identifier} with: #{inspect(err)}")
1115 def blocks_import(%User{} = blocker, blocked_identifiers) when is_list(blocked_identifiers),
1117 PleromaJobQueue.enqueue(:background, __MODULE__, [
1123 def follow_import(%User{} = follower, followed_identifiers) when is_list(followed_identifiers),
1125 PleromaJobQueue.enqueue(:background, __MODULE__, [
1128 followed_identifiers
1131 def delete_user_activities(%User{ap_id: ap_id} = user) do
1134 |> Activity.query_by_actor()
1135 |> Activity.with_preloaded_object()
1138 Repo.transaction(fn -> Enum.each(stream, &delete_activity(&1)) end, timeout: :infinity)
1143 defp delete_activity(%{data: %{"type" => "Create"}} = activity) do
1144 Object.normalize(activity) |> ActivityPub.delete()
1147 defp delete_activity(_activity), do: "Doing nothing"
1149 def html_filter_policy(%User{info: %{no_rich_text: true}}) do
1150 Pleroma.HTML.Scrubber.TwitterText
1153 @default_scrubbers Pleroma.Config.get([:markup, :scrub_policy])
1155 def html_filter_policy(_), do: @default_scrubbers
1157 def fetch_by_ap_id(ap_id) do
1158 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
1165 case OStatus.make_user(ap_id) do
1166 {:ok, user} -> {:ok, user}
1167 _ -> {:error, "Could not fetch by AP id"}
1172 def get_or_fetch_by_ap_id(ap_id) do
1173 user = get_cached_by_ap_id(ap_id)
1175 if !is_nil(user) and !User.needs_update?(user) do
1178 # Whether to fetch initial posts for the user (if it's a new user & the fetching is enabled)
1179 should_fetch_initial = is_nil(user) and Pleroma.Config.get([:fetch_initial_posts, :enabled])
1181 resp = fetch_by_ap_id(ap_id)
1183 if should_fetch_initial do
1184 with {:ok, %User{} = user} <- resp do
1185 fetch_initial_posts(user)
1193 def get_or_create_instance_user do
1194 relay_uri = "#{Pleroma.Web.Endpoint.url()}/relay"
1196 if user = get_cached_by_ap_id(relay_uri) do
1200 %User{info: %User.Info{}}
1201 |> cast(%{}, [:ap_id, :nickname, :local])
1202 |> put_change(:ap_id, relay_uri)
1203 |> put_change(:nickname, nil)
1204 |> put_change(:local, true)
1205 |> put_change(:follower_address, relay_uri <> "/followers")
1207 {:ok, user} = Repo.insert(changes)
1213 def public_key_from_info(%{
1214 source_data: %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
1218 |> :public_key.pem_decode()
1220 |> :public_key.pem_entry_decode()
1226 def public_key_from_info(%{magic_key: magic_key}) do
1227 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
1230 def get_public_key_for_ap_id(ap_id) do
1231 with {:ok, %User{} = user} <- get_or_fetch_by_ap_id(ap_id),
1232 {:ok, public_key} <- public_key_from_info(user.info) do
1239 defp blank?(""), do: nil
1240 defp blank?(n), do: n
1242 def insert_or_update_user(data) do
1244 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
1245 |> remote_user_creation()
1246 |> Repo.insert(on_conflict: :replace_all, conflict_target: :nickname)
1250 def ap_enabled?(%User{local: true}), do: true
1251 def ap_enabled?(%User{info: info}), do: info.ap_enabled
1252 def ap_enabled?(_), do: false
1254 @doc "Gets or fetch a user by uri or nickname."
1255 @spec get_or_fetch(String.t()) :: {:ok, User.t()} | {:error, String.t()}
1256 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
1257 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
1259 # wait a period of time and return newest version of the User structs
1260 # this is because we have synchronous follow APIs and need to simulate them
1261 # with an async handshake
1262 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
1263 with %User{} = a <- User.get_cached_by_id(a.id),
1264 %User{} = b <- User.get_cached_by_id(b.id) do
1272 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
1273 with :ok <- :timer.sleep(timeout),
1274 %User{} = a <- User.get_cached_by_id(a.id),
1275 %User{} = b <- User.get_cached_by_id(b.id) do
1283 def parse_bio(bio) when is_binary(bio) and bio != "" do
1285 |> CommonUtils.format_input("text/plain", mentions_format: :full)
1289 def parse_bio(_), do: ""
1291 def parse_bio(bio, user) when is_binary(bio) and bio != "" do
1292 # TODO: get profile URLs other than user.ap_id
1293 profile_urls = [user.ap_id]
1296 |> CommonUtils.format_input("text/plain",
1297 mentions_format: :full,
1298 rel: &RelMe.maybe_put_rel_me(&1, profile_urls)
1303 def parse_bio(_, _), do: ""
1305 def tag(user_identifiers, tags) when is_list(user_identifiers) do
1306 Repo.transaction(fn ->
1307 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
1311 def tag(nickname, tags) when is_binary(nickname),
1312 do: tag(get_by_nickname(nickname), tags)
1314 def tag(%User{} = user, tags),
1315 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
1317 def untag(user_identifiers, tags) when is_list(user_identifiers) do
1318 Repo.transaction(fn ->
1319 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
1323 def untag(nickname, tags) when is_binary(nickname),
1324 do: untag(get_by_nickname(nickname), tags)
1326 def untag(%User{} = user, tags),
1327 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
1329 defp update_tags(%User{} = user, new_tags) do
1330 {:ok, updated_user} =
1332 |> change(%{tags: new_tags})
1333 |> update_and_set_cache()
1338 defp normalize_tags(tags) do
1341 |> Enum.map(&String.downcase(&1))
1344 defp local_nickname_regex do
1345 if Pleroma.Config.get([:instance, :extended_nickname_format]) do
1346 @extended_local_nickname_regex
1348 @strict_local_nickname_regex
1352 def local_nickname(nickname_or_mention) do
1355 |> String.split("@")
1359 def full_nickname(nickname_or_mention),
1360 do: String.trim_leading(nickname_or_mention, "@")
1362 def error_user(ap_id) do
1367 nickname: "erroruser@example.com",
1368 inserted_at: NaiveDateTime.utc_now()
1372 @spec all_superusers() :: [User.t()]
1373 def all_superusers do
1374 User.Query.build(%{super_users: true, local: true, deactivated: false})
1378 def showing_reblogs?(%User{} = user, %User{} = target) do
1379 target.ap_id not in user.info.muted_reblogs
1382 @spec toggle_confirmation(User.t()) :: {:ok, User.t()} | {:error, Changeset.t()}
1383 def toggle_confirmation(%User{} = user) do
1384 need_confirmation? = !user.info.confirmation_pending
1387 User.Info.confirmation_changeset(user.info, need_confirmation: need_confirmation?)
1391 |> put_embed(:info, info_changeset)
1392 |> update_and_set_cache()