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 case Config.get([:instance, :account_activation_required]) do
266 true -> :confirmation_pending
271 def account_status(%User{}), do: :active
273 @spec visible_for?(User.t(), User.t() | nil) :: boolean()
274 def visible_for?(user, for_user \\ nil)
276 def visible_for?(%User{invisible: true}, _), do: false
278 def visible_for?(%User{id: user_id}, %User{id: user_id}), do: true
280 def visible_for?(%User{local: local} = user, nil) do
286 if Config.get([:restrict_unauthenticated, :profiles, cfg_key]),
288 else: account_status(user) == :active
291 def visible_for?(%User{} = user, for_user) do
292 account_status(user) == :active || superuser?(for_user)
295 def visible_for?(_, _), do: false
297 @spec superuser?(User.t()) :: boolean()
298 def superuser?(%User{local: true, is_admin: true}), do: true
299 def superuser?(%User{local: true, is_moderator: true}), do: true
300 def superuser?(_), do: false
302 @spec invisible?(User.t()) :: boolean()
303 def invisible?(%User{invisible: true}), do: true
304 def invisible?(_), do: false
306 def avatar_url(user, options \\ []) do
308 %{"url" => [%{"href" => href} | _]} ->
312 unless options[:no_default] do
313 Config.get([:assets, :default_user_avatar], "#{Web.base_url()}/images/avi.png")
318 def banner_url(user, options \\ []) do
320 %{"url" => [%{"href" => href} | _]} -> href
321 _ -> !options[:no_default] && "#{Web.base_url()}/images/banner.png"
325 # Should probably be renamed or removed
326 def ap_id(%User{nickname: nickname}), do: "#{Web.base_url()}/users/#{nickname}"
328 def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
329 def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
331 @spec ap_following(User.t()) :: String.t()
332 def ap_following(%User{following_address: fa}) when is_binary(fa), do: fa
333 def ap_following(%User{} = user), do: "#{ap_id(user)}/following"
335 @spec restrict_deactivated(Ecto.Query.t()) :: Ecto.Query.t()
336 def restrict_deactivated(query) do
337 from(u in query, where: u.deactivated != ^true)
340 defdelegate following_count(user), to: FollowingRelationship
342 defp truncate_fields_param(params) do
343 if Map.has_key?(params, :fields) do
344 Map.put(params, :fields, Enum.map(params[:fields], &truncate_field/1))
350 defp truncate_if_exists(params, key, max_length) do
351 if Map.has_key?(params, key) and is_binary(params[key]) do
352 {value, _chopped} = String.split_at(params[key], max_length)
353 Map.put(params, key, value)
359 defp fix_follower_address(%{follower_address: _, following_address: _} = params), do: params
361 defp fix_follower_address(%{nickname: nickname} = params),
362 do: Map.put(params, :follower_address, ap_followers(%User{nickname: nickname}))
364 defp fix_follower_address(params), do: params
366 def remote_user_changeset(struct \\ %User{local: false}, params) do
367 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
368 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
371 case params[:name] do
372 name when is_binary(name) and byte_size(name) > 0 -> name
373 _ -> params[:nickname]
378 |> Map.put(:name, name)
379 |> Map.put_new(:last_refreshed_at, NaiveDateTime.utc_now())
380 |> truncate_if_exists(:name, name_limit)
381 |> truncate_if_exists(:bio, bio_limit)
382 |> truncate_fields_param()
383 |> fix_follower_address()
407 :hide_followers_count,
418 |> validate_required([:name, :ap_id])
419 |> unique_constraint(:nickname)
420 |> validate_format(:nickname, @email_regex)
421 |> validate_length(:bio, max: bio_limit)
422 |> validate_length(:name, max: name_limit)
423 |> validate_fields(true)
426 def update_changeset(struct, params \\ %{}) do
427 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
428 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
447 :hide_followers_count,
450 :allow_following_move,
453 :skip_thread_containment,
456 :pleroma_settings_store,
462 |> unique_constraint(:nickname)
463 |> validate_format(:nickname, local_nickname_regex())
464 |> validate_length(:bio, max: bio_limit)
465 |> validate_length(:name, min: 1, max: name_limit)
468 |> put_change_if_present(:bio, &{:ok, parse_bio(&1, struct)})
469 |> put_change_if_present(:avatar, &put_upload(&1, :avatar))
470 |> put_change_if_present(:banner, &put_upload(&1, :banner))
471 |> put_change_if_present(:background, &put_upload(&1, :background))
472 |> put_change_if_present(
473 :pleroma_settings_store,
474 &{:ok, Map.merge(struct.pleroma_settings_store, &1)}
476 |> validate_fields(false)
479 defp put_fields(changeset) do
480 if raw_fields = get_change(changeset, :raw_fields) do
483 |> Enum.filter(fn %{"name" => n} -> n != "" end)
487 |> Enum.map(fn f -> Map.update!(f, "value", &parse_fields(&1)) end)
490 |> put_change(:raw_fields, raw_fields)
491 |> put_change(:fields, fields)
497 defp parse_fields(value) do
499 |> Formatter.linkify(mentions_format: :full)
503 defp put_emoji(changeset) do
504 bio = get_change(changeset, :bio)
505 name = get_change(changeset, :name)
508 emoji = Map.merge(Emoji.Formatter.get_emoji_map(bio), Emoji.Formatter.get_emoji_map(name))
509 put_change(changeset, :emoji, emoji)
515 defp put_change_if_present(changeset, map_field, value_function) do
516 if value = get_change(changeset, map_field) do
517 with {:ok, new_value} <- value_function.(value) do
518 put_change(changeset, map_field, new_value)
527 defp put_upload(value, type) do
528 with %Plug.Upload{} <- value,
529 {:ok, object} <- ActivityPub.upload(value, type: type) do
534 def update_as_admin_changeset(struct, params) do
536 |> update_changeset(params)
537 |> cast(params, [:email])
538 |> delete_change(:also_known_as)
539 |> unique_constraint(:email)
540 |> validate_format(:email, @email_regex)
541 |> validate_inclusion(:actor_type, ["Person", "Service"])
544 @spec update_as_admin(User.t(), map()) :: {:ok, User.t()} | {:error, Changeset.t()}
545 def update_as_admin(user, params) do
546 params = Map.put(params, "password_confirmation", params["password"])
547 changeset = update_as_admin_changeset(user, params)
549 if params["password"] do
550 reset_password(user, changeset, params)
552 User.update_and_set_cache(changeset)
556 def password_update_changeset(struct, params) do
558 |> cast(params, [:password, :password_confirmation])
559 |> validate_required([:password, :password_confirmation])
560 |> validate_confirmation(:password)
561 |> put_password_hash()
562 |> put_change(:password_reset_pending, false)
565 @spec reset_password(User.t(), map()) :: {:ok, User.t()} | {:error, Changeset.t()}
566 def reset_password(%User{} = user, params) do
567 reset_password(user, user, params)
570 def reset_password(%User{id: user_id} = user, struct, params) do
573 |> Multi.update(:user, password_update_changeset(struct, params))
574 |> Multi.delete_all(:tokens, OAuth.Token.Query.get_by_user(user_id))
575 |> Multi.delete_all(:auth, OAuth.Authorization.delete_by_user_query(user))
577 case Repo.transaction(multi) do
578 {:ok, %{user: user} = _} -> set_cache(user)
579 {:error, _, changeset, _} -> {:error, changeset}
583 def update_password_reset_pending(user, value) do
586 |> put_change(:password_reset_pending, value)
587 |> update_and_set_cache()
590 def force_password_reset_async(user) do
591 BackgroundWorker.enqueue("force_password_reset", %{"user_id" => user.id})
594 @spec force_password_reset(User.t()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
595 def force_password_reset(user), do: update_password_reset_pending(user, true)
597 def register_changeset(struct, params \\ %{}, opts \\ []) do
598 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
599 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
602 if is_nil(opts[:need_confirmation]) do
603 Pleroma.Config.get([:instance, :account_activation_required])
605 opts[:need_confirmation]
609 |> confirmation_changeset(need_confirmation: need_confirmation?)
610 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation, :emoji])
611 |> validate_required([:name, :nickname, :password, :password_confirmation])
612 |> validate_confirmation(:password)
613 |> unique_constraint(:email)
614 |> unique_constraint(:nickname)
615 |> validate_exclusion(:nickname, Pleroma.Config.get([User, :restricted_nicknames]))
616 |> validate_format(:nickname, local_nickname_regex())
617 |> validate_format(:email, @email_regex)
618 |> validate_length(:bio, max: bio_limit)
619 |> validate_length(:name, min: 1, max: name_limit)
620 |> maybe_validate_required_email(opts[:external])
623 |> unique_constraint(:ap_id)
624 |> put_following_and_follower_address()
627 def maybe_validate_required_email(changeset, true), do: changeset
629 def maybe_validate_required_email(changeset, _) do
630 if Pleroma.Config.get([:instance, :account_activation_required]) do
631 validate_required(changeset, [:email])
637 defp put_ap_id(changeset) do
638 ap_id = ap_id(%User{nickname: get_field(changeset, :nickname)})
639 put_change(changeset, :ap_id, ap_id)
642 defp put_following_and_follower_address(changeset) do
643 followers = ap_followers(%User{nickname: get_field(changeset, :nickname)})
646 |> put_change(:follower_address, followers)
649 defp autofollow_users(user) do
650 candidates = Pleroma.Config.get([:instance, :autofollowed_nicknames])
653 User.Query.build(%{nickname: candidates, local: true, deactivated: false})
656 follow_all(user, autofollowed_users)
659 @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
660 def register(%Ecto.Changeset{} = changeset) do
661 with {:ok, user} <- Repo.insert(changeset) do
662 post_register_action(user)
666 def post_register_action(%User{} = user) do
667 with {:ok, user} <- autofollow_users(user),
668 {:ok, user} <- set_cache(user),
669 {:ok, _} <- User.WelcomeMessage.post_welcome_message_to_user(user),
670 {:ok, _} <- try_send_confirmation_email(user) do
675 def try_send_confirmation_email(%User{} = user) do
676 if user.confirmation_pending &&
677 Pleroma.Config.get([:instance, :account_activation_required]) do
679 |> Pleroma.Emails.UserEmail.account_confirmation_email()
680 |> Pleroma.Emails.Mailer.deliver_async()
688 def try_send_confirmation_email(users) do
689 Enum.each(users, &try_send_confirmation_email/1)
692 def needs_update?(%User{local: true}), do: false
694 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
696 def needs_update?(%User{local: false} = user) do
697 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
700 def needs_update?(_), do: true
702 @spec maybe_direct_follow(User.t(), User.t()) :: {:ok, User.t()} | {:error, String.t()}
704 # "Locked" (self-locked) users demand explicit authorization of follow requests
705 def maybe_direct_follow(%User{} = follower, %User{local: true, locked: true} = followed) do
706 follow(follower, followed, :follow_pending)
709 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
710 follow(follower, followed)
713 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
714 if not ap_enabled?(followed) do
715 follow(follower, followed)
721 @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
722 @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
723 def follow_all(follower, followeds) do
725 |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
726 |> Enum.each(&follow(follower, &1, :follow_accept))
731 defdelegate following(user), to: FollowingRelationship
733 def follow(%User{} = follower, %User{} = followed, state \\ :follow_accept) do
734 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
737 followed.deactivated ->
738 {:error, "Could not follow user: #{followed.nickname} is deactivated."}
740 deny_follow_blocked and blocks?(followed, follower) ->
741 {:error, "Could not follow user: #{followed.nickname} blocked you."}
744 FollowingRelationship.follow(follower, followed, state)
746 {:ok, _} = update_follower_count(followed)
749 |> update_following_count()
753 def unfollow(%User{ap_id: ap_id}, %User{ap_id: ap_id}) do
754 {:error, "Not subscribed!"}
757 @spec unfollow(User.t(), User.t()) :: {:ok, User.t(), Activity.t()} | {:error, String.t()}
758 def unfollow(%User{} = follower, %User{} = followed) do
759 case do_unfollow(follower, followed) do
760 {:ok, follower, followed} ->
761 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
768 @spec do_unfollow(User.t(), User.t()) :: {:ok, User.t(), User.t()} | {:error, String.t()}
769 defp do_unfollow(%User{} = follower, %User{} = followed) do
770 case get_follow_state(follower, followed) do
771 state when state in [:follow_pending, :follow_accept] ->
772 FollowingRelationship.unfollow(follower, followed)
773 {:ok, followed} = update_follower_count(followed)
777 |> update_following_count()
779 {:ok, follower, followed}
782 {:error, "Not subscribed!"}
786 defdelegate following?(follower, followed), to: FollowingRelationship
788 @doc "Returns follow state as Pleroma.FollowingRelationship.State value"
789 def get_follow_state(%User{} = follower, %User{} = following) do
790 following_relationship = FollowingRelationship.get(follower, following)
791 get_follow_state(follower, following, following_relationship)
794 def get_follow_state(
797 following_relationship
799 case {following_relationship, following.local} do
801 case Utils.fetch_latest_follow(follower, following) do
802 %Activity{data: %{"state" => state}} when state in ["pending", "accept"] ->
803 FollowingRelationship.state_to_enum(state)
809 {%{state: state}, _} ->
817 def locked?(%User{} = user) do
822 Repo.get_by(User, id: id)
825 def get_by_ap_id(ap_id) do
826 Repo.get_by(User, ap_id: ap_id)
829 def get_all_by_ap_id(ap_ids) do
830 from(u in __MODULE__,
831 where: u.ap_id in ^ap_ids
836 def get_all_by_ids(ids) do
837 from(u in __MODULE__, where: u.id in ^ids)
841 # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
842 # of the ap_id and the domain and tries to get that user
843 def get_by_guessed_nickname(ap_id) do
844 domain = URI.parse(ap_id).host
845 name = List.last(String.split(ap_id, "/"))
846 nickname = "#{name}@#{domain}"
848 get_cached_by_nickname(nickname)
851 def set_cache({:ok, user}), do: set_cache(user)
852 def set_cache({:error, err}), do: {:error, err}
854 def set_cache(%User{} = user) do
855 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
856 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
857 Cachex.put(:user_cache, "friends_ap_ids:#{user.nickname}", get_user_friends_ap_ids(user))
861 def update_and_set_cache(struct, params) do
863 |> update_changeset(params)
864 |> update_and_set_cache()
867 def update_and_set_cache(changeset) do
868 with {:ok, user} <- Repo.update(changeset, stale_error_field: :id) do
873 def get_user_friends_ap_ids(user) do
874 from(u in User.get_friends_query(user), select: u.ap_id)
878 @spec get_cached_user_friends_ap_ids(User.t()) :: [String.t()]
879 def get_cached_user_friends_ap_ids(user) do
880 Cachex.fetch!(:user_cache, "friends_ap_ids:#{user.ap_id}", fn _ ->
881 get_user_friends_ap_ids(user)
885 def invalidate_cache(user) do
886 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
887 Cachex.del(:user_cache, "nickname:#{user.nickname}")
888 Cachex.del(:user_cache, "friends_ap_ids:#{user.ap_id}")
891 @spec get_cached_by_ap_id(String.t()) :: User.t() | nil
892 def get_cached_by_ap_id(ap_id) do
893 key = "ap_id:#{ap_id}"
895 with {:ok, nil} <- Cachex.get(:user_cache, key),
896 user when not is_nil(user) <- get_by_ap_id(ap_id),
897 {:ok, true} <- Cachex.put(:user_cache, key, user) do
905 def get_cached_by_id(id) do
909 Cachex.fetch!(:user_cache, key, fn _ ->
913 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
914 {:commit, user.ap_id}
920 get_cached_by_ap_id(ap_id)
923 def get_cached_by_nickname(nickname) do
924 key = "nickname:#{nickname}"
926 Cachex.fetch!(:user_cache, key, fn ->
927 case get_or_fetch_by_nickname(nickname) do
928 {:ok, user} -> {:commit, user}
929 {:error, _error} -> {:ignore, nil}
934 def get_cached_by_nickname_or_id(nickname_or_id, opts \\ []) do
935 restrict_to_local = Pleroma.Config.get([:instance, :limit_to_local_content])
938 is_integer(nickname_or_id) or FlakeId.flake_id?(nickname_or_id) ->
939 get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
941 restrict_to_local == false or not String.contains?(nickname_or_id, "@") ->
942 get_cached_by_nickname(nickname_or_id)
944 restrict_to_local == :unauthenticated and match?(%User{}, opts[:for]) ->
945 get_cached_by_nickname(nickname_or_id)
952 @spec get_by_nickname(String.t()) :: User.t() | nil
953 def get_by_nickname(nickname) do
954 Repo.get_by(User, nickname: nickname) ||
955 if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
956 Repo.get_by(User, nickname: local_nickname(nickname))
960 def get_by_email(email), do: Repo.get_by(User, email: email)
962 def get_by_nickname_or_email(nickname_or_email) do
963 get_by_nickname(nickname_or_email) || get_by_email(nickname_or_email)
966 def fetch_by_nickname(nickname), do: ActivityPub.make_user_from_nickname(nickname)
968 def get_or_fetch_by_nickname(nickname) do
969 with %User{} = user <- get_by_nickname(nickname) do
973 with [_nick, _domain] <- String.split(nickname, "@"),
974 {:ok, user} <- fetch_by_nickname(nickname) do
977 _e -> {:error, "not found " <> nickname}
982 @spec get_followers_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
983 def get_followers_query(%User{} = user, nil) do
984 User.Query.build(%{followers: user, deactivated: false})
987 def get_followers_query(user, page) do
989 |> get_followers_query(nil)
990 |> User.Query.paginate(page, 20)
993 @spec get_followers_query(User.t()) :: Ecto.Query.t()
994 def get_followers_query(user), do: get_followers_query(user, nil)
996 @spec get_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
997 def get_followers(user, page \\ nil) do
999 |> get_followers_query(page)
1003 @spec get_external_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
1004 def get_external_followers(user, page \\ nil) do
1006 |> get_followers_query(page)
1007 |> User.Query.build(%{external: true})
1011 def get_followers_ids(user, page \\ nil) do
1013 |> get_followers_query(page)
1014 |> select([u], u.id)
1018 @spec get_friends_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
1019 def get_friends_query(%User{} = user, nil) do
1020 User.Query.build(%{friends: user, deactivated: false})
1023 def get_friends_query(user, page) do
1025 |> get_friends_query(nil)
1026 |> User.Query.paginate(page, 20)
1029 @spec get_friends_query(User.t()) :: Ecto.Query.t()
1030 def get_friends_query(user), do: get_friends_query(user, nil)
1032 def get_friends(user, page \\ nil) do
1034 |> get_friends_query(page)
1038 def get_friends_ap_ids(user) do
1040 |> get_friends_query(nil)
1041 |> select([u], u.ap_id)
1045 def get_friends_ids(user, page \\ nil) do
1047 |> get_friends_query(page)
1048 |> select([u], u.id)
1052 defdelegate get_follow_requests(user), to: FollowingRelationship
1054 def increase_note_count(%User{} = user) do
1056 |> where(id: ^user.id)
1057 |> update([u], inc: [note_count: 1])
1059 |> Repo.update_all([])
1061 {1, [user]} -> set_cache(user)
1066 def decrease_note_count(%User{} = user) do
1068 |> where(id: ^user.id)
1071 note_count: fragment("greatest(0, note_count - 1)")
1075 |> Repo.update_all([])
1077 {1, [user]} -> set_cache(user)
1082 def update_note_count(%User{} = user, note_count \\ nil) do
1087 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
1093 |> cast(%{note_count: note_count}, [:note_count])
1094 |> update_and_set_cache()
1097 @spec maybe_fetch_follow_information(User.t()) :: User.t()
1098 def maybe_fetch_follow_information(user) do
1099 with {:ok, user} <- fetch_follow_information(user) do
1103 Logger.error("Follower/Following counter update for #{user.ap_id} failed.\n#{inspect(e)}")
1109 def fetch_follow_information(user) do
1110 with {:ok, info} <- ActivityPub.fetch_follow_information_for_user(user) do
1112 |> follow_information_changeset(info)
1113 |> update_and_set_cache()
1117 defp follow_information_changeset(user, params) do
1124 :hide_followers_count,
1129 @spec update_follower_count(User.t()) :: {:ok, User.t()}
1130 def update_follower_count(%User{} = user) do
1131 if user.local or !Pleroma.Config.get([:instance, :external_user_synchronization]) do
1132 follower_count = FollowingRelationship.follower_count(user)
1135 |> follow_information_changeset(%{follower_count: follower_count})
1136 |> update_and_set_cache
1138 {:ok, maybe_fetch_follow_information(user)}
1142 @spec update_following_count(User.t()) :: {:ok, User.t()}
1143 def update_following_count(%User{local: false} = user) do
1144 if Pleroma.Config.get([:instance, :external_user_synchronization]) do
1145 {:ok, maybe_fetch_follow_information(user)}
1151 def update_following_count(%User{local: true} = user) do
1152 following_count = FollowingRelationship.following_count(user)
1155 |> follow_information_changeset(%{following_count: following_count})
1156 |> update_and_set_cache()
1159 def set_unread_conversation_count(%User{local: true} = user) do
1160 unread_query = Participation.unread_conversation_count_for_user(user)
1163 |> join(:inner, [u], p in subquery(unread_query))
1165 set: [unread_conversation_count: p.count]
1167 |> where([u], u.id == ^user.id)
1169 |> Repo.update_all([])
1171 {1, [user]} -> set_cache(user)
1176 def set_unread_conversation_count(user), do: {:ok, user}
1178 def increment_unread_conversation_count(conversation, %User{local: true} = user) do
1180 Participation.unread_conversation_count_for_user(user)
1181 |> where([p], p.conversation_id == ^conversation.id)
1184 |> join(:inner, [u], p in subquery(unread_query))
1186 inc: [unread_conversation_count: 1]
1188 |> where([u], u.id == ^user.id)
1189 |> where([u, p], p.count == 0)
1191 |> Repo.update_all([])
1193 {1, [user]} -> set_cache(user)
1198 def increment_unread_conversation_count(_, user), do: {:ok, user}
1200 @spec get_users_from_set([String.t()], keyword()) :: [User.t()]
1201 def get_users_from_set(ap_ids, opts \\ []) do
1202 local_only = Keyword.get(opts, :local_only, true)
1203 criteria = %{ap_id: ap_ids, deactivated: false}
1204 criteria = if local_only, do: Map.put(criteria, :local, true), else: criteria
1206 User.Query.build(criteria)
1210 @spec get_recipients_from_activity(Activity.t()) :: [User.t()]
1211 def get_recipients_from_activity(%Activity{recipients: to, actor: actor}) do
1214 query = User.Query.build(%{recipients_from_activity: to, local: true, deactivated: false})
1220 @spec mute(User.t(), User.t(), boolean()) ::
1221 {:ok, list(UserRelationship.t())} | {:error, String.t()}
1222 def mute(%User{} = muter, %User{} = mutee, notifications? \\ true) do
1223 add_to_mutes(muter, mutee, notifications?)
1226 def unmute(%User{} = muter, %User{} = mutee) do
1227 remove_from_mutes(muter, mutee)
1230 def subscribe(%User{} = subscriber, %User{} = target) do
1231 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
1233 if blocks?(target, subscriber) and deny_follow_blocked do
1234 {:error, "Could not subscribe: #{target.nickname} is blocking you"}
1236 # Note: the relationship is inverse: subscriber acts as relationship target
1237 UserRelationship.create_inverse_subscription(target, subscriber)
1241 def subscribe(%User{} = subscriber, %{ap_id: ap_id}) do
1242 with %User{} = subscribee <- get_cached_by_ap_id(ap_id) do
1243 subscribe(subscriber, subscribee)
1247 def unsubscribe(%User{} = unsubscriber, %User{} = target) do
1248 # Note: the relationship is inverse: subscriber acts as relationship target
1249 UserRelationship.delete_inverse_subscription(target, unsubscriber)
1252 def unsubscribe(%User{} = unsubscriber, %{ap_id: ap_id}) do
1253 with %User{} = user <- get_cached_by_ap_id(ap_id) do
1254 unsubscribe(unsubscriber, user)
1258 def block(%User{} = blocker, %User{} = blocked) do
1259 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
1261 if following?(blocker, blocked) do
1262 {:ok, blocker, _} = unfollow(blocker, blocked)
1268 # clear any requested follows as well
1270 case CommonAPI.reject_follow_request(blocked, blocker) do
1271 {:ok, %User{} = updated_blocked} -> updated_blocked
1275 unsubscribe(blocked, blocker)
1277 if following?(blocked, blocker), do: unfollow(blocked, blocker)
1279 {:ok, blocker} = update_follower_count(blocker)
1280 {:ok, blocker, _} = Participation.mark_all_as_read(blocker, blocked)
1281 add_to_block(blocker, blocked)
1284 # helper to handle the block given only an actor's AP id
1285 def block(%User{} = blocker, %{ap_id: ap_id}) do
1286 block(blocker, get_cached_by_ap_id(ap_id))
1289 def unblock(%User{} = blocker, %User{} = blocked) do
1290 remove_from_block(blocker, blocked)
1293 # helper to handle the block given only an actor's AP id
1294 def unblock(%User{} = blocker, %{ap_id: ap_id}) do
1295 unblock(blocker, get_cached_by_ap_id(ap_id))
1298 def mutes?(nil, _), do: false
1299 def mutes?(%User{} = user, %User{} = target), do: mutes_user?(user, target)
1301 def mutes_user?(%User{} = user, %User{} = target) do
1302 UserRelationship.mute_exists?(user, target)
1305 @spec muted_notifications?(User.t() | nil, User.t() | map()) :: boolean()
1306 def muted_notifications?(nil, _), do: false
1308 def muted_notifications?(%User{} = user, %User{} = target),
1309 do: UserRelationship.notification_mute_exists?(user, target)
1311 def blocks?(nil, _), do: false
1313 def blocks?(%User{} = user, %User{} = target) do
1314 blocks_user?(user, target) ||
1315 (blocks_domain?(user, target) and not User.following?(user, target))
1318 def blocks_user?(%User{} = user, %User{} = target) do
1319 UserRelationship.block_exists?(user, target)
1322 def blocks_user?(_, _), do: false
1324 def blocks_domain?(%User{} = user, %User{} = target) do
1325 domain_blocks = Pleroma.Web.ActivityPub.MRF.subdomains_regex(user.domain_blocks)
1326 %{host: host} = URI.parse(target.ap_id)
1327 Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, host)
1330 def blocks_domain?(_, _), do: false
1332 def subscribed_to?(%User{} = user, %User{} = target) do
1333 # Note: the relationship is inverse: subscriber acts as relationship target
1334 UserRelationship.inverse_subscription_exists?(target, user)
1337 def subscribed_to?(%User{} = user, %{ap_id: ap_id}) do
1338 with %User{} = target <- get_cached_by_ap_id(ap_id) do
1339 subscribed_to?(user, target)
1344 Returns map of outgoing (blocked, muted etc.) relationships' user AP IDs by relation type.
1345 E.g. `outgoing_relationships_ap_ids(user, [:block])` -> `%{block: ["https://some.site/users/userapid"]}`
1347 @spec outgoing_relationships_ap_ids(User.t(), list(atom())) :: %{atom() => list(String.t())}
1348 def outgoing_relationships_ap_ids(_user, []), do: %{}
1350 def outgoing_relationships_ap_ids(nil, _relationship_types), do: %{}
1352 def outgoing_relationships_ap_ids(%User{} = user, relationship_types)
1353 when is_list(relationship_types) do
1356 |> assoc(:outgoing_relationships)
1357 |> join(:inner, [user_rel], u in assoc(user_rel, :target))
1358 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1359 |> select([user_rel, u], [user_rel.relationship_type, fragment("array_agg(?)", u.ap_id)])
1360 |> group_by([user_rel, u], user_rel.relationship_type)
1362 |> Enum.into(%{}, fn [k, v] -> {k, v} end)
1367 fn rel_type -> {rel_type, db_result[rel_type] || []} end
1371 def incoming_relationships_ungrouped_ap_ids(user, relationship_types, ap_ids \\ nil)
1373 def incoming_relationships_ungrouped_ap_ids(_user, [], _ap_ids), do: []
1375 def incoming_relationships_ungrouped_ap_ids(nil, _relationship_types, _ap_ids), do: []
1377 def incoming_relationships_ungrouped_ap_ids(%User{} = user, relationship_types, ap_ids)
1378 when is_list(relationship_types) do
1380 |> assoc(:incoming_relationships)
1381 |> join(:inner, [user_rel], u in assoc(user_rel, :source))
1382 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1383 |> maybe_filter_on_ap_id(ap_ids)
1384 |> select([user_rel, u], u.ap_id)
1389 defp maybe_filter_on_ap_id(query, ap_ids) when is_list(ap_ids) do
1390 where(query, [user_rel, u], u.ap_id in ^ap_ids)
1393 defp maybe_filter_on_ap_id(query, _ap_ids), do: query
1395 def deactivate_async(user, status \\ true) do
1396 BackgroundWorker.enqueue("deactivate_user", %{"user_id" => user.id, "status" => status})
1399 def deactivate(user, status \\ true)
1401 def deactivate(users, status) when is_list(users) do
1402 Repo.transaction(fn ->
1403 for user <- users, do: deactivate(user, status)
1407 def deactivate(%User{} = user, status) do
1408 with {:ok, user} <- set_activation_status(user, status) do
1411 |> Enum.filter(& &1.local)
1412 |> Enum.each(&set_cache(update_following_count(&1)))
1414 # Only update local user counts, remote will be update during the next pull.
1417 |> Enum.filter(& &1.local)
1418 |> Enum.each(&do_unfollow(user, &1))
1424 def update_notification_settings(%User{} = user, settings) do
1426 |> cast(%{notification_settings: settings}, [])
1427 |> cast_embed(:notification_settings)
1428 |> validate_required([:notification_settings])
1429 |> update_and_set_cache()
1432 def delete(users) when is_list(users) do
1433 for user <- users, do: delete(user)
1436 def delete(%User{} = user) do
1437 BackgroundWorker.enqueue("delete_user", %{"user_id" => user.id})
1440 defp delete_and_invalidate_cache(%User{} = user) do
1441 invalidate_cache(user)
1445 defp delete_or_deactivate(%User{local: false} = user), do: delete_and_invalidate_cache(user)
1447 defp delete_or_deactivate(%User{local: true} = user) do
1448 status = account_status(user)
1450 if status == :confirmation_pending do
1451 delete_and_invalidate_cache(user)
1454 |> change(%{deactivated: true, email: nil})
1455 |> update_and_set_cache()
1459 def perform(:force_password_reset, user), do: force_password_reset(user)
1461 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1462 def perform(:delete, %User{} = user) do
1463 # Remove all relationships
1466 |> Enum.each(fn follower ->
1467 ActivityPub.unfollow(follower, user)
1468 unfollow(follower, user)
1473 |> Enum.each(fn followed ->
1474 ActivityPub.unfollow(user, followed)
1475 unfollow(user, followed)
1478 delete_user_activities(user)
1479 delete_notifications_from_user_activities(user)
1481 delete_outgoing_pending_follow_requests(user)
1483 delete_or_deactivate(user)
1486 def perform(:deactivate_async, user, status), do: deactivate(user, status)
1488 @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
1489 def perform(:blocks_import, %User{} = blocker, blocked_identifiers)
1490 when is_list(blocked_identifiers) do
1492 blocked_identifiers,
1493 fn blocked_identifier ->
1494 with {:ok, %User{} = blocked} <- get_or_fetch(blocked_identifier),
1495 {:ok, _user_block} <- block(blocker, blocked),
1496 {:ok, _} <- ActivityPub.block(blocker, blocked) do
1500 Logger.debug("blocks_import failed for #{blocked_identifier} with: #{inspect(err)}")
1507 def perform(:follow_import, %User{} = follower, followed_identifiers)
1508 when is_list(followed_identifiers) do
1510 followed_identifiers,
1511 fn followed_identifier ->
1512 with {:ok, %User{} = followed} <- get_or_fetch(followed_identifier),
1513 {:ok, follower} <- maybe_direct_follow(follower, followed),
1514 {:ok, _} <- ActivityPub.follow(follower, followed) do
1518 Logger.debug("follow_import failed for #{followed_identifier} with: #{inspect(err)}")
1525 @spec external_users_query() :: Ecto.Query.t()
1526 def external_users_query do
1534 @spec external_users(keyword()) :: [User.t()]
1535 def external_users(opts \\ []) do
1537 external_users_query()
1538 |> select([u], struct(u, [:id, :ap_id]))
1542 do: where(query, [u], u.id > ^opts[:max_id]),
1547 do: limit(query, ^opts[:limit]),
1553 def blocks_import(%User{} = blocker, blocked_identifiers) when is_list(blocked_identifiers) do
1554 BackgroundWorker.enqueue("blocks_import", %{
1555 "blocker_id" => blocker.id,
1556 "blocked_identifiers" => blocked_identifiers
1560 def follow_import(%User{} = follower, followed_identifiers)
1561 when is_list(followed_identifiers) do
1562 BackgroundWorker.enqueue("follow_import", %{
1563 "follower_id" => follower.id,
1564 "followed_identifiers" => followed_identifiers
1568 def delete_notifications_from_user_activities(%User{ap_id: ap_id}) do
1570 |> join(:inner, [n], activity in assoc(n, :activity))
1571 |> where([n, a], fragment("? = ?", a.actor, ^ap_id))
1572 |> Repo.delete_all()
1575 def delete_user_activities(%User{ap_id: ap_id} = user) do
1577 |> Activity.Queries.by_actor()
1578 |> RepoStreamer.chunk_stream(50)
1579 |> Stream.each(fn activities ->
1580 Enum.each(activities, fn activity -> delete_activity(activity, user) end)
1585 defp delete_activity(%{data: %{"type" => "Create", "object" => object}} = activity, user) do
1586 with {_, %Object{}} <- {:find_object, Object.get_by_ap_id(object)},
1587 {:ok, delete_data, _} <- Builder.delete(user, object) do
1588 Pipeline.common_pipeline(delete_data, local: user.local)
1590 {:find_object, nil} ->
1591 # We have the create activity, but not the object, it was probably pruned.
1592 # Insert a tombstone and try again
1593 with {:ok, tombstone_data, _} <- Builder.tombstone(user.ap_id, object),
1594 {:ok, _tombstone} <- Object.create(tombstone_data) do
1595 delete_activity(activity, user)
1599 Logger.error("Could not delete #{object} created by #{activity.data["ap_id"]}")
1600 Logger.error("Error: #{inspect(e)}")
1604 defp delete_activity(%{data: %{"type" => type}} = activity, user)
1605 when type in ["Like", "Announce"] do
1606 {:ok, undo, _} = Builder.undo(user, activity)
1607 Pipeline.common_pipeline(undo, local: user.local)
1610 defp delete_activity(_activity, _user), do: "Doing nothing"
1612 defp delete_outgoing_pending_follow_requests(user) do
1614 |> FollowingRelationship.outgoing_pending_follow_requests_query()
1615 |> Repo.delete_all()
1618 def html_filter_policy(%User{no_rich_text: true}) do
1619 Pleroma.HTML.Scrubber.TwitterText
1622 def html_filter_policy(_), do: Pleroma.Config.get([:markup, :scrub_policy])
1624 def fetch_by_ap_id(ap_id), do: ActivityPub.make_user_from_ap_id(ap_id)
1626 def get_or_fetch_by_ap_id(ap_id) do
1627 cached_user = get_cached_by_ap_id(ap_id)
1629 maybe_fetched_user = needs_update?(cached_user) && fetch_by_ap_id(ap_id)
1631 case {cached_user, maybe_fetched_user} do
1632 {_, {:ok, %User{} = user}} ->
1635 {%User{} = user, _} ->
1639 {:error, :not_found}
1644 Creates an internal service actor by URI if missing.
1645 Optionally takes nickname for addressing.
1647 @spec get_or_create_service_actor_by_ap_id(String.t(), String.t()) :: User.t() | nil
1648 def get_or_create_service_actor_by_ap_id(uri, nickname) do
1650 case get_cached_by_ap_id(uri) do
1652 with {:error, %{errors: errors}} <- create_service_actor(uri, nickname) do
1653 Logger.error("Cannot create service actor: #{uri}/.\n#{inspect(errors)}")
1657 %User{invisible: false} = user ->
1667 @spec set_invisible(User.t()) :: {:ok, User.t()}
1668 defp set_invisible(user) do
1670 |> change(%{invisible: true})
1671 |> update_and_set_cache()
1674 @spec create_service_actor(String.t(), String.t()) ::
1675 {:ok, User.t()} | {:error, Ecto.Changeset.t()}
1676 defp create_service_actor(uri, nickname) do
1682 follower_address: uri <> "/followers"
1685 |> unique_constraint(:nickname)
1690 def public_key(%{public_key: public_key_pem}) when is_binary(public_key_pem) do
1693 |> :public_key.pem_decode()
1695 |> :public_key.pem_entry_decode()
1700 def public_key(_), do: {:error, "key not found"}
1702 def get_public_key_for_ap_id(ap_id) do
1703 with {:ok, %User{} = user} <- get_or_fetch_by_ap_id(ap_id),
1704 {:ok, public_key} <- public_key(user) do
1711 def ap_enabled?(%User{local: true}), do: true
1712 def ap_enabled?(%User{ap_enabled: ap_enabled}), do: ap_enabled
1713 def ap_enabled?(_), do: false
1715 @doc "Gets or fetch a user by uri or nickname."
1716 @spec get_or_fetch(String.t()) :: {:ok, User.t()} | {:error, String.t()}
1717 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
1718 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
1720 # wait a period of time and return newest version of the User structs
1721 # this is because we have synchronous follow APIs and need to simulate them
1722 # with an async handshake
1723 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
1724 with %User{} = a <- get_cached_by_id(a.id),
1725 %User{} = b <- get_cached_by_id(b.id) do
1732 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
1733 with :ok <- :timer.sleep(timeout),
1734 %User{} = a <- get_cached_by_id(a.id),
1735 %User{} = b <- get_cached_by_id(b.id) do
1742 def parse_bio(bio) when is_binary(bio) and bio != "" do
1744 |> CommonUtils.format_input("text/plain", mentions_format: :full)
1748 def parse_bio(_), do: ""
1750 def parse_bio(bio, user) when is_binary(bio) and bio != "" do
1751 # TODO: get profile URLs other than user.ap_id
1752 profile_urls = [user.ap_id]
1755 |> CommonUtils.format_input("text/plain",
1756 mentions_format: :full,
1757 rel: &RelMe.maybe_put_rel_me(&1, profile_urls)
1762 def parse_bio(_, _), do: ""
1764 def tag(user_identifiers, tags) when is_list(user_identifiers) do
1765 Repo.transaction(fn ->
1766 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
1770 def tag(nickname, tags) when is_binary(nickname),
1771 do: tag(get_by_nickname(nickname), tags)
1773 def tag(%User{} = user, tags),
1774 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
1776 def untag(user_identifiers, tags) when is_list(user_identifiers) do
1777 Repo.transaction(fn ->
1778 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
1782 def untag(nickname, tags) when is_binary(nickname),
1783 do: untag(get_by_nickname(nickname), tags)
1785 def untag(%User{} = user, tags),
1786 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
1788 defp update_tags(%User{} = user, new_tags) do
1789 {:ok, updated_user} =
1791 |> change(%{tags: new_tags})
1792 |> update_and_set_cache()
1797 defp normalize_tags(tags) do
1800 |> Enum.map(&String.downcase/1)
1803 defp local_nickname_regex do
1804 if Pleroma.Config.get([:instance, :extended_nickname_format]) do
1805 @extended_local_nickname_regex
1807 @strict_local_nickname_regex
1811 def local_nickname(nickname_or_mention) do
1814 |> String.split("@")
1818 def full_nickname(nickname_or_mention),
1819 do: String.trim_leading(nickname_or_mention, "@")
1821 def error_user(ap_id) do
1825 nickname: "erroruser@example.com",
1826 inserted_at: NaiveDateTime.utc_now()
1830 @spec all_superusers() :: [User.t()]
1831 def all_superusers do
1832 User.Query.build(%{super_users: true, local: true, deactivated: false})
1836 def muting_reblogs?(%User{} = user, %User{} = target) do
1837 UserRelationship.reblog_mute_exists?(user, target)
1840 def showing_reblogs?(%User{} = user, %User{} = target) do
1841 not muting_reblogs?(user, target)
1845 The function returns a query to get users with no activity for given interval of days.
1846 Inactive users are those who didn't read any notification, or had any activity where
1847 the user is the activity's actor, during `inactivity_threshold` days.
1848 Deactivated users will not appear in this list.
1852 iex> Pleroma.User.list_inactive_users()
1855 @spec list_inactive_users_query(integer()) :: Ecto.Query.t()
1856 def list_inactive_users_query(inactivity_threshold \\ 7) do
1857 negative_inactivity_threshold = -inactivity_threshold
1858 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
1859 # Subqueries are not supported in `where` clauses, join gets too complicated.
1860 has_read_notifications =
1861 from(n in Pleroma.Notification,
1862 where: n.seen == true,
1864 having: max(n.updated_at) > datetime_add(^now, ^negative_inactivity_threshold, "day"),
1867 |> Pleroma.Repo.all()
1869 from(u in Pleroma.User,
1870 left_join: a in Pleroma.Activity,
1871 on: u.ap_id == a.actor,
1872 where: not is_nil(u.nickname),
1873 where: u.deactivated != ^true,
1874 where: u.id not in ^has_read_notifications,
1877 max(a.inserted_at) < datetime_add(^now, ^negative_inactivity_threshold, "day") or
1878 is_nil(max(a.inserted_at))
1883 Enable or disable email notifications for user
1887 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => false}}, "digest", true)
1888 Pleroma.User{email_notifications: %{"digest" => true}}
1890 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => true}}, "digest", false)
1891 Pleroma.User{email_notifications: %{"digest" => false}}
1893 @spec switch_email_notifications(t(), String.t(), boolean()) ::
1894 {:ok, t()} | {:error, Ecto.Changeset.t()}
1895 def switch_email_notifications(user, type, status) do
1896 User.update_email_notifications(user, %{type => status})
1900 Set `last_digest_emailed_at` value for the user to current time
1902 @spec touch_last_digest_emailed_at(t()) :: t()
1903 def touch_last_digest_emailed_at(user) do
1904 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
1906 {:ok, updated_user} =
1908 |> change(%{last_digest_emailed_at: now})
1909 |> update_and_set_cache()
1914 @spec toggle_confirmation(User.t()) :: {:ok, User.t()} | {:error, Changeset.t()}
1915 def toggle_confirmation(%User{} = user) do
1917 |> confirmation_changeset(need_confirmation: !user.confirmation_pending)
1918 |> update_and_set_cache()
1921 @spec toggle_confirmation([User.t()]) :: [{:ok, User.t()} | {:error, Changeset.t()}]
1922 def toggle_confirmation(users) do
1923 Enum.map(users, &toggle_confirmation/1)
1926 def get_mascot(%{mascot: %{} = mascot}) when not is_nil(mascot) do
1930 def get_mascot(%{mascot: mascot}) when is_nil(mascot) do
1931 # use instance-default
1932 config = Pleroma.Config.get([:assets, :mascots])
1933 default_mascot = Pleroma.Config.get([:assets, :default_mascot])
1934 mascot = Keyword.get(config, default_mascot)
1937 "id" => "default-mascot",
1938 "url" => mascot[:url],
1939 "preview_url" => mascot[:url],
1941 "mime_type" => mascot[:mime_type]
1946 def ensure_keys_present(%{keys: keys} = user) when not is_nil(keys), do: {:ok, user}
1948 def ensure_keys_present(%User{} = user) do
1949 with {:ok, pem} <- Keys.generate_rsa_pem() do
1951 |> cast(%{keys: pem}, [:keys])
1952 |> validate_required([:keys])
1953 |> update_and_set_cache()
1957 def get_ap_ids_by_nicknames(nicknames) do
1959 where: u.nickname in ^nicknames,
1965 defdelegate search(query, opts \\ []), to: User.Search
1967 defp put_password_hash(
1968 %Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset
1970 change(changeset, password_hash: Pbkdf2.hash_pwd_salt(password))
1973 defp put_password_hash(changeset), do: changeset
1975 def is_internal_user?(%User{nickname: nil}), do: true
1976 def is_internal_user?(%User{local: true, nickname: "internal." <> _}), do: true
1977 def is_internal_user?(_), do: false
1979 # A hack because user delete activities have a fake id for whatever reason
1980 # TODO: Get rid of this
1981 def get_delivered_users_by_object_id("pleroma:fake_object_id"), do: []
1983 def get_delivered_users_by_object_id(object_id) do
1985 inner_join: delivery in assoc(u, :deliveries),
1986 where: delivery.object_id == ^object_id
1991 def change_email(user, email) do
1993 |> cast(%{email: email}, [:email])
1994 |> validate_required([:email])
1995 |> unique_constraint(:email)
1996 |> validate_format(:email, @email_regex)
1997 |> update_and_set_cache()
2000 # Internal function; public one is `deactivate/2`
2001 defp set_activation_status(user, deactivated) do
2003 |> cast(%{deactivated: deactivated}, [:deactivated])
2004 |> update_and_set_cache()
2007 def update_banner(user, banner) do
2009 |> cast(%{banner: banner}, [:banner])
2010 |> update_and_set_cache()
2013 def update_background(user, background) do
2015 |> cast(%{background: background}, [:background])
2016 |> update_and_set_cache()
2019 def roles(%{is_moderator: is_moderator, is_admin: is_admin}) do
2022 moderator: is_moderator
2026 def validate_fields(changeset, remote? \\ false) do
2027 limit_name = if remote?, do: :max_remote_account_fields, else: :max_account_fields
2028 limit = Pleroma.Config.get([:instance, limit_name], 0)
2031 |> validate_length(:fields, max: limit)
2032 |> validate_change(:fields, fn :fields, fields ->
2033 if Enum.all?(fields, &valid_field?/1) do
2041 defp valid_field?(%{"name" => name, "value" => value}) do
2042 name_limit = Pleroma.Config.get([:instance, :account_field_name_length], 255)
2043 value_limit = Pleroma.Config.get([:instance, :account_field_value_length], 255)
2045 is_binary(name) && is_binary(value) && String.length(name) <= name_limit &&
2046 String.length(value) <= value_limit
2049 defp valid_field?(_), do: false
2051 defp truncate_field(%{"name" => name, "value" => value}) do
2053 String.split_at(name, Pleroma.Config.get([:instance, :account_field_name_length], 255))
2056 String.split_at(value, Pleroma.Config.get([:instance, :account_field_value_length], 255))
2058 %{"name" => name, "value" => value}
2061 def admin_api_update(user, params) do
2068 |> update_and_set_cache()
2071 @doc "Signs user out of all applications"
2072 def global_sign_out(user) do
2073 OAuth.Authorization.delete_user_authorizations(user)
2074 OAuth.Token.delete_user_tokens(user)
2077 def mascot_update(user, url) do
2079 |> cast(%{mascot: url}, [:mascot])
2080 |> validate_required([:mascot])
2081 |> update_and_set_cache()
2084 def mastodon_settings_update(user, settings) do
2086 |> cast(%{settings: settings}, [:settings])
2087 |> validate_required([:settings])
2088 |> update_and_set_cache()
2091 @spec confirmation_changeset(User.t(), keyword()) :: Changeset.t()
2092 def confirmation_changeset(user, need_confirmation: need_confirmation?) do
2094 if need_confirmation? do
2096 confirmation_pending: true,
2097 confirmation_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64()
2101 confirmation_pending: false,
2102 confirmation_token: nil
2106 cast(user, params, [:confirmation_pending, :confirmation_token])
2109 def add_pinnned_activity(user, %Pleroma.Activity{id: id}) do
2110 if id not in user.pinned_activities do
2111 max_pinned_statuses = Pleroma.Config.get([:instance, :max_pinned_statuses], 0)
2112 params = %{pinned_activities: user.pinned_activities ++ [id]}
2115 |> cast(params, [:pinned_activities])
2116 |> validate_length(:pinned_activities,
2117 max: max_pinned_statuses,
2118 message: "You have already pinned the maximum number of statuses"
2123 |> update_and_set_cache()
2126 def remove_pinnned_activity(user, %Pleroma.Activity{id: id}) do
2127 params = %{pinned_activities: List.delete(user.pinned_activities, id)}
2130 |> cast(params, [:pinned_activities])
2131 |> update_and_set_cache()
2134 def update_email_notifications(user, settings) do
2135 email_notifications =
2136 user.email_notifications
2137 |> Map.merge(settings)
2138 |> Map.take(["digest"])
2140 params = %{email_notifications: email_notifications}
2141 fields = [:email_notifications]
2144 |> cast(params, fields)
2145 |> validate_required(fields)
2146 |> update_and_set_cache()
2149 defp set_domain_blocks(user, domain_blocks) do
2150 params = %{domain_blocks: domain_blocks}
2153 |> cast(params, [:domain_blocks])
2154 |> validate_required([:domain_blocks])
2155 |> update_and_set_cache()
2158 def block_domain(user, domain_blocked) do
2159 set_domain_blocks(user, Enum.uniq([domain_blocked | user.domain_blocks]))
2162 def unblock_domain(user, domain_blocked) do
2163 set_domain_blocks(user, List.delete(user.domain_blocks, domain_blocked))
2166 @spec add_to_block(User.t(), User.t()) ::
2167 {:ok, UserRelationship.t()} | {:error, Ecto.Changeset.t()}
2168 defp add_to_block(%User{} = user, %User{} = blocked) do
2169 UserRelationship.create_block(user, blocked)
2172 @spec add_to_block(User.t(), User.t()) ::
2173 {:ok, UserRelationship.t()} | {:ok, nil} | {:error, Ecto.Changeset.t()}
2174 defp remove_from_block(%User{} = user, %User{} = blocked) do
2175 UserRelationship.delete_block(user, blocked)
2178 defp add_to_mutes(%User{} = user, %User{} = muted_user, notifications?) do
2179 with {:ok, user_mute} <- UserRelationship.create_mute(user, muted_user),
2180 {:ok, user_notification_mute} <-
2181 (notifications? && UserRelationship.create_notification_mute(user, muted_user)) ||
2183 {:ok, Enum.filter([user_mute, user_notification_mute], & &1)}
2187 defp remove_from_mutes(user, %User{} = muted_user) do
2188 with {:ok, user_mute} <- UserRelationship.delete_mute(user, muted_user),
2189 {:ok, user_notification_mute} <-
2190 UserRelationship.delete_notification_mute(user, muted_user) do
2191 {:ok, [user_mute, user_notification_mute]}
2195 def set_invisible(user, invisible) do
2196 params = %{invisible: invisible}
2199 |> cast(params, [:invisible])
2200 |> validate_required([:invisible])
2201 |> update_and_set_cache()
2204 def sanitize_html(%User{} = user) do
2205 sanitize_html(user, nil)
2208 # User data that mastodon isn't filtering (treated as plaintext):
2211 def sanitize_html(%User{} = user, filter) do
2213 Enum.map(user.fields, fn %{"name" => name, "value" => value} ->
2216 "value" => HTML.filter_tags(value, Pleroma.HTML.Scrubber.LinksOnly)
2221 |> Map.put(:bio, HTML.filter_tags(user.bio, filter))
2222 |> Map.put(:fields, fields)