1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.User do
12 alias Pleroma.Activity
13 alias Pleroma.Formatter
14 alias Pleroma.Notification
19 alias Pleroma.Web.ActivityPub.ActivityPub
20 alias Pleroma.Web.ActivityPub.Utils
21 alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils
22 alias Pleroma.Web.OAuth
23 alias Pleroma.Web.OStatus
24 alias Pleroma.Web.RelMe
25 alias Pleroma.Web.Websub
29 @type t :: %__MODULE__{}
31 @primary_key {:id, Pleroma.FlakeId, autogenerate: true}
33 # credo:disable-for-next-line Credo.Check.Readability.MaxLineLength
34 @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])?)*$/
36 @strict_local_nickname_regex ~r/^[a-zA-Z\d]+$/
37 @extended_local_nickname_regex ~r/^[a-zA-Z\d_-]+$/
41 field(:email, :string)
43 field(:nickname, :string)
44 field(:password_hash, :string)
45 field(:password, :string, virtual: true)
46 field(:password_confirmation, :string, virtual: true)
47 field(:following, {:array, :string}, default: [])
48 field(:ap_id, :string)
50 field(:local, :boolean, default: true)
51 field(:follower_address, :string)
52 field(:search_rank, :float, virtual: true)
53 field(:search_type, :integer, virtual: true)
54 field(:tags, {:array, :string}, default: [])
55 field(:bookmarks, {:array, :string}, default: [])
56 field(:last_refreshed_at, :naive_datetime_usec)
57 has_many(:notifications, Notification)
58 embeds_one(:info, Pleroma.User.Info)
63 def auth_active?(%User{local: false}), do: true
65 def auth_active?(%User{info: %User.Info{confirmation_pending: false}}), do: true
67 def auth_active?(%User{info: %User.Info{confirmation_pending: true}}),
68 do: !Pleroma.Config.get([:instance, :account_activation_required])
70 def auth_active?(_), do: false
72 def visible_for?(user, for_user \\ nil)
74 def visible_for?(%User{id: user_id}, %User{id: for_id}) when user_id == for_id, do: true
76 def visible_for?(%User{} = user, for_user) do
77 auth_active?(user) || superuser?(for_user)
80 def visible_for?(_, _), do: false
82 def superuser?(%User{local: true, info: %User.Info{is_admin: true}}), do: true
83 def superuser?(%User{local: true, info: %User.Info{is_moderator: true}}), do: true
84 def superuser?(_), do: false
86 def avatar_url(user, options \\ []) do
88 %{"url" => [%{"href" => href} | _]} -> href
89 _ -> !options[:no_default] && "#{Web.base_url()}/images/avi.png"
93 def banner_url(user, options \\ []) do
94 case user.info.banner do
95 %{"url" => [%{"href" => href} | _]} -> href
96 _ -> !options[:no_default] && "#{Web.base_url()}/images/banner.png"
100 def profile_url(%User{info: %{source_data: %{"url" => url}}}), do: url
101 def profile_url(%User{ap_id: ap_id}), do: ap_id
102 def profile_url(_), do: nil
104 def ap_id(%User{nickname: nickname}) do
105 "#{Web.base_url()}/users/#{nickname}"
108 def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
109 def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
111 def user_info(%User{} = user) do
112 oneself = if user.local, do: 1, else: 0
115 following_count: length(user.following) - oneself,
116 note_count: user.info.note_count,
117 follower_count: user.info.follower_count,
118 locked: user.info.locked,
119 confirmation_pending: user.info.confirmation_pending,
120 default_scope: user.info.default_scope
124 def remote_user_creation(params) do
127 |> Map.put(:info, params[:info] || %{})
129 info_cng = User.Info.remote_user_creation(%User.Info{}, params[:info])
133 |> cast(params, [:bio, :name, :ap_id, :nickname, :avatar])
134 |> validate_required([:name, :ap_id])
135 |> unique_constraint(:nickname)
136 |> validate_format(:nickname, @email_regex)
137 |> validate_length(:bio, max: 5000)
138 |> validate_length(:name, max: 100)
139 |> put_change(:local, false)
140 |> put_embed(:info, info_cng)
143 case info_cng.changes[:source_data] do
144 %{"followers" => followers} ->
146 |> put_change(:follower_address, followers)
149 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
152 |> put_change(:follower_address, followers)
159 def update_changeset(struct, params \\ %{}) do
161 |> cast(params, [:bio, :name, :avatar])
162 |> unique_constraint(:nickname)
163 |> validate_format(:nickname, local_nickname_regex())
164 |> validate_length(:bio, max: 5000)
165 |> validate_length(:name, min: 1, max: 100)
168 def upgrade_changeset(struct, params \\ %{}) do
171 |> Map.put(:last_refreshed_at, NaiveDateTime.utc_now())
175 |> User.Info.user_upgrade(params[:info])
178 |> cast(params, [:bio, :name, :follower_address, :avatar, :last_refreshed_at])
179 |> unique_constraint(:nickname)
180 |> validate_format(:nickname, local_nickname_regex())
181 |> validate_length(:bio, max: 5000)
182 |> validate_length(:name, max: 100)
183 |> put_embed(:info, info_cng)
186 def password_update_changeset(struct, params) do
189 |> cast(params, [:password, :password_confirmation])
190 |> validate_required([:password, :password_confirmation])
191 |> validate_confirmation(:password)
193 OAuth.Token.delete_user_tokens(struct)
194 OAuth.Authorization.delete_user_authorizations(struct)
196 if changeset.valid? do
197 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
200 |> put_change(:password_hash, hashed)
206 def reset_password(user, data) do
207 update_and_set_cache(password_update_changeset(user, data))
210 def register_changeset(struct, params \\ %{}, opts \\ []) do
211 confirmation_status =
212 if opts[:confirmed] || !Pleroma.Config.get([:instance, :account_activation_required]) do
218 info_change = User.Info.confirmation_changeset(%User.Info{}, confirmation_status)
222 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
223 |> validate_required([:email, :name, :nickname, :password, :password_confirmation])
224 |> validate_confirmation(:password)
225 |> unique_constraint(:email)
226 |> unique_constraint(:nickname)
227 |> validate_exclusion(:nickname, Pleroma.Config.get([Pleroma.User, :restricted_nicknames]))
228 |> validate_format(:nickname, local_nickname_regex())
229 |> validate_format(:email, @email_regex)
230 |> validate_length(:bio, max: 1000)
231 |> validate_length(:name, min: 1, max: 100)
232 |> put_change(:info, info_change)
234 if changeset.valid? do
235 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
236 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
237 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
240 |> put_change(:password_hash, hashed)
241 |> put_change(:ap_id, ap_id)
242 |> unique_constraint(:ap_id)
243 |> put_change(:following, [followers])
244 |> put_change(:follower_address, followers)
250 defp autofollow_users(user) do
251 candidates = Pleroma.Config.get([:instance, :autofollowed_nicknames])
255 where: u.local == true,
256 where: u.nickname in ^candidates
260 follow_all(user, autofollowed_users)
263 @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
264 def register(%Ecto.Changeset{} = changeset) do
265 with {:ok, user} <- Repo.insert(changeset),
266 {:ok, user} <- autofollow_users(user),
267 {:ok, _} <- Pleroma.User.WelcomeMessage.post_welcome_message_to_user(user),
268 {:ok, _} <- try_send_confirmation_email(user) do
273 def try_send_confirmation_email(%User{} = user) do
274 if user.info.confirmation_pending &&
275 Pleroma.Config.get([:instance, :account_activation_required]) do
277 |> Pleroma.UserEmail.account_confirmation_email()
278 |> Pleroma.Mailer.deliver_async()
284 def needs_update?(%User{local: true}), do: false
286 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
288 def needs_update?(%User{local: false} = user) do
289 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
292 def needs_update?(_), do: true
294 def maybe_direct_follow(%User{} = follower, %User{local: true, info: %{locked: true}}) do
298 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
299 follow(follower, followed)
302 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
303 if not User.ap_enabled?(followed) do
304 follow(follower, followed)
310 def maybe_follow(%User{} = follower, %User{info: _info} = followed) do
311 if not following?(follower, followed) do
312 follow(follower, followed)
318 @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
319 @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
320 def follow_all(follower, followeds) do
323 |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
324 |> Enum.map(fn %{follower_address: fa} -> fa end)
328 where: u.id == ^follower.id,
333 "array(select distinct unnest (array_cat(?, ?)))",
342 {1, [follower]} = Repo.update_all(q, [])
344 Enum.each(followeds, fn followed ->
345 update_follower_count(followed)
351 def follow(%User{} = follower, %User{info: info} = followed) do
352 user_config = Application.get_env(:pleroma, :user)
353 deny_follow_blocked = Keyword.get(user_config, :deny_follow_blocked)
355 ap_followers = followed.follower_address
358 following?(follower, followed) or info.deactivated ->
359 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
361 deny_follow_blocked and blocks?(followed, follower) ->
362 {:error, "Could not follow user: #{followed.nickname} blocked you."}
365 if !followed.local && follower.local && !ap_enabled?(followed) do
366 Websub.subscribe(follower, followed)
371 where: u.id == ^follower.id,
372 update: [push: [following: ^ap_followers]],
376 {1, [follower]} = Repo.update_all(q, [])
378 {:ok, _} = update_follower_count(followed)
384 def unfollow(%User{} = follower, %User{} = followed) do
385 ap_followers = followed.follower_address
387 if following?(follower, followed) and follower.ap_id != followed.ap_id do
390 where: u.id == ^follower.id,
391 update: [pull: [following: ^ap_followers]],
395 {1, [follower]} = Repo.update_all(q, [])
397 {:ok, followed} = update_follower_count(followed)
401 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
403 {:error, "Not subscribed!"}
407 @spec following?(User.t(), User.t()) :: boolean
408 def following?(%User{} = follower, %User{} = followed) do
409 Enum.member?(follower.following, followed.follower_address)
412 def follow_import(%User{} = follower, followed_identifiers)
413 when is_list(followed_identifiers) do
415 followed_identifiers,
416 fn followed_identifier ->
417 with %User{} = followed <- get_or_fetch(followed_identifier),
418 {:ok, follower} <- maybe_direct_follow(follower, followed),
419 {:ok, _} <- ActivityPub.follow(follower, followed) do
423 Logger.debug("follow_import failed for #{followed_identifier} with: #{inspect(err)}")
430 def locked?(%User{} = user) do
431 user.info.locked || false
435 Repo.get_by(User, id: id)
438 def get_by_ap_id(ap_id) do
439 Repo.get_by(User, ap_id: ap_id)
442 # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
443 # of the ap_id and the domain and tries to get that user
444 def get_by_guessed_nickname(ap_id) do
445 domain = URI.parse(ap_id).host
446 name = List.last(String.split(ap_id, "/"))
447 nickname = "#{name}@#{domain}"
449 get_by_nickname(nickname)
452 def set_cache(user) do
453 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
454 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
455 Cachex.put(:user_cache, "user_info:#{user.id}", user_info(user))
459 def update_and_set_cache(changeset) do
460 with {:ok, user} <- Repo.update(changeset) do
467 def invalidate_cache(user) do
468 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
469 Cachex.del(:user_cache, "nickname:#{user.nickname}")
470 Cachex.del(:user_cache, "user_info:#{user.id}")
473 def get_cached_by_ap_id(ap_id) do
474 key = "ap_id:#{ap_id}"
475 Cachex.fetch!(:user_cache, key, fn _ -> get_by_ap_id(ap_id) end)
478 def get_cached_by_id(id) do
482 Cachex.fetch!(:user_cache, key, fn _ ->
486 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
487 {:commit, user.ap_id}
493 get_cached_by_ap_id(ap_id)
496 def get_cached_by_nickname(nickname) do
497 key = "nickname:#{nickname}"
498 Cachex.fetch!(:user_cache, key, fn _ -> get_or_fetch_by_nickname(nickname) end)
501 def get_cached_by_nickname_or_id(nickname_or_id) do
502 get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
505 def get_by_nickname(nickname) do
506 Repo.get_by(User, nickname: nickname) ||
507 if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
508 Repo.get_by(User, nickname: local_nickname(nickname))
512 def get_by_nickname_or_email(nickname_or_email) do
513 case user = Repo.get_by(User, nickname: nickname_or_email) do
515 nil -> Repo.get_by(User, email: nickname_or_email)
519 def get_cached_user_info(user) do
520 key = "user_info:#{user.id}"
521 Cachex.fetch!(:user_cache, key, fn _ -> user_info(user) end)
524 def fetch_by_nickname(nickname) do
525 ap_try = ActivityPub.make_user_from_nickname(nickname)
528 {:ok, user} -> {:ok, user}
529 _ -> OStatus.make_user(nickname)
533 def get_or_fetch_by_nickname(nickname) do
534 with %User{} = user <- get_by_nickname(nickname) do
538 with [_nick, _domain] <- String.split(nickname, "@"),
539 {:ok, user} <- fetch_by_nickname(nickname) do
540 if Pleroma.Config.get([:fetch_initial_posts, :enabled]) do
541 {:ok, _} = Task.start(__MODULE__, :fetch_initial_posts, [user])
551 @doc "Fetch some posts when the user has just been federated with"
552 def fetch_initial_posts(user) do
553 pages = Pleroma.Config.get!([:fetch_initial_posts, :pages])
556 # Insert all the posts in reverse order, so they're in the right order on the timeline
557 Enum.reverse(Utils.fetch_ordered_collection(user.info.source_data["outbox"], pages)),
558 &Pleroma.Web.Federator.incoming_ap_doc/1
562 def get_followers_query(%User{id: id, follower_address: follower_address}, nil) do
565 where: fragment("? <@ ?", ^[follower_address], u.following),
570 def get_followers_query(user, page) do
571 from(u in get_followers_query(user, nil))
572 |> paginate(page, 20)
575 def get_followers_query(user), do: get_followers_query(user, nil)
577 def get_followers(user, page \\ nil) do
578 q = get_followers_query(user, page)
583 def get_followers_ids(user, page \\ nil) do
584 q = get_followers_query(user, page)
586 Repo.all(from(u in q, select: u.id))
589 def get_friends_query(%User{id: id, following: following}, nil) do
592 where: u.follower_address in ^following,
597 def get_friends_query(user, page) do
598 from(u in get_friends_query(user, nil))
599 |> paginate(page, 20)
602 def get_friends_query(user), do: get_friends_query(user, nil)
604 def get_friends(user, page \\ nil) do
605 q = get_friends_query(user, page)
610 def get_friends_ids(user, page \\ nil) do
611 q = get_friends_query(user, page)
613 Repo.all(from(u in q, select: u.id))
616 def get_follow_requests_query(%User{} = user) do
621 "? ->> 'type' = 'Follow'",
626 "? ->> 'state' = 'pending'",
631 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
639 def get_follow_requests(%User{} = user) do
642 |> User.get_follow_requests_query()
643 |> join(:inner, [a], u in User, on: a.actor == u.ap_id)
644 |> where([a, u], not fragment("? @> ?", u.following, ^[user.follower_address]))
645 |> group_by([a, u], u.id)
652 def increase_note_count(%User{} = user) do
654 |> where(id: ^user.id)
659 "jsonb_set(?, '{note_count}', ((?->>'note_count')::int + 1)::varchar::jsonb, true)",
666 |> Repo.update_all([])
668 {1, [user]} -> set_cache(user)
673 def decrease_note_count(%User{} = user) do
675 |> where(id: ^user.id)
680 "jsonb_set(?, '{note_count}', (greatest(0, (?->>'note_count')::int - 1))::varchar::jsonb, true)",
687 |> Repo.update_all([])
689 {1, [user]} -> set_cache(user)
694 def update_note_count(%User{} = user) do
698 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
702 note_count = Repo.one(note_count_query)
704 info_cng = User.Info.set_note_count(user.info, note_count)
708 |> put_embed(:info, info_cng)
710 update_and_set_cache(cng)
713 def update_follower_count(%User{} = user) do
714 follower_count_query =
716 |> where([u], ^user.follower_address in u.following)
717 |> where([u], u.id != ^user.id)
718 |> select([u], %{count: count(u.id)})
721 |> where(id: ^user.id)
722 |> join(:inner, [u], s in subquery(follower_count_query))
727 "jsonb_set(?, '{follower_count}', ?::varchar::jsonb, true)",
734 |> Repo.update_all([])
736 {1, [user]} -> set_cache(user)
741 def get_users_from_set_query(ap_ids, false) do
744 where: u.ap_id in ^ap_ids
748 def get_users_from_set_query(ap_ids, true) do
749 query = get_users_from_set_query(ap_ids, false)
753 where: u.local == true
757 def get_users_from_set(ap_ids, local_only \\ true) do
758 get_users_from_set_query(ap_ids, local_only)
762 def get_recipients_from_activity(%Activity{recipients: to}) do
766 where: u.ap_id in ^to,
767 or_where: fragment("? && ?", u.following, ^to)
770 query = from(u in query, where: u.local == true)
775 @spec search_for_admin(%{
779 }) :: {:ok, [Pleroma.User.t()], number()}
780 def search_for_admin(%{query: nil, local: local, page: page, page_size: page_size}) do
782 from(u in User, order_by: u.nickname)
783 |> maybe_local_user_query(local)
787 |> paginate(page, page_size)
791 |> Repo.aggregate(:count, :id)
793 {:ok, Repo.all(paginated_query), count}
796 @spec search_for_admin(%{
801 }) :: {:ok, [Pleroma.User.t()], number()}
802 def search_for_admin(%{
808 maybe_local_query = User |> maybe_local_user_query(local)
810 search_query = from(u in maybe_local_query, where: ilike(u.nickname, ^"%#{term}%"))
811 count = search_query |> Repo.aggregate(:count, :id)
815 |> paginate(page, page_size)
818 {:ok, results, count}
821 def search(query, resolve \\ false, for_user \\ nil) do
822 # Strip the beginning @ off if there is a query
823 query = String.trim_leading(query, "@")
825 if resolve, do: get_or_fetch(query)
828 Repo.transaction(fn ->
829 Ecto.Adapters.SQL.query(Repo, "select set_limit(0.25)", [])
830 Repo.all(search_query(query, for_user))
836 def search_query(query, for_user) do
837 fts_subquery = fts_search_subquery(query)
838 trigram_subquery = trigram_search_subquery(query)
839 union_query = from(s in trigram_subquery, union_all: ^fts_subquery)
840 distinct_query = from(s in subquery(union_query), order_by: s.search_type, distinct: s.id)
842 from(s in subquery(boost_search_rank_query(distinct_query, for_user)),
843 order_by: [desc: s.search_rank],
848 defp boost_search_rank_query(query, nil), do: query
850 defp boost_search_rank_query(query, for_user) do
851 friends_ids = get_friends_ids(for_user)
852 followers_ids = get_followers_ids(for_user)
854 from(u in subquery(query),
859 CASE WHEN (?) THEN (?) * 1.3
860 WHEN (?) THEN (?) * 1.2
861 WHEN (?) THEN (?) * 1.1
864 u.id in ^friends_ids and u.id in ^followers_ids,
866 u.id in ^friends_ids,
868 u.id in ^followers_ids,
876 defp fts_search_subquery(term, query \\ User) do
879 |> String.replace(~r/\W+/, " ")
882 |> Enum.map(&(&1 <> ":*"))
893 setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
894 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B'),
895 to_tsquery('simple', ?),
907 (setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
908 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B')) @@ to_tsquery('simple', ?)
917 defp trigram_search_subquery(term) do
921 # ^1 gives 'Postgrex expected a binary, got 1' for some weird reason
922 search_type: fragment("?", 1),
925 "similarity(?, trim(? || ' ' || coalesce(?, '')))",
931 where: fragment("trim(? || ' ' || coalesce(?, '')) % ?", u.nickname, u.name, ^term)
935 def blocks_import(%User{} = blocker, blocked_identifiers) when is_list(blocked_identifiers) do
938 fn blocked_identifier ->
939 with %User{} = blocked <- get_or_fetch(blocked_identifier),
940 {:ok, blocker} <- block(blocker, blocked),
941 {:ok, _} <- ActivityPub.block(blocker, blocked) do
945 Logger.debug("blocks_import failed for #{blocked_identifier} with: #{inspect(err)}")
952 def mute(muter, %User{ap_id: ap_id}) do
955 |> User.Info.add_to_mutes(ap_id)
959 |> put_embed(:info, info_cng)
961 update_and_set_cache(cng)
964 def unmute(muter, %{ap_id: ap_id}) do
967 |> User.Info.remove_from_mutes(ap_id)
971 |> put_embed(:info, info_cng)
973 update_and_set_cache(cng)
976 def block(blocker, %User{ap_id: ap_id} = blocked) do
977 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
979 if following?(blocker, blocked) do
980 {:ok, blocker, _} = unfollow(blocker, blocked)
986 if following?(blocked, blocker) do
987 unfollow(blocked, blocker)
992 |> User.Info.add_to_block(ap_id)
996 |> put_embed(:info, info_cng)
998 update_and_set_cache(cng)
1001 # helper to handle the block given only an actor's AP id
1002 def block(blocker, %{ap_id: ap_id}) do
1003 block(blocker, User.get_by_ap_id(ap_id))
1006 def unblock(blocker, %{ap_id: ap_id}) do
1009 |> User.Info.remove_from_block(ap_id)
1013 |> put_embed(:info, info_cng)
1015 update_and_set_cache(cng)
1018 def mutes?(nil, _), do: false
1019 def mutes?(user, %{ap_id: ap_id}), do: Enum.member?(user.info.mutes, ap_id)
1021 def blocks?(user, %{ap_id: ap_id}) do
1022 blocks = user.info.blocks
1023 domain_blocks = user.info.domain_blocks
1024 %{host: host} = URI.parse(ap_id)
1026 Enum.member?(blocks, ap_id) ||
1027 Enum.any?(domain_blocks, fn domain ->
1032 def muted_users(user),
1033 do: Repo.all(from(u in User, where: u.ap_id in ^user.info.mutes))
1035 def blocked_users(user),
1036 do: Repo.all(from(u in User, where: u.ap_id in ^user.info.blocks))
1038 def block_domain(user, domain) do
1041 |> User.Info.add_to_domain_block(domain)
1045 |> put_embed(:info, info_cng)
1047 update_and_set_cache(cng)
1050 def unblock_domain(user, domain) do
1053 |> User.Info.remove_from_domain_block(domain)
1057 |> put_embed(:info, info_cng)
1059 update_and_set_cache(cng)
1062 def maybe_local_user_query(query, local) do
1063 if local, do: local_user_query(query), else: query
1066 def local_user_query(query \\ User) do
1069 where: u.local == true,
1070 where: not is_nil(u.nickname)
1074 def active_local_user_query do
1076 u in local_user_query(),
1077 where: fragment("not (?->'deactivated' @> 'true')", u.info)
1081 def moderator_user_query do
1084 where: u.local == true,
1085 where: fragment("?->'is_moderator' @> 'true'", u.info)
1089 def deactivate(%User{} = user, status \\ true) do
1090 info_cng = User.Info.set_activation_status(user.info, status)
1094 |> put_embed(:info, info_cng)
1096 update_and_set_cache(cng)
1099 def delete(%User{} = user) do
1100 {:ok, user} = User.deactivate(user)
1102 # Remove all relationships
1103 {:ok, followers} = User.get_followers(user)
1106 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
1108 {:ok, friends} = User.get_friends(user)
1111 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
1114 from(a in Activity, where: a.actor == ^user.ap_id)
1115 |> Activity.with_preloaded_object()
1118 |> Enum.each(fn activity ->
1119 case activity.data["type"] do
1121 ActivityPub.delete(Object.normalize(activity))
1123 # TODO: Do something with likes, follows, repeats.
1132 def html_filter_policy(%User{info: %{no_rich_text: true}}) do
1133 Pleroma.HTML.Scrubber.TwitterText
1136 @default_scrubbers Pleroma.Config.get([:markup, :scrub_policy])
1138 def html_filter_policy(_), do: @default_scrubbers
1140 def fetch_by_ap_id(ap_id) do
1141 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
1148 case OStatus.make_user(ap_id) do
1150 _ -> {:error, "Could not fetch by AP id"}
1155 def get_or_fetch_by_ap_id(ap_id) do
1156 user = get_by_ap_id(ap_id)
1158 if !is_nil(user) and !User.needs_update?(user) do
1161 # Whether to fetch initial posts for the user (if it's a new user & the fetching is enabled)
1162 should_fetch_initial = is_nil(user) and Pleroma.Config.get([:fetch_initial_posts, :enabled])
1164 user = fetch_by_ap_id(ap_id)
1166 if should_fetch_initial do
1167 with %User{} = user do
1168 {:ok, _} = Task.start(__MODULE__, :fetch_initial_posts, [user])
1176 def get_or_create_instance_user do
1177 relay_uri = "#{Pleroma.Web.Endpoint.url()}/relay"
1179 if user = get_by_ap_id(relay_uri) do
1183 %User{info: %User.Info{}}
1184 |> cast(%{}, [:ap_id, :nickname, :local])
1185 |> put_change(:ap_id, relay_uri)
1186 |> put_change(:nickname, nil)
1187 |> put_change(:local, true)
1188 |> put_change(:follower_address, relay_uri <> "/followers")
1190 {:ok, user} = Repo.insert(changes)
1196 def public_key_from_info(%{
1197 source_data: %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
1201 |> :public_key.pem_decode()
1203 |> :public_key.pem_entry_decode()
1209 def public_key_from_info(%{magic_key: magic_key}) do
1210 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
1213 def get_public_key_for_ap_id(ap_id) do
1214 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
1215 {:ok, public_key} <- public_key_from_info(user.info) do
1222 defp blank?(""), do: nil
1223 defp blank?(n), do: n
1225 def insert_or_update_user(data) do
1228 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
1230 cs = User.remote_user_creation(data)
1232 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
1235 def ap_enabled?(%User{local: true}), do: true
1236 def ap_enabled?(%User{info: info}), do: info.ap_enabled
1237 def ap_enabled?(_), do: false
1239 @doc "Gets or fetch a user by uri or nickname."
1240 @spec get_or_fetch(String.t()) :: User.t()
1241 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
1242 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
1244 # wait a period of time and return newest version of the User structs
1245 # this is because we have synchronous follow APIs and need to simulate them
1246 # with an async handshake
1247 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
1248 with %User{} = a <- Repo.get(User, a.id),
1249 %User{} = b <- Repo.get(User, b.id) do
1257 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
1258 with :ok <- :timer.sleep(timeout),
1259 %User{} = a <- Repo.get(User, a.id),
1260 %User{} = b <- Repo.get(User, b.id) do
1268 def parse_bio(bio, user \\ %User{info: %{source_data: %{}}})
1269 def parse_bio(nil, _user), do: ""
1270 def parse_bio(bio, _user) when bio == "", do: bio
1272 def parse_bio(bio, user) do
1274 (user.info.source_data["tag"] || [])
1275 |> Enum.filter(fn %{"type" => t} -> t == "Emoji" end)
1276 |> Enum.map(fn %{"icon" => %{"url" => url}, "name" => name} ->
1277 {String.trim(name, ":"), url}
1280 # TODO: get profile URLs other than user.ap_id
1281 profile_urls = [user.ap_id]
1284 |> CommonUtils.format_input("text/plain",
1285 mentions_format: :full,
1286 rel: &RelMe.maybe_put_rel_me(&1, profile_urls)
1289 |> Formatter.emojify(emoji)
1292 def tag(user_identifiers, tags) when is_list(user_identifiers) do
1293 Repo.transaction(fn ->
1294 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
1298 def tag(nickname, tags) when is_binary(nickname),
1299 do: tag(User.get_by_nickname(nickname), tags)
1301 def tag(%User{} = user, tags),
1302 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
1304 def untag(user_identifiers, tags) when is_list(user_identifiers) do
1305 Repo.transaction(fn ->
1306 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
1310 def untag(nickname, tags) when is_binary(nickname),
1311 do: untag(User.get_by_nickname(nickname), tags)
1313 def untag(%User{} = user, tags),
1314 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
1316 defp update_tags(%User{} = user, new_tags) do
1317 {:ok, updated_user} =
1319 |> change(%{tags: new_tags})
1320 |> update_and_set_cache()
1325 def bookmark(%User{} = user, status_id) do
1326 bookmarks = Enum.uniq(user.bookmarks ++ [status_id])
1327 update_bookmarks(user, bookmarks)
1330 def unbookmark(%User{} = user, status_id) do
1331 bookmarks = Enum.uniq(user.bookmarks -- [status_id])
1332 update_bookmarks(user, bookmarks)
1335 def update_bookmarks(%User{} = user, bookmarks) do
1337 |> change(%{bookmarks: bookmarks})
1338 |> update_and_set_cache
1341 defp normalize_tags(tags) do
1344 |> Enum.map(&String.downcase(&1))
1347 defp local_nickname_regex do
1348 if Pleroma.Config.get([:instance, :extended_nickname_format]) do
1349 @extended_local_nickname_regex
1351 @strict_local_nickname_regex
1355 def local_nickname(nickname_or_mention) do
1358 |> String.split("@")
1362 def full_nickname(nickname_or_mention),
1363 do: String.trim_leading(nickname_or_mention, "@")
1365 def error_user(ap_id) do
1370 nickname: "erroruser@example.com",
1371 inserted_at: NaiveDateTime.utc_now()
1375 def all_superusers do
1378 where: u.local == true,
1379 where: fragment("?->'is_admin' @> 'true' OR ?->'is_moderator' @> 'true'", u.info, u.info)
1384 defp paginate(query, page, page_size) do
1387 offset: ^((page - 1) * page_size)
1391 def showing_reblogs?(%User{} = user, %User{} = target) do
1392 target.ap_id not in user.info.muted_reblogs