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
17 alias Pleroma.EctoType.ActivityPub.ObjectValidators
19 alias Pleroma.FollowingRelationship
20 alias Pleroma.Formatter
24 alias Pleroma.Notification
26 alias Pleroma.Registration
28 alias Pleroma.RepoStreamer
30 alias Pleroma.UserRelationship
32 alias Pleroma.Web.ActivityPub.ActivityPub
33 alias Pleroma.Web.ActivityPub.Builder
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(:raw_bio, :string)
83 field(:email, :string)
85 field(:nickname, :string)
86 field(:password_hash, :string)
87 field(:password, :string, virtual: true)
88 field(:password_confirmation, :string, virtual: true)
90 field(:public_key, :string)
91 field(:ap_id, :string)
93 field(:local, :boolean, default: true)
94 field(:follower_address, :string)
95 field(:following_address, :string)
96 field(:search_rank, :float, virtual: true)
97 field(:search_type, :integer, virtual: true)
98 field(:tags, {:array, :string}, default: [])
99 field(:last_refreshed_at, :naive_datetime_usec)
100 field(:last_digest_emailed_at, :naive_datetime)
101 field(:banner, :map, default: %{})
102 field(:background, :map, default: %{})
103 field(:note_count, :integer, default: 0)
104 field(:follower_count, :integer, default: 0)
105 field(:following_count, :integer, default: 0)
106 field(:locked, :boolean, default: false)
107 field(:confirmation_pending, :boolean, default: false)
108 field(:password_reset_pending, :boolean, default: false)
109 field(:confirmation_token, :string, default: nil)
110 field(:default_scope, :string, default: "public")
111 field(:domain_blocks, {:array, :string}, default: [])
112 field(:deactivated, :boolean, default: false)
113 field(:no_rich_text, :boolean, default: false)
114 field(:ap_enabled, :boolean, default: false)
115 field(:is_moderator, :boolean, default: false)
116 field(:is_admin, :boolean, default: false)
117 field(:show_role, :boolean, default: true)
118 field(:mastofe_settings, :map, default: nil)
119 field(:uri, ObjectValidators.Uri, default: nil)
120 field(:hide_followers_count, :boolean, default: false)
121 field(:hide_follows_count, :boolean, default: false)
122 field(:hide_followers, :boolean, default: false)
123 field(:hide_follows, :boolean, default: false)
124 field(:hide_favorites, :boolean, default: true)
125 field(:unread_conversation_count, :integer, default: 0)
126 field(:pinned_activities, {:array, :string}, default: [])
127 field(:email_notifications, :map, default: %{"digest" => false})
128 field(:mascot, :map, default: nil)
129 field(:emoji, :map, default: %{})
130 field(:pleroma_settings_store, :map, default: %{})
131 field(:fields, {:array, :map}, default: [])
132 field(:raw_fields, {:array, :map}, default: [])
133 field(:discoverable, :boolean, default: false)
134 field(:invisible, :boolean, default: false)
135 field(:allow_following_move, :boolean, default: true)
136 field(:skip_thread_containment, :boolean, default: false)
137 field(:actor_type, :string, default: "Person")
138 field(:also_known_as, {:array, :string}, default: [])
139 field(:inbox, :string)
140 field(:shared_inbox, :string)
141 field(:accepts_chat_messages, :boolean, default: nil)
144 :notification_settings,
145 Pleroma.User.NotificationSetting,
149 has_many(:notifications, Notification)
150 has_many(:registrations, Registration)
151 has_many(:deliveries, Delivery)
153 has_many(:outgoing_relationships, UserRelationship, foreign_key: :source_id)
154 has_many(:incoming_relationships, UserRelationship, foreign_key: :target_id)
156 for {relationship_type,
158 {outgoing_relation, outgoing_relation_target},
159 {incoming_relation, incoming_relation_source}
160 ]} <- @user_relationships_config do
161 # Definitions of `has_many` relations: :blocker_blocks, :muter_mutes, :reblog_muter_mutes,
162 # :notification_muter_mutes, :subscribee_subscriptions
163 has_many(outgoing_relation, UserRelationship,
164 foreign_key: :source_id,
165 where: [relationship_type: relationship_type]
168 # Definitions of `has_many` relations: :blockee_blocks, :mutee_mutes, :reblog_mutee_mutes,
169 # :notification_mutee_mutes, :subscriber_subscriptions
170 has_many(incoming_relation, UserRelationship,
171 foreign_key: :target_id,
172 where: [relationship_type: relationship_type]
175 # Definitions of `has_many` relations: :blocked_users, :muted_users, :reblog_muted_users,
176 # :notification_muted_users, :subscriber_users
177 has_many(outgoing_relation_target, through: [outgoing_relation, :target])
179 # Definitions of `has_many` relations: :blocker_users, :muter_users, :reblog_muter_users,
180 # :notification_muter_users, :subscribee_users
181 has_many(incoming_relation_source, through: [incoming_relation, :source])
184 # `:blocks` is deprecated (replaced with `blocked_users` relation)
185 field(:blocks, {:array, :string}, default: [])
186 # `:mutes` is deprecated (replaced with `muted_users` relation)
187 field(:mutes, {:array, :string}, default: [])
188 # `:muted_reblogs` is deprecated (replaced with `reblog_muted_users` relation)
189 field(:muted_reblogs, {:array, :string}, default: [])
190 # `:muted_notifications` is deprecated (replaced with `notification_muted_users` relation)
191 field(:muted_notifications, {:array, :string}, default: [])
192 # `:subscribers` is deprecated (replaced with `subscriber_users` relation)
193 field(:subscribers, {:array, :string}, default: [])
196 :multi_factor_authentication_settings,
204 for {_relationship_type, [{_outgoing_relation, outgoing_relation_target}, _]} <-
205 @user_relationships_config do
206 # `def blocked_users_relation/2`, `def muted_users_relation/2`,
207 # `def reblog_muted_users_relation/2`, `def notification_muted_users/2`,
208 # `def subscriber_users/2`
209 def unquote(:"#{outgoing_relation_target}_relation")(user, restrict_deactivated? \\ false) do
210 target_users_query = assoc(user, unquote(outgoing_relation_target))
212 if restrict_deactivated? do
213 restrict_deactivated(target_users_query)
219 # `def blocked_users/2`, `def muted_users/2`, `def reblog_muted_users/2`,
220 # `def notification_muted_users/2`, `def subscriber_users/2`
221 def unquote(outgoing_relation_target)(user, restrict_deactivated? \\ false) do
223 |> apply(unquote(:"#{outgoing_relation_target}_relation"), [
225 restrict_deactivated?
230 # `def blocked_users_ap_ids/2`, `def muted_users_ap_ids/2`, `def reblog_muted_users_ap_ids/2`,
231 # `def notification_muted_users_ap_ids/2`, `def subscriber_users_ap_ids/2`
232 def unquote(:"#{outgoing_relation_target}_ap_ids")(user, restrict_deactivated? \\ false) do
234 |> apply(unquote(:"#{outgoing_relation_target}_relation"), [
236 restrict_deactivated?
238 |> select([u], u.ap_id)
244 Dumps Flake Id to SQL-compatible format (16-byte UUID).
245 E.g. "9pQtDGXuq4p3VlcJEm" -> <<0, 0, 1, 110, 179, 218, 42, 92, 213, 41, 44, 227, 95, 213, 0, 0>>
247 def binary_id(source_id) when is_binary(source_id) do
248 with {:ok, dumped_id} <- FlakeId.Ecto.CompatType.dump(source_id) do
255 def binary_id(source_ids) when is_list(source_ids) do
256 Enum.map(source_ids, &binary_id/1)
259 def binary_id(%User{} = user), do: binary_id(user.id)
261 @doc "Returns status account"
262 @spec account_status(User.t()) :: account_status()
263 def account_status(%User{deactivated: true}), do: :deactivated
264 def account_status(%User{password_reset_pending: true}), do: :password_reset_pending
266 def account_status(%User{confirmation_pending: true}) do
267 if Config.get([:instance, :account_activation_required]) do
268 :confirmation_pending
274 def account_status(%User{}), do: :active
276 @spec visible_for(User.t(), User.t() | nil) ::
279 | :restricted_unauthenticated
281 | :confirmation_pending
282 def visible_for(user, for_user \\ nil)
284 def visible_for(%User{invisible: true}, _), do: :invisible
286 def visible_for(%User{id: user_id}, %User{id: user_id}), do: :visible
288 def visible_for(%User{} = user, nil) do
289 if restrict_unauthenticated?(user) do
290 :restrict_unauthenticated
292 visible_account_status(user)
296 def visible_for(%User{} = user, for_user) do
297 if superuser?(for_user) do
300 visible_account_status(user)
304 def visible_for(_, _), do: :invisible
306 defp restrict_unauthenticated?(%User{local: local}) do
307 config_key = if local, do: :local, else: :remote
309 Config.get([:restrict_unauthenticated, :profiles, config_key], false)
312 defp visible_account_status(user) do
313 status = account_status(user)
315 if status in [:active, :password_reset_pending] do
322 @spec superuser?(User.t()) :: boolean()
323 def superuser?(%User{local: true, is_admin: true}), do: true
324 def superuser?(%User{local: true, is_moderator: true}), do: true
325 def superuser?(_), do: false
327 @spec invisible?(User.t()) :: boolean()
328 def invisible?(%User{invisible: true}), do: true
329 def invisible?(_), do: false
331 def avatar_url(user, options \\ []) do
333 %{"url" => [%{"href" => href} | _]} ->
337 unless options[:no_default] do
338 Config.get([:assets, :default_user_avatar], "#{Web.base_url()}/images/avi.png")
343 def banner_url(user, options \\ []) do
345 %{"url" => [%{"href" => href} | _]} -> href
346 _ -> !options[:no_default] && "#{Web.base_url()}/images/banner.png"
350 # Should probably be renamed or removed
351 def ap_id(%User{nickname: nickname}), do: "#{Web.base_url()}/users/#{nickname}"
353 def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
354 def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
356 @spec ap_following(User.t()) :: String.t()
357 def ap_following(%User{following_address: fa}) when is_binary(fa), do: fa
358 def ap_following(%User{} = user), do: "#{ap_id(user)}/following"
360 @spec restrict_deactivated(Ecto.Query.t()) :: Ecto.Query.t()
361 def restrict_deactivated(query) do
362 from(u in query, where: u.deactivated != ^true)
365 defdelegate following_count(user), to: FollowingRelationship
367 defp truncate_fields_param(params) do
368 if Map.has_key?(params, :fields) do
369 Map.put(params, :fields, Enum.map(params[:fields], &truncate_field/1))
375 defp truncate_if_exists(params, key, max_length) do
376 if Map.has_key?(params, key) and is_binary(params[key]) do
377 {value, _chopped} = String.split_at(params[key], max_length)
378 Map.put(params, key, value)
384 defp fix_follower_address(%{follower_address: _, following_address: _} = params), do: params
386 defp fix_follower_address(%{nickname: nickname} = params),
387 do: Map.put(params, :follower_address, ap_followers(%User{nickname: nickname}))
389 defp fix_follower_address(params), do: params
391 def remote_user_changeset(struct \\ %User{local: false}, params) do
392 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
393 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
396 case params[:name] do
397 name when is_binary(name) and byte_size(name) > 0 -> name
398 _ -> params[:nickname]
403 |> Map.put(:name, name)
404 |> Map.put_new(:last_refreshed_at, NaiveDateTime.utc_now())
405 |> truncate_if_exists(:name, name_limit)
406 |> truncate_if_exists(:bio, bio_limit)
407 |> truncate_fields_param()
408 |> fix_follower_address()
432 :hide_followers_count,
441 :accepts_chat_messages
444 |> validate_required([:name, :ap_id])
445 |> unique_constraint(:nickname)
446 |> validate_format(:nickname, @email_regex)
447 |> validate_length(:bio, max: bio_limit)
448 |> validate_length(:name, max: name_limit)
449 |> validate_fields(true)
452 def update_changeset(struct, params \\ %{}) do
453 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
454 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
474 :hide_followers_count,
477 :allow_following_move,
480 :skip_thread_containment,
483 :pleroma_settings_store,
487 :accepts_chat_messages
490 |> unique_constraint(:nickname)
491 |> validate_format(:nickname, local_nickname_regex())
492 |> validate_length(:bio, max: bio_limit)
493 |> validate_length(:name, min: 1, max: name_limit)
494 |> validate_inclusion(:actor_type, ["Person", "Service"])
497 |> put_change_if_present(:bio, &{:ok, parse_bio(&1, struct)})
498 |> put_change_if_present(:avatar, &put_upload(&1, :avatar))
499 |> put_change_if_present(:banner, &put_upload(&1, :banner))
500 |> put_change_if_present(:background, &put_upload(&1, :background))
501 |> put_change_if_present(
502 :pleroma_settings_store,
503 &{:ok, Map.merge(struct.pleroma_settings_store, &1)}
505 |> validate_fields(false)
508 defp put_fields(changeset) do
509 if raw_fields = get_change(changeset, :raw_fields) do
512 |> Enum.filter(fn %{"name" => n} -> n != "" end)
516 |> Enum.map(fn f -> Map.update!(f, "value", &parse_fields(&1)) end)
519 |> put_change(:raw_fields, raw_fields)
520 |> put_change(:fields, fields)
526 defp parse_fields(value) do
528 |> Formatter.linkify(mentions_format: :full)
532 defp put_emoji(changeset) do
533 bio = get_change(changeset, :bio)
534 name = get_change(changeset, :name)
537 emoji = Map.merge(Emoji.Formatter.get_emoji_map(bio), Emoji.Formatter.get_emoji_map(name))
538 put_change(changeset, :emoji, emoji)
544 defp put_change_if_present(changeset, map_field, value_function) do
545 if value = get_change(changeset, map_field) do
546 with {:ok, new_value} <- value_function.(value) do
547 put_change(changeset, map_field, new_value)
556 defp put_upload(value, type) do
557 with %Plug.Upload{} <- value,
558 {:ok, object} <- ActivityPub.upload(value, type: type) do
563 def update_as_admin_changeset(struct, params) do
565 |> update_changeset(params)
566 |> cast(params, [:email])
567 |> delete_change(:also_known_as)
568 |> unique_constraint(:email)
569 |> validate_format(:email, @email_regex)
570 |> validate_inclusion(:actor_type, ["Person", "Service"])
573 @spec update_as_admin(User.t(), map()) :: {:ok, User.t()} | {:error, Changeset.t()}
574 def update_as_admin(user, params) do
575 params = Map.put(params, "password_confirmation", params["password"])
576 changeset = update_as_admin_changeset(user, params)
578 if params["password"] do
579 reset_password(user, changeset, params)
581 User.update_and_set_cache(changeset)
585 def password_update_changeset(struct, params) do
587 |> cast(params, [:password, :password_confirmation])
588 |> validate_required([:password, :password_confirmation])
589 |> validate_confirmation(:password)
590 |> put_password_hash()
591 |> put_change(:password_reset_pending, false)
594 @spec reset_password(User.t(), map()) :: {:ok, User.t()} | {:error, Changeset.t()}
595 def reset_password(%User{} = user, params) do
596 reset_password(user, user, params)
599 def reset_password(%User{id: user_id} = user, struct, params) do
602 |> Multi.update(:user, password_update_changeset(struct, params))
603 |> Multi.delete_all(:tokens, OAuth.Token.Query.get_by_user(user_id))
604 |> Multi.delete_all(:auth, OAuth.Authorization.delete_by_user_query(user))
606 case Repo.transaction(multi) do
607 {:ok, %{user: user} = _} -> set_cache(user)
608 {:error, _, changeset, _} -> {:error, changeset}
612 def update_password_reset_pending(user, value) do
615 |> put_change(:password_reset_pending, value)
616 |> update_and_set_cache()
619 def force_password_reset_async(user) do
620 BackgroundWorker.enqueue("force_password_reset", %{"user_id" => user.id})
623 @spec force_password_reset(User.t()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
624 def force_password_reset(user), do: update_password_reset_pending(user, true)
626 def register_changeset(struct, params \\ %{}, opts \\ []) do
627 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
628 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
629 params = Map.put_new(params, :accepts_chat_messages, true)
632 if is_nil(opts[:need_confirmation]) do
633 Pleroma.Config.get([:instance, :account_activation_required])
635 opts[:need_confirmation]
639 |> confirmation_changeset(need_confirmation: need_confirmation?)
647 :password_confirmation,
649 :accepts_chat_messages
651 |> validate_required([:name, :nickname, :password, :password_confirmation])
652 |> validate_confirmation(:password)
653 |> unique_constraint(:email)
654 |> unique_constraint(:nickname)
655 |> validate_exclusion(:nickname, Pleroma.Config.get([User, :restricted_nicknames]))
656 |> validate_format(:nickname, local_nickname_regex())
657 |> validate_format(:email, @email_regex)
658 |> validate_length(:bio, max: bio_limit)
659 |> validate_length(:name, min: 1, max: name_limit)
660 |> maybe_validate_required_email(opts[:external])
663 |> unique_constraint(:ap_id)
664 |> put_following_and_follower_address()
667 def maybe_validate_required_email(changeset, true), do: changeset
669 def maybe_validate_required_email(changeset, _) do
670 if Pleroma.Config.get([:instance, :account_activation_required]) do
671 validate_required(changeset, [:email])
677 defp put_ap_id(changeset) do
678 ap_id = ap_id(%User{nickname: get_field(changeset, :nickname)})
679 put_change(changeset, :ap_id, ap_id)
682 defp put_following_and_follower_address(changeset) do
683 followers = ap_followers(%User{nickname: get_field(changeset, :nickname)})
686 |> put_change(:follower_address, followers)
689 defp autofollow_users(user) do
690 candidates = Pleroma.Config.get([:instance, :autofollowed_nicknames])
693 User.Query.build(%{nickname: candidates, local: true, deactivated: false})
696 follow_all(user, autofollowed_users)
699 @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
700 def register(%Ecto.Changeset{} = changeset) do
701 with {:ok, user} <- Repo.insert(changeset) do
702 post_register_action(user)
706 def post_register_action(%User{} = user) do
707 with {:ok, user} <- autofollow_users(user),
708 {:ok, user} <- set_cache(user),
709 {:ok, _} <- User.WelcomeMessage.post_welcome_message_to_user(user),
710 {:ok, _} <- try_send_confirmation_email(user) do
715 def try_send_confirmation_email(%User{} = user) do
716 if user.confirmation_pending &&
717 Pleroma.Config.get([:instance, :account_activation_required]) do
719 |> Pleroma.Emails.UserEmail.account_confirmation_email()
720 |> Pleroma.Emails.Mailer.deliver_async()
728 def try_send_confirmation_email(users) do
729 Enum.each(users, &try_send_confirmation_email/1)
732 def needs_update?(%User{local: true}), do: false
734 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
736 def needs_update?(%User{local: false} = user) do
737 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
740 def needs_update?(_), do: true
742 @spec maybe_direct_follow(User.t(), User.t()) :: {:ok, User.t()} | {:error, String.t()}
744 # "Locked" (self-locked) users demand explicit authorization of follow requests
745 def maybe_direct_follow(%User{} = follower, %User{local: true, locked: true} = followed) do
746 follow(follower, followed, :follow_pending)
749 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
750 follow(follower, followed)
753 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
754 if not ap_enabled?(followed) do
755 follow(follower, followed)
761 @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
762 @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
763 def follow_all(follower, followeds) do
765 |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
766 |> Enum.each(&follow(follower, &1, :follow_accept))
771 defdelegate following(user), to: FollowingRelationship
773 def follow(%User{} = follower, %User{} = followed, state \\ :follow_accept) do
774 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
777 followed.deactivated ->
778 {:error, "Could not follow user: #{followed.nickname} is deactivated."}
780 deny_follow_blocked and blocks?(followed, follower) ->
781 {:error, "Could not follow user: #{followed.nickname} blocked you."}
784 FollowingRelationship.follow(follower, followed, state)
786 {:ok, _} = update_follower_count(followed)
789 |> update_following_count()
793 def unfollow(%User{ap_id: ap_id}, %User{ap_id: ap_id}) do
794 {:error, "Not subscribed!"}
797 @spec unfollow(User.t(), User.t()) :: {:ok, User.t(), Activity.t()} | {:error, String.t()}
798 def unfollow(%User{} = follower, %User{} = followed) do
799 case do_unfollow(follower, followed) do
800 {:ok, follower, followed} ->
801 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
808 @spec do_unfollow(User.t(), User.t()) :: {:ok, User.t(), User.t()} | {:error, String.t()}
809 defp do_unfollow(%User{} = follower, %User{} = followed) do
810 case get_follow_state(follower, followed) do
811 state when state in [:follow_pending, :follow_accept] ->
812 FollowingRelationship.unfollow(follower, followed)
813 {:ok, followed} = update_follower_count(followed)
817 |> update_following_count()
819 {:ok, follower, followed}
822 {:error, "Not subscribed!"}
826 defdelegate following?(follower, followed), to: FollowingRelationship
828 @doc "Returns follow state as Pleroma.FollowingRelationship.State value"
829 def get_follow_state(%User{} = follower, %User{} = following) do
830 following_relationship = FollowingRelationship.get(follower, following)
831 get_follow_state(follower, following, following_relationship)
834 def get_follow_state(
837 following_relationship
839 case {following_relationship, following.local} do
841 case Utils.fetch_latest_follow(follower, following) do
842 %Activity{data: %{"state" => state}} when state in ["pending", "accept"] ->
843 FollowingRelationship.state_to_enum(state)
849 {%{state: state}, _} ->
857 def locked?(%User{} = user) do
862 Repo.get_by(User, id: id)
865 def get_by_ap_id(ap_id) do
866 Repo.get_by(User, ap_id: ap_id)
869 def get_all_by_ap_id(ap_ids) do
870 from(u in __MODULE__,
871 where: u.ap_id in ^ap_ids
876 def get_all_by_ids(ids) do
877 from(u in __MODULE__, where: u.id in ^ids)
881 # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
882 # of the ap_id and the domain and tries to get that user
883 def get_by_guessed_nickname(ap_id) do
884 domain = URI.parse(ap_id).host
885 name = List.last(String.split(ap_id, "/"))
886 nickname = "#{name}@#{domain}"
888 get_cached_by_nickname(nickname)
891 def set_cache({:ok, user}), do: set_cache(user)
892 def set_cache({:error, err}), do: {:error, err}
894 def set_cache(%User{} = user) do
895 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
896 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
897 Cachex.put(:user_cache, "friends_ap_ids:#{user.nickname}", get_user_friends_ap_ids(user))
901 def update_and_set_cache(struct, params) do
903 |> update_changeset(params)
904 |> update_and_set_cache()
907 def update_and_set_cache(changeset) do
908 with {:ok, user} <- Repo.update(changeset, stale_error_field: :id) do
913 def get_user_friends_ap_ids(user) do
914 from(u in User.get_friends_query(user), select: u.ap_id)
918 @spec get_cached_user_friends_ap_ids(User.t()) :: [String.t()]
919 def get_cached_user_friends_ap_ids(user) do
920 Cachex.fetch!(:user_cache, "friends_ap_ids:#{user.ap_id}", fn _ ->
921 get_user_friends_ap_ids(user)
925 def invalidate_cache(user) do
926 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
927 Cachex.del(:user_cache, "nickname:#{user.nickname}")
928 Cachex.del(:user_cache, "friends_ap_ids:#{user.ap_id}")
931 @spec get_cached_by_ap_id(String.t()) :: User.t() | nil
932 def get_cached_by_ap_id(ap_id) do
933 key = "ap_id:#{ap_id}"
935 with {:ok, nil} <- Cachex.get(:user_cache, key),
936 user when not is_nil(user) <- get_by_ap_id(ap_id),
937 {:ok, true} <- Cachex.put(:user_cache, key, user) do
945 def get_cached_by_id(id) do
949 Cachex.fetch!(:user_cache, key, fn _ ->
953 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
954 {:commit, user.ap_id}
960 get_cached_by_ap_id(ap_id)
963 def get_cached_by_nickname(nickname) do
964 key = "nickname:#{nickname}"
966 Cachex.fetch!(:user_cache, key, fn ->
967 case get_or_fetch_by_nickname(nickname) do
968 {:ok, user} -> {:commit, user}
969 {:error, _error} -> {:ignore, nil}
974 def get_cached_by_nickname_or_id(nickname_or_id, opts \\ []) do
975 restrict_to_local = Pleroma.Config.get([:instance, :limit_to_local_content])
978 is_integer(nickname_or_id) or FlakeId.flake_id?(nickname_or_id) ->
979 get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
981 restrict_to_local == false or not String.contains?(nickname_or_id, "@") ->
982 get_cached_by_nickname(nickname_or_id)
984 restrict_to_local == :unauthenticated and match?(%User{}, opts[:for]) ->
985 get_cached_by_nickname(nickname_or_id)
992 @spec get_by_nickname(String.t()) :: User.t() | nil
993 def get_by_nickname(nickname) do
994 Repo.get_by(User, nickname: nickname) ||
995 if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
996 Repo.get_by(User, nickname: local_nickname(nickname))
1000 def get_by_email(email), do: Repo.get_by(User, email: email)
1002 def get_by_nickname_or_email(nickname_or_email) do
1003 get_by_nickname(nickname_or_email) || get_by_email(nickname_or_email)
1006 def fetch_by_nickname(nickname), do: ActivityPub.make_user_from_nickname(nickname)
1008 def get_or_fetch_by_nickname(nickname) do
1009 with %User{} = user <- get_by_nickname(nickname) do
1013 with [_nick, _domain] <- String.split(nickname, "@"),
1014 {:ok, user} <- fetch_by_nickname(nickname) do
1017 _e -> {:error, "not found " <> nickname}
1022 @spec get_followers_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
1023 def get_followers_query(%User{} = user, nil) do
1024 User.Query.build(%{followers: user, deactivated: false})
1027 def get_followers_query(user, page) do
1029 |> get_followers_query(nil)
1030 |> User.Query.paginate(page, 20)
1033 @spec get_followers_query(User.t()) :: Ecto.Query.t()
1034 def get_followers_query(user), do: get_followers_query(user, nil)
1036 @spec get_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
1037 def get_followers(user, page \\ nil) do
1039 |> get_followers_query(page)
1043 @spec get_external_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
1044 def get_external_followers(user, page \\ nil) do
1046 |> get_followers_query(page)
1047 |> User.Query.build(%{external: true})
1051 def get_followers_ids(user, page \\ nil) do
1053 |> get_followers_query(page)
1054 |> select([u], u.id)
1058 @spec get_friends_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
1059 def get_friends_query(%User{} = user, nil) do
1060 User.Query.build(%{friends: user, deactivated: false})
1063 def get_friends_query(user, page) do
1065 |> get_friends_query(nil)
1066 |> User.Query.paginate(page, 20)
1069 @spec get_friends_query(User.t()) :: Ecto.Query.t()
1070 def get_friends_query(user), do: get_friends_query(user, nil)
1072 def get_friends(user, page \\ nil) do
1074 |> get_friends_query(page)
1078 def get_friends_ap_ids(user) do
1080 |> get_friends_query(nil)
1081 |> select([u], u.ap_id)
1085 def get_friends_ids(user, page \\ nil) do
1087 |> get_friends_query(page)
1088 |> select([u], u.id)
1092 defdelegate get_follow_requests(user), to: FollowingRelationship
1094 def increase_note_count(%User{} = user) do
1096 |> where(id: ^user.id)
1097 |> update([u], inc: [note_count: 1])
1099 |> Repo.update_all([])
1101 {1, [user]} -> set_cache(user)
1106 def decrease_note_count(%User{} = user) do
1108 |> where(id: ^user.id)
1111 note_count: fragment("greatest(0, note_count - 1)")
1115 |> Repo.update_all([])
1117 {1, [user]} -> set_cache(user)
1122 def update_note_count(%User{} = user, note_count \\ nil) do
1127 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
1133 |> cast(%{note_count: note_count}, [:note_count])
1134 |> update_and_set_cache()
1137 @spec maybe_fetch_follow_information(User.t()) :: User.t()
1138 def maybe_fetch_follow_information(user) do
1139 with {:ok, user} <- fetch_follow_information(user) do
1143 Logger.error("Follower/Following counter update for #{user.ap_id} failed.\n#{inspect(e)}")
1149 def fetch_follow_information(user) do
1150 with {:ok, info} <- ActivityPub.fetch_follow_information_for_user(user) do
1152 |> follow_information_changeset(info)
1153 |> update_and_set_cache()
1157 defp follow_information_changeset(user, params) do
1164 :hide_followers_count,
1169 @spec update_follower_count(User.t()) :: {:ok, User.t()}
1170 def update_follower_count(%User{} = user) do
1171 if user.local or !Pleroma.Config.get([:instance, :external_user_synchronization]) do
1172 follower_count = FollowingRelationship.follower_count(user)
1175 |> follow_information_changeset(%{follower_count: follower_count})
1176 |> update_and_set_cache
1178 {:ok, maybe_fetch_follow_information(user)}
1182 @spec update_following_count(User.t()) :: {:ok, User.t()}
1183 def update_following_count(%User{local: false} = user) do
1184 if Pleroma.Config.get([:instance, :external_user_synchronization]) do
1185 {:ok, maybe_fetch_follow_information(user)}
1191 def update_following_count(%User{local: true} = user) do
1192 following_count = FollowingRelationship.following_count(user)
1195 |> follow_information_changeset(%{following_count: following_count})
1196 |> update_and_set_cache()
1199 def set_unread_conversation_count(%User{local: true} = user) do
1200 unread_query = Participation.unread_conversation_count_for_user(user)
1203 |> join(:inner, [u], p in subquery(unread_query))
1205 set: [unread_conversation_count: p.count]
1207 |> where([u], u.id == ^user.id)
1209 |> Repo.update_all([])
1211 {1, [user]} -> set_cache(user)
1216 def set_unread_conversation_count(user), do: {:ok, user}
1218 def increment_unread_conversation_count(conversation, %User{local: true} = user) do
1220 Participation.unread_conversation_count_for_user(user)
1221 |> where([p], p.conversation_id == ^conversation.id)
1224 |> join(:inner, [u], p in subquery(unread_query))
1226 inc: [unread_conversation_count: 1]
1228 |> where([u], u.id == ^user.id)
1229 |> where([u, p], p.count == 0)
1231 |> Repo.update_all([])
1233 {1, [user]} -> set_cache(user)
1238 def increment_unread_conversation_count(_, user), do: {:ok, user}
1240 @spec get_users_from_set([String.t()], keyword()) :: [User.t()]
1241 def get_users_from_set(ap_ids, opts \\ []) do
1242 local_only = Keyword.get(opts, :local_only, true)
1243 criteria = %{ap_id: ap_ids, deactivated: false}
1244 criteria = if local_only, do: Map.put(criteria, :local, true), else: criteria
1246 User.Query.build(criteria)
1250 @spec get_recipients_from_activity(Activity.t()) :: [User.t()]
1251 def get_recipients_from_activity(%Activity{recipients: to, actor: actor}) do
1254 query = User.Query.build(%{recipients_from_activity: to, local: true, deactivated: false})
1260 @spec mute(User.t(), User.t(), boolean()) ::
1261 {:ok, list(UserRelationship.t())} | {:error, String.t()}
1262 def mute(%User{} = muter, %User{} = mutee, notifications? \\ true) do
1263 add_to_mutes(muter, mutee, notifications?)
1266 def unmute(%User{} = muter, %User{} = mutee) do
1267 remove_from_mutes(muter, mutee)
1270 def subscribe(%User{} = subscriber, %User{} = target) do
1271 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
1273 if blocks?(target, subscriber) and deny_follow_blocked do
1274 {:error, "Could not subscribe: #{target.nickname} is blocking you"}
1276 # Note: the relationship is inverse: subscriber acts as relationship target
1277 UserRelationship.create_inverse_subscription(target, subscriber)
1281 def subscribe(%User{} = subscriber, %{ap_id: ap_id}) do
1282 with %User{} = subscribee <- get_cached_by_ap_id(ap_id) do
1283 subscribe(subscriber, subscribee)
1287 def unsubscribe(%User{} = unsubscriber, %User{} = target) do
1288 # Note: the relationship is inverse: subscriber acts as relationship target
1289 UserRelationship.delete_inverse_subscription(target, unsubscriber)
1292 def unsubscribe(%User{} = unsubscriber, %{ap_id: ap_id}) do
1293 with %User{} = user <- get_cached_by_ap_id(ap_id) do
1294 unsubscribe(unsubscriber, user)
1298 def block(%User{} = blocker, %User{} = blocked) do
1299 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
1301 if following?(blocker, blocked) do
1302 {:ok, blocker, _} = unfollow(blocker, blocked)
1308 # clear any requested follows as well
1310 case CommonAPI.reject_follow_request(blocked, blocker) do
1311 {:ok, %User{} = updated_blocked} -> updated_blocked
1315 unsubscribe(blocked, blocker)
1317 unfollowing_blocked = Config.get([:activitypub, :unfollow_blocked], true)
1318 if unfollowing_blocked && following?(blocked, blocker), do: unfollow(blocked, blocker)
1320 {:ok, blocker} = update_follower_count(blocker)
1321 {:ok, blocker, _} = Participation.mark_all_as_read(blocker, blocked)
1322 add_to_block(blocker, blocked)
1325 # helper to handle the block given only an actor's AP id
1326 def block(%User{} = blocker, %{ap_id: ap_id}) do
1327 block(blocker, get_cached_by_ap_id(ap_id))
1330 def unblock(%User{} = blocker, %User{} = blocked) do
1331 remove_from_block(blocker, blocked)
1334 # helper to handle the block given only an actor's AP id
1335 def unblock(%User{} = blocker, %{ap_id: ap_id}) do
1336 unblock(blocker, get_cached_by_ap_id(ap_id))
1339 def mutes?(nil, _), do: false
1340 def mutes?(%User{} = user, %User{} = target), do: mutes_user?(user, target)
1342 def mutes_user?(%User{} = user, %User{} = target) do
1343 UserRelationship.mute_exists?(user, target)
1346 @spec muted_notifications?(User.t() | nil, User.t() | map()) :: boolean()
1347 def muted_notifications?(nil, _), do: false
1349 def muted_notifications?(%User{} = user, %User{} = target),
1350 do: UserRelationship.notification_mute_exists?(user, target)
1352 def blocks?(nil, _), do: false
1354 def blocks?(%User{} = user, %User{} = target) do
1355 blocks_user?(user, target) ||
1356 (blocks_domain?(user, target) and not User.following?(user, target))
1359 def blocks_user?(%User{} = user, %User{} = target) do
1360 UserRelationship.block_exists?(user, target)
1363 def blocks_user?(_, _), do: false
1365 def blocks_domain?(%User{} = user, %User{} = target) do
1366 domain_blocks = Pleroma.Web.ActivityPub.MRF.subdomains_regex(user.domain_blocks)
1367 %{host: host} = URI.parse(target.ap_id)
1368 Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, host)
1371 def blocks_domain?(_, _), do: false
1373 def subscribed_to?(%User{} = user, %User{} = target) do
1374 # Note: the relationship is inverse: subscriber acts as relationship target
1375 UserRelationship.inverse_subscription_exists?(target, user)
1378 def subscribed_to?(%User{} = user, %{ap_id: ap_id}) do
1379 with %User{} = target <- get_cached_by_ap_id(ap_id) do
1380 subscribed_to?(user, target)
1385 Returns map of outgoing (blocked, muted etc.) relationships' user AP IDs by relation type.
1386 E.g. `outgoing_relationships_ap_ids(user, [:block])` -> `%{block: ["https://some.site/users/userapid"]}`
1388 @spec outgoing_relationships_ap_ids(User.t(), list(atom())) :: %{atom() => list(String.t())}
1389 def outgoing_relationships_ap_ids(_user, []), do: %{}
1391 def outgoing_relationships_ap_ids(nil, _relationship_types), do: %{}
1393 def outgoing_relationships_ap_ids(%User{} = user, relationship_types)
1394 when is_list(relationship_types) do
1397 |> assoc(:outgoing_relationships)
1398 |> join(:inner, [user_rel], u in assoc(user_rel, :target))
1399 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1400 |> select([user_rel, u], [user_rel.relationship_type, fragment("array_agg(?)", u.ap_id)])
1401 |> group_by([user_rel, u], user_rel.relationship_type)
1403 |> Enum.into(%{}, fn [k, v] -> {k, v} end)
1408 fn rel_type -> {rel_type, db_result[rel_type] || []} end
1412 def incoming_relationships_ungrouped_ap_ids(user, relationship_types, ap_ids \\ nil)
1414 def incoming_relationships_ungrouped_ap_ids(_user, [], _ap_ids), do: []
1416 def incoming_relationships_ungrouped_ap_ids(nil, _relationship_types, _ap_ids), do: []
1418 def incoming_relationships_ungrouped_ap_ids(%User{} = user, relationship_types, ap_ids)
1419 when is_list(relationship_types) do
1421 |> assoc(:incoming_relationships)
1422 |> join(:inner, [user_rel], u in assoc(user_rel, :source))
1423 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1424 |> maybe_filter_on_ap_id(ap_ids)
1425 |> select([user_rel, u], u.ap_id)
1430 defp maybe_filter_on_ap_id(query, ap_ids) when is_list(ap_ids) do
1431 where(query, [user_rel, u], u.ap_id in ^ap_ids)
1434 defp maybe_filter_on_ap_id(query, _ap_ids), do: query
1436 def deactivate_async(user, status \\ true) do
1437 BackgroundWorker.enqueue("deactivate_user", %{"user_id" => user.id, "status" => status})
1440 def deactivate(user, status \\ true)
1442 def deactivate(users, status) when is_list(users) do
1443 Repo.transaction(fn ->
1444 for user <- users, do: deactivate(user, status)
1448 def deactivate(%User{} = user, status) do
1449 with {:ok, user} <- set_activation_status(user, status) do
1452 |> Enum.filter(& &1.local)
1453 |> Enum.each(&set_cache(update_following_count(&1)))
1455 # Only update local user counts, remote will be update during the next pull.
1458 |> Enum.filter(& &1.local)
1459 |> Enum.each(&do_unfollow(user, &1))
1465 def update_notification_settings(%User{} = user, settings) do
1467 |> cast(%{notification_settings: settings}, [])
1468 |> cast_embed(:notification_settings)
1469 |> validate_required([:notification_settings])
1470 |> update_and_set_cache()
1473 def delete(users) when is_list(users) do
1474 for user <- users, do: delete(user)
1477 def delete(%User{} = user) do
1478 BackgroundWorker.enqueue("delete_user", %{"user_id" => user.id})
1481 defp delete_and_invalidate_cache(%User{} = user) do
1482 invalidate_cache(user)
1486 defp delete_or_deactivate(%User{local: false} = user), do: delete_and_invalidate_cache(user)
1488 defp delete_or_deactivate(%User{local: true} = user) do
1489 status = account_status(user)
1491 if status == :confirmation_pending do
1492 delete_and_invalidate_cache(user)
1495 |> change(%{deactivated: true, email: nil})
1496 |> update_and_set_cache()
1500 def perform(:force_password_reset, user), do: force_password_reset(user)
1502 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1503 def perform(:delete, %User{} = user) do
1504 # Remove all relationships
1507 |> Enum.each(fn follower ->
1508 ActivityPub.unfollow(follower, user)
1509 unfollow(follower, user)
1514 |> Enum.each(fn followed ->
1515 ActivityPub.unfollow(user, followed)
1516 unfollow(user, followed)
1519 delete_user_activities(user)
1520 delete_notifications_from_user_activities(user)
1522 delete_outgoing_pending_follow_requests(user)
1524 delete_or_deactivate(user)
1527 def perform(:deactivate_async, user, status), do: deactivate(user, status)
1529 @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
1530 def perform(:blocks_import, %User{} = blocker, blocked_identifiers)
1531 when is_list(blocked_identifiers) do
1533 blocked_identifiers,
1534 fn blocked_identifier ->
1535 with {:ok, %User{} = blocked} <- get_or_fetch(blocked_identifier),
1536 {:ok, _block} <- CommonAPI.block(blocker, blocked) do
1540 Logger.debug("blocks_import failed for #{blocked_identifier} with: #{inspect(err)}")
1547 def perform(:follow_import, %User{} = follower, followed_identifiers)
1548 when is_list(followed_identifiers) do
1550 followed_identifiers,
1551 fn followed_identifier ->
1552 with {:ok, %User{} = followed} <- get_or_fetch(followed_identifier),
1553 {:ok, follower} <- maybe_direct_follow(follower, followed),
1554 {:ok, _} <- ActivityPub.follow(follower, followed) do
1558 Logger.debug("follow_import failed for #{followed_identifier} with: #{inspect(err)}")
1565 @spec external_users_query() :: Ecto.Query.t()
1566 def external_users_query do
1574 @spec external_users(keyword()) :: [User.t()]
1575 def external_users(opts \\ []) do
1577 external_users_query()
1578 |> select([u], struct(u, [:id, :ap_id]))
1582 do: where(query, [u], u.id > ^opts[:max_id]),
1587 do: limit(query, ^opts[:limit]),
1593 def blocks_import(%User{} = blocker, blocked_identifiers) when is_list(blocked_identifiers) do
1594 BackgroundWorker.enqueue("blocks_import", %{
1595 "blocker_id" => blocker.id,
1596 "blocked_identifiers" => blocked_identifiers
1600 def follow_import(%User{} = follower, followed_identifiers)
1601 when is_list(followed_identifiers) do
1602 BackgroundWorker.enqueue("follow_import", %{
1603 "follower_id" => follower.id,
1604 "followed_identifiers" => followed_identifiers
1608 def delete_notifications_from_user_activities(%User{ap_id: ap_id}) do
1610 |> join(:inner, [n], activity in assoc(n, :activity))
1611 |> where([n, a], fragment("? = ?", a.actor, ^ap_id))
1612 |> Repo.delete_all()
1615 def delete_user_activities(%User{ap_id: ap_id} = user) do
1617 |> Activity.Queries.by_actor()
1618 |> RepoStreamer.chunk_stream(50)
1619 |> Stream.each(fn activities ->
1620 Enum.each(activities, fn activity -> delete_activity(activity, user) end)
1625 defp delete_activity(%{data: %{"type" => "Create", "object" => object}} = activity, user) do
1626 with {_, %Object{}} <- {:find_object, Object.get_by_ap_id(object)},
1627 {:ok, delete_data, _} <- Builder.delete(user, object) do
1628 Pipeline.common_pipeline(delete_data, local: user.local)
1630 {:find_object, nil} ->
1631 # We have the create activity, but not the object, it was probably pruned.
1632 # Insert a tombstone and try again
1633 with {:ok, tombstone_data, _} <- Builder.tombstone(user.ap_id, object),
1634 {:ok, _tombstone} <- Object.create(tombstone_data) do
1635 delete_activity(activity, user)
1639 Logger.error("Could not delete #{object} created by #{activity.data["ap_id"]}")
1640 Logger.error("Error: #{inspect(e)}")
1644 defp delete_activity(%{data: %{"type" => type}} = activity, user)
1645 when type in ["Like", "Announce"] do
1646 {:ok, undo, _} = Builder.undo(user, activity)
1647 Pipeline.common_pipeline(undo, local: user.local)
1650 defp delete_activity(_activity, _user), do: "Doing nothing"
1652 defp delete_outgoing_pending_follow_requests(user) do
1654 |> FollowingRelationship.outgoing_pending_follow_requests_query()
1655 |> Repo.delete_all()
1658 def html_filter_policy(%User{no_rich_text: true}) do
1659 Pleroma.HTML.Scrubber.TwitterText
1662 def html_filter_policy(_), do: Pleroma.Config.get([:markup, :scrub_policy])
1664 def fetch_by_ap_id(ap_id), do: ActivityPub.make_user_from_ap_id(ap_id)
1666 def get_or_fetch_by_ap_id(ap_id) do
1667 cached_user = get_cached_by_ap_id(ap_id)
1669 maybe_fetched_user = needs_update?(cached_user) && fetch_by_ap_id(ap_id)
1671 case {cached_user, maybe_fetched_user} do
1672 {_, {:ok, %User{} = user}} ->
1675 {%User{} = user, _} ->
1679 {:error, :not_found}
1684 Creates an internal service actor by URI if missing.
1685 Optionally takes nickname for addressing.
1687 @spec get_or_create_service_actor_by_ap_id(String.t(), String.t()) :: User.t() | nil
1688 def get_or_create_service_actor_by_ap_id(uri, nickname) do
1690 case get_cached_by_ap_id(uri) do
1692 with {:error, %{errors: errors}} <- create_service_actor(uri, nickname) do
1693 Logger.error("Cannot create service actor: #{uri}/.\n#{inspect(errors)}")
1697 %User{invisible: false} = user ->
1707 @spec set_invisible(User.t()) :: {:ok, User.t()}
1708 defp set_invisible(user) do
1710 |> change(%{invisible: true})
1711 |> update_and_set_cache()
1714 @spec create_service_actor(String.t(), String.t()) ::
1715 {:ok, User.t()} | {:error, Ecto.Changeset.t()}
1716 defp create_service_actor(uri, nickname) do
1722 follower_address: uri <> "/followers"
1725 |> unique_constraint(:nickname)
1730 def public_key(%{public_key: public_key_pem}) when is_binary(public_key_pem) do
1733 |> :public_key.pem_decode()
1735 |> :public_key.pem_entry_decode()
1740 def public_key(_), do: {:error, "key not found"}
1742 def get_public_key_for_ap_id(ap_id) do
1743 with {:ok, %User{} = user} <- get_or_fetch_by_ap_id(ap_id),
1744 {:ok, public_key} <- public_key(user) do
1751 def ap_enabled?(%User{local: true}), do: true
1752 def ap_enabled?(%User{ap_enabled: ap_enabled}), do: ap_enabled
1753 def ap_enabled?(_), do: false
1755 @doc "Gets or fetch a user by uri or nickname."
1756 @spec get_or_fetch(String.t()) :: {:ok, User.t()} | {:error, String.t()}
1757 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
1758 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
1760 # wait a period of time and return newest version of the User structs
1761 # this is because we have synchronous follow APIs and need to simulate them
1762 # with an async handshake
1763 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
1764 with %User{} = a <- get_cached_by_id(a.id),
1765 %User{} = b <- get_cached_by_id(b.id) do
1772 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
1773 with :ok <- :timer.sleep(timeout),
1774 %User{} = a <- get_cached_by_id(a.id),
1775 %User{} = b <- get_cached_by_id(b.id) do
1782 def parse_bio(bio) when is_binary(bio) and bio != "" do
1784 |> CommonUtils.format_input("text/plain", mentions_format: :full)
1788 def parse_bio(_), do: ""
1790 def parse_bio(bio, user) when is_binary(bio) and bio != "" do
1791 # TODO: get profile URLs other than user.ap_id
1792 profile_urls = [user.ap_id]
1795 |> CommonUtils.format_input("text/plain",
1796 mentions_format: :full,
1797 rel: &RelMe.maybe_put_rel_me(&1, profile_urls)
1802 def parse_bio(_, _), do: ""
1804 def tag(user_identifiers, tags) when is_list(user_identifiers) do
1805 Repo.transaction(fn ->
1806 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
1810 def tag(nickname, tags) when is_binary(nickname),
1811 do: tag(get_by_nickname(nickname), tags)
1813 def tag(%User{} = user, tags),
1814 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
1816 def untag(user_identifiers, tags) when is_list(user_identifiers) do
1817 Repo.transaction(fn ->
1818 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
1822 def untag(nickname, tags) when is_binary(nickname),
1823 do: untag(get_by_nickname(nickname), tags)
1825 def untag(%User{} = user, tags),
1826 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
1828 defp update_tags(%User{} = user, new_tags) do
1829 {:ok, updated_user} =
1831 |> change(%{tags: new_tags})
1832 |> update_and_set_cache()
1837 defp normalize_tags(tags) do
1840 |> Enum.map(&String.downcase/1)
1843 defp local_nickname_regex do
1844 if Pleroma.Config.get([:instance, :extended_nickname_format]) do
1845 @extended_local_nickname_regex
1847 @strict_local_nickname_regex
1851 def local_nickname(nickname_or_mention) do
1854 |> String.split("@")
1858 def full_nickname(nickname_or_mention),
1859 do: String.trim_leading(nickname_or_mention, "@")
1861 def error_user(ap_id) do
1865 nickname: "erroruser@example.com",
1866 inserted_at: NaiveDateTime.utc_now()
1870 @spec all_superusers() :: [User.t()]
1871 def all_superusers do
1872 User.Query.build(%{super_users: true, local: true, deactivated: false})
1876 def muting_reblogs?(%User{} = user, %User{} = target) do
1877 UserRelationship.reblog_mute_exists?(user, target)
1880 def showing_reblogs?(%User{} = user, %User{} = target) do
1881 not muting_reblogs?(user, target)
1885 The function returns a query to get users with no activity for given interval of days.
1886 Inactive users are those who didn't read any notification, or had any activity where
1887 the user is the activity's actor, during `inactivity_threshold` days.
1888 Deactivated users will not appear in this list.
1892 iex> Pleroma.User.list_inactive_users()
1895 @spec list_inactive_users_query(integer()) :: Ecto.Query.t()
1896 def list_inactive_users_query(inactivity_threshold \\ 7) do
1897 negative_inactivity_threshold = -inactivity_threshold
1898 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
1899 # Subqueries are not supported in `where` clauses, join gets too complicated.
1900 has_read_notifications =
1901 from(n in Pleroma.Notification,
1902 where: n.seen == true,
1904 having: max(n.updated_at) > datetime_add(^now, ^negative_inactivity_threshold, "day"),
1907 |> Pleroma.Repo.all()
1909 from(u in Pleroma.User,
1910 left_join: a in Pleroma.Activity,
1911 on: u.ap_id == a.actor,
1912 where: not is_nil(u.nickname),
1913 where: u.deactivated != ^true,
1914 where: u.id not in ^has_read_notifications,
1917 max(a.inserted_at) < datetime_add(^now, ^negative_inactivity_threshold, "day") or
1918 is_nil(max(a.inserted_at))
1923 Enable or disable email notifications for user
1927 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => false}}, "digest", true)
1928 Pleroma.User{email_notifications: %{"digest" => true}}
1930 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => true}}, "digest", false)
1931 Pleroma.User{email_notifications: %{"digest" => false}}
1933 @spec switch_email_notifications(t(), String.t(), boolean()) ::
1934 {:ok, t()} | {:error, Ecto.Changeset.t()}
1935 def switch_email_notifications(user, type, status) do
1936 User.update_email_notifications(user, %{type => status})
1940 Set `last_digest_emailed_at` value for the user to current time
1942 @spec touch_last_digest_emailed_at(t()) :: t()
1943 def touch_last_digest_emailed_at(user) do
1944 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
1946 {:ok, updated_user} =
1948 |> change(%{last_digest_emailed_at: now})
1949 |> update_and_set_cache()
1954 @spec toggle_confirmation(User.t()) :: {:ok, User.t()} | {:error, Changeset.t()}
1955 def toggle_confirmation(%User{} = user) do
1957 |> confirmation_changeset(need_confirmation: !user.confirmation_pending)
1958 |> update_and_set_cache()
1961 @spec toggle_confirmation([User.t()]) :: [{:ok, User.t()} | {:error, Changeset.t()}]
1962 def toggle_confirmation(users) do
1963 Enum.map(users, &toggle_confirmation/1)
1966 def get_mascot(%{mascot: %{} = mascot}) when not is_nil(mascot) do
1970 def get_mascot(%{mascot: mascot}) when is_nil(mascot) do
1971 # use instance-default
1972 config = Pleroma.Config.get([:assets, :mascots])
1973 default_mascot = Pleroma.Config.get([:assets, :default_mascot])
1974 mascot = Keyword.get(config, default_mascot)
1977 "id" => "default-mascot",
1978 "url" => mascot[:url],
1979 "preview_url" => mascot[:url],
1981 "mime_type" => mascot[:mime_type]
1986 def ensure_keys_present(%{keys: keys} = user) when not is_nil(keys), do: {:ok, user}
1988 def ensure_keys_present(%User{} = user) do
1989 with {:ok, pem} <- Keys.generate_rsa_pem() do
1991 |> cast(%{keys: pem}, [:keys])
1992 |> validate_required([:keys])
1993 |> update_and_set_cache()
1997 def get_ap_ids_by_nicknames(nicknames) do
1999 where: u.nickname in ^nicknames,
2005 defdelegate search(query, opts \\ []), to: User.Search
2007 defp put_password_hash(
2008 %Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset
2010 change(changeset, password_hash: Pbkdf2.hash_pwd_salt(password))
2013 defp put_password_hash(changeset), do: changeset
2015 def is_internal_user?(%User{nickname: nil}), do: true
2016 def is_internal_user?(%User{local: true, nickname: "internal." <> _}), do: true
2017 def is_internal_user?(_), do: false
2019 # A hack because user delete activities have a fake id for whatever reason
2020 # TODO: Get rid of this
2021 def get_delivered_users_by_object_id("pleroma:fake_object_id"), do: []
2023 def get_delivered_users_by_object_id(object_id) do
2025 inner_join: delivery in assoc(u, :deliveries),
2026 where: delivery.object_id == ^object_id
2031 def change_email(user, email) do
2033 |> cast(%{email: email}, [:email])
2034 |> validate_required([:email])
2035 |> unique_constraint(:email)
2036 |> validate_format(:email, @email_regex)
2037 |> update_and_set_cache()
2040 # Internal function; public one is `deactivate/2`
2041 defp set_activation_status(user, deactivated) do
2043 |> cast(%{deactivated: deactivated}, [:deactivated])
2044 |> update_and_set_cache()
2047 def update_banner(user, banner) do
2049 |> cast(%{banner: banner}, [:banner])
2050 |> update_and_set_cache()
2053 def update_background(user, background) do
2055 |> cast(%{background: background}, [:background])
2056 |> update_and_set_cache()
2059 def roles(%{is_moderator: is_moderator, is_admin: is_admin}) do
2062 moderator: is_moderator
2066 def validate_fields(changeset, remote? \\ false) do
2067 limit_name = if remote?, do: :max_remote_account_fields, else: :max_account_fields
2068 limit = Pleroma.Config.get([:instance, limit_name], 0)
2071 |> validate_length(:fields, max: limit)
2072 |> validate_change(:fields, fn :fields, fields ->
2073 if Enum.all?(fields, &valid_field?/1) do
2081 defp valid_field?(%{"name" => name, "value" => value}) do
2082 name_limit = Pleroma.Config.get([:instance, :account_field_name_length], 255)
2083 value_limit = Pleroma.Config.get([:instance, :account_field_value_length], 255)
2085 is_binary(name) && is_binary(value) && String.length(name) <= name_limit &&
2086 String.length(value) <= value_limit
2089 defp valid_field?(_), do: false
2091 defp truncate_field(%{"name" => name, "value" => value}) do
2093 String.split_at(name, Pleroma.Config.get([:instance, :account_field_name_length], 255))
2096 String.split_at(value, Pleroma.Config.get([:instance, :account_field_value_length], 255))
2098 %{"name" => name, "value" => value}
2101 def admin_api_update(user, params) do
2108 |> update_and_set_cache()
2111 @doc "Signs user out of all applications"
2112 def global_sign_out(user) do
2113 OAuth.Authorization.delete_user_authorizations(user)
2114 OAuth.Token.delete_user_tokens(user)
2117 def mascot_update(user, url) do
2119 |> cast(%{mascot: url}, [:mascot])
2120 |> validate_required([:mascot])
2121 |> update_and_set_cache()
2124 def mastodon_settings_update(user, settings) do
2126 |> cast(%{mastofe_settings: settings}, [:mastofe_settings])
2127 |> validate_required([:mastofe_settings])
2128 |> update_and_set_cache()
2131 @spec confirmation_changeset(User.t(), keyword()) :: Changeset.t()
2132 def confirmation_changeset(user, need_confirmation: need_confirmation?) do
2134 if need_confirmation? do
2136 confirmation_pending: true,
2137 confirmation_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64()
2141 confirmation_pending: false,
2142 confirmation_token: nil
2146 cast(user, params, [:confirmation_pending, :confirmation_token])
2149 def add_pinnned_activity(user, %Pleroma.Activity{id: id}) do
2150 if id not in user.pinned_activities do
2151 max_pinned_statuses = Pleroma.Config.get([:instance, :max_pinned_statuses], 0)
2152 params = %{pinned_activities: user.pinned_activities ++ [id]}
2155 |> cast(params, [:pinned_activities])
2156 |> validate_length(:pinned_activities,
2157 max: max_pinned_statuses,
2158 message: "You have already pinned the maximum number of statuses"
2163 |> update_and_set_cache()
2166 def remove_pinnned_activity(user, %Pleroma.Activity{id: id}) do
2167 params = %{pinned_activities: List.delete(user.pinned_activities, id)}
2170 |> cast(params, [:pinned_activities])
2171 |> update_and_set_cache()
2174 def update_email_notifications(user, settings) do
2175 email_notifications =
2176 user.email_notifications
2177 |> Map.merge(settings)
2178 |> Map.take(["digest"])
2180 params = %{email_notifications: email_notifications}
2181 fields = [:email_notifications]
2184 |> cast(params, fields)
2185 |> validate_required(fields)
2186 |> update_and_set_cache()
2189 defp set_domain_blocks(user, domain_blocks) do
2190 params = %{domain_blocks: domain_blocks}
2193 |> cast(params, [:domain_blocks])
2194 |> validate_required([:domain_blocks])
2195 |> update_and_set_cache()
2198 def block_domain(user, domain_blocked) do
2199 set_domain_blocks(user, Enum.uniq([domain_blocked | user.domain_blocks]))
2202 def unblock_domain(user, domain_blocked) do
2203 set_domain_blocks(user, List.delete(user.domain_blocks, domain_blocked))
2206 @spec add_to_block(User.t(), User.t()) ::
2207 {:ok, UserRelationship.t()} | {:error, Ecto.Changeset.t()}
2208 defp add_to_block(%User{} = user, %User{} = blocked) do
2209 UserRelationship.create_block(user, blocked)
2212 @spec add_to_block(User.t(), User.t()) ::
2213 {:ok, UserRelationship.t()} | {:ok, nil} | {:error, Ecto.Changeset.t()}
2214 defp remove_from_block(%User{} = user, %User{} = blocked) do
2215 UserRelationship.delete_block(user, blocked)
2218 defp add_to_mutes(%User{} = user, %User{} = muted_user, notifications?) do
2219 with {:ok, user_mute} <- UserRelationship.create_mute(user, muted_user),
2220 {:ok, user_notification_mute} <-
2221 (notifications? && UserRelationship.create_notification_mute(user, muted_user)) ||
2223 {:ok, Enum.filter([user_mute, user_notification_mute], & &1)}
2227 defp remove_from_mutes(user, %User{} = muted_user) do
2228 with {:ok, user_mute} <- UserRelationship.delete_mute(user, muted_user),
2229 {:ok, user_notification_mute} <-
2230 UserRelationship.delete_notification_mute(user, muted_user) do
2231 {:ok, [user_mute, user_notification_mute]}
2235 def set_invisible(user, invisible) do
2236 params = %{invisible: invisible}
2239 |> cast(params, [:invisible])
2240 |> validate_required([:invisible])
2241 |> update_and_set_cache()
2244 def sanitize_html(%User{} = user) do
2245 sanitize_html(user, nil)
2248 # User data that mastodon isn't filtering (treated as plaintext):
2251 def sanitize_html(%User{} = user, filter) do
2253 Enum.map(user.fields, fn %{"name" => name, "value" => value} ->
2256 "value" => HTML.filter_tags(value, Pleroma.HTML.Scrubber.LinksOnly)
2261 |> Map.put(:bio, HTML.filter_tags(user.bio, filter))
2262 |> Map.put(:fields, fields)