1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.User do
10 import Ecto, only: [assoc: 2]
13 alias Pleroma.Activity
15 alias Pleroma.Conversation.Participation
16 alias Pleroma.Delivery
18 alias Pleroma.FollowingRelationship
19 alias Pleroma.Formatter
23 alias Pleroma.Notification
25 alias Pleroma.Registration
27 alias Pleroma.RepoStreamer
29 alias Pleroma.UserRelationship
31 alias Pleroma.Web.ActivityPub.ActivityPub
32 alias Pleroma.Web.ActivityPub.Builder
33 alias Pleroma.Web.ActivityPub.ObjectValidators.Types
34 alias Pleroma.Web.ActivityPub.Pipeline
35 alias Pleroma.Web.ActivityPub.Utils
36 alias Pleroma.Web.CommonAPI
37 alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils
38 alias Pleroma.Web.OAuth
39 alias Pleroma.Web.RelMe
40 alias Pleroma.Workers.BackgroundWorker
44 @type t :: %__MODULE__{}
45 @type account_status :: :active | :deactivated | :password_reset_pending | :confirmation_pending
46 @primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
48 # credo:disable-for-next-line Credo.Check.Readability.MaxLineLength
49 @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])?)*$/
51 @strict_local_nickname_regex ~r/^[a-zA-Z\d]+$/
52 @extended_local_nickname_regex ~r/^[a-zA-Z\d_-]+$/
54 # AP ID user relationships (blocks, mutes etc.)
55 # Format: [rel_type: [outgoing_rel: :outgoing_rel_target, incoming_rel: :incoming_rel_source]]
56 @user_relationships_config [
58 blocker_blocks: :blocked_users,
59 blockee_blocks: :blocker_users
62 muter_mutes: :muted_users,
63 mutee_mutes: :muter_users
66 reblog_muter_mutes: :reblog_muted_users,
67 reblog_mutee_mutes: :reblog_muter_users
70 notification_muter_mutes: :notification_muted_users,
71 notification_mutee_mutes: :notification_muter_users
73 # Note: `inverse_subscription` relationship is inverse: subscriber acts as relationship target
74 inverse_subscription: [
75 subscribee_subscriptions: :subscriber_users,
76 subscriber_subscriptions: :subscribee_users
82 field(:email, :string)
84 field(:nickname, :string)
85 field(:password_hash, :string)
86 field(:password, :string, virtual: true)
87 field(:password_confirmation, :string, virtual: true)
89 field(:public_key, :string)
90 field(:ap_id, :string)
92 field(:local, :boolean, default: true)
93 field(:follower_address, :string)
94 field(:following_address, :string)
95 field(:search_rank, :float, virtual: true)
96 field(:search_type, :integer, virtual: true)
97 field(:tags, {:array, :string}, default: [])
98 field(:last_refreshed_at, :naive_datetime_usec)
99 field(:last_digest_emailed_at, :naive_datetime)
100 field(:banner, :map, default: %{})
101 field(:background, :map, default: %{})
102 field(:note_count, :integer, default: 0)
103 field(:follower_count, :integer, default: 0)
104 field(:following_count, :integer, default: 0)
105 field(:locked, :boolean, default: false)
106 field(:confirmation_pending, :boolean, default: false)
107 field(:password_reset_pending, :boolean, default: false)
108 field(:confirmation_token, :string, default: nil)
109 field(:default_scope, :string, default: "public")
110 field(:domain_blocks, {:array, :string}, default: [])
111 field(:deactivated, :boolean, default: false)
112 field(:no_rich_text, :boolean, default: false)
113 field(:ap_enabled, :boolean, default: false)
114 field(:is_moderator, :boolean, default: false)
115 field(:is_admin, :boolean, default: false)
116 field(:show_role, :boolean, default: true)
117 field(:settings, :map, default: nil)
118 field(:uri, Types.Uri, default: nil)
119 field(:hide_followers_count, :boolean, default: false)
120 field(:hide_follows_count, :boolean, default: false)
121 field(:hide_followers, :boolean, default: false)
122 field(:hide_follows, :boolean, default: false)
123 field(:hide_favorites, :boolean, default: true)
124 field(:unread_conversation_count, :integer, default: 0)
125 field(:pinned_activities, {:array, :string}, default: [])
126 field(:email_notifications, :map, default: %{"digest" => false})
127 field(:mascot, :map, default: nil)
128 field(:emoji, :map, default: %{})
129 field(:pleroma_settings_store, :map, default: %{})
130 field(:fields, {:array, :map}, default: [])
131 field(:raw_fields, {:array, :map}, default: [])
132 field(:discoverable, :boolean, default: false)
133 field(:invisible, :boolean, default: false)
134 field(:allow_following_move, :boolean, default: true)
135 field(:skip_thread_containment, :boolean, default: false)
136 field(:actor_type, :string, default: "Person")
137 field(:also_known_as, {:array, :string}, default: [])
138 field(:inbox, :string)
139 field(:shared_inbox, :string)
142 :notification_settings,
143 Pleroma.User.NotificationSetting,
147 has_many(:notifications, Notification)
148 has_many(:registrations, Registration)
149 has_many(:deliveries, Delivery)
151 has_many(:outgoing_relationships, UserRelationship, foreign_key: :source_id)
152 has_many(:incoming_relationships, UserRelationship, foreign_key: :target_id)
154 for {relationship_type,
156 {outgoing_relation, outgoing_relation_target},
157 {incoming_relation, incoming_relation_source}
158 ]} <- @user_relationships_config do
159 # Definitions of `has_many` relations: :blocker_blocks, :muter_mutes, :reblog_muter_mutes,
160 # :notification_muter_mutes, :subscribee_subscriptions
161 has_many(outgoing_relation, UserRelationship,
162 foreign_key: :source_id,
163 where: [relationship_type: relationship_type]
166 # Definitions of `has_many` relations: :blockee_blocks, :mutee_mutes, :reblog_mutee_mutes,
167 # :notification_mutee_mutes, :subscriber_subscriptions
168 has_many(incoming_relation, UserRelationship,
169 foreign_key: :target_id,
170 where: [relationship_type: relationship_type]
173 # Definitions of `has_many` relations: :blocked_users, :muted_users, :reblog_muted_users,
174 # :notification_muted_users, :subscriber_users
175 has_many(outgoing_relation_target, through: [outgoing_relation, :target])
177 # Definitions of `has_many` relations: :blocker_users, :muter_users, :reblog_muter_users,
178 # :notification_muter_users, :subscribee_users
179 has_many(incoming_relation_source, through: [incoming_relation, :source])
182 # `:blocks` is deprecated (replaced with `blocked_users` relation)
183 field(:blocks, {:array, :string}, default: [])
184 # `:mutes` is deprecated (replaced with `muted_users` relation)
185 field(:mutes, {:array, :string}, default: [])
186 # `:muted_reblogs` is deprecated (replaced with `reblog_muted_users` relation)
187 field(:muted_reblogs, {:array, :string}, default: [])
188 # `:muted_notifications` is deprecated (replaced with `notification_muted_users` relation)
189 field(:muted_notifications, {:array, :string}, default: [])
190 # `:subscribers` is deprecated (replaced with `subscriber_users` relation)
191 field(:subscribers, {:array, :string}, default: [])
194 :multi_factor_authentication_settings,
202 for {_relationship_type, [{_outgoing_relation, outgoing_relation_target}, _]} <-
203 @user_relationships_config do
204 # `def blocked_users_relation/2`, `def muted_users_relation/2`,
205 # `def reblog_muted_users_relation/2`, `def notification_muted_users/2`,
206 # `def subscriber_users/2`
207 def unquote(:"#{outgoing_relation_target}_relation")(user, restrict_deactivated? \\ false) do
208 target_users_query = assoc(user, unquote(outgoing_relation_target))
210 if restrict_deactivated? do
211 restrict_deactivated(target_users_query)
217 # `def blocked_users/2`, `def muted_users/2`, `def reblog_muted_users/2`,
218 # `def notification_muted_users/2`, `def subscriber_users/2`
219 def unquote(outgoing_relation_target)(user, restrict_deactivated? \\ false) do
221 |> apply(unquote(:"#{outgoing_relation_target}_relation"), [
223 restrict_deactivated?
228 # `def blocked_users_ap_ids/2`, `def muted_users_ap_ids/2`, `def reblog_muted_users_ap_ids/2`,
229 # `def notification_muted_users_ap_ids/2`, `def subscriber_users_ap_ids/2`
230 def unquote(:"#{outgoing_relation_target}_ap_ids")(user, restrict_deactivated? \\ false) do
232 |> apply(unquote(:"#{outgoing_relation_target}_relation"), [
234 restrict_deactivated?
236 |> select([u], u.ap_id)
242 Dumps Flake Id to SQL-compatible format (16-byte UUID).
243 E.g. "9pQtDGXuq4p3VlcJEm" -> <<0, 0, 1, 110, 179, 218, 42, 92, 213, 41, 44, 227, 95, 213, 0, 0>>
245 def binary_id(source_id) when is_binary(source_id) do
246 with {:ok, dumped_id} <- FlakeId.Ecto.CompatType.dump(source_id) do
253 def binary_id(source_ids) when is_list(source_ids) do
254 Enum.map(source_ids, &binary_id/1)
257 def binary_id(%User{} = user), do: binary_id(user.id)
259 @doc "Returns status account"
260 @spec account_status(User.t()) :: account_status()
261 def account_status(%User{deactivated: true}), do: :deactivated
262 def account_status(%User{password_reset_pending: true}), do: :password_reset_pending
264 def account_status(%User{confirmation_pending: true}) do
265 if Config.get([:instance, :account_activation_required]) do
266 :confirmation_pending
272 def account_status(%User{}), do: :active
274 @spec visible_for(User.t(), User.t() | nil) ::
277 | :restricted_unauthenticated
279 | :confirmation_pending
280 def visible_for(user, for_user \\ nil)
282 def visible_for(%User{invisible: true}, _), do: :invisible
284 def visible_for(%User{id: user_id}, %User{id: user_id}), do: :visible
286 def visible_for(%User{} = user, nil) do
287 if restrict_unauthenticated?(user) do
288 :restrict_unauthenticated
290 visible_account_status(user)
294 def visible_for(%User{} = user, for_user) do
295 if superuser?(for_user) do
298 visible_account_status(user)
302 def visible_for(_, _), do: :invisible
304 defp restrict_unauthenticated?(%User{local: local}) do
305 config_key = if local, do: :local, else: :remote
307 Config.get([:restrict_unauthenticated, :profiles, config_key], false)
310 defp visible_account_status(user) do
311 status = account_status(user)
313 if status in [:active, :password_reset_pending] do
320 @spec superuser?(User.t()) :: boolean()
321 def superuser?(%User{local: true, is_admin: true}), do: true
322 def superuser?(%User{local: true, is_moderator: true}), do: true
323 def superuser?(_), do: false
325 @spec invisible?(User.t()) :: boolean()
326 def invisible?(%User{invisible: true}), do: true
327 def invisible?(_), do: false
329 def avatar_url(user, options \\ []) do
331 %{"url" => [%{"href" => href} | _]} -> href
332 _ -> !options[:no_default] && "#{Web.base_url()}/images/avi.png"
336 def banner_url(user, options \\ []) do
338 %{"url" => [%{"href" => href} | _]} -> href
339 _ -> !options[:no_default] && "#{Web.base_url()}/images/banner.png"
343 # Should probably be renamed or removed
344 def ap_id(%User{nickname: nickname}), do: "#{Web.base_url()}/users/#{nickname}"
346 def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
347 def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
349 @spec ap_following(User.t()) :: String.t()
350 def ap_following(%User{following_address: fa}) when is_binary(fa), do: fa
351 def ap_following(%User{} = user), do: "#{ap_id(user)}/following"
353 @spec restrict_deactivated(Ecto.Query.t()) :: Ecto.Query.t()
354 def restrict_deactivated(query) do
355 from(u in query, where: u.deactivated != ^true)
358 defdelegate following_count(user), to: FollowingRelationship
360 defp truncate_fields_param(params) do
361 if Map.has_key?(params, :fields) do
362 Map.put(params, :fields, Enum.map(params[:fields], &truncate_field/1))
368 defp truncate_if_exists(params, key, max_length) do
369 if Map.has_key?(params, key) and is_binary(params[key]) do
370 {value, _chopped} = String.split_at(params[key], max_length)
371 Map.put(params, key, value)
377 defp fix_follower_address(%{follower_address: _, following_address: _} = params), do: params
379 defp fix_follower_address(%{nickname: nickname} = params),
380 do: Map.put(params, :follower_address, ap_followers(%User{nickname: nickname}))
382 defp fix_follower_address(params), do: params
384 def remote_user_changeset(struct \\ %User{local: false}, params) do
385 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
386 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
389 case params[:name] do
390 name when is_binary(name) and byte_size(name) > 0 -> name
391 _ -> params[:nickname]
396 |> Map.put(:name, name)
397 |> Map.put_new(:last_refreshed_at, NaiveDateTime.utc_now())
398 |> truncate_if_exists(:name, name_limit)
399 |> truncate_if_exists(:bio, bio_limit)
400 |> truncate_fields_param()
401 |> fix_follower_address()
425 :hide_followers_count,
436 |> validate_required([:name, :ap_id])
437 |> unique_constraint(:nickname)
438 |> validate_format(:nickname, @email_regex)
439 |> validate_length(:bio, max: bio_limit)
440 |> validate_length(:name, max: name_limit)
441 |> validate_fields(true)
444 def update_changeset(struct, params \\ %{}) do
445 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
446 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
465 :hide_followers_count,
468 :allow_following_move,
471 :skip_thread_containment,
474 :pleroma_settings_store,
480 |> unique_constraint(:nickname)
481 |> validate_format(:nickname, local_nickname_regex())
482 |> validate_length(:bio, max: bio_limit)
483 |> validate_length(:name, min: 1, max: name_limit)
486 |> put_change_if_present(:bio, &{:ok, parse_bio(&1, struct)})
487 |> put_change_if_present(:avatar, &put_upload(&1, :avatar))
488 |> put_change_if_present(:banner, &put_upload(&1, :banner))
489 |> put_change_if_present(:background, &put_upload(&1, :background))
490 |> put_change_if_present(
491 :pleroma_settings_store,
492 &{:ok, Map.merge(struct.pleroma_settings_store, &1)}
494 |> validate_fields(false)
497 defp put_fields(changeset) do
498 if raw_fields = get_change(changeset, :raw_fields) do
501 |> Enum.filter(fn %{"name" => n} -> n != "" end)
505 |> Enum.map(fn f -> Map.update!(f, "value", &parse_fields(&1)) end)
508 |> put_change(:raw_fields, raw_fields)
509 |> put_change(:fields, fields)
515 defp parse_fields(value) do
517 |> Formatter.linkify(mentions_format: :full)
521 defp put_emoji(changeset) do
522 bio = get_change(changeset, :bio)
523 name = get_change(changeset, :name)
526 emoji = Map.merge(Emoji.Formatter.get_emoji_map(bio), Emoji.Formatter.get_emoji_map(name))
527 put_change(changeset, :emoji, emoji)
533 defp put_change_if_present(changeset, map_field, value_function) do
534 if value = get_change(changeset, map_field) do
535 with {:ok, new_value} <- value_function.(value) do
536 put_change(changeset, map_field, new_value)
545 defp put_upload(value, type) do
546 with %Plug.Upload{} <- value,
547 {:ok, object} <- ActivityPub.upload(value, type: type) do
552 def update_as_admin_changeset(struct, params) do
554 |> update_changeset(params)
555 |> cast(params, [:email])
556 |> delete_change(:also_known_as)
557 |> unique_constraint(:email)
558 |> validate_format(:email, @email_regex)
561 @spec update_as_admin(%User{}, map) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
562 def update_as_admin(user, params) do
563 params = Map.put(params, "password_confirmation", params["password"])
564 changeset = update_as_admin_changeset(user, params)
566 if params["password"] do
567 reset_password(user, changeset, params)
569 User.update_and_set_cache(changeset)
573 def password_update_changeset(struct, params) do
575 |> cast(params, [:password, :password_confirmation])
576 |> validate_required([:password, :password_confirmation])
577 |> validate_confirmation(:password)
578 |> put_password_hash()
579 |> put_change(:password_reset_pending, false)
582 @spec reset_password(User.t(), map) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
583 def reset_password(%User{} = user, params) do
584 reset_password(user, user, params)
587 def reset_password(%User{id: user_id} = user, struct, params) do
590 |> Multi.update(:user, password_update_changeset(struct, params))
591 |> Multi.delete_all(:tokens, OAuth.Token.Query.get_by_user(user_id))
592 |> Multi.delete_all(:auth, OAuth.Authorization.delete_by_user_query(user))
594 case Repo.transaction(multi) do
595 {:ok, %{user: user} = _} -> set_cache(user)
596 {:error, _, changeset, _} -> {:error, changeset}
600 def update_password_reset_pending(user, value) do
603 |> put_change(:password_reset_pending, value)
604 |> update_and_set_cache()
607 def force_password_reset_async(user) do
608 BackgroundWorker.enqueue("force_password_reset", %{"user_id" => user.id})
611 @spec force_password_reset(User.t()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
612 def force_password_reset(user), do: update_password_reset_pending(user, true)
614 def register_changeset(struct, params \\ %{}, opts \\ []) do
615 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
616 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
619 if is_nil(opts[:need_confirmation]) do
620 Pleroma.Config.get([:instance, :account_activation_required])
622 opts[:need_confirmation]
626 |> confirmation_changeset(need_confirmation: need_confirmation?)
627 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation, :emoji])
628 |> validate_required([:name, :nickname, :password, :password_confirmation])
629 |> validate_confirmation(:password)
630 |> unique_constraint(:email)
631 |> unique_constraint(:nickname)
632 |> validate_exclusion(:nickname, Pleroma.Config.get([User, :restricted_nicknames]))
633 |> validate_format(:nickname, local_nickname_regex())
634 |> validate_format(:email, @email_regex)
635 |> validate_length(:bio, max: bio_limit)
636 |> validate_length(:name, min: 1, max: name_limit)
637 |> maybe_validate_required_email(opts[:external])
640 |> unique_constraint(:ap_id)
641 |> put_following_and_follower_address()
644 def maybe_validate_required_email(changeset, true), do: changeset
646 def maybe_validate_required_email(changeset, _) do
647 if Pleroma.Config.get([:instance, :account_activation_required]) do
648 validate_required(changeset, [:email])
654 defp put_ap_id(changeset) do
655 ap_id = ap_id(%User{nickname: get_field(changeset, :nickname)})
656 put_change(changeset, :ap_id, ap_id)
659 defp put_following_and_follower_address(changeset) do
660 followers = ap_followers(%User{nickname: get_field(changeset, :nickname)})
663 |> put_change(:follower_address, followers)
666 defp autofollow_users(user) do
667 candidates = Pleroma.Config.get([:instance, :autofollowed_nicknames])
670 User.Query.build(%{nickname: candidates, local: true, deactivated: false})
673 follow_all(user, autofollowed_users)
676 @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
677 def register(%Ecto.Changeset{} = changeset) do
678 with {:ok, user} <- Repo.insert(changeset) do
679 post_register_action(user)
683 def post_register_action(%User{} = user) do
684 with {:ok, user} <- autofollow_users(user),
685 {:ok, user} <- set_cache(user),
686 {:ok, _} <- User.WelcomeMessage.post_welcome_message_to_user(user),
687 {:ok, _} <- try_send_confirmation_email(user) do
692 def try_send_confirmation_email(%User{} = user) do
693 if user.confirmation_pending &&
694 Pleroma.Config.get([:instance, :account_activation_required]) do
696 |> Pleroma.Emails.UserEmail.account_confirmation_email()
697 |> Pleroma.Emails.Mailer.deliver_async()
705 def try_send_confirmation_email(users) do
706 Enum.each(users, &try_send_confirmation_email/1)
709 def needs_update?(%User{local: true}), do: false
711 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
713 def needs_update?(%User{local: false} = user) do
714 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
717 def needs_update?(_), do: true
719 @spec maybe_direct_follow(User.t(), User.t()) :: {:ok, User.t()} | {:error, String.t()}
721 # "Locked" (self-locked) users demand explicit authorization of follow requests
722 def maybe_direct_follow(%User{} = follower, %User{local: true, locked: true} = followed) do
723 follow(follower, followed, :follow_pending)
726 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
727 follow(follower, followed)
730 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
731 if not ap_enabled?(followed) do
732 follow(follower, followed)
738 @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
739 @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
740 def follow_all(follower, followeds) do
742 |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
743 |> Enum.each(&follow(follower, &1, :follow_accept))
748 defdelegate following(user), to: FollowingRelationship
750 def follow(%User{} = follower, %User{} = followed, state \\ :follow_accept) do
751 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
754 followed.deactivated ->
755 {:error, "Could not follow user: #{followed.nickname} is deactivated."}
757 deny_follow_blocked and blocks?(followed, follower) ->
758 {:error, "Could not follow user: #{followed.nickname} blocked you."}
761 FollowingRelationship.follow(follower, followed, state)
763 {:ok, _} = update_follower_count(followed)
766 |> update_following_count()
771 def unfollow(%User{ap_id: ap_id}, %User{ap_id: ap_id}) do
772 {:error, "Not subscribed!"}
775 def unfollow(%User{} = follower, %User{} = followed) do
776 case get_follow_state(follower, followed) do
777 state when state in [:follow_pending, :follow_accept] ->
778 FollowingRelationship.unfollow(follower, followed)
779 {:ok, followed} = update_follower_count(followed)
783 |> update_following_count()
786 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
789 {:error, "Not subscribed!"}
793 defdelegate following?(follower, followed), to: FollowingRelationship
795 @doc "Returns follow state as Pleroma.FollowingRelationship.State value"
796 def get_follow_state(%User{} = follower, %User{} = following) do
797 following_relationship = FollowingRelationship.get(follower, following)
798 get_follow_state(follower, following, following_relationship)
801 def get_follow_state(
804 following_relationship
806 case {following_relationship, following.local} do
808 case Utils.fetch_latest_follow(follower, following) do
809 %Activity{data: %{"state" => state}} when state in ["pending", "accept"] ->
810 FollowingRelationship.state_to_enum(state)
816 {%{state: state}, _} ->
824 def locked?(%User{} = user) do
829 Repo.get_by(User, id: id)
832 def get_by_ap_id(ap_id) do
833 Repo.get_by(User, ap_id: ap_id)
836 def get_all_by_ap_id(ap_ids) do
837 from(u in __MODULE__,
838 where: u.ap_id in ^ap_ids
843 def get_all_by_ids(ids) do
844 from(u in __MODULE__, where: u.id in ^ids)
848 # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
849 # of the ap_id and the domain and tries to get that user
850 def get_by_guessed_nickname(ap_id) do
851 domain = URI.parse(ap_id).host
852 name = List.last(String.split(ap_id, "/"))
853 nickname = "#{name}@#{domain}"
855 get_cached_by_nickname(nickname)
858 def set_cache({:ok, user}), do: set_cache(user)
859 def set_cache({:error, err}), do: {:error, err}
861 def set_cache(%User{} = user) do
862 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
863 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
864 Cachex.put(:user_cache, "friends_ap_ids:#{user.nickname}", get_user_friends_ap_ids(user))
868 def update_and_set_cache(struct, params) do
870 |> update_changeset(params)
871 |> update_and_set_cache()
874 def update_and_set_cache(changeset) do
875 with {:ok, user} <- Repo.update(changeset, stale_error_field: :id) do
880 def get_user_friends_ap_ids(user) do
881 from(u in User.get_friends_query(user), select: u.ap_id)
885 @spec get_cached_user_friends_ap_ids(User.t()) :: [String.t()]
886 def get_cached_user_friends_ap_ids(user) do
887 Cachex.fetch!(:user_cache, "friends_ap_ids:#{user.ap_id}", fn _ ->
888 get_user_friends_ap_ids(user)
892 def invalidate_cache(user) do
893 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
894 Cachex.del(:user_cache, "nickname:#{user.nickname}")
895 Cachex.del(:user_cache, "friends_ap_ids:#{user.ap_id}")
898 @spec get_cached_by_ap_id(String.t()) :: User.t() | nil
899 def get_cached_by_ap_id(ap_id) do
900 key = "ap_id:#{ap_id}"
902 with {:ok, nil} <- Cachex.get(:user_cache, key),
903 user when not is_nil(user) <- get_by_ap_id(ap_id),
904 {:ok, true} <- Cachex.put(:user_cache, key, user) do
912 def get_cached_by_id(id) do
916 Cachex.fetch!(:user_cache, key, fn _ ->
920 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
921 {:commit, user.ap_id}
927 get_cached_by_ap_id(ap_id)
930 def get_cached_by_nickname(nickname) do
931 key = "nickname:#{nickname}"
933 Cachex.fetch!(:user_cache, key, fn ->
934 case get_or_fetch_by_nickname(nickname) do
935 {:ok, user} -> {:commit, user}
936 {:error, _error} -> {:ignore, nil}
941 def get_cached_by_nickname_or_id(nickname_or_id, opts \\ []) do
942 restrict_to_local = Pleroma.Config.get([:instance, :limit_to_local_content])
945 is_integer(nickname_or_id) or FlakeId.flake_id?(nickname_or_id) ->
946 get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
948 restrict_to_local == false or not String.contains?(nickname_or_id, "@") ->
949 get_cached_by_nickname(nickname_or_id)
951 restrict_to_local == :unauthenticated and match?(%User{}, opts[:for]) ->
952 get_cached_by_nickname(nickname_or_id)
959 @spec get_by_nickname(String.t()) :: User.t() | nil
960 def get_by_nickname(nickname) do
961 Repo.get_by(User, nickname: nickname) ||
962 if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
963 Repo.get_by(User, nickname: local_nickname(nickname))
967 def get_by_email(email), do: Repo.get_by(User, email: email)
969 def get_by_nickname_or_email(nickname_or_email) do
970 get_by_nickname(nickname_or_email) || get_by_email(nickname_or_email)
973 def fetch_by_nickname(nickname), do: ActivityPub.make_user_from_nickname(nickname)
975 def get_or_fetch_by_nickname(nickname) do
976 with %User{} = user <- get_by_nickname(nickname) do
980 with [_nick, _domain] <- String.split(nickname, "@"),
981 {:ok, user} <- fetch_by_nickname(nickname) do
984 _e -> {:error, "not found " <> nickname}
989 @spec get_followers_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
990 def get_followers_query(%User{} = user, nil) do
991 User.Query.build(%{followers: user, deactivated: false})
994 def get_followers_query(user, page) do
996 |> get_followers_query(nil)
997 |> User.Query.paginate(page, 20)
1000 @spec get_followers_query(User.t()) :: Ecto.Query.t()
1001 def get_followers_query(user), do: get_followers_query(user, nil)
1003 @spec get_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
1004 def get_followers(user, page \\ nil) do
1006 |> get_followers_query(page)
1010 @spec get_external_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
1011 def get_external_followers(user, page \\ nil) do
1013 |> get_followers_query(page)
1014 |> User.Query.build(%{external: true})
1018 def get_followers_ids(user, page \\ nil) do
1020 |> get_followers_query(page)
1021 |> select([u], u.id)
1025 @spec get_friends_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
1026 def get_friends_query(%User{} = user, nil) do
1027 User.Query.build(%{friends: user, deactivated: false})
1030 def get_friends_query(user, page) do
1032 |> get_friends_query(nil)
1033 |> User.Query.paginate(page, 20)
1036 @spec get_friends_query(User.t()) :: Ecto.Query.t()
1037 def get_friends_query(user), do: get_friends_query(user, nil)
1039 def get_friends(user, page \\ nil) do
1041 |> get_friends_query(page)
1045 def get_friends_ap_ids(user) do
1047 |> get_friends_query(nil)
1048 |> select([u], u.ap_id)
1052 def get_friends_ids(user, page \\ nil) do
1054 |> get_friends_query(page)
1055 |> select([u], u.id)
1059 defdelegate get_follow_requests(user), to: FollowingRelationship
1061 def increase_note_count(%User{} = user) do
1063 |> where(id: ^user.id)
1064 |> update([u], inc: [note_count: 1])
1066 |> Repo.update_all([])
1068 {1, [user]} -> set_cache(user)
1073 def decrease_note_count(%User{} = user) do
1075 |> where(id: ^user.id)
1078 note_count: fragment("greatest(0, note_count - 1)")
1082 |> Repo.update_all([])
1084 {1, [user]} -> set_cache(user)
1089 def update_note_count(%User{} = user, note_count \\ nil) do
1094 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
1100 |> cast(%{note_count: note_count}, [:note_count])
1101 |> update_and_set_cache()
1104 @spec maybe_fetch_follow_information(User.t()) :: User.t()
1105 def maybe_fetch_follow_information(user) do
1106 with {:ok, user} <- fetch_follow_information(user) do
1110 Logger.error("Follower/Following counter update for #{user.ap_id} failed.\n#{inspect(e)}")
1116 def fetch_follow_information(user) do
1117 with {:ok, info} <- ActivityPub.fetch_follow_information_for_user(user) do
1119 |> follow_information_changeset(info)
1120 |> update_and_set_cache()
1124 defp follow_information_changeset(user, params) do
1131 :hide_followers_count,
1136 def update_follower_count(%User{} = user) do
1137 if user.local or !Pleroma.Config.get([:instance, :external_user_synchronization]) do
1138 follower_count_query =
1139 User.Query.build(%{followers: user, deactivated: false})
1140 |> select([u], %{count: count(u.id)})
1143 |> where(id: ^user.id)
1144 |> join(:inner, [u], s in subquery(follower_count_query))
1146 set: [follower_count: s.count]
1149 |> Repo.update_all([])
1151 {1, [user]} -> set_cache(user)
1155 {:ok, maybe_fetch_follow_information(user)}
1159 @spec update_following_count(User.t()) :: User.t()
1160 def update_following_count(%User{local: false} = user) do
1161 if Pleroma.Config.get([:instance, :external_user_synchronization]) do
1162 maybe_fetch_follow_information(user)
1168 def update_following_count(%User{local: true} = user) do
1169 following_count = FollowingRelationship.following_count(user)
1172 |> follow_information_changeset(%{following_count: following_count})
1176 def set_unread_conversation_count(%User{local: true} = user) do
1177 unread_query = Participation.unread_conversation_count_for_user(user)
1180 |> join(:inner, [u], p in subquery(unread_query))
1182 set: [unread_conversation_count: p.count]
1184 |> where([u], u.id == ^user.id)
1186 |> Repo.update_all([])
1188 {1, [user]} -> set_cache(user)
1193 def set_unread_conversation_count(user), do: {:ok, user}
1195 def increment_unread_conversation_count(conversation, %User{local: true} = user) do
1197 Participation.unread_conversation_count_for_user(user)
1198 |> where([p], p.conversation_id == ^conversation.id)
1201 |> join(:inner, [u], p in subquery(unread_query))
1203 inc: [unread_conversation_count: 1]
1205 |> where([u], u.id == ^user.id)
1206 |> where([u, p], p.count == 0)
1208 |> Repo.update_all([])
1210 {1, [user]} -> set_cache(user)
1215 def increment_unread_conversation_count(_, user), do: {:ok, user}
1217 @spec get_users_from_set([String.t()], boolean()) :: [User.t()]
1218 def get_users_from_set(ap_ids, local_only \\ true) do
1219 criteria = %{ap_id: ap_ids, deactivated: false}
1220 criteria = if local_only, do: Map.put(criteria, :local, true), else: criteria
1222 User.Query.build(criteria)
1226 @spec get_recipients_from_activity(Activity.t()) :: [User.t()]
1227 def get_recipients_from_activity(%Activity{recipients: to, actor: actor}) do
1230 User.Query.build(%{recipients_from_activity: to, local: true, deactivated: false})
1234 @spec mute(User.t(), User.t(), boolean()) ::
1235 {:ok, list(UserRelationship.t())} | {:error, String.t()}
1236 def mute(%User{} = muter, %User{} = mutee, notifications? \\ true) do
1237 add_to_mutes(muter, mutee, notifications?)
1240 def unmute(%User{} = muter, %User{} = mutee) do
1241 remove_from_mutes(muter, mutee)
1244 def subscribe(%User{} = subscriber, %User{} = target) do
1245 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
1247 if blocks?(target, subscriber) and deny_follow_blocked do
1248 {:error, "Could not subscribe: #{target.nickname} is blocking you"}
1250 # Note: the relationship is inverse: subscriber acts as relationship target
1251 UserRelationship.create_inverse_subscription(target, subscriber)
1255 def subscribe(%User{} = subscriber, %{ap_id: ap_id}) do
1256 with %User{} = subscribee <- get_cached_by_ap_id(ap_id) do
1257 subscribe(subscriber, subscribee)
1261 def unsubscribe(%User{} = unsubscriber, %User{} = target) do
1262 # Note: the relationship is inverse: subscriber acts as relationship target
1263 UserRelationship.delete_inverse_subscription(target, unsubscriber)
1266 def unsubscribe(%User{} = unsubscriber, %{ap_id: ap_id}) do
1267 with %User{} = user <- get_cached_by_ap_id(ap_id) do
1268 unsubscribe(unsubscriber, user)
1272 def block(%User{} = blocker, %User{} = blocked) do
1273 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
1275 if following?(blocker, blocked) do
1276 {:ok, blocker, _} = unfollow(blocker, blocked)
1282 # clear any requested follows as well
1284 case CommonAPI.reject_follow_request(blocked, blocker) do
1285 {:ok, %User{} = updated_blocked} -> updated_blocked
1289 unsubscribe(blocked, blocker)
1291 if following?(blocked, blocker), do: unfollow(blocked, blocker)
1293 {:ok, blocker} = update_follower_count(blocker)
1294 {:ok, blocker, _} = Participation.mark_all_as_read(blocker, blocked)
1295 add_to_block(blocker, blocked)
1298 # helper to handle the block given only an actor's AP id
1299 def block(%User{} = blocker, %{ap_id: ap_id}) do
1300 block(blocker, get_cached_by_ap_id(ap_id))
1303 def unblock(%User{} = blocker, %User{} = blocked) do
1304 remove_from_block(blocker, blocked)
1307 # helper to handle the block given only an actor's AP id
1308 def unblock(%User{} = blocker, %{ap_id: ap_id}) do
1309 unblock(blocker, get_cached_by_ap_id(ap_id))
1312 def mutes?(nil, _), do: false
1313 def mutes?(%User{} = user, %User{} = target), do: mutes_user?(user, target)
1315 def mutes_user?(%User{} = user, %User{} = target) do
1316 UserRelationship.mute_exists?(user, target)
1319 @spec muted_notifications?(User.t() | nil, User.t() | map()) :: boolean()
1320 def muted_notifications?(nil, _), do: false
1322 def muted_notifications?(%User{} = user, %User{} = target),
1323 do: UserRelationship.notification_mute_exists?(user, target)
1325 def blocks?(nil, _), do: false
1327 def blocks?(%User{} = user, %User{} = target) do
1328 blocks_user?(user, target) ||
1329 (blocks_domain?(user, target) and not User.following?(user, target))
1332 def blocks_user?(%User{} = user, %User{} = target) do
1333 UserRelationship.block_exists?(user, target)
1336 def blocks_user?(_, _), do: false
1338 def blocks_domain?(%User{} = user, %User{} = target) do
1339 domain_blocks = Pleroma.Web.ActivityPub.MRF.subdomains_regex(user.domain_blocks)
1340 %{host: host} = URI.parse(target.ap_id)
1341 Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, host)
1344 def blocks_domain?(_, _), do: false
1346 def subscribed_to?(%User{} = user, %User{} = target) do
1347 # Note: the relationship is inverse: subscriber acts as relationship target
1348 UserRelationship.inverse_subscription_exists?(target, user)
1351 def subscribed_to?(%User{} = user, %{ap_id: ap_id}) do
1352 with %User{} = target <- get_cached_by_ap_id(ap_id) do
1353 subscribed_to?(user, target)
1358 Returns map of outgoing (blocked, muted etc.) relationships' user AP IDs by relation type.
1359 E.g. `outgoing_relationships_ap_ids(user, [:block])` -> `%{block: ["https://some.site/users/userapid"]}`
1361 @spec outgoing_relationships_ap_ids(User.t(), list(atom())) :: %{atom() => list(String.t())}
1362 def outgoing_relationships_ap_ids(_user, []), do: %{}
1364 def outgoing_relationships_ap_ids(nil, _relationship_types), do: %{}
1366 def outgoing_relationships_ap_ids(%User{} = user, relationship_types)
1367 when is_list(relationship_types) do
1370 |> assoc(:outgoing_relationships)
1371 |> join(:inner, [user_rel], u in assoc(user_rel, :target))
1372 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1373 |> select([user_rel, u], [user_rel.relationship_type, fragment("array_agg(?)", u.ap_id)])
1374 |> group_by([user_rel, u], user_rel.relationship_type)
1376 |> Enum.into(%{}, fn [k, v] -> {k, v} end)
1381 fn rel_type -> {rel_type, db_result[rel_type] || []} end
1385 def incoming_relationships_ungrouped_ap_ids(user, relationship_types, ap_ids \\ nil)
1387 def incoming_relationships_ungrouped_ap_ids(_user, [], _ap_ids), do: []
1389 def incoming_relationships_ungrouped_ap_ids(nil, _relationship_types, _ap_ids), do: []
1391 def incoming_relationships_ungrouped_ap_ids(%User{} = user, relationship_types, ap_ids)
1392 when is_list(relationship_types) do
1394 |> assoc(:incoming_relationships)
1395 |> join(:inner, [user_rel], u in assoc(user_rel, :source))
1396 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1397 |> maybe_filter_on_ap_id(ap_ids)
1398 |> select([user_rel, u], u.ap_id)
1403 defp maybe_filter_on_ap_id(query, ap_ids) when is_list(ap_ids) do
1404 where(query, [user_rel, u], u.ap_id in ^ap_ids)
1407 defp maybe_filter_on_ap_id(query, _ap_ids), do: query
1409 def deactivate_async(user, status \\ true) do
1410 BackgroundWorker.enqueue("deactivate_user", %{"user_id" => user.id, "status" => status})
1413 def deactivate(user, status \\ true)
1415 def deactivate(users, status) when is_list(users) do
1416 Repo.transaction(fn ->
1417 for user <- users, do: deactivate(user, status)
1421 def deactivate(%User{} = user, status) do
1422 with {:ok, user} <- set_activation_status(user, status) do
1425 |> Enum.filter(& &1.local)
1426 |> Enum.each(fn follower ->
1427 follower |> update_following_count() |> set_cache()
1430 # Only update local user counts, remote will be update during the next pull.
1433 |> Enum.filter(& &1.local)
1434 |> Enum.each(&update_follower_count/1)
1440 def update_notification_settings(%User{} = user, settings) do
1442 |> cast(%{notification_settings: settings}, [])
1443 |> cast_embed(:notification_settings)
1444 |> validate_required([:notification_settings])
1445 |> update_and_set_cache()
1448 def delete(users) when is_list(users) do
1449 for user <- users, do: delete(user)
1452 def delete(%User{} = user) do
1453 BackgroundWorker.enqueue("delete_user", %{"user_id" => user.id})
1456 def perform(:force_password_reset, user), do: force_password_reset(user)
1458 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1459 def perform(:delete, %User{} = user) do
1460 # Remove all relationships
1463 |> Enum.each(fn follower ->
1464 ActivityPub.unfollow(follower, user)
1465 unfollow(follower, user)
1470 |> Enum.each(fn followed ->
1471 ActivityPub.unfollow(user, followed)
1472 unfollow(user, followed)
1475 delete_user_activities(user)
1479 |> change(%{deactivated: true, email: nil})
1480 |> update_and_set_cache()
1482 invalidate_cache(user)
1487 def perform(:deactivate_async, user, status), do: deactivate(user, status)
1489 @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
1490 def perform(:blocks_import, %User{} = blocker, blocked_identifiers)
1491 when is_list(blocked_identifiers) do
1493 blocked_identifiers,
1494 fn blocked_identifier ->
1495 with {:ok, %User{} = blocked} <- get_or_fetch(blocked_identifier),
1496 {:ok, _user_block} <- block(blocker, blocked),
1497 {:ok, _} <- ActivityPub.block(blocker, blocked) do
1501 Logger.debug("blocks_import failed for #{blocked_identifier} with: #{inspect(err)}")
1508 def perform(:follow_import, %User{} = follower, followed_identifiers)
1509 when is_list(followed_identifiers) do
1511 followed_identifiers,
1512 fn followed_identifier ->
1513 with {:ok, %User{} = followed} <- get_or_fetch(followed_identifier),
1514 {:ok, follower} <- maybe_direct_follow(follower, followed),
1515 {:ok, _} <- ActivityPub.follow(follower, followed) do
1519 Logger.debug("follow_import failed for #{followed_identifier} with: #{inspect(err)}")
1526 @spec external_users_query() :: Ecto.Query.t()
1527 def external_users_query do
1535 @spec external_users(keyword()) :: [User.t()]
1536 def external_users(opts \\ []) do
1538 external_users_query()
1539 |> select([u], struct(u, [:id, :ap_id]))
1543 do: where(query, [u], u.id > ^opts[:max_id]),
1548 do: limit(query, ^opts[:limit]),
1554 def blocks_import(%User{} = blocker, blocked_identifiers) when is_list(blocked_identifiers) do
1555 BackgroundWorker.enqueue("blocks_import", %{
1556 "blocker_id" => blocker.id,
1557 "blocked_identifiers" => blocked_identifiers
1561 def follow_import(%User{} = follower, followed_identifiers)
1562 when is_list(followed_identifiers) do
1563 BackgroundWorker.enqueue("follow_import", %{
1564 "follower_id" => follower.id,
1565 "followed_identifiers" => followed_identifiers
1569 def delete_user_activities(%User{ap_id: ap_id} = user) do
1571 |> Activity.Queries.by_actor()
1572 |> RepoStreamer.chunk_stream(50)
1573 |> Stream.each(fn activities ->
1574 Enum.each(activities, fn activity -> delete_activity(activity, user) end)
1579 defp delete_activity(%{data: %{"type" => "Create", "object" => object}} = activity, user) do
1580 with {_, %Object{}} <- {:find_object, Object.get_by_ap_id(object)},
1581 {:ok, delete_data, _} <- Builder.delete(user, object) do
1582 Pipeline.common_pipeline(delete_data, local: user.local)
1584 {:find_object, nil} ->
1585 # We have the create activity, but not the object, it was probably pruned.
1586 # Insert a tombstone and try again
1587 with {:ok, tombstone_data, _} <- Builder.tombstone(user.ap_id, object),
1588 {:ok, _tombstone} <- Object.create(tombstone_data) do
1589 delete_activity(activity, user)
1593 Logger.error("Could not delete #{object} created by #{activity.data["ap_id"]}")
1594 Logger.error("Error: #{inspect(e)}")
1598 defp delete_activity(%{data: %{"type" => type}} = activity, user)
1599 when type in ["Like", "Announce"] do
1600 {:ok, undo, _} = Builder.undo(user, activity)
1601 Pipeline.common_pipeline(undo, local: user.local)
1604 defp delete_activity(_activity, _user), do: "Doing nothing"
1606 def html_filter_policy(%User{no_rich_text: true}) do
1607 Pleroma.HTML.Scrubber.TwitterText
1610 def html_filter_policy(_), do: Pleroma.Config.get([:markup, :scrub_policy])
1612 def fetch_by_ap_id(ap_id), do: ActivityPub.make_user_from_ap_id(ap_id)
1614 def get_or_fetch_by_ap_id(ap_id) do
1615 user = get_cached_by_ap_id(ap_id)
1617 if !is_nil(user) and !needs_update?(user) do
1620 fetch_by_ap_id(ap_id)
1625 Creates an internal service actor by URI if missing.
1626 Optionally takes nickname for addressing.
1628 @spec get_or_create_service_actor_by_ap_id(String.t(), String.t()) :: User.t() | nil
1629 def get_or_create_service_actor_by_ap_id(uri, nickname) do
1631 case get_cached_by_ap_id(uri) do
1633 with {:error, %{errors: errors}} <- create_service_actor(uri, nickname) do
1634 Logger.error("Cannot create service actor: #{uri}/.\n#{inspect(errors)}")
1638 %User{invisible: false} = user ->
1648 @spec set_invisible(User.t()) :: {:ok, User.t()}
1649 defp set_invisible(user) do
1651 |> change(%{invisible: true})
1652 |> update_and_set_cache()
1655 @spec create_service_actor(String.t(), String.t()) ::
1656 {:ok, User.t()} | {:error, Ecto.Changeset.t()}
1657 defp create_service_actor(uri, nickname) do
1663 follower_address: uri <> "/followers"
1666 |> unique_constraint(:nickname)
1671 def public_key(%{public_key: public_key_pem}) when is_binary(public_key_pem) do
1674 |> :public_key.pem_decode()
1676 |> :public_key.pem_entry_decode()
1681 def public_key(_), do: {:error, "key not found"}
1683 def get_public_key_for_ap_id(ap_id) do
1684 with {:ok, %User{} = user} <- get_or_fetch_by_ap_id(ap_id),
1685 {:ok, public_key} <- public_key(user) do
1692 def ap_enabled?(%User{local: true}), do: true
1693 def ap_enabled?(%User{ap_enabled: ap_enabled}), do: ap_enabled
1694 def ap_enabled?(_), do: false
1696 @doc "Gets or fetch a user by uri or nickname."
1697 @spec get_or_fetch(String.t()) :: {:ok, User.t()} | {:error, String.t()}
1698 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
1699 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
1701 # wait a period of time and return newest version of the User structs
1702 # this is because we have synchronous follow APIs and need to simulate them
1703 # with an async handshake
1704 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
1705 with %User{} = a <- get_cached_by_id(a.id),
1706 %User{} = b <- get_cached_by_id(b.id) do
1713 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
1714 with :ok <- :timer.sleep(timeout),
1715 %User{} = a <- get_cached_by_id(a.id),
1716 %User{} = b <- get_cached_by_id(b.id) do
1723 def parse_bio(bio) when is_binary(bio) and bio != "" do
1725 |> CommonUtils.format_input("text/plain", mentions_format: :full)
1729 def parse_bio(_), do: ""
1731 def parse_bio(bio, user) when is_binary(bio) and bio != "" do
1732 # TODO: get profile URLs other than user.ap_id
1733 profile_urls = [user.ap_id]
1736 |> CommonUtils.format_input("text/plain",
1737 mentions_format: :full,
1738 rel: &RelMe.maybe_put_rel_me(&1, profile_urls)
1743 def parse_bio(_, _), do: ""
1745 def tag(user_identifiers, tags) when is_list(user_identifiers) do
1746 Repo.transaction(fn ->
1747 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
1751 def tag(nickname, tags) when is_binary(nickname),
1752 do: tag(get_by_nickname(nickname), tags)
1754 def tag(%User{} = user, tags),
1755 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
1757 def untag(user_identifiers, tags) when is_list(user_identifiers) do
1758 Repo.transaction(fn ->
1759 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
1763 def untag(nickname, tags) when is_binary(nickname),
1764 do: untag(get_by_nickname(nickname), tags)
1766 def untag(%User{} = user, tags),
1767 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
1769 defp update_tags(%User{} = user, new_tags) do
1770 {:ok, updated_user} =
1772 |> change(%{tags: new_tags})
1773 |> update_and_set_cache()
1778 defp normalize_tags(tags) do
1781 |> Enum.map(&String.downcase/1)
1784 defp local_nickname_regex do
1785 if Pleroma.Config.get([:instance, :extended_nickname_format]) do
1786 @extended_local_nickname_regex
1788 @strict_local_nickname_regex
1792 def local_nickname(nickname_or_mention) do
1795 |> String.split("@")
1799 def full_nickname(nickname_or_mention),
1800 do: String.trim_leading(nickname_or_mention, "@")
1802 def error_user(ap_id) do
1806 nickname: "erroruser@example.com",
1807 inserted_at: NaiveDateTime.utc_now()
1811 @spec all_superusers() :: [User.t()]
1812 def all_superusers do
1813 User.Query.build(%{super_users: true, local: true, deactivated: false})
1817 def muting_reblogs?(%User{} = user, %User{} = target) do
1818 UserRelationship.reblog_mute_exists?(user, target)
1821 def showing_reblogs?(%User{} = user, %User{} = target) do
1822 not muting_reblogs?(user, target)
1826 The function returns a query to get users with no activity for given interval of days.
1827 Inactive users are those who didn't read any notification, or had any activity where
1828 the user is the activity's actor, during `inactivity_threshold` days.
1829 Deactivated users will not appear in this list.
1833 iex> Pleroma.User.list_inactive_users()
1836 @spec list_inactive_users_query(integer()) :: Ecto.Query.t()
1837 def list_inactive_users_query(inactivity_threshold \\ 7) do
1838 negative_inactivity_threshold = -inactivity_threshold
1839 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
1840 # Subqueries are not supported in `where` clauses, join gets too complicated.
1841 has_read_notifications =
1842 from(n in Pleroma.Notification,
1843 where: n.seen == true,
1845 having: max(n.updated_at) > datetime_add(^now, ^negative_inactivity_threshold, "day"),
1848 |> Pleroma.Repo.all()
1850 from(u in Pleroma.User,
1851 left_join: a in Pleroma.Activity,
1852 on: u.ap_id == a.actor,
1853 where: not is_nil(u.nickname),
1854 where: u.deactivated != ^true,
1855 where: u.id not in ^has_read_notifications,
1858 max(a.inserted_at) < datetime_add(^now, ^negative_inactivity_threshold, "day") or
1859 is_nil(max(a.inserted_at))
1864 Enable or disable email notifications for user
1868 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => false}}, "digest", true)
1869 Pleroma.User{email_notifications: %{"digest" => true}}
1871 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => true}}, "digest", false)
1872 Pleroma.User{email_notifications: %{"digest" => false}}
1874 @spec switch_email_notifications(t(), String.t(), boolean()) ::
1875 {:ok, t()} | {:error, Ecto.Changeset.t()}
1876 def switch_email_notifications(user, type, status) do
1877 User.update_email_notifications(user, %{type => status})
1881 Set `last_digest_emailed_at` value for the user to current time
1883 @spec touch_last_digest_emailed_at(t()) :: t()
1884 def touch_last_digest_emailed_at(user) do
1885 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
1887 {:ok, updated_user} =
1889 |> change(%{last_digest_emailed_at: now})
1890 |> update_and_set_cache()
1895 @spec toggle_confirmation(User.t()) :: {:ok, User.t()} | {:error, Changeset.t()}
1896 def toggle_confirmation(%User{} = user) do
1898 |> confirmation_changeset(need_confirmation: !user.confirmation_pending)
1899 |> update_and_set_cache()
1902 @spec toggle_confirmation([User.t()]) :: [{:ok, User.t()} | {:error, Changeset.t()}]
1903 def toggle_confirmation(users) do
1904 Enum.map(users, &toggle_confirmation/1)
1907 def get_mascot(%{mascot: %{} = mascot}) when not is_nil(mascot) do
1911 def get_mascot(%{mascot: mascot}) when is_nil(mascot) do
1912 # use instance-default
1913 config = Pleroma.Config.get([:assets, :mascots])
1914 default_mascot = Pleroma.Config.get([:assets, :default_mascot])
1915 mascot = Keyword.get(config, default_mascot)
1918 "id" => "default-mascot",
1919 "url" => mascot[:url],
1920 "preview_url" => mascot[:url],
1922 "mime_type" => mascot[:mime_type]
1927 def ensure_keys_present(%{keys: keys} = user) when not is_nil(keys), do: {:ok, user}
1929 def ensure_keys_present(%User{} = user) do
1930 with {:ok, pem} <- Keys.generate_rsa_pem() do
1932 |> cast(%{keys: pem}, [:keys])
1933 |> validate_required([:keys])
1934 |> update_and_set_cache()
1938 def get_ap_ids_by_nicknames(nicknames) do
1940 where: u.nickname in ^nicknames,
1946 defdelegate search(query, opts \\ []), to: User.Search
1948 defp put_password_hash(
1949 %Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset
1951 change(changeset, password_hash: Pbkdf2.hash_pwd_salt(password))
1954 defp put_password_hash(changeset), do: changeset
1956 def is_internal_user?(%User{nickname: nil}), do: true
1957 def is_internal_user?(%User{local: true, nickname: "internal." <> _}), do: true
1958 def is_internal_user?(_), do: false
1960 # A hack because user delete activities have a fake id for whatever reason
1961 # TODO: Get rid of this
1962 def get_delivered_users_by_object_id("pleroma:fake_object_id"), do: []
1964 def get_delivered_users_by_object_id(object_id) do
1966 inner_join: delivery in assoc(u, :deliveries),
1967 where: delivery.object_id == ^object_id
1972 def change_email(user, email) do
1974 |> cast(%{email: email}, [:email])
1975 |> validate_required([:email])
1976 |> unique_constraint(:email)
1977 |> validate_format(:email, @email_regex)
1978 |> update_and_set_cache()
1981 # Internal function; public one is `deactivate/2`
1982 defp set_activation_status(user, deactivated) do
1984 |> cast(%{deactivated: deactivated}, [:deactivated])
1985 |> update_and_set_cache()
1988 def update_banner(user, banner) do
1990 |> cast(%{banner: banner}, [:banner])
1991 |> update_and_set_cache()
1994 def update_background(user, background) do
1996 |> cast(%{background: background}, [:background])
1997 |> update_and_set_cache()
2000 def roles(%{is_moderator: is_moderator, is_admin: is_admin}) do
2003 moderator: is_moderator
2007 def validate_fields(changeset, remote? \\ false) do
2008 limit_name = if remote?, do: :max_remote_account_fields, else: :max_account_fields
2009 limit = Pleroma.Config.get([:instance, limit_name], 0)
2012 |> validate_length(:fields, max: limit)
2013 |> validate_change(:fields, fn :fields, fields ->
2014 if Enum.all?(fields, &valid_field?/1) do
2022 defp valid_field?(%{"name" => name, "value" => value}) do
2023 name_limit = Pleroma.Config.get([:instance, :account_field_name_length], 255)
2024 value_limit = Pleroma.Config.get([:instance, :account_field_value_length], 255)
2026 is_binary(name) && is_binary(value) && String.length(name) <= name_limit &&
2027 String.length(value) <= value_limit
2030 defp valid_field?(_), do: false
2032 defp truncate_field(%{"name" => name, "value" => value}) do
2034 String.split_at(name, Pleroma.Config.get([:instance, :account_field_name_length], 255))
2037 String.split_at(value, Pleroma.Config.get([:instance, :account_field_value_length], 255))
2039 %{"name" => name, "value" => value}
2042 def admin_api_update(user, params) do
2049 |> update_and_set_cache()
2052 @doc "Signs user out of all applications"
2053 def global_sign_out(user) do
2054 OAuth.Authorization.delete_user_authorizations(user)
2055 OAuth.Token.delete_user_tokens(user)
2058 def mascot_update(user, url) do
2060 |> cast(%{mascot: url}, [:mascot])
2061 |> validate_required([:mascot])
2062 |> update_and_set_cache()
2065 def mastodon_settings_update(user, settings) do
2067 |> cast(%{settings: settings}, [:settings])
2068 |> validate_required([:settings])
2069 |> update_and_set_cache()
2072 @spec confirmation_changeset(User.t(), keyword()) :: Changeset.t()
2073 def confirmation_changeset(user, need_confirmation: need_confirmation?) do
2075 if need_confirmation? do
2077 confirmation_pending: true,
2078 confirmation_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64()
2082 confirmation_pending: false,
2083 confirmation_token: nil
2087 cast(user, params, [:confirmation_pending, :confirmation_token])
2090 def add_pinnned_activity(user, %Pleroma.Activity{id: id}) do
2091 if id not in user.pinned_activities do
2092 max_pinned_statuses = Pleroma.Config.get([:instance, :max_pinned_statuses], 0)
2093 params = %{pinned_activities: user.pinned_activities ++ [id]}
2096 |> cast(params, [:pinned_activities])
2097 |> validate_length(:pinned_activities,
2098 max: max_pinned_statuses,
2099 message: "You have already pinned the maximum number of statuses"
2104 |> update_and_set_cache()
2107 def remove_pinnned_activity(user, %Pleroma.Activity{id: id}) do
2108 params = %{pinned_activities: List.delete(user.pinned_activities, id)}
2111 |> cast(params, [:pinned_activities])
2112 |> update_and_set_cache()
2115 def update_email_notifications(user, settings) do
2116 email_notifications =
2117 user.email_notifications
2118 |> Map.merge(settings)
2119 |> Map.take(["digest"])
2121 params = %{email_notifications: email_notifications}
2122 fields = [:email_notifications]
2125 |> cast(params, fields)
2126 |> validate_required(fields)
2127 |> update_and_set_cache()
2130 defp set_domain_blocks(user, domain_blocks) do
2131 params = %{domain_blocks: domain_blocks}
2134 |> cast(params, [:domain_blocks])
2135 |> validate_required([:domain_blocks])
2136 |> update_and_set_cache()
2139 def block_domain(user, domain_blocked) do
2140 set_domain_blocks(user, Enum.uniq([domain_blocked | user.domain_blocks]))
2143 def unblock_domain(user, domain_blocked) do
2144 set_domain_blocks(user, List.delete(user.domain_blocks, domain_blocked))
2147 @spec add_to_block(User.t(), User.t()) ::
2148 {:ok, UserRelationship.t()} | {:error, Ecto.Changeset.t()}
2149 defp add_to_block(%User{} = user, %User{} = blocked) do
2150 UserRelationship.create_block(user, blocked)
2153 @spec add_to_block(User.t(), User.t()) ::
2154 {:ok, UserRelationship.t()} | {:ok, nil} | {:error, Ecto.Changeset.t()}
2155 defp remove_from_block(%User{} = user, %User{} = blocked) do
2156 UserRelationship.delete_block(user, blocked)
2159 defp add_to_mutes(%User{} = user, %User{} = muted_user, notifications?) do
2160 with {:ok, user_mute} <- UserRelationship.create_mute(user, muted_user),
2161 {:ok, user_notification_mute} <-
2162 (notifications? && UserRelationship.create_notification_mute(user, muted_user)) ||
2164 {:ok, Enum.filter([user_mute, user_notification_mute], & &1)}
2168 defp remove_from_mutes(user, %User{} = muted_user) do
2169 with {:ok, user_mute} <- UserRelationship.delete_mute(user, muted_user),
2170 {:ok, user_notification_mute} <-
2171 UserRelationship.delete_notification_mute(user, muted_user) do
2172 {:ok, [user_mute, user_notification_mute]}
2176 def set_invisible(user, invisible) do
2177 params = %{invisible: invisible}
2180 |> cast(params, [:invisible])
2181 |> validate_required([:invisible])
2182 |> update_and_set_cache()
2185 def sanitize_html(%User{} = user) do
2186 sanitize_html(user, nil)
2189 # User data that mastodon isn't filtering (treated as plaintext):
2192 def sanitize_html(%User{} = user, filter) do
2194 Enum.map(user.fields, fn %{"name" => name, "value" => value} ->
2197 "value" => HTML.filter_tags(value, Pleroma.HTML.Scrubber.LinksOnly)
2202 |> Map.put(:bio, HTML.filter_tags(user.bio, filter))
2203 |> Map.put(:fields, fields)