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]
14 alias Pleroma.Activity
16 alias Pleroma.Conversation.Participation
17 alias Pleroma.Delivery
18 alias Pleroma.FollowingRelationship
20 alias Pleroma.Notification
22 alias Pleroma.Registration
24 alias Pleroma.RepoStreamer
26 alias Pleroma.UserRelationship
28 alias Pleroma.Web.ActivityPub.ActivityPub
29 alias Pleroma.Web.ActivityPub.Utils
30 alias Pleroma.Web.CommonAPI
31 alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils
32 alias Pleroma.Web.OAuth
33 alias Pleroma.Web.RelMe
34 alias Pleroma.Workers.BackgroundWorker
38 @type t :: %__MODULE__{}
39 @type account_status :: :active | :deactivated | :password_reset_pending | :confirmation_pending
40 @primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
42 # credo:disable-for-next-line Credo.Check.Readability.MaxLineLength
43 @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])?)*$/
45 @strict_local_nickname_regex ~r/^[a-zA-Z\d]+$/
46 @extended_local_nickname_regex ~r/^[a-zA-Z\d_-]+$/
48 # AP ID user relationships (blocks, mutes etc.)
49 # Format: [rel_type: [outgoing_rel: :outgoing_rel_target, incoming_rel: :incoming_rel_source]]
50 @user_relationships_config [
52 blocker_blocks: :blocked_users,
53 blockee_blocks: :blocker_users
56 muter_mutes: :muted_users,
57 mutee_mutes: :muter_users
60 reblog_muter_mutes: :reblog_muted_users,
61 reblog_mutee_mutes: :reblog_muter_users
64 notification_muter_mutes: :notification_muted_users,
65 notification_mutee_mutes: :notification_muter_users
67 # Note: `inverse_subscription` relationship is inverse: subscriber acts as relationship target
68 inverse_subscription: [
69 subscribee_subscriptions: :subscriber_users,
70 subscriber_subscriptions: :subscribee_users
76 field(:email, :string)
78 field(:nickname, :string)
79 field(:password_hash, :string)
80 field(:password, :string, virtual: true)
81 field(:password_confirmation, :string, virtual: true)
83 field(:ap_id, :string)
85 field(:local, :boolean, default: true)
86 field(:follower_address, :string)
87 field(:following_address, :string)
88 field(:search_rank, :float, virtual: true)
89 field(:search_type, :integer, virtual: true)
90 field(:tags, {:array, :string}, default: [])
91 field(:last_refreshed_at, :naive_datetime_usec)
92 field(:last_digest_emailed_at, :naive_datetime)
93 field(:banner, :map, default: %{})
94 field(:background, :map, default: %{})
95 field(:source_data, :map, default: %{})
96 field(:note_count, :integer, default: 0)
97 field(:follower_count, :integer, default: 0)
98 field(:following_count, :integer, default: 0)
99 field(:locked, :boolean, default: false)
100 field(:confirmation_pending, :boolean, default: false)
101 field(:password_reset_pending, :boolean, default: false)
102 field(:confirmation_token, :string, default: nil)
103 field(:default_scope, :string, default: "public")
104 field(:domain_blocks, {:array, :string}, default: [])
105 field(:deactivated, :boolean, default: false)
106 field(:no_rich_text, :boolean, default: false)
107 field(:ap_enabled, :boolean, default: false)
108 field(:is_moderator, :boolean, default: false)
109 field(:is_admin, :boolean, default: false)
110 field(:show_role, :boolean, default: true)
111 field(:settings, :map, default: nil)
112 field(:magic_key, :string, default: nil)
113 field(:uri, :string, default: nil)
114 field(:hide_followers_count, :boolean, default: false)
115 field(:hide_follows_count, :boolean, default: false)
116 field(:hide_followers, :boolean, default: false)
117 field(:hide_follows, :boolean, default: false)
118 field(:hide_favorites, :boolean, default: true)
119 field(:unread_conversation_count, :integer, default: 0)
120 field(:pinned_activities, {:array, :string}, default: [])
121 field(:email_notifications, :map, default: %{"digest" => false})
122 field(:mascot, :map, default: nil)
123 field(:emoji, {:array, :map}, default: [])
124 field(:pleroma_settings_store, :map, default: %{})
125 field(:fields, {:array, :map}, default: [])
126 field(:raw_fields, {:array, :map}, default: [])
127 field(:discoverable, :boolean, default: false)
128 field(:invisible, :boolean, default: false)
129 field(:allow_following_move, :boolean, default: true)
130 field(:skip_thread_containment, :boolean, default: false)
131 field(:actor_type, :string, default: "Person")
132 field(:also_known_as, {:array, :string}, default: [])
135 :notification_settings,
136 Pleroma.User.NotificationSetting,
140 has_many(:notifications, Notification)
141 has_many(:registrations, Registration)
142 has_many(:deliveries, Delivery)
144 has_many(:outgoing_relationships, UserRelationship, foreign_key: :source_id)
145 has_many(:incoming_relationships, UserRelationship, foreign_key: :target_id)
147 for {relationship_type,
149 {outgoing_relation, outgoing_relation_target},
150 {incoming_relation, incoming_relation_source}
151 ]} <- @user_relationships_config do
152 # Definitions of `has_many` relations: :blocker_blocks, :muter_mutes, :reblog_muter_mutes,
153 # :notification_muter_mutes, :subscribee_subscriptions
154 has_many(outgoing_relation, UserRelationship,
155 foreign_key: :source_id,
156 where: [relationship_type: relationship_type]
159 # Definitions of `has_many` relations: :blockee_blocks, :mutee_mutes, :reblog_mutee_mutes,
160 # :notification_mutee_mutes, :subscriber_subscriptions
161 has_many(incoming_relation, UserRelationship,
162 foreign_key: :target_id,
163 where: [relationship_type: relationship_type]
166 # Definitions of `has_many` relations: :blocked_users, :muted_users, :reblog_muted_users,
167 # :notification_muted_users, :subscriber_users
168 has_many(outgoing_relation_target, through: [outgoing_relation, :target])
170 # Definitions of `has_many` relations: :blocker_users, :muter_users, :reblog_muter_users,
171 # :notification_muter_users, :subscribee_users
172 has_many(incoming_relation_source, through: [incoming_relation, :source])
175 # `:blocks` is deprecated (replaced with `blocked_users` relation)
176 field(:blocks, {:array, :string}, default: [])
177 # `:mutes` is deprecated (replaced with `muted_users` relation)
178 field(:mutes, {:array, :string}, default: [])
179 # `:muted_reblogs` is deprecated (replaced with `reblog_muted_users` relation)
180 field(:muted_reblogs, {:array, :string}, default: [])
181 # `:muted_notifications` is deprecated (replaced with `notification_muted_users` relation)
182 field(:muted_notifications, {:array, :string}, default: [])
183 # `:subscribers` is deprecated (replaced with `subscriber_users` relation)
184 field(:subscribers, {:array, :string}, default: [])
189 for {_relationship_type, [{_outgoing_relation, outgoing_relation_target}, _]} <-
190 @user_relationships_config do
191 # `def blocked_users_relation/2`, `def muted_users_relation/2`,
192 # `def reblog_muted_users_relation/2`, `def notification_muted_users/2`,
193 # `def subscriber_users/2`
194 def unquote(:"#{outgoing_relation_target}_relation")(user, restrict_deactivated? \\ false) do
195 target_users_query = assoc(user, unquote(outgoing_relation_target))
197 if restrict_deactivated? do
198 restrict_deactivated(target_users_query)
204 # `def blocked_users/2`, `def muted_users/2`, `def reblog_muted_users/2`,
205 # `def notification_muted_users/2`, `def subscriber_users/2`
206 def unquote(outgoing_relation_target)(user, restrict_deactivated? \\ false) do
208 |> apply(unquote(:"#{outgoing_relation_target}_relation"), [
210 restrict_deactivated?
215 # `def blocked_users_ap_ids/2`, `def muted_users_ap_ids/2`, `def reblog_muted_users_ap_ids/2`,
216 # `def notification_muted_users_ap_ids/2`, `def subscriber_users_ap_ids/2`
217 def unquote(:"#{outgoing_relation_target}_ap_ids")(user, restrict_deactivated? \\ false) do
219 |> apply(unquote(:"#{outgoing_relation_target}_relation"), [
221 restrict_deactivated?
223 |> select([u], u.ap_id)
228 @doc "Returns status account"
229 @spec account_status(User.t()) :: account_status()
230 def account_status(%User{deactivated: true}), do: :deactivated
231 def account_status(%User{password_reset_pending: true}), do: :password_reset_pending
233 def account_status(%User{confirmation_pending: true}) do
234 case Config.get([:instance, :account_activation_required]) do
235 true -> :confirmation_pending
240 def account_status(%User{}), do: :active
242 @spec visible_for?(User.t(), User.t() | nil) :: boolean()
243 def visible_for?(user, for_user \\ nil)
245 def visible_for?(%User{invisible: true}, _), do: false
247 def visible_for?(%User{id: user_id}, %User{id: for_id}) when user_id == for_id, do: true
249 def visible_for?(%User{} = user, for_user) do
250 account_status(user) == :active || superuser?(for_user)
253 def visible_for?(_, _), do: false
255 @spec superuser?(User.t()) :: boolean()
256 def superuser?(%User{local: true, is_admin: true}), do: true
257 def superuser?(%User{local: true, is_moderator: true}), do: true
258 def superuser?(_), do: false
260 @spec invisible?(User.t()) :: boolean()
261 def invisible?(%User{invisible: true}), do: true
262 def invisible?(_), do: false
264 def avatar_url(user, options \\ []) do
266 %{"url" => [%{"href" => href} | _]} -> href
267 _ -> !options[:no_default] && "#{Web.base_url()}/images/avi.png"
271 def banner_url(user, options \\ []) do
273 %{"url" => [%{"href" => href} | _]} -> href
274 _ -> !options[:no_default] && "#{Web.base_url()}/images/banner.png"
278 def profile_url(%User{source_data: %{"url" => url}}), do: url
279 def profile_url(%User{ap_id: ap_id}), do: ap_id
280 def profile_url(_), do: nil
282 def ap_id(%User{nickname: nickname}), do: "#{Web.base_url()}/users/#{nickname}"
284 def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
285 def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
287 @spec ap_following(User.t()) :: Sring.t()
288 def ap_following(%User{following_address: fa}) when is_binary(fa), do: fa
289 def ap_following(%User{} = user), do: "#{ap_id(user)}/following"
291 def follow_state(%User{} = user, %User{} = target) do
292 case Utils.fetch_latest_follow(user, target) do
293 %{data: %{"state" => state}} -> state
294 # Ideally this would be nil, but then Cachex does not commit the value
299 def get_cached_follow_state(user, target) do
300 key = "follow_state:#{user.ap_id}|#{target.ap_id}"
301 Cachex.fetch!(:user_cache, key, fn _ -> {:commit, follow_state(user, target)} end)
304 @spec set_follow_state_cache(String.t(), String.t(), String.t()) :: {:ok | :error, boolean()}
305 def set_follow_state_cache(user_ap_id, target_ap_id, state) do
306 Cachex.put(:user_cache, "follow_state:#{user_ap_id}|#{target_ap_id}", state)
309 @spec restrict_deactivated(Ecto.Query.t()) :: Ecto.Query.t()
310 def restrict_deactivated(query) do
311 from(u in query, where: u.deactivated != ^true)
314 defdelegate following_count(user), to: FollowingRelationship
316 defp truncate_fields_param(params) do
317 if Map.has_key?(params, :fields) do
318 Map.put(params, :fields, Enum.map(params[:fields], &truncate_field/1))
324 defp truncate_if_exists(params, key, max_length) do
325 if Map.has_key?(params, key) and is_binary(params[key]) do
326 {value, _chopped} = String.split_at(params[key], max_length)
327 Map.put(params, key, value)
333 def remote_user_creation(params) do
334 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
335 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
339 |> truncate_if_exists(:name, name_limit)
340 |> truncate_if_exists(:bio, bio_limit)
341 |> truncate_fields_param()
361 :hide_followers_count,
372 |> validate_required([:name, :ap_id])
373 |> unique_constraint(:nickname)
374 |> validate_format(:nickname, @email_regex)
375 |> validate_length(:bio, max: bio_limit)
376 |> validate_length(:name, max: name_limit)
377 |> validate_fields(true)
379 case params[:source_data] do
380 %{"followers" => followers, "following" => following} ->
382 |> put_change(:follower_address, followers)
383 |> put_change(:following_address, following)
386 followers = ap_followers(%User{nickname: get_field(changeset, :nickname)})
387 put_change(changeset, :follower_address, followers)
391 def update_changeset(struct, params \\ %{}) do
392 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
393 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
408 :hide_followers_count,
411 :allow_following_move,
414 :skip_thread_containment,
417 :pleroma_settings_store,
423 |> unique_constraint(:nickname)
424 |> validate_format(:nickname, local_nickname_regex())
425 |> validate_length(:bio, max: bio_limit)
426 |> validate_length(:name, min: 1, max: name_limit)
427 |> validate_fields(false)
430 def upgrade_changeset(struct, params \\ %{}, remote? \\ false) do
431 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
432 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
434 params = Map.put(params, :last_refreshed_at, NaiveDateTime.utc_now())
436 params = if remote?, do: truncate_fields_param(params), else: params
458 :allow_following_move,
460 :hide_followers_count,
466 |> unique_constraint(:nickname)
467 |> validate_format(:nickname, local_nickname_regex())
468 |> validate_length(:bio, max: bio_limit)
469 |> validate_length(:name, max: name_limit)
470 |> validate_fields(remote?)
473 def password_update_changeset(struct, params) do
475 |> cast(params, [:password, :password_confirmation])
476 |> validate_required([:password, :password_confirmation])
477 |> validate_confirmation(:password)
478 |> put_password_hash()
479 |> put_change(:password_reset_pending, false)
482 @spec reset_password(User.t(), map) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
483 def reset_password(%User{id: user_id} = user, data) do
486 |> Multi.update(:user, password_update_changeset(user, data))
487 |> Multi.delete_all(:tokens, OAuth.Token.Query.get_by_user(user_id))
488 |> Multi.delete_all(:auth, OAuth.Authorization.delete_by_user_query(user))
490 case Repo.transaction(multi) do
491 {:ok, %{user: user} = _} -> set_cache(user)
492 {:error, _, changeset, _} -> {:error, changeset}
496 def update_password_reset_pending(user, value) do
499 |> put_change(:password_reset_pending, value)
500 |> update_and_set_cache()
503 def force_password_reset_async(user) do
504 BackgroundWorker.enqueue("force_password_reset", %{"user_id" => user.id})
507 @spec force_password_reset(User.t()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
508 def force_password_reset(user), do: update_password_reset_pending(user, true)
510 def register_changeset(struct, params \\ %{}, opts \\ []) do
511 bio_limit = Pleroma.Config.get([:instance, :user_bio_length], 5000)
512 name_limit = Pleroma.Config.get([:instance, :user_name_length], 100)
515 if is_nil(opts[:need_confirmation]) do
516 Pleroma.Config.get([:instance, :account_activation_required])
518 opts[:need_confirmation]
522 |> confirmation_changeset(need_confirmation: need_confirmation?)
523 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
524 |> validate_required([:name, :nickname, :password, :password_confirmation])
525 |> validate_confirmation(:password)
526 |> unique_constraint(:email)
527 |> unique_constraint(:nickname)
528 |> validate_exclusion(:nickname, Pleroma.Config.get([User, :restricted_nicknames]))
529 |> validate_format(:nickname, local_nickname_regex())
530 |> validate_format(:email, @email_regex)
531 |> validate_length(:bio, max: bio_limit)
532 |> validate_length(:name, min: 1, max: name_limit)
533 |> maybe_validate_required_email(opts[:external])
536 |> unique_constraint(:ap_id)
537 |> put_following_and_follower_address()
540 def maybe_validate_required_email(changeset, true), do: changeset
542 def maybe_validate_required_email(changeset, _) do
543 if Pleroma.Config.get([:instance, :account_activation_required]) do
544 validate_required(changeset, [:email])
550 defp put_ap_id(changeset) do
551 ap_id = ap_id(%User{nickname: get_field(changeset, :nickname)})
552 put_change(changeset, :ap_id, ap_id)
555 defp put_following_and_follower_address(changeset) do
556 followers = ap_followers(%User{nickname: get_field(changeset, :nickname)})
559 |> put_change(:follower_address, followers)
562 defp autofollow_users(user) do
563 candidates = Pleroma.Config.get([:instance, :autofollowed_nicknames])
566 User.Query.build(%{nickname: candidates, local: true, deactivated: false})
569 follow_all(user, autofollowed_users)
572 @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
573 def register(%Ecto.Changeset{} = changeset) do
574 with {:ok, user} <- Repo.insert(changeset) do
575 post_register_action(user)
579 def post_register_action(%User{} = user) do
580 with {:ok, user} <- autofollow_users(user),
581 {:ok, user} <- set_cache(user),
582 {:ok, _} <- User.WelcomeMessage.post_welcome_message_to_user(user),
583 {:ok, _} <- try_send_confirmation_email(user) do
588 def try_send_confirmation_email(%User{} = user) do
589 if user.confirmation_pending &&
590 Pleroma.Config.get([:instance, :account_activation_required]) do
592 |> Pleroma.Emails.UserEmail.account_confirmation_email()
593 |> Pleroma.Emails.Mailer.deliver_async()
601 def try_send_confirmation_email(users) do
602 Enum.each(users, &try_send_confirmation_email/1)
605 def needs_update?(%User{local: true}), do: false
607 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
609 def needs_update?(%User{local: false} = user) do
610 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
613 def needs_update?(_), do: true
615 @spec maybe_direct_follow(User.t(), User.t()) :: {:ok, User.t()} | {:error, String.t()}
616 def maybe_direct_follow(%User{} = follower, %User{local: true, locked: true} = followed) do
617 follow(follower, followed, "pending")
620 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
621 follow(follower, followed)
624 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
625 if not ap_enabled?(followed) do
626 follow(follower, followed)
632 @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
633 @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
634 def follow_all(follower, followeds) do
636 |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
637 |> Enum.each(&follow(follower, &1, "accept"))
642 defdelegate following(user), to: FollowingRelationship
644 def follow(%User{} = follower, %User{} = followed, state \\ "accept") do
645 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
648 followed.deactivated ->
649 {:error, "Could not follow user: #{followed.nickname} is deactivated."}
651 deny_follow_blocked and blocks?(followed, follower) ->
652 {:error, "Could not follow user: #{followed.nickname} blocked you."}
655 FollowingRelationship.follow(follower, followed, state)
657 {:ok, _} = update_follower_count(followed)
660 |> update_following_count()
665 def unfollow(%User{ap_id: ap_id}, %User{ap_id: ap_id}) do
666 {:error, "Not subscribed!"}
669 def unfollow(%User{} = follower, %User{} = followed) do
670 case get_follow_state(follower, followed) do
671 state when state in ["accept", "pending"] ->
672 FollowingRelationship.unfollow(follower, followed)
673 {:ok, followed} = update_follower_count(followed)
677 |> update_following_count()
680 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
683 {:error, "Not subscribed!"}
687 defdelegate following?(follower, followed), to: FollowingRelationship
689 def get_follow_state(%User{} = follower, %User{} = following) do
690 following_relationship = FollowingRelationship.get(follower, following)
692 case {following_relationship, following.local} do
694 case Utils.fetch_latest_follow(follower, following) do
695 %{data: %{"state" => state}} when state in ["pending", "accept"] -> state
699 {%{state: state}, _} ->
707 def locked?(%User{} = user) do
712 Repo.get_by(User, id: id)
715 def get_by_ap_id(ap_id) do
716 Repo.get_by(User, ap_id: ap_id)
719 def get_all_by_ap_id(ap_ids) do
720 from(u in __MODULE__,
721 where: u.ap_id in ^ap_ids
726 def get_all_by_ids(ids) do
727 from(u in __MODULE__, where: u.id in ^ids)
731 # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
732 # of the ap_id and the domain and tries to get that user
733 def get_by_guessed_nickname(ap_id) do
734 domain = URI.parse(ap_id).host
735 name = List.last(String.split(ap_id, "/"))
736 nickname = "#{name}@#{domain}"
738 get_cached_by_nickname(nickname)
741 def set_cache({:ok, user}), do: set_cache(user)
742 def set_cache({:error, err}), do: {:error, err}
744 def set_cache(%User{} = user) do
745 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
746 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
750 def update_and_set_cache(struct, params) do
752 |> update_changeset(params)
753 |> update_and_set_cache()
756 def update_and_set_cache(changeset) do
757 with {:ok, user} <- Repo.update(changeset, stale_error_field: :id) do
762 def invalidate_cache(user) do
763 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
764 Cachex.del(:user_cache, "nickname:#{user.nickname}")
767 @spec get_cached_by_ap_id(String.t()) :: User.t() | nil
768 def get_cached_by_ap_id(ap_id) do
769 key = "ap_id:#{ap_id}"
771 with {:ok, nil} <- Cachex.get(:user_cache, key),
772 user when not is_nil(user) <- get_by_ap_id(ap_id),
773 {:ok, true} <- Cachex.put(:user_cache, key, user) do
781 def get_cached_by_id(id) do
785 Cachex.fetch!(:user_cache, key, fn _ ->
789 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
790 {:commit, user.ap_id}
796 get_cached_by_ap_id(ap_id)
799 def get_cached_by_nickname(nickname) do
800 key = "nickname:#{nickname}"
802 Cachex.fetch!(:user_cache, key, fn ->
803 case get_or_fetch_by_nickname(nickname) do
804 {:ok, user} -> {:commit, user}
805 {:error, _error} -> {:ignore, nil}
810 def get_cached_by_nickname_or_id(nickname_or_id, opts \\ []) do
811 restrict_to_local = Pleroma.Config.get([:instance, :limit_to_local_content])
814 is_integer(nickname_or_id) or FlakeId.flake_id?(nickname_or_id) ->
815 get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
817 restrict_to_local == false or not String.contains?(nickname_or_id, "@") ->
818 get_cached_by_nickname(nickname_or_id)
820 restrict_to_local == :unauthenticated and match?(%User{}, opts[:for]) ->
821 get_cached_by_nickname(nickname_or_id)
828 def get_by_nickname(nickname) do
829 Repo.get_by(User, nickname: nickname) ||
830 if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
831 Repo.get_by(User, nickname: local_nickname(nickname))
835 def get_by_email(email), do: Repo.get_by(User, email: email)
837 def get_by_nickname_or_email(nickname_or_email) do
838 get_by_nickname(nickname_or_email) || get_by_email(nickname_or_email)
841 def fetch_by_nickname(nickname), do: ActivityPub.make_user_from_nickname(nickname)
843 def get_or_fetch_by_nickname(nickname) do
844 with %User{} = user <- get_by_nickname(nickname) do
848 with [_nick, _domain] <- String.split(nickname, "@"),
849 {:ok, user} <- fetch_by_nickname(nickname) do
852 _e -> {:error, "not found " <> nickname}
857 @spec get_followers_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
858 def get_followers_query(%User{} = user, nil) do
859 User.Query.build(%{followers: user, deactivated: false})
862 def get_followers_query(user, page) do
864 |> get_followers_query(nil)
865 |> User.Query.paginate(page, 20)
868 @spec get_followers_query(User.t()) :: Ecto.Query.t()
869 def get_followers_query(user), do: get_followers_query(user, nil)
871 @spec get_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
872 def get_followers(user, page \\ nil) do
874 |> get_followers_query(page)
878 @spec get_external_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
879 def get_external_followers(user, page \\ nil) do
881 |> get_followers_query(page)
882 |> User.Query.build(%{external: true})
886 def get_followers_ids(user, page \\ nil) do
888 |> get_followers_query(page)
893 @spec get_friends_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
894 def get_friends_query(%User{} = user, nil) do
895 User.Query.build(%{friends: user, deactivated: false})
898 def get_friends_query(user, page) do
900 |> get_friends_query(nil)
901 |> User.Query.paginate(page, 20)
904 @spec get_friends_query(User.t()) :: Ecto.Query.t()
905 def get_friends_query(user), do: get_friends_query(user, nil)
907 def get_friends(user, page \\ nil) do
909 |> get_friends_query(page)
913 def get_friends_ap_ids(user) do
915 |> get_friends_query(nil)
916 |> select([u], u.ap_id)
920 def get_friends_ids(user, page \\ nil) do
922 |> get_friends_query(page)
927 defdelegate get_follow_requests(user), to: FollowingRelationship
929 def increase_note_count(%User{} = user) do
931 |> where(id: ^user.id)
932 |> update([u], inc: [note_count: 1])
934 |> Repo.update_all([])
936 {1, [user]} -> set_cache(user)
941 def decrease_note_count(%User{} = user) do
943 |> where(id: ^user.id)
946 note_count: fragment("greatest(0, note_count - 1)")
950 |> Repo.update_all([])
952 {1, [user]} -> set_cache(user)
957 def update_note_count(%User{} = user, note_count \\ nil) do
962 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
968 |> cast(%{note_count: note_count}, [:note_count])
969 |> update_and_set_cache()
972 @spec maybe_fetch_follow_information(User.t()) :: User.t()
973 def maybe_fetch_follow_information(user) do
974 with {:ok, user} <- fetch_follow_information(user) do
978 Logger.error("Follower/Following counter update for #{user.ap_id} failed.\n#{inspect(e)}")
984 def fetch_follow_information(user) do
985 with {:ok, info} <- ActivityPub.fetch_follow_information_for_user(user) do
987 |> follow_information_changeset(info)
988 |> update_and_set_cache()
992 defp follow_information_changeset(user, params) do
999 :hide_followers_count,
1004 def update_follower_count(%User{} = user) do
1005 if user.local or !Pleroma.Config.get([:instance, :external_user_synchronization]) do
1006 follower_count_query =
1007 User.Query.build(%{followers: user, deactivated: false})
1008 |> select([u], %{count: count(u.id)})
1011 |> where(id: ^user.id)
1012 |> join(:inner, [u], s in subquery(follower_count_query))
1014 set: [follower_count: s.count]
1017 |> Repo.update_all([])
1019 {1, [user]} -> set_cache(user)
1023 {:ok, maybe_fetch_follow_information(user)}
1027 @spec update_following_count(User.t()) :: User.t()
1028 def update_following_count(%User{local: false} = user) do
1029 if Pleroma.Config.get([:instance, :external_user_synchronization]) do
1030 maybe_fetch_follow_information(user)
1036 def update_following_count(%User{local: true} = user) do
1037 following_count = FollowingRelationship.following_count(user)
1040 |> follow_information_changeset(%{following_count: following_count})
1044 def set_unread_conversation_count(%User{local: true} = user) do
1045 unread_query = Participation.unread_conversation_count_for_user(user)
1048 |> join(:inner, [u], p in subquery(unread_query))
1050 set: [unread_conversation_count: p.count]
1052 |> where([u], u.id == ^user.id)
1054 |> Repo.update_all([])
1056 {1, [user]} -> set_cache(user)
1061 def set_unread_conversation_count(user), do: {:ok, user}
1063 def increment_unread_conversation_count(conversation, %User{local: true} = user) do
1065 Participation.unread_conversation_count_for_user(user)
1066 |> where([p], p.conversation_id == ^conversation.id)
1069 |> join(:inner, [u], p in subquery(unread_query))
1071 inc: [unread_conversation_count: 1]
1073 |> where([u], u.id == ^user.id)
1074 |> where([u, p], p.count == 0)
1076 |> Repo.update_all([])
1078 {1, [user]} -> set_cache(user)
1083 def increment_unread_conversation_count(_, user), do: {:ok, user}
1085 @spec get_users_from_set([String.t()], boolean()) :: [User.t()]
1086 def get_users_from_set(ap_ids, local_only \\ true) do
1087 criteria = %{ap_id: ap_ids, deactivated: false}
1088 criteria = if local_only, do: Map.put(criteria, :local, true), else: criteria
1090 User.Query.build(criteria)
1094 @spec get_recipients_from_activity(Activity.t()) :: [User.t()]
1095 def get_recipients_from_activity(%Activity{recipients: to}) do
1096 User.Query.build(%{recipients_from_activity: to, local: true, deactivated: false})
1100 @spec mute(User.t(), User.t(), boolean()) ::
1101 {:ok, list(UserRelationship.t())} | {:error, String.t()}
1102 def mute(%User{} = muter, %User{} = mutee, notifications? \\ true) do
1103 add_to_mutes(muter, mutee, notifications?)
1106 def unmute(%User{} = muter, %User{} = mutee) do
1107 remove_from_mutes(muter, mutee)
1110 def subscribe(%User{} = subscriber, %User{} = target) do
1111 deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
1113 if blocks?(target, subscriber) and deny_follow_blocked do
1114 {:error, "Could not subscribe: #{target.nickname} is blocking you"}
1116 # Note: the relationship is inverse: subscriber acts as relationship target
1117 UserRelationship.create_inverse_subscription(target, subscriber)
1121 def subscribe(%User{} = subscriber, %{ap_id: ap_id}) do
1122 with %User{} = subscribee <- get_cached_by_ap_id(ap_id) do
1123 subscribe(subscriber, subscribee)
1127 def unsubscribe(%User{} = unsubscriber, %User{} = target) do
1128 # Note: the relationship is inverse: subscriber acts as relationship target
1129 UserRelationship.delete_inverse_subscription(target, unsubscriber)
1132 def unsubscribe(%User{} = unsubscriber, %{ap_id: ap_id}) do
1133 with %User{} = user <- get_cached_by_ap_id(ap_id) do
1134 unsubscribe(unsubscriber, user)
1138 def block(%User{} = blocker, %User{} = blocked) do
1139 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
1141 if following?(blocker, blocked) do
1142 {:ok, blocker, _} = unfollow(blocker, blocked)
1148 # clear any requested follows as well
1150 case CommonAPI.reject_follow_request(blocked, blocker) do
1151 {:ok, %User{} = updated_blocked} -> updated_blocked
1155 unsubscribe(blocked, blocker)
1157 if following?(blocked, blocker), do: unfollow(blocked, blocker)
1159 {:ok, blocker} = update_follower_count(blocker)
1160 {:ok, blocker, _} = Participation.mark_all_as_read(blocker, blocked)
1161 add_to_block(blocker, blocked)
1164 # helper to handle the block given only an actor's AP id
1165 def block(%User{} = blocker, %{ap_id: ap_id}) do
1166 block(blocker, get_cached_by_ap_id(ap_id))
1169 def unblock(%User{} = blocker, %User{} = blocked) do
1170 remove_from_block(blocker, blocked)
1173 # helper to handle the block given only an actor's AP id
1174 def unblock(%User{} = blocker, %{ap_id: ap_id}) do
1175 unblock(blocker, get_cached_by_ap_id(ap_id))
1178 def mutes?(nil, _), do: false
1179 def mutes?(%User{} = user, %User{} = target), do: mutes_user?(user, target)
1181 def mutes_user?(%User{} = user, %User{} = target) do
1182 UserRelationship.mute_exists?(user, target)
1185 @spec muted_notifications?(User.t() | nil, User.t() | map()) :: boolean()
1186 def muted_notifications?(nil, _), do: false
1188 def muted_notifications?(%User{} = user, %User{} = target),
1189 do: UserRelationship.notification_mute_exists?(user, target)
1191 def blocks?(nil, _), do: false
1193 def blocks?(%User{} = user, %User{} = target) do
1194 blocks_user?(user, target) ||
1195 (!User.following?(user, target) && blocks_domain?(user, target))
1198 def blocks_user?(%User{} = user, %User{} = target) do
1199 UserRelationship.block_exists?(user, target)
1202 def blocks_user?(_, _), do: false
1204 def blocks_domain?(%User{} = user, %User{} = target) do
1205 domain_blocks = Pleroma.Web.ActivityPub.MRF.subdomains_regex(user.domain_blocks)
1206 %{host: host} = URI.parse(target.ap_id)
1207 Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, host)
1210 def blocks_domain?(_, _), do: false
1212 def subscribed_to?(%User{} = user, %User{} = target) do
1213 # Note: the relationship is inverse: subscriber acts as relationship target
1214 UserRelationship.inverse_subscription_exists?(target, user)
1217 def subscribed_to?(%User{} = user, %{ap_id: ap_id}) do
1218 with %User{} = target <- get_cached_by_ap_id(ap_id) do
1219 subscribed_to?(user, target)
1224 Returns map of outgoing (blocked, muted etc.) relations' user AP IDs by relation type.
1225 E.g. `outgoing_relations_ap_ids(user, [:block])` -> `%{block: ["https://some.site/users/userapid"]}`
1227 @spec outgoing_relations_ap_ids(User.t(), list(atom())) :: %{atom() => list(String.t())}
1228 def outgoing_relations_ap_ids(_user, []), do: %{}
1230 def outgoing_relations_ap_ids(nil, _relationship_types), do: %{}
1232 def outgoing_relations_ap_ids(%User{} = user, relationship_types)
1233 when is_list(relationship_types) do
1236 |> assoc(:outgoing_relationships)
1237 |> join(:inner, [user_rel], u in assoc(user_rel, :target))
1238 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1239 |> select([user_rel, u], [user_rel.relationship_type, fragment("array_agg(?)", u.ap_id)])
1240 |> group_by([user_rel, u], user_rel.relationship_type)
1242 |> Enum.into(%{}, fn [k, v] -> {k, v} end)
1247 fn rel_type -> {rel_type, db_result[rel_type] || []} end
1251 def incoming_relations_ungrouped_ap_ids(user, relationship_types, ap_ids \\ nil)
1253 def incoming_relations_ungrouped_ap_ids(_user, [], _ap_ids), do: []
1255 def incoming_relations_ungrouped_ap_ids(nil, _relationship_types, _ap_ids), do: []
1257 def incoming_relations_ungrouped_ap_ids(%User{} = user, relationship_types, ap_ids)
1258 when is_list(relationship_types) do
1260 |> assoc(:incoming_relationships)
1261 |> join(:inner, [user_rel], u in assoc(user_rel, :source))
1262 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1263 |> maybe_filter_on_ap_id(ap_ids)
1264 |> select([user_rel, u], u.ap_id)
1269 defp maybe_filter_on_ap_id(query, ap_ids) when is_list(ap_ids) do
1270 where(query, [user_rel, u], u.ap_id in ^ap_ids)
1273 defp maybe_filter_on_ap_id(query, _ap_ids), do: query
1275 def deactivate_async(user, status \\ true) do
1276 BackgroundWorker.enqueue("deactivate_user", %{"user_id" => user.id, "status" => status})
1279 def deactivate(user, status \\ true)
1281 def deactivate(users, status) when is_list(users) do
1282 Repo.transaction(fn ->
1283 for user <- users, do: deactivate(user, status)
1287 def deactivate(%User{} = user, status) do
1288 with {:ok, user} <- set_activation_status(user, status) do
1291 |> Enum.filter(& &1.local)
1292 |> Enum.each(fn follower ->
1293 follower |> update_following_count() |> set_cache()
1296 # Only update local user counts, remote will be update during the next pull.
1299 |> Enum.filter(& &1.local)
1300 |> Enum.each(&update_follower_count/1)
1306 def update_notification_settings(%User{} = user, settings) do
1308 |> cast(%{notification_settings: settings}, [])
1309 |> cast_embed(:notification_settings)
1310 |> validate_required([:notification_settings])
1311 |> update_and_set_cache()
1314 def delete(users) when is_list(users) do
1315 for user <- users, do: delete(user)
1318 def delete(%User{} = user) do
1319 BackgroundWorker.enqueue("delete_user", %{"user_id" => user.id})
1322 def perform(:force_password_reset, user), do: force_password_reset(user)
1324 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1325 def perform(:delete, %User{} = user) do
1326 {:ok, _user} = ActivityPub.delete(user)
1328 # Remove all relationships
1331 |> Enum.each(fn follower ->
1332 ActivityPub.unfollow(follower, user)
1333 unfollow(follower, user)
1338 |> Enum.each(fn followed ->
1339 ActivityPub.unfollow(user, followed)
1340 unfollow(user, followed)
1343 delete_user_activities(user)
1344 invalidate_cache(user)
1348 def perform(:deactivate_async, user, status), do: deactivate(user, status)
1350 @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
1351 def perform(:blocks_import, %User{} = blocker, blocked_identifiers)
1352 when is_list(blocked_identifiers) do
1354 blocked_identifiers,
1355 fn blocked_identifier ->
1356 with {:ok, %User{} = blocked} <- get_or_fetch(blocked_identifier),
1357 {:ok, _user_block} <- block(blocker, blocked),
1358 {:ok, _} <- ActivityPub.block(blocker, blocked) do
1362 Logger.debug("blocks_import failed for #{blocked_identifier} with: #{inspect(err)}")
1369 def perform(:follow_import, %User{} = follower, followed_identifiers)
1370 when is_list(followed_identifiers) do
1372 followed_identifiers,
1373 fn followed_identifier ->
1374 with {:ok, %User{} = followed} <- get_or_fetch(followed_identifier),
1375 {:ok, follower} <- maybe_direct_follow(follower, followed),
1376 {:ok, _} <- ActivityPub.follow(follower, followed) do
1380 Logger.debug("follow_import failed for #{followed_identifier} with: #{inspect(err)}")
1387 @spec external_users_query() :: Ecto.Query.t()
1388 def external_users_query do
1396 @spec external_users(keyword()) :: [User.t()]
1397 def external_users(opts \\ []) do
1399 external_users_query()
1400 |> select([u], struct(u, [:id, :ap_id]))
1404 do: where(query, [u], u.id > ^opts[:max_id]),
1409 do: limit(query, ^opts[:limit]),
1415 def blocks_import(%User{} = blocker, blocked_identifiers) when is_list(blocked_identifiers) do
1416 BackgroundWorker.enqueue("blocks_import", %{
1417 "blocker_id" => blocker.id,
1418 "blocked_identifiers" => blocked_identifiers
1422 def follow_import(%User{} = follower, followed_identifiers)
1423 when is_list(followed_identifiers) do
1424 BackgroundWorker.enqueue("follow_import", %{
1425 "follower_id" => follower.id,
1426 "followed_identifiers" => followed_identifiers
1430 def delete_user_activities(%User{ap_id: ap_id}) do
1432 |> Activity.Queries.by_actor()
1433 |> RepoStreamer.chunk_stream(50)
1434 |> Stream.each(fn activities -> Enum.each(activities, &delete_activity/1) end)
1438 defp delete_activity(%{data: %{"type" => "Create"}} = activity) do
1440 |> Object.normalize()
1441 |> ActivityPub.delete()
1444 defp delete_activity(%{data: %{"type" => "Like"}} = activity) do
1445 object = Object.normalize(activity)
1448 |> get_cached_by_ap_id()
1449 |> ActivityPub.unlike(object)
1452 defp delete_activity(%{data: %{"type" => "Announce"}} = activity) do
1453 object = Object.normalize(activity)
1456 |> get_cached_by_ap_id()
1457 |> ActivityPub.unannounce(object)
1460 defp delete_activity(_activity), do: "Doing nothing"
1462 def html_filter_policy(%User{no_rich_text: true}) do
1463 Pleroma.HTML.Scrubber.TwitterText
1466 def html_filter_policy(_), do: Pleroma.Config.get([:markup, :scrub_policy])
1468 def fetch_by_ap_id(ap_id), do: ActivityPub.make_user_from_ap_id(ap_id)
1470 def get_or_fetch_by_ap_id(ap_id) do
1471 user = get_cached_by_ap_id(ap_id)
1473 if !is_nil(user) and !needs_update?(user) do
1476 fetch_by_ap_id(ap_id)
1481 Creates an internal service actor by URI if missing.
1482 Optionally takes nickname for addressing.
1484 @spec get_or_create_service_actor_by_ap_id(String.t(), String.t()) :: User.t() | nil
1485 def get_or_create_service_actor_by_ap_id(uri, nickname) do
1487 case get_cached_by_ap_id(uri) do
1489 with {:error, %{errors: errors}} <- create_service_actor(uri, nickname) do
1490 Logger.error("Cannot create service actor: #{uri}/.\n#{inspect(errors)}")
1494 %User{invisible: false} = user ->
1504 @spec set_invisible(User.t()) :: {:ok, User.t()}
1505 defp set_invisible(user) do
1507 |> change(%{invisible: true})
1508 |> update_and_set_cache()
1511 @spec create_service_actor(String.t(), String.t()) ::
1512 {:ok, User.t()} | {:error, Ecto.Changeset.t()}
1513 defp create_service_actor(uri, nickname) do
1519 follower_address: uri <> "/followers"
1522 |> unique_constraint(:nickname)
1528 def public_key(%{source_data: %{"publicKey" => %{"publicKeyPem" => public_key_pem}}}) do
1531 |> :public_key.pem_decode()
1533 |> :public_key.pem_entry_decode()
1538 def public_key(_), do: {:error, "not found key"}
1540 def get_public_key_for_ap_id(ap_id) do
1541 with {:ok, %User{} = user} <- get_or_fetch_by_ap_id(ap_id),
1542 {:ok, public_key} <- public_key(user) do
1549 defp blank?(""), do: nil
1550 defp blank?(n), do: n
1552 def insert_or_update_user(data) do
1554 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
1555 |> remote_user_creation()
1556 |> Repo.insert(on_conflict: {:replace_all_except, [:id]}, conflict_target: :nickname)
1560 def ap_enabled?(%User{local: true}), do: true
1561 def ap_enabled?(%User{ap_enabled: ap_enabled}), do: ap_enabled
1562 def ap_enabled?(_), do: false
1564 @doc "Gets or fetch a user by uri or nickname."
1565 @spec get_or_fetch(String.t()) :: {:ok, User.t()} | {:error, String.t()}
1566 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
1567 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
1569 # wait a period of time and return newest version of the User structs
1570 # this is because we have synchronous follow APIs and need to simulate them
1571 # with an async handshake
1572 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
1573 with %User{} = a <- get_cached_by_id(a.id),
1574 %User{} = b <- get_cached_by_id(b.id) do
1581 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
1582 with :ok <- :timer.sleep(timeout),
1583 %User{} = a <- get_cached_by_id(a.id),
1584 %User{} = b <- get_cached_by_id(b.id) do
1591 def parse_bio(bio) when is_binary(bio) and bio != "" do
1593 |> CommonUtils.format_input("text/plain", mentions_format: :full)
1597 def parse_bio(_), do: ""
1599 def parse_bio(bio, user) when is_binary(bio) and bio != "" do
1600 # TODO: get profile URLs other than user.ap_id
1601 profile_urls = [user.ap_id]
1604 |> CommonUtils.format_input("text/plain",
1605 mentions_format: :full,
1606 rel: &RelMe.maybe_put_rel_me(&1, profile_urls)
1611 def parse_bio(_, _), do: ""
1613 def tag(user_identifiers, tags) when is_list(user_identifiers) do
1614 Repo.transaction(fn ->
1615 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
1619 def tag(nickname, tags) when is_binary(nickname),
1620 do: tag(get_by_nickname(nickname), tags)
1622 def tag(%User{} = user, tags),
1623 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
1625 def untag(user_identifiers, tags) when is_list(user_identifiers) do
1626 Repo.transaction(fn ->
1627 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
1631 def untag(nickname, tags) when is_binary(nickname),
1632 do: untag(get_by_nickname(nickname), tags)
1634 def untag(%User{} = user, tags),
1635 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
1637 defp update_tags(%User{} = user, new_tags) do
1638 {:ok, updated_user} =
1640 |> change(%{tags: new_tags})
1641 |> update_and_set_cache()
1646 defp normalize_tags(tags) do
1649 |> Enum.map(&String.downcase/1)
1652 defp local_nickname_regex do
1653 if Pleroma.Config.get([:instance, :extended_nickname_format]) do
1654 @extended_local_nickname_regex
1656 @strict_local_nickname_regex
1660 def local_nickname(nickname_or_mention) do
1663 |> String.split("@")
1667 def full_nickname(nickname_or_mention),
1668 do: String.trim_leading(nickname_or_mention, "@")
1670 def error_user(ap_id) do
1674 nickname: "erroruser@example.com",
1675 inserted_at: NaiveDateTime.utc_now()
1679 @spec all_superusers() :: [User.t()]
1680 def all_superusers do
1681 User.Query.build(%{super_users: true, local: true, deactivated: false})
1685 def showing_reblogs?(%User{} = user, %User{} = target) do
1686 not UserRelationship.reblog_mute_exists?(user, target)
1690 The function returns a query to get users with no activity for given interval of days.
1691 Inactive users are those who didn't read any notification, or had any activity where
1692 the user is the activity's actor, during `inactivity_threshold` days.
1693 Deactivated users will not appear in this list.
1697 iex> Pleroma.User.list_inactive_users()
1700 @spec list_inactive_users_query(integer()) :: Ecto.Query.t()
1701 def list_inactive_users_query(inactivity_threshold \\ 7) do
1702 negative_inactivity_threshold = -inactivity_threshold
1703 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
1704 # Subqueries are not supported in `where` clauses, join gets too complicated.
1705 has_read_notifications =
1706 from(n in Pleroma.Notification,
1707 where: n.seen == true,
1709 having: max(n.updated_at) > datetime_add(^now, ^negative_inactivity_threshold, "day"),
1712 |> Pleroma.Repo.all()
1714 from(u in Pleroma.User,
1715 left_join: a in Pleroma.Activity,
1716 on: u.ap_id == a.actor,
1717 where: not is_nil(u.nickname),
1718 where: u.deactivated != ^true,
1719 where: u.id not in ^has_read_notifications,
1722 max(a.inserted_at) < datetime_add(^now, ^negative_inactivity_threshold, "day") or
1723 is_nil(max(a.inserted_at))
1728 Enable or disable email notifications for user
1732 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => false}}, "digest", true)
1733 Pleroma.User{email_notifications: %{"digest" => true}}
1735 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => true}}, "digest", false)
1736 Pleroma.User{email_notifications: %{"digest" => false}}
1738 @spec switch_email_notifications(t(), String.t(), boolean()) ::
1739 {:ok, t()} | {:error, Ecto.Changeset.t()}
1740 def switch_email_notifications(user, type, status) do
1741 User.update_email_notifications(user, %{type => status})
1745 Set `last_digest_emailed_at` value for the user to current time
1747 @spec touch_last_digest_emailed_at(t()) :: t()
1748 def touch_last_digest_emailed_at(user) do
1749 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
1751 {:ok, updated_user} =
1753 |> change(%{last_digest_emailed_at: now})
1754 |> update_and_set_cache()
1759 @spec toggle_confirmation(User.t()) :: {:ok, User.t()} | {:error, Changeset.t()}
1760 def toggle_confirmation(%User{} = user) do
1762 |> confirmation_changeset(need_confirmation: !user.confirmation_pending)
1763 |> update_and_set_cache()
1766 @spec toggle_confirmation([User.t()]) :: [{:ok, User.t()} | {:error, Changeset.t()}]
1767 def toggle_confirmation(users) do
1768 Enum.map(users, &toggle_confirmation/1)
1771 def get_mascot(%{mascot: %{} = mascot}) when not is_nil(mascot) do
1775 def get_mascot(%{mascot: mascot}) when is_nil(mascot) do
1776 # use instance-default
1777 config = Pleroma.Config.get([:assets, :mascots])
1778 default_mascot = Pleroma.Config.get([:assets, :default_mascot])
1779 mascot = Keyword.get(config, default_mascot)
1782 "id" => "default-mascot",
1783 "url" => mascot[:url],
1784 "preview_url" => mascot[:url],
1786 "mime_type" => mascot[:mime_type]
1791 def ensure_keys_present(%{keys: keys} = user) when not is_nil(keys), do: {:ok, user}
1793 def ensure_keys_present(%User{} = user) do
1794 with {:ok, pem} <- Keys.generate_rsa_pem() do
1796 |> cast(%{keys: pem}, [:keys])
1797 |> validate_required([:keys])
1798 |> update_and_set_cache()
1802 def get_ap_ids_by_nicknames(nicknames) do
1804 where: u.nickname in ^nicknames,
1810 defdelegate search(query, opts \\ []), to: User.Search
1812 defp put_password_hash(
1813 %Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset
1815 change(changeset, password_hash: Pbkdf2.hashpwsalt(password))
1818 defp put_password_hash(changeset), do: changeset
1820 def is_internal_user?(%User{nickname: nil}), do: true
1821 def is_internal_user?(%User{local: true, nickname: "internal." <> _}), do: true
1822 def is_internal_user?(_), do: false
1824 # A hack because user delete activities have a fake id for whatever reason
1825 # TODO: Get rid of this
1826 def get_delivered_users_by_object_id("pleroma:fake_object_id"), do: []
1828 def get_delivered_users_by_object_id(object_id) do
1830 inner_join: delivery in assoc(u, :deliveries),
1831 where: delivery.object_id == ^object_id
1836 def change_email(user, email) do
1838 |> cast(%{email: email}, [:email])
1839 |> validate_required([:email])
1840 |> unique_constraint(:email)
1841 |> validate_format(:email, @email_regex)
1842 |> update_and_set_cache()
1845 # Internal function; public one is `deactivate/2`
1846 defp set_activation_status(user, deactivated) do
1848 |> cast(%{deactivated: deactivated}, [:deactivated])
1849 |> update_and_set_cache()
1852 def update_banner(user, banner) do
1854 |> cast(%{banner: banner}, [:banner])
1855 |> update_and_set_cache()
1858 def update_background(user, background) do
1860 |> cast(%{background: background}, [:background])
1861 |> update_and_set_cache()
1864 def update_source_data(user, source_data) do
1866 |> cast(%{source_data: source_data}, [:source_data])
1867 |> update_and_set_cache()
1870 def roles(%{is_moderator: is_moderator, is_admin: is_admin}) do
1873 moderator: is_moderator
1877 # ``fields`` is an array of mastodon profile field, containing ``{"name": "…", "value": "…"}``.
1878 # For example: [{"name": "Pronoun", "value": "she/her"}, …]
1879 def fields(%{fields: nil, source_data: %{"attachment" => attachment}}) do
1880 limit = Pleroma.Config.get([:instance, :max_remote_account_fields], 0)
1883 |> Enum.filter(fn %{"type" => t} -> t == "PropertyValue" end)
1884 |> Enum.map(fn fields -> Map.take(fields, ["name", "value"]) end)
1888 def fields(%{fields: nil}), do: []
1890 def fields(%{fields: fields}), do: fields
1892 def validate_fields(changeset, remote? \\ false) do
1893 limit_name = if remote?, do: :max_remote_account_fields, else: :max_account_fields
1894 limit = Pleroma.Config.get([:instance, limit_name], 0)
1897 |> validate_length(:fields, max: limit)
1898 |> validate_change(:fields, fn :fields, fields ->
1899 if Enum.all?(fields, &valid_field?/1) do
1907 defp valid_field?(%{"name" => name, "value" => value}) do
1908 name_limit = Pleroma.Config.get([:instance, :account_field_name_length], 255)
1909 value_limit = Pleroma.Config.get([:instance, :account_field_value_length], 255)
1911 is_binary(name) && is_binary(value) && String.length(name) <= name_limit &&
1912 String.length(value) <= value_limit
1915 defp valid_field?(_), do: false
1917 defp truncate_field(%{"name" => name, "value" => value}) do
1919 String.split_at(name, Pleroma.Config.get([:instance, :account_field_name_length], 255))
1922 String.split_at(value, Pleroma.Config.get([:instance, :account_field_value_length], 255))
1924 %{"name" => name, "value" => value}
1927 def admin_api_update(user, params) do
1934 |> update_and_set_cache()
1937 @doc "Signs user out of all applications"
1938 def global_sign_out(user) do
1939 OAuth.Authorization.delete_user_authorizations(user)
1940 OAuth.Token.delete_user_tokens(user)
1943 def mascot_update(user, url) do
1945 |> cast(%{mascot: url}, [:mascot])
1946 |> validate_required([:mascot])
1947 |> update_and_set_cache()
1950 def mastodon_settings_update(user, settings) do
1952 |> cast(%{settings: settings}, [:settings])
1953 |> validate_required([:settings])
1954 |> update_and_set_cache()
1957 @spec confirmation_changeset(User.t(), keyword()) :: Changeset.t()
1958 def confirmation_changeset(user, need_confirmation: need_confirmation?) do
1960 if need_confirmation? do
1962 confirmation_pending: true,
1963 confirmation_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64()
1967 confirmation_pending: false,
1968 confirmation_token: nil
1972 cast(user, params, [:confirmation_pending, :confirmation_token])
1975 def add_pinnned_activity(user, %Pleroma.Activity{id: id}) do
1976 if id not in user.pinned_activities do
1977 max_pinned_statuses = Pleroma.Config.get([:instance, :max_pinned_statuses], 0)
1978 params = %{pinned_activities: user.pinned_activities ++ [id]}
1981 |> cast(params, [:pinned_activities])
1982 |> validate_length(:pinned_activities,
1983 max: max_pinned_statuses,
1984 message: "You have already pinned the maximum number of statuses"
1989 |> update_and_set_cache()
1992 def remove_pinnned_activity(user, %Pleroma.Activity{id: id}) do
1993 params = %{pinned_activities: List.delete(user.pinned_activities, id)}
1996 |> cast(params, [:pinned_activities])
1997 |> update_and_set_cache()
2000 def update_email_notifications(user, settings) do
2001 email_notifications =
2002 user.email_notifications
2003 |> Map.merge(settings)
2004 |> Map.take(["digest"])
2006 params = %{email_notifications: email_notifications}
2007 fields = [:email_notifications]
2010 |> cast(params, fields)
2011 |> validate_required(fields)
2012 |> update_and_set_cache()
2015 defp set_domain_blocks(user, domain_blocks) do
2016 params = %{domain_blocks: domain_blocks}
2019 |> cast(params, [:domain_blocks])
2020 |> validate_required([:domain_blocks])
2021 |> update_and_set_cache()
2024 def block_domain(user, domain_blocked) do
2025 set_domain_blocks(user, Enum.uniq([domain_blocked | user.domain_blocks]))
2028 def unblock_domain(user, domain_blocked) do
2029 set_domain_blocks(user, List.delete(user.domain_blocks, domain_blocked))
2032 @spec add_to_block(User.t(), User.t()) ::
2033 {:ok, UserRelationship.t()} | {:error, Ecto.Changeset.t()}
2034 defp add_to_block(%User{} = user, %User{} = blocked) do
2035 UserRelationship.create_block(user, blocked)
2038 @spec add_to_block(User.t(), User.t()) ::
2039 {:ok, UserRelationship.t()} | {:ok, nil} | {:error, Ecto.Changeset.t()}
2040 defp remove_from_block(%User{} = user, %User{} = blocked) do
2041 UserRelationship.delete_block(user, blocked)
2044 defp add_to_mutes(%User{} = user, %User{} = muted_user, notifications?) do
2045 with {:ok, user_mute} <- UserRelationship.create_mute(user, muted_user),
2046 {:ok, user_notification_mute} <-
2047 (notifications? && UserRelationship.create_notification_mute(user, muted_user)) ||
2049 {:ok, Enum.filter([user_mute, user_notification_mute], & &1)}
2053 defp remove_from_mutes(user, %User{} = muted_user) do
2054 with {:ok, user_mute} <- UserRelationship.delete_mute(user, muted_user),
2055 {:ok, user_notification_mute} <-
2056 UserRelationship.delete_notification_mute(user, muted_user) do
2057 {:ok, [user_mute, user_notification_mute]}
2061 def set_invisible(user, invisible) do
2062 params = %{invisible: invisible}
2065 |> cast(params, [:invisible])
2066 |> validate_required([:invisible])
2067 |> update_and_set_cache()