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
14 alias Pleroma.Notification
16 alias Pleroma.Registration
20 alias Pleroma.Web.ActivityPub.ActivityPub
21 alias Pleroma.Web.ActivityPub.Utils
22 alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils
23 alias Pleroma.Web.OAuth
24 alias Pleroma.Web.OStatus
25 alias Pleroma.Web.RelMe
26 alias Pleroma.Web.Websub
30 @type t :: %__MODULE__{}
32 @primary_key {:id, Pleroma.FlakeId, autogenerate: true}
34 # credo:disable-for-next-line Credo.Check.Readability.MaxLineLength
35 @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])?)*$/
37 @strict_local_nickname_regex ~r/^[a-zA-Z\d]+$/
38 @extended_local_nickname_regex ~r/^[a-zA-Z\d_-]+$/
42 field(:email, :string)
44 field(:nickname, :string)
45 field(:password_hash, :string)
46 field(:password, :string, virtual: true)
47 field(:password_confirmation, :string, virtual: true)
48 field(:following, {:array, :string}, default: [])
49 field(:ap_id, :string)
51 field(:local, :boolean, default: true)
52 field(:follower_address, :string)
53 field(:search_rank, :float, virtual: true)
54 field(:search_type, :integer, virtual: true)
55 field(:tags, {:array, :string}, default: [])
56 field(:last_refreshed_at, :naive_datetime_usec)
57 has_many(:notifications, Notification)
58 has_many(:registrations, Registration)
59 embeds_one(:info, User.Info)
64 def auth_active?(%User{info: %User.Info{confirmation_pending: true}}),
65 do: !Pleroma.Config.get([:instance, :account_activation_required])
67 def auth_active?(%User{}), do: true
69 def visible_for?(user, for_user \\ nil)
71 def visible_for?(%User{id: user_id}, %User{id: for_id}) when user_id == for_id, do: true
73 def visible_for?(%User{} = user, for_user) do
74 auth_active?(user) || superuser?(for_user)
77 def visible_for?(_, _), do: false
79 def superuser?(%User{local: true, info: %User.Info{is_admin: true}}), do: true
80 def superuser?(%User{local: true, info: %User.Info{is_moderator: true}}), do: true
81 def superuser?(_), do: false
83 def avatar_url(user, options \\ []) do
85 %{"url" => [%{"href" => href} | _]} -> href
86 _ -> !options[:no_default] && "#{Web.base_url()}/images/avi.png"
90 def banner_url(user, options \\ []) do
91 case user.info.banner do
92 %{"url" => [%{"href" => href} | _]} -> href
93 _ -> !options[:no_default] && "#{Web.base_url()}/images/banner.png"
97 def profile_url(%User{info: %{source_data: %{"url" => url}}}), do: url
98 def profile_url(%User{ap_id: ap_id}), do: ap_id
99 def profile_url(_), do: nil
101 def ap_id(%User{nickname: nickname}) do
102 "#{Web.base_url()}/users/#{nickname}"
105 def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
106 def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
108 def user_info(%User{} = user) do
110 following_count: following_count(user),
111 note_count: user.info.note_count,
112 follower_count: user.info.follower_count,
113 locked: user.info.locked,
114 confirmation_pending: user.info.confirmation_pending,
115 default_scope: user.info.default_scope
119 def restrict_deactivated(query) do
121 where: not fragment("? \\? 'deactivated' AND ?->'deactivated' @> 'true'", u.info, u.info)
125 def following_count(%User{following: []}), do: 0
127 def following_count(%User{} = user) do
129 |> get_friends_query()
130 |> Repo.aggregate(:count, :id)
133 def remote_user_creation(params) do
136 |> Map.put(:info, params[:info] || %{})
138 info_cng = User.Info.remote_user_creation(%User.Info{}, params[:info])
142 |> cast(params, [:bio, :name, :ap_id, :nickname, :avatar])
143 |> validate_required([:name, :ap_id])
144 |> unique_constraint(:nickname)
145 |> validate_format(:nickname, @email_regex)
146 |> validate_length(:bio, max: 5000)
147 |> validate_length(:name, max: 100)
148 |> put_change(:local, false)
149 |> put_embed(:info, info_cng)
152 case info_cng.changes[:source_data] do
153 %{"followers" => followers} ->
155 |> put_change(:follower_address, followers)
158 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
161 |> put_change(:follower_address, followers)
168 def update_changeset(struct, params \\ %{}) do
170 |> cast(params, [:bio, :name, :avatar, :following])
171 |> unique_constraint(:nickname)
172 |> validate_format(:nickname, local_nickname_regex())
173 |> validate_length(:bio, max: 5000)
174 |> validate_length(:name, min: 1, max: 100)
177 def upgrade_changeset(struct, params \\ %{}) do
180 |> Map.put(:last_refreshed_at, NaiveDateTime.utc_now())
184 |> User.Info.user_upgrade(params[:info])
187 |> cast(params, [:bio, :name, :follower_address, :avatar, :last_refreshed_at])
188 |> unique_constraint(:nickname)
189 |> validate_format(:nickname, local_nickname_regex())
190 |> validate_length(:bio, max: 5000)
191 |> validate_length(:name, max: 100)
192 |> put_embed(:info, info_cng)
195 def password_update_changeset(struct, params) do
198 |> cast(params, [:password, :password_confirmation])
199 |> validate_required([:password, :password_confirmation])
200 |> validate_confirmation(:password)
202 OAuth.Token.delete_user_tokens(struct)
203 OAuth.Authorization.delete_user_authorizations(struct)
205 if changeset.valid? do
206 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
209 |> put_change(:password_hash, hashed)
215 def reset_password(user, data) do
216 update_and_set_cache(password_update_changeset(user, data))
219 def register_changeset(struct, params \\ %{}, opts \\ []) do
221 if is_nil(opts[:need_confirmation]) do
222 Pleroma.Config.get([:instance, :account_activation_required])
224 opts[:need_confirmation]
228 User.Info.confirmation_changeset(%User.Info{}, need_confirmation: need_confirmation?)
232 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
233 |> validate_required([:name, :nickname, :password, :password_confirmation])
234 |> validate_confirmation(:password)
235 |> unique_constraint(:email)
236 |> unique_constraint(:nickname)
237 |> validate_exclusion(:nickname, Pleroma.Config.get([User, :restricted_nicknames]))
238 |> validate_format(:nickname, local_nickname_regex())
239 |> validate_format(:email, @email_regex)
240 |> validate_length(:bio, max: 1000)
241 |> validate_length(:name, min: 1, max: 100)
242 |> put_change(:info, info_change)
245 if opts[:external] do
248 validate_required(changeset, [:email])
251 if changeset.valid? do
252 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
253 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
254 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
257 |> put_change(:password_hash, hashed)
258 |> put_change(:ap_id, ap_id)
259 |> unique_constraint(:ap_id)
260 |> put_change(:following, [followers])
261 |> put_change(:follower_address, followers)
267 defp autofollow_users(user) do
268 candidates = Pleroma.Config.get([:instance, :autofollowed_nicknames])
271 User.Query.build(%{nickname: candidates, local: true, deactivated: false})
274 follow_all(user, autofollowed_users)
277 @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
278 def register(%Ecto.Changeset{} = changeset) do
279 with {:ok, user} <- Repo.insert(changeset),
280 {:ok, user} <- autofollow_users(user),
281 {:ok, user} <- set_cache(user),
282 {:ok, _} <- User.WelcomeMessage.post_welcome_message_to_user(user),
283 {:ok, _} <- try_send_confirmation_email(user) do
288 def try_send_confirmation_email(%User{} = user) do
289 if user.info.confirmation_pending &&
290 Pleroma.Config.get([:instance, :account_activation_required]) do
292 |> Pleroma.Emails.UserEmail.account_confirmation_email()
293 |> Pleroma.Emails.Mailer.deliver_async()
301 def needs_update?(%User{local: true}), do: false
303 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
305 def needs_update?(%User{local: false} = user) do
306 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
309 def needs_update?(_), do: true
311 def maybe_direct_follow(%User{} = follower, %User{local: true, info: %{locked: true}}) do
315 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
316 follow(follower, followed)
319 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
320 if not User.ap_enabled?(followed) do
321 follow(follower, followed)
327 def maybe_follow(%User{} = follower, %User{info: _info} = followed) do
328 if not following?(follower, followed) do
329 follow(follower, followed)
335 @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
336 @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
337 def follow_all(follower, followeds) do
340 |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
341 |> Enum.map(fn %{follower_address: fa} -> fa end)
345 where: u.id == ^follower.id,
350 "array(select distinct unnest (array_cat(?, ?)))",
359 {1, [follower]} = Repo.update_all(q, [])
361 Enum.each(followeds, fn followed ->
362 update_follower_count(followed)
368 def follow(%User{} = follower, %User{info: info} = followed) do
369 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
370 ap_followers = followed.follower_address
373 following?(follower, followed) or info.deactivated ->
374 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
376 deny_follow_blocked and blocks?(followed, follower) ->
377 {:error, "Could not follow user: #{followed.nickname} blocked you."}
380 if !followed.local && follower.local && !ap_enabled?(followed) do
381 Websub.subscribe(follower, followed)
386 where: u.id == ^follower.id,
387 update: [push: [following: ^ap_followers]],
391 {1, [follower]} = Repo.update_all(q, [])
393 {:ok, _} = update_follower_count(followed)
399 def unfollow(%User{} = follower, %User{} = followed) do
400 ap_followers = followed.follower_address
402 if following?(follower, followed) and follower.ap_id != followed.ap_id do
405 where: u.id == ^follower.id,
406 update: [pull: [following: ^ap_followers]],
410 {1, [follower]} = Repo.update_all(q, [])
412 {:ok, followed} = update_follower_count(followed)
416 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
418 {:error, "Not subscribed!"}
422 @spec following?(User.t(), User.t()) :: boolean
423 def following?(%User{} = follower, %User{} = followed) do
424 Enum.member?(follower.following, followed.follower_address)
427 def locked?(%User{} = user) do
428 user.info.locked || false
432 Repo.get_by(User, id: id)
435 def get_by_ap_id(ap_id) do
436 Repo.get_by(User, ap_id: ap_id)
439 # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
440 # of the ap_id and the domain and tries to get that user
441 def get_by_guessed_nickname(ap_id) do
442 domain = URI.parse(ap_id).host
443 name = List.last(String.split(ap_id, "/"))
444 nickname = "#{name}@#{domain}"
446 get_cached_by_nickname(nickname)
449 def set_cache({:ok, user}), do: set_cache(user)
450 def set_cache({:error, err}), do: {:error, err}
452 def set_cache(%User{} = user) do
453 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
454 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
455 Cachex.put(:user_cache, "user_info:#{user.id}", user_info(user))
459 def update_and_set_cache(changeset) do
460 with {:ok, user} <- Repo.update(changeset) do
467 def invalidate_cache(user) do
468 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
469 Cachex.del(:user_cache, "nickname:#{user.nickname}")
470 Cachex.del(:user_cache, "user_info:#{user.id}")
473 def get_cached_by_ap_id(ap_id) do
474 key = "ap_id:#{ap_id}"
475 Cachex.fetch!(:user_cache, key, fn _ -> get_by_ap_id(ap_id) end)
478 def get_cached_by_id(id) do
482 Cachex.fetch!(:user_cache, key, fn _ ->
486 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
487 {:commit, user.ap_id}
493 get_cached_by_ap_id(ap_id)
496 def get_cached_by_nickname(nickname) do
497 key = "nickname:#{nickname}"
499 Cachex.fetch!(:user_cache, key, fn ->
500 user_result = get_or_fetch_by_nickname(nickname)
503 {:ok, user} -> {:commit, user}
504 {:error, _error} -> {:ignore, nil}
509 def get_cached_by_nickname_or_id(nickname_or_id) do
510 get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
513 def get_by_nickname(nickname) do
514 Repo.get_by(User, nickname: nickname) ||
515 if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
516 Repo.get_by(User, nickname: local_nickname(nickname))
520 def get_by_email(email), do: Repo.get_by(User, email: email)
522 def get_by_nickname_or_email(nickname_or_email) do
523 get_by_nickname(nickname_or_email) || get_by_email(nickname_or_email)
526 def get_cached_user_info(user) do
527 key = "user_info:#{user.id}"
528 Cachex.fetch!(:user_cache, key, fn _ -> user_info(user) end)
531 def fetch_by_nickname(nickname) do
532 ap_try = ActivityPub.make_user_from_nickname(nickname)
535 {:ok, user} -> {:ok, user}
536 _ -> OStatus.make_user(nickname)
540 def get_or_fetch_by_nickname(nickname) do
541 with %User{} = user <- get_by_nickname(nickname) do
545 with [_nick, _domain] <- String.split(nickname, "@"),
546 {:ok, user} <- fetch_by_nickname(nickname) do
547 if Pleroma.Config.get([:fetch_initial_posts, :enabled]) do
548 fetch_initial_posts(user)
553 _e -> {:error, "not found " <> nickname}
558 @doc "Fetch some posts when the user has just been federated with"
559 def fetch_initial_posts(user),
560 do: PleromaJobQueue.enqueue(:background, __MODULE__, [:fetch_initial_posts, user])
562 @spec get_followers_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
563 def get_followers_query(%User{} = user, nil) do
564 User.Query.build(%{followers: user, deactivated: false})
567 def get_followers_query(user, page) do
568 from(u in get_followers_query(user, nil))
569 |> User.Query.paginate(page, 20)
572 @spec get_followers_query(User.t()) :: Ecto.Query.t()
573 def get_followers_query(user), do: get_followers_query(user, nil)
575 def get_followers(user, page \\ nil) do
576 q = get_followers_query(user, page)
581 def get_followers_ids(user, page \\ nil) do
582 q = get_followers_query(user, page)
584 Repo.all(from(u in q, select: u.id))
587 @spec get_friends_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
588 def get_friends_query(%User{} = user, nil) do
589 User.Query.build(%{friends: user, deactivated: false})
592 def get_friends_query(user, page) do
593 from(u in get_friends_query(user, nil))
594 |> User.Query.paginate(page, 20)
597 @spec get_friends_query(User.t()) :: Ecto.Query.t()
598 def get_friends_query(user), do: get_friends_query(user, nil)
600 def get_friends(user, page \\ nil) do
601 q = get_friends_query(user, page)
606 def get_friends_ids(user, page \\ nil) do
607 q = get_friends_query(user, page)
609 Repo.all(from(u in q, select: u.id))
612 @spec get_follow_requests(User.t()) :: {:ok, [User.t()]}
613 def get_follow_requests(%User{} = user) do
615 Activity.follow_requests_for_actor(user)
616 |> join(:inner, [a], u in User, on: a.actor == u.ap_id)
617 |> where([a, u], not fragment("? @> ?", u.following, ^[user.follower_address]))
618 |> group_by([a, u], u.id)
625 def increase_note_count(%User{} = user) do
627 |> where(id: ^user.id)
632 "jsonb_set(?, '{note_count}', ((?->>'note_count')::int + 1)::varchar::jsonb, true)",
639 |> Repo.update_all([])
641 {1, [user]} -> set_cache(user)
646 def decrease_note_count(%User{} = user) do
648 |> where(id: ^user.id)
653 "jsonb_set(?, '{note_count}', (greatest(0, (?->>'note_count')::int - 1))::varchar::jsonb, true)",
660 |> Repo.update_all([])
662 {1, [user]} -> set_cache(user)
667 def update_note_count(%User{} = user) do
671 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
675 note_count = Repo.one(note_count_query)
677 info_cng = User.Info.set_note_count(user.info, note_count)
681 |> put_embed(:info, info_cng)
682 |> update_and_set_cache()
685 def update_follower_count(%User{} = user) do
686 follower_count_query =
687 User.Query.build(%{followers: user, deactivated: false})
688 |> select([u], %{count: count(u.id)})
691 |> where(id: ^user.id)
692 |> join(:inner, [u], s in subquery(follower_count_query))
697 "jsonb_set(?, '{follower_count}', ?::varchar::jsonb, true)",
704 |> Repo.update_all([])
706 {1, [user]} -> set_cache(user)
711 def remove_duplicated_following(%User{following: following} = user) do
712 uniq_following = Enum.uniq(following)
714 if length(following) == length(uniq_following) do
718 |> update_changeset(%{following: uniq_following})
719 |> update_and_set_cache()
723 @spec get_users_from_set([String.t()], boolean()) :: [User.t()]
724 def get_users_from_set(ap_ids, local_only \\ true) do
725 criteria = %{ap_id: ap_ids, deactivated: false}
726 criteria = if local_only, do: Map.put(criteria, :local, true), else: criteria
728 User.Query.build(criteria)
732 @spec get_recipients_from_activity(Activity.t()) :: [User.t()]
733 def get_recipients_from_activity(%Activity{recipients: to}) do
734 User.Query.build(%{recipients_from_activity: to, local: true, deactivated: false})
738 def search(query, resolve \\ false, for_user \\ nil) do
739 # Strip the beginning @ off if there is a query
740 query = String.trim_leading(query, "@")
742 if resolve, do: get_or_fetch(query)
745 Repo.transaction(fn ->
746 Ecto.Adapters.SQL.query(Repo, "select set_limit(0.25)", [])
747 Repo.all(search_query(query, for_user))
753 def search_query(query, for_user) do
754 fts_subquery = fts_search_subquery(query)
755 trigram_subquery = trigram_search_subquery(query)
756 union_query = from(s in trigram_subquery, union_all: ^fts_subquery)
757 distinct_query = from(s in subquery(union_query), order_by: s.search_type, distinct: s.id)
759 from(s in subquery(boost_search_rank_query(distinct_query, for_user)),
760 order_by: [desc: s.search_rank],
765 defp boost_search_rank_query(query, nil), do: query
767 defp boost_search_rank_query(query, for_user) do
768 friends_ids = get_friends_ids(for_user)
769 followers_ids = get_followers_ids(for_user)
771 from(u in subquery(query),
776 CASE WHEN (?) THEN (?) * 1.3
777 WHEN (?) THEN (?) * 1.2
778 WHEN (?) THEN (?) * 1.1
781 u.id in ^friends_ids and u.id in ^followers_ids,
783 u.id in ^friends_ids,
785 u.id in ^followers_ids,
793 defp fts_search_subquery(term, query \\ User) do
796 |> String.replace(~r/\W+/, " ")
799 |> Enum.map(&(&1 <> ":*"))
810 setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
811 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B'),
812 to_tsquery('simple', ?),
824 (setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
825 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B')) @@ to_tsquery('simple', ?)
832 |> restrict_deactivated()
835 defp trigram_search_subquery(term) do
839 # ^1 gives 'Postgrex expected a binary, got 1' for some weird reason
840 search_type: fragment("?", 1),
843 "similarity(?, trim(? || ' ' || coalesce(?, '')))",
849 where: fragment("trim(? || ' ' || coalesce(?, '')) % ?", u.nickname, u.name, ^term)
851 |> restrict_deactivated()
854 def mute(muter, %User{ap_id: ap_id}) do
857 |> User.Info.add_to_mutes(ap_id)
861 |> put_embed(:info, info_cng)
863 update_and_set_cache(cng)
866 def unmute(muter, %{ap_id: ap_id}) do
869 |> User.Info.remove_from_mutes(ap_id)
873 |> put_embed(:info, info_cng)
875 update_and_set_cache(cng)
878 def subscribe(subscriber, %{ap_id: ap_id}) do
879 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
881 with %User{} = subscribed <- get_cached_by_ap_id(ap_id) do
882 blocked = blocks?(subscribed, subscriber) and deny_follow_blocked
885 {:error, "Could not subscribe: #{subscribed.nickname} is blocking you"}
889 |> User.Info.add_to_subscribers(subscriber.ap_id)
892 |> put_embed(:info, info_cng)
893 |> update_and_set_cache()
898 def unsubscribe(unsubscriber, %{ap_id: ap_id}) do
899 with %User{} = user <- get_cached_by_ap_id(ap_id) do
902 |> User.Info.remove_from_subscribers(unsubscriber.ap_id)
905 |> put_embed(:info, info_cng)
906 |> update_and_set_cache()
910 def block(blocker, %User{ap_id: ap_id} = blocked) do
911 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
913 if following?(blocker, blocked) do
914 {:ok, blocker, _} = unfollow(blocker, blocked)
921 if subscribed_to?(blocked, blocker) do
922 {:ok, blocker} = unsubscribe(blocked, blocker)
928 if following?(blocked, blocker) do
929 unfollow(blocked, blocker)
932 {:ok, blocker} = update_follower_count(blocker)
936 |> User.Info.add_to_block(ap_id)
940 |> put_embed(:info, info_cng)
942 update_and_set_cache(cng)
945 # helper to handle the block given only an actor's AP id
946 def block(blocker, %{ap_id: ap_id}) do
947 block(blocker, get_cached_by_ap_id(ap_id))
950 def unblock(blocker, %{ap_id: ap_id}) do
953 |> User.Info.remove_from_block(ap_id)
957 |> put_embed(:info, info_cng)
959 update_and_set_cache(cng)
962 def mutes?(nil, _), do: false
963 def mutes?(user, %{ap_id: ap_id}), do: Enum.member?(user.info.mutes, ap_id)
965 def blocks?(user, %{ap_id: ap_id}) do
966 blocks = user.info.blocks
967 domain_blocks = user.info.domain_blocks
968 %{host: host} = URI.parse(ap_id)
970 Enum.member?(blocks, ap_id) ||
971 Enum.any?(domain_blocks, fn domain ->
976 def subscribed_to?(user, %{ap_id: ap_id}) do
977 with %User{} = target <- get_cached_by_ap_id(ap_id) do
978 Enum.member?(target.info.subscribers, user.ap_id)
982 @spec muted_users(User.t()) :: [User.t()]
983 def muted_users(user) do
984 User.Query.build(%{ap_id: user.info.mutes, deactivated: false})
988 @spec blocked_users(User.t()) :: [User.t()]
989 def blocked_users(user) do
990 User.Query.build(%{ap_id: user.info.blocks, deactivated: false})
994 @spec subscribers(User.t()) :: [User.t()]
995 def subscribers(user) do
996 User.Query.build(%{ap_id: user.info.subscribers, deactivated: false})
1000 def block_domain(user, domain) do
1003 |> User.Info.add_to_domain_block(domain)
1007 |> put_embed(:info, info_cng)
1009 update_and_set_cache(cng)
1012 def unblock_domain(user, domain) do
1015 |> User.Info.remove_from_domain_block(domain)
1019 |> put_embed(:info, info_cng)
1021 update_and_set_cache(cng)
1024 def deactivate_async(user, status \\ true) do
1025 PleromaJobQueue.enqueue(:background, __MODULE__, [:deactivate_async, user, status])
1028 def deactivate(%User{} = user, status \\ true) do
1029 info_cng = User.Info.set_activation_status(user.info, status)
1031 with {:ok, friends} <- User.get_friends(user),
1032 {:ok, followers} <- User.get_followers(user),
1036 |> put_embed(:info, info_cng)
1037 |> update_and_set_cache() do
1038 Enum.each(followers, &invalidate_cache(&1))
1039 Enum.each(friends, &update_follower_count(&1))
1045 def update_notification_settings(%User{} = user, settings \\ %{}) do
1046 info_changeset = User.Info.update_notification_settings(user.info, settings)
1049 |> put_embed(:info, info_changeset)
1050 |> update_and_set_cache()
1053 @spec delete(User.t()) :: :ok
1054 def delete(%User{} = user),
1055 do: PleromaJobQueue.enqueue(:background, __MODULE__, [:delete, user])
1057 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1058 def perform(:delete, %User{} = user) do
1059 {:ok, user} = User.deactivate(user)
1061 # Remove all relationships
1062 {:ok, followers} = User.get_followers(user)
1064 Enum.each(followers, fn follower -> User.unfollow(follower, user) end)
1066 {:ok, friends} = User.get_friends(user)
1068 Enum.each(friends, fn followed -> User.unfollow(user, followed) end)
1070 delete_user_activities(user)
1073 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1074 def perform(:fetch_initial_posts, %User{} = user) do
1075 pages = Pleroma.Config.get!([:fetch_initial_posts, :pages])
1078 # Insert all the posts in reverse order, so they're in the right order on the timeline
1079 Enum.reverse(Utils.fetch_ordered_collection(user.info.source_data["outbox"], pages)),
1080 &Pleroma.Web.Federator.incoming_ap_doc/1
1086 def perform(:deactivate_async, user, status), do: deactivate(user, status)
1088 @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
1089 def perform(:blocks_import, %User{} = blocker, blocked_identifiers)
1090 when is_list(blocked_identifiers) do
1092 blocked_identifiers,
1093 fn blocked_identifier ->
1094 with {:ok, %User{} = blocked} <- get_or_fetch(blocked_identifier),
1095 {:ok, blocker} <- block(blocker, blocked),
1096 {:ok, _} <- ActivityPub.block(blocker, blocked) do
1100 Logger.debug("blocks_import failed for #{blocked_identifier} with: #{inspect(err)}")
1107 @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
1108 def perform(:follow_import, %User{} = follower, followed_identifiers)
1109 when is_list(followed_identifiers) do
1111 followed_identifiers,
1112 fn followed_identifier ->
1113 with {:ok, %User{} = followed} <- get_or_fetch(followed_identifier),
1114 {:ok, follower} <- maybe_direct_follow(follower, followed),
1115 {:ok, _} <- ActivityPub.follow(follower, followed) do
1119 Logger.debug("follow_import failed for #{followed_identifier} with: #{inspect(err)}")
1126 def blocks_import(%User{} = blocker, blocked_identifiers) when is_list(blocked_identifiers),
1128 PleromaJobQueue.enqueue(:background, __MODULE__, [
1134 def follow_import(%User{} = follower, followed_identifiers) when is_list(followed_identifiers),
1136 PleromaJobQueue.enqueue(:background, __MODULE__, [
1139 followed_identifiers
1142 def delete_user_activities(%User{ap_id: ap_id} = user) do
1145 |> Activity.query_by_actor()
1148 Repo.transaction(fn -> Enum.each(stream, &delete_activity(&1)) end, timeout: :infinity)
1153 defp delete_activity(%{data: %{"type" => "Create"}} = activity) do
1154 Object.normalize(activity) |> ActivityPub.delete()
1157 defp delete_activity(_activity), do: "Doing nothing"
1159 def html_filter_policy(%User{info: %{no_rich_text: true}}) do
1160 Pleroma.HTML.Scrubber.TwitterText
1163 @default_scrubbers Pleroma.Config.get([:markup, :scrub_policy])
1165 def html_filter_policy(_), do: @default_scrubbers
1167 def fetch_by_ap_id(ap_id) do
1168 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
1175 case OStatus.make_user(ap_id) do
1176 {:ok, user} -> {:ok, user}
1177 _ -> {:error, "Could not fetch by AP id"}
1182 def get_or_fetch_by_ap_id(ap_id) do
1183 user = get_cached_by_ap_id(ap_id)
1185 if !is_nil(user) and !User.needs_update?(user) do
1188 # Whether to fetch initial posts for the user (if it's a new user & the fetching is enabled)
1189 should_fetch_initial = is_nil(user) and Pleroma.Config.get([:fetch_initial_posts, :enabled])
1191 resp = fetch_by_ap_id(ap_id)
1193 if should_fetch_initial do
1194 with {:ok, %User{} = user} <- resp do
1195 fetch_initial_posts(user)
1203 def get_or_create_instance_user do
1204 relay_uri = "#{Pleroma.Web.Endpoint.url()}/relay"
1206 if user = get_cached_by_ap_id(relay_uri) do
1210 %User{info: %User.Info{}}
1211 |> cast(%{}, [:ap_id, :nickname, :local])
1212 |> put_change(:ap_id, relay_uri)
1213 |> put_change(:nickname, nil)
1214 |> put_change(:local, true)
1215 |> put_change(:follower_address, relay_uri <> "/followers")
1217 {:ok, user} = Repo.insert(changes)
1223 def public_key_from_info(%{
1224 source_data: %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
1228 |> :public_key.pem_decode()
1230 |> :public_key.pem_entry_decode()
1236 def public_key_from_info(%{magic_key: magic_key}) do
1237 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
1240 def get_public_key_for_ap_id(ap_id) do
1241 with {:ok, %User{} = user} <- get_or_fetch_by_ap_id(ap_id),
1242 {:ok, public_key} <- public_key_from_info(user.info) do
1249 defp blank?(""), do: nil
1250 defp blank?(n), do: n
1252 def insert_or_update_user(data) do
1254 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
1255 |> remote_user_creation()
1256 |> Repo.insert(on_conflict: :replace_all, conflict_target: :nickname)
1260 def ap_enabled?(%User{local: true}), do: true
1261 def ap_enabled?(%User{info: info}), do: info.ap_enabled
1262 def ap_enabled?(_), do: false
1264 @doc "Gets or fetch a user by uri or nickname."
1265 @spec get_or_fetch(String.t()) :: {:ok, User.t()} | {:error, String.t()}
1266 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
1267 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
1269 # wait a period of time and return newest version of the User structs
1270 # this is because we have synchronous follow APIs and need to simulate them
1271 # with an async handshake
1272 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
1273 with %User{} = a <- User.get_cached_by_id(a.id),
1274 %User{} = b <- User.get_cached_by_id(b.id) do
1282 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
1283 with :ok <- :timer.sleep(timeout),
1284 %User{} = a <- User.get_cached_by_id(a.id),
1285 %User{} = b <- User.get_cached_by_id(b.id) do
1293 def parse_bio(bio) when is_binary(bio) and bio != "" do
1295 |> CommonUtils.format_input("text/plain", mentions_format: :full)
1299 def parse_bio(_), do: ""
1301 def parse_bio(bio, user) when is_binary(bio) and bio != "" do
1302 # TODO: get profile URLs other than user.ap_id
1303 profile_urls = [user.ap_id]
1306 |> CommonUtils.format_input("text/plain",
1307 mentions_format: :full,
1308 rel: &RelMe.maybe_put_rel_me(&1, profile_urls)
1313 def parse_bio(_, _), do: ""
1315 def tag(user_identifiers, tags) when is_list(user_identifiers) do
1316 Repo.transaction(fn ->
1317 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
1321 def tag(nickname, tags) when is_binary(nickname),
1322 do: tag(get_by_nickname(nickname), tags)
1324 def tag(%User{} = user, tags),
1325 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
1327 def untag(user_identifiers, tags) when is_list(user_identifiers) do
1328 Repo.transaction(fn ->
1329 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
1333 def untag(nickname, tags) when is_binary(nickname),
1334 do: untag(get_by_nickname(nickname), tags)
1336 def untag(%User{} = user, tags),
1337 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
1339 defp update_tags(%User{} = user, new_tags) do
1340 {:ok, updated_user} =
1342 |> change(%{tags: new_tags})
1343 |> update_and_set_cache()
1348 defp normalize_tags(tags) do
1351 |> Enum.map(&String.downcase(&1))
1354 defp local_nickname_regex do
1355 if Pleroma.Config.get([:instance, :extended_nickname_format]) do
1356 @extended_local_nickname_regex
1358 @strict_local_nickname_regex
1362 def local_nickname(nickname_or_mention) do
1365 |> String.split("@")
1369 def full_nickname(nickname_or_mention),
1370 do: String.trim_leading(nickname_or_mention, "@")
1372 def error_user(ap_id) do
1377 nickname: "erroruser@example.com",
1378 inserted_at: NaiveDateTime.utc_now()
1382 @spec all_superusers() :: [User.t()]
1383 def all_superusers do
1384 User.Query.build(%{super_users: true, local: true, deactivated: false})
1388 def showing_reblogs?(%User{} = user, %User{} = target) do
1389 target.ap_id not in user.info.muted_reblogs
1392 @spec toggle_confirmation(User.t()) :: {:ok, User.t()} | {:error, Changeset.t()}
1393 def toggle_confirmation(%User{} = user) do
1394 need_confirmation? = !user.info.confirmation_pending
1397 User.Info.confirmation_changeset(user.info, need_confirmation: need_confirmation?)
1401 |> put_embed(:info, info_changeset)
1402 |> update_and_set_cache()
1405 def get_mascot(%{info: %{mascot: %{} = mascot}}) when not is_nil(mascot) do
1409 def get_mascot(%{info: %{mascot: mascot}}) when is_nil(mascot) do
1410 # use instance-default
1411 config = Pleroma.Config.get([:assets, :mascots])
1412 default_mascot = Pleroma.Config.get([:assets, :default_mascot])
1413 mascot = Keyword.get(config, default_mascot)
1416 "id" => "default-mascot",
1417 "url" => mascot[:url],
1418 "preview_url" => mascot[:url],
1420 "mime_type" => mascot[:mime_type]
1425 def ensure_keys_present(user) do
1431 {:ok, pem} = Keys.generate_rsa_pem()
1435 |> User.Info.set_keys(pem)
1438 Ecto.Changeset.change(user)
1439 |> Ecto.Changeset.put_embed(:info, info_cng)
1441 update_and_set_cache(cng)
1445 def get_ap_ids_by_nicknames(nicknames) do
1447 where: u.nickname in ^nicknames,