Merge remote-tracking branch 'upstream/develop' into develop
[akkoma] / lib / pleroma / user.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.User do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9 import Ecto.Query
10 import Ecto, only: [assoc: 2]
11
12 alias Ecto.Multi
13 alias Pleroma.Activity
14 alias Pleroma.Config
15 alias Pleroma.Conversation.Participation
16 alias Pleroma.Delivery
17 alias Pleroma.EctoType.ActivityPub.ObjectValidators
18 alias Pleroma.Emoji
19 alias Pleroma.FollowingRelationship
20 alias Pleroma.Formatter
21 alias Pleroma.HTML
22 alias Pleroma.Keys
23 alias Pleroma.MFA
24 alias Pleroma.Notification
25 alias Pleroma.Object
26 alias Pleroma.Registration
27 alias Pleroma.Repo
28 alias Pleroma.User
29 alias Pleroma.UserRelationship
30 alias Pleroma.Web.ActivityPub.ActivityPub
31 alias Pleroma.Web.ActivityPub.Builder
32 alias Pleroma.Web.ActivityPub.Pipeline
33 alias Pleroma.Web.ActivityPub.Utils
34 alias Pleroma.Web.CommonAPI
35 alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils
36 alias Pleroma.Web.Endpoint
37 alias Pleroma.Web.OAuth
38 alias Pleroma.Web.RelMe
39 alias Pleroma.Workers.BackgroundWorker
40
41 require Logger
42
43 @type t :: %__MODULE__{}
44 @type account_status ::
45 :active
46 | :deactivated
47 | :password_reset_pending
48 | :confirmation_pending
49 | :approval_pending
50 @primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
51
52 # credo:disable-for-next-line Credo.Check.Readability.MaxLineLength
53 @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])?)*$/
54
55 @strict_local_nickname_regex ~r/^[a-zA-Z\d]+$/
56 @extended_local_nickname_regex ~r/^[a-zA-Z\d_-]+$/
57
58 # AP ID user relationships (blocks, mutes etc.)
59 # Format: [rel_type: [outgoing_rel: :outgoing_rel_target, incoming_rel: :incoming_rel_source]]
60 @user_relationships_config [
61 block: [
62 blocker_blocks: :blocked_users,
63 blockee_blocks: :blocker_users
64 ],
65 mute: [
66 muter_mutes: :muted_users,
67 mutee_mutes: :muter_users
68 ],
69 reblog_mute: [
70 reblog_muter_mutes: :reblog_muted_users,
71 reblog_mutee_mutes: :reblog_muter_users
72 ],
73 notification_mute: [
74 notification_muter_mutes: :notification_muted_users,
75 notification_mutee_mutes: :notification_muter_users
76 ],
77 # Note: `inverse_subscription` relationship is inverse: subscriber acts as relationship target
78 inverse_subscription: [
79 subscribee_subscriptions: :subscriber_users,
80 subscriber_subscriptions: :subscribee_users
81 ]
82 ]
83
84 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
85
86 schema "users" do
87 field(:bio, :string, default: "")
88 field(:raw_bio, :string)
89 field(:email, :string)
90 field(:name, :string)
91 field(:nickname, :string)
92 field(:password_hash, :string)
93 field(:password, :string, virtual: true)
94 field(:password_confirmation, :string, virtual: true)
95 field(:keys, :string)
96 field(:public_key, :string)
97 field(:ap_id, :string)
98 field(:avatar, :map, default: %{})
99 field(:local, :boolean, default: true)
100 field(:follower_address, :string)
101 field(:following_address, :string)
102 field(:featured_address, :string)
103 field(:search_rank, :float, virtual: true)
104 field(:search_type, :integer, virtual: true)
105 field(:tags, {:array, :string}, default: [])
106 field(:last_refreshed_at, :naive_datetime_usec)
107 field(:last_digest_emailed_at, :naive_datetime)
108 field(:banner, :map, default: %{})
109 field(:background, :map, default: %{})
110 field(:note_count, :integer, default: 0)
111 field(:follower_count, :integer, default: 0)
112 field(:following_count, :integer, default: 0)
113 field(:is_locked, :boolean, default: false)
114 field(:is_confirmed, :boolean, default: true)
115 field(:password_reset_pending, :boolean, default: false)
116 field(:is_approved, :boolean, default: true)
117 field(:registration_reason, :string, default: nil)
118 field(:confirmation_token, :string, default: nil)
119 field(:default_scope, :string, default: "public")
120 field(:domain_blocks, {:array, :string}, default: [])
121 field(:is_active, :boolean, default: true)
122 field(:no_rich_text, :boolean, default: false)
123 field(:ap_enabled, :boolean, default: false)
124 field(:is_moderator, :boolean, default: false)
125 field(:is_admin, :boolean, default: false)
126 field(:show_role, :boolean, default: true)
127 field(:uri, ObjectValidators.Uri, default: nil)
128 field(:hide_followers_count, :boolean, default: false)
129 field(:hide_follows_count, :boolean, default: false)
130 field(:hide_followers, :boolean, default: false)
131 field(:hide_follows, :boolean, default: false)
132 field(:hide_favorites, :boolean, default: true)
133 field(:email_notifications, :map, default: %{"digest" => false})
134 field(:mascot, :map, default: nil)
135 field(:emoji, :map, default: %{})
136 field(:pleroma_settings_store, :map, default: %{})
137 field(:fields, {:array, :map}, default: [])
138 field(:raw_fields, {:array, :map}, default: [])
139 field(:is_discoverable, :boolean, default: false)
140 field(:invisible, :boolean, default: false)
141 field(:allow_following_move, :boolean, default: true)
142 field(:skip_thread_containment, :boolean, default: false)
143 field(:actor_type, :string, default: "Person")
144 field(:also_known_as, {:array, ObjectValidators.ObjectID}, default: [])
145 field(:inbox, :string)
146 field(:shared_inbox, :string)
147 field(:accepts_chat_messages, :boolean, default: nil)
148 field(:last_active_at, :naive_datetime)
149 field(:disclose_client, :boolean, default: true)
150 field(:pinned_objects, :map, default: %{})
151 field(:is_suggested, :boolean, default: false)
152 field(:last_status_at, :naive_datetime)
153
154 embeds_one(
155 :notification_settings,
156 Pleroma.User.NotificationSetting,
157 on_replace: :update
158 )
159
160 has_many(:notifications, Notification)
161 has_many(:registrations, Registration)
162 has_many(:deliveries, Delivery)
163
164 has_many(:outgoing_relationships, UserRelationship, foreign_key: :source_id)
165 has_many(:incoming_relationships, UserRelationship, foreign_key: :target_id)
166
167 for {relationship_type,
168 [
169 {outgoing_relation, outgoing_relation_target},
170 {incoming_relation, incoming_relation_source}
171 ]} <- @user_relationships_config do
172 # Definitions of `has_many` relations: :blocker_blocks, :muter_mutes, :reblog_muter_mutes,
173 # :notification_muter_mutes, :subscribee_subscriptions
174 has_many(outgoing_relation, UserRelationship,
175 foreign_key: :source_id,
176 where: [relationship_type: relationship_type]
177 )
178
179 # Definitions of `has_many` relations: :blockee_blocks, :mutee_mutes, :reblog_mutee_mutes,
180 # :notification_mutee_mutes, :subscriber_subscriptions
181 has_many(incoming_relation, UserRelationship,
182 foreign_key: :target_id,
183 where: [relationship_type: relationship_type]
184 )
185
186 # Definitions of `has_many` relations: :blocked_users, :muted_users, :reblog_muted_users,
187 # :notification_muted_users, :subscriber_users
188 has_many(outgoing_relation_target, through: [outgoing_relation, :target])
189
190 # Definitions of `has_many` relations: :blocker_users, :muter_users, :reblog_muter_users,
191 # :notification_muter_users, :subscribee_users
192 has_many(incoming_relation_source, through: [incoming_relation, :source])
193 end
194
195 # `:blocks` is deprecated (replaced with `blocked_users` relation)
196 field(:blocks, {:array, :string}, default: [])
197 # `:mutes` is deprecated (replaced with `muted_users` relation)
198 field(:mutes, {:array, :string}, default: [])
199 # `:muted_reblogs` is deprecated (replaced with `reblog_muted_users` relation)
200 field(:muted_reblogs, {:array, :string}, default: [])
201 # `:muted_notifications` is deprecated (replaced with `notification_muted_users` relation)
202 field(:muted_notifications, {:array, :string}, default: [])
203 # `:subscribers` is deprecated (replaced with `subscriber_users` relation)
204 field(:subscribers, {:array, :string}, default: [])
205
206 embeds_one(
207 :multi_factor_authentication_settings,
208 MFA.Settings,
209 on_replace: :delete
210 )
211
212 timestamps()
213 end
214
215 for {_relationship_type, [{_outgoing_relation, outgoing_relation_target}, _]} <-
216 @user_relationships_config do
217 # `def blocked_users_relation/2`, `def muted_users_relation/2`,
218 # `def reblog_muted_users_relation/2`, `def notification_muted_users/2`,
219 # `def subscriber_users/2`
220 def unquote(:"#{outgoing_relation_target}_relation")(user, restrict_deactivated? \\ false) do
221 target_users_query = assoc(user, unquote(outgoing_relation_target))
222
223 if restrict_deactivated? do
224 target_users_query
225 |> User.Query.build(%{deactivated: false})
226 else
227 target_users_query
228 end
229 end
230
231 # `def blocked_users/2`, `def muted_users/2`, `def reblog_muted_users/2`,
232 # `def notification_muted_users/2`, `def subscriber_users/2`
233 def unquote(outgoing_relation_target)(user, restrict_deactivated? \\ false) do
234 __MODULE__
235 |> apply(unquote(:"#{outgoing_relation_target}_relation"), [
236 user,
237 restrict_deactivated?
238 ])
239 |> Repo.all()
240 end
241
242 # `def blocked_users_ap_ids/2`, `def muted_users_ap_ids/2`, `def reblog_muted_users_ap_ids/2`,
243 # `def notification_muted_users_ap_ids/2`, `def subscriber_users_ap_ids/2`
244 def unquote(:"#{outgoing_relation_target}_ap_ids")(user, restrict_deactivated? \\ false) do
245 __MODULE__
246 |> apply(unquote(:"#{outgoing_relation_target}_relation"), [
247 user,
248 restrict_deactivated?
249 ])
250 |> select([u], u.ap_id)
251 |> Repo.all()
252 end
253 end
254
255 def cached_blocked_users_ap_ids(user) do
256 @cachex.fetch!(:user_cache, "blocked_users_ap_ids:#{user.ap_id}", fn _ ->
257 blocked_users_ap_ids(user)
258 end)
259 end
260
261 def cached_muted_users_ap_ids(user) do
262 @cachex.fetch!(:user_cache, "muted_users_ap_ids:#{user.ap_id}", fn _ ->
263 muted_users_ap_ids(user)
264 end)
265 end
266
267 defdelegate following_count(user), to: FollowingRelationship
268 defdelegate following(user), to: FollowingRelationship
269 defdelegate following?(follower, followed), to: FollowingRelationship
270 defdelegate following_ap_ids(user), to: FollowingRelationship
271 defdelegate get_follow_requests(user), to: FollowingRelationship
272 defdelegate search(query, opts \\ []), to: User.Search
273
274 @doc """
275 Dumps Flake Id to SQL-compatible format (16-byte UUID).
276 E.g. "9pQtDGXuq4p3VlcJEm" -> <<0, 0, 1, 110, 179, 218, 42, 92, 213, 41, 44, 227, 95, 213, 0, 0>>
277 """
278 def binary_id(source_id) when is_binary(source_id) do
279 with {:ok, dumped_id} <- FlakeId.Ecto.CompatType.dump(source_id) do
280 dumped_id
281 else
282 _ -> source_id
283 end
284 end
285
286 def binary_id(source_ids) when is_list(source_ids) do
287 Enum.map(source_ids, &binary_id/1)
288 end
289
290 def binary_id(%User{} = user), do: binary_id(user.id)
291
292 @doc "Returns status account"
293 @spec account_status(User.t()) :: account_status()
294 def account_status(%User{is_active: false}), do: :deactivated
295 def account_status(%User{password_reset_pending: true}), do: :password_reset_pending
296 def account_status(%User{local: true, is_approved: false}), do: :approval_pending
297 def account_status(%User{local: true, is_confirmed: false}), do: :confirmation_pending
298 def account_status(%User{}), do: :active
299
300 @spec visible_for(User.t(), User.t() | nil) ::
301 :visible
302 | :invisible
303 | :restricted_unauthenticated
304 | :deactivated
305 | :confirmation_pending
306 def visible_for(user, for_user \\ nil)
307
308 def visible_for(%User{invisible: true}, _), do: :invisible
309
310 def visible_for(%User{id: user_id}, %User{id: user_id}), do: :visible
311
312 def visible_for(%User{} = user, nil) do
313 if restrict_unauthenticated?(user) do
314 :restrict_unauthenticated
315 else
316 visible_account_status(user)
317 end
318 end
319
320 def visible_for(%User{} = user, for_user) do
321 if superuser?(for_user) do
322 :visible
323 else
324 visible_account_status(user)
325 end
326 end
327
328 def visible_for(_, _), do: :invisible
329
330 defp restrict_unauthenticated?(%User{local: true}) do
331 Config.restrict_unauthenticated_access?(:profiles, :local)
332 end
333
334 defp restrict_unauthenticated?(%User{local: _}) do
335 Config.restrict_unauthenticated_access?(:profiles, :remote)
336 end
337
338 defp visible_account_status(user) do
339 status = account_status(user)
340
341 if status in [:active, :password_reset_pending] do
342 :visible
343 else
344 status
345 end
346 end
347
348 @spec superuser?(User.t()) :: boolean()
349 def superuser?(%User{local: true, is_admin: true}), do: true
350 def superuser?(%User{local: true, is_moderator: true}), do: true
351 def superuser?(_), do: false
352
353 @spec invisible?(User.t()) :: boolean()
354 def invisible?(%User{invisible: true}), do: true
355 def invisible?(_), do: false
356
357 def avatar_url(user, options \\ []) do
358 case user.avatar do
359 %{"url" => [%{"href" => href} | _]} ->
360 href
361
362 _ ->
363 unless options[:no_default] do
364 Config.get([:assets, :default_user_avatar], "#{Endpoint.url()}/images/avi.png")
365 end
366 end
367 end
368
369 def banner_url(user, options \\ []) do
370 case user.banner do
371 %{"url" => [%{"href" => href} | _]} -> href
372 _ -> !options[:no_default] && "#{Endpoint.url()}/images/banner.png"
373 end
374 end
375
376 # Should probably be renamed or removed
377 @spec ap_id(User.t()) :: String.t()
378 def ap_id(%User{nickname: nickname}), do: "#{Endpoint.url()}/users/#{nickname}"
379
380 @spec ap_followers(User.t()) :: String.t()
381 def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
382 def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
383
384 @spec ap_following(User.t()) :: String.t()
385 def ap_following(%User{following_address: fa}) when is_binary(fa), do: fa
386 def ap_following(%User{} = user), do: "#{ap_id(user)}/following"
387
388 @spec ap_featured_collection(User.t()) :: String.t()
389 def ap_featured_collection(%User{featured_address: fa}) when is_binary(fa), do: fa
390
391 def ap_featured_collection(%User{} = user), do: "#{ap_id(user)}/collections/featured"
392
393 defp truncate_fields_param(params) do
394 if Map.has_key?(params, :fields) do
395 Map.put(params, :fields, Enum.map(params[:fields], &truncate_field/1))
396 else
397 params
398 end
399 end
400
401 defp truncate_if_exists(params, key, max_length) do
402 if Map.has_key?(params, key) and is_binary(params[key]) do
403 {value, _chopped} = String.split_at(params[key], max_length)
404 Map.put(params, key, value)
405 else
406 params
407 end
408 end
409
410 defp fix_follower_address(%{follower_address: _, following_address: _} = params), do: params
411
412 defp fix_follower_address(%{nickname: nickname} = params),
413 do: Map.put(params, :follower_address, ap_followers(%User{nickname: nickname}))
414
415 defp fix_follower_address(params), do: params
416
417 def remote_user_changeset(struct \\ %User{local: false}, params) do
418 bio_limit = Config.get([:instance, :user_bio_length], 5000)
419 name_limit = Config.get([:instance, :user_name_length], 100)
420
421 name =
422 case params[:name] do
423 name when is_binary(name) and byte_size(name) > 0 -> name
424 _ -> params[:nickname]
425 end
426
427 params =
428 params
429 |> Map.put(:name, name)
430 |> Map.put_new(:last_refreshed_at, NaiveDateTime.utc_now())
431 |> truncate_if_exists(:name, name_limit)
432 |> truncate_if_exists(:bio, bio_limit)
433 |> truncate_fields_param()
434 |> fix_follower_address()
435
436 struct
437 |> cast(
438 params,
439 [
440 :bio,
441 :emoji,
442 :ap_id,
443 :inbox,
444 :shared_inbox,
445 :nickname,
446 :public_key,
447 :avatar,
448 :ap_enabled,
449 :banner,
450 :is_locked,
451 :last_refreshed_at,
452 :uri,
453 :follower_address,
454 :following_address,
455 :featured_address,
456 :hide_followers,
457 :hide_follows,
458 :hide_followers_count,
459 :hide_follows_count,
460 :follower_count,
461 :fields,
462 :following_count,
463 :is_discoverable,
464 :invisible,
465 :actor_type,
466 :also_known_as,
467 :accepts_chat_messages,
468 :pinned_objects
469 ]
470 )
471 |> cast(params, [:name], empty_values: [])
472 |> validate_required([:ap_id])
473 |> validate_required([:name], trim: false)
474 |> unique_constraint(:nickname)
475 |> validate_format(:nickname, @email_regex)
476 |> validate_length(:bio, max: bio_limit)
477 |> validate_length(:name, max: name_limit)
478 |> validate_fields(true)
479 |> validate_non_local()
480 end
481
482 defp validate_non_local(cng) do
483 local? = get_field(cng, :local)
484
485 if local? do
486 cng
487 |> add_error(:local, "User is local, can't update with this changeset.")
488 else
489 cng
490 end
491 end
492
493 def update_changeset(struct, params \\ %{}) do
494 bio_limit = Config.get([:instance, :user_bio_length], 5000)
495 name_limit = Config.get([:instance, :user_name_length], 100)
496
497 struct
498 |> cast(
499 params,
500 [
501 :bio,
502 :raw_bio,
503 :name,
504 :emoji,
505 :avatar,
506 :public_key,
507 :inbox,
508 :shared_inbox,
509 :is_locked,
510 :no_rich_text,
511 :default_scope,
512 :banner,
513 :hide_follows,
514 :hide_followers,
515 :hide_followers_count,
516 :hide_follows_count,
517 :hide_favorites,
518 :allow_following_move,
519 :also_known_as,
520 :background,
521 :show_role,
522 :skip_thread_containment,
523 :fields,
524 :raw_fields,
525 :pleroma_settings_store,
526 :is_discoverable,
527 :actor_type,
528 :accepts_chat_messages,
529 :disclose_client
530 ]
531 )
532 |> unique_constraint(:nickname)
533 |> validate_format(:nickname, local_nickname_regex())
534 |> validate_length(:bio, max: bio_limit)
535 |> validate_length(:name, min: 1, max: name_limit)
536 |> validate_inclusion(:actor_type, ["Person", "Service"])
537 |> put_fields()
538 |> put_emoji()
539 |> put_change_if_present(:bio, &{:ok, parse_bio(&1, struct)})
540 |> put_change_if_present(:avatar, &put_upload(&1, :avatar))
541 |> put_change_if_present(:banner, &put_upload(&1, :banner))
542 |> put_change_if_present(:background, &put_upload(&1, :background))
543 |> put_change_if_present(
544 :pleroma_settings_store,
545 &{:ok, Map.merge(struct.pleroma_settings_store, &1)}
546 )
547 |> validate_fields(false)
548 end
549
550 defp put_fields(changeset) do
551 if raw_fields = get_change(changeset, :raw_fields) do
552 raw_fields =
553 raw_fields
554 |> Enum.filter(fn %{"name" => n} -> n != "" end)
555
556 fields =
557 raw_fields
558 |> Enum.map(fn f -> Map.update!(f, "value", &parse_fields(&1)) end)
559
560 changeset
561 |> put_change(:raw_fields, raw_fields)
562 |> put_change(:fields, fields)
563 else
564 changeset
565 end
566 end
567
568 defp parse_fields(value) do
569 value
570 |> Formatter.linkify(mentions_format: :full)
571 |> elem(0)
572 end
573
574 defp put_emoji(changeset) do
575 emojified_fields = [:bio, :name, :raw_fields]
576
577 if Enum.any?(changeset.changes, fn {k, _} -> k in emojified_fields end) do
578 bio = Emoji.Formatter.get_emoji_map(get_field(changeset, :bio))
579 name = Emoji.Formatter.get_emoji_map(get_field(changeset, :name))
580
581 emoji = Map.merge(bio, name)
582
583 emoji =
584 changeset
585 |> get_field(:raw_fields)
586 |> Enum.reduce(emoji, fn x, acc ->
587 Map.merge(acc, Emoji.Formatter.get_emoji_map(x["name"] <> x["value"]))
588 end)
589
590 put_change(changeset, :emoji, emoji)
591 else
592 changeset
593 end
594 end
595
596 defp put_change_if_present(changeset, map_field, value_function) do
597 with {:ok, value} <- fetch_change(changeset, map_field),
598 {:ok, new_value} <- value_function.(value) do
599 put_change(changeset, map_field, new_value)
600 else
601 _ -> changeset
602 end
603 end
604
605 defp put_upload(value, type) do
606 with %Plug.Upload{} <- value,
607 {:ok, object} <- ActivityPub.upload(value, type: type) do
608 {:ok, object.data}
609 end
610 end
611
612 def update_as_admin_changeset(struct, params) do
613 struct
614 |> update_changeset(params)
615 |> cast(params, [:email])
616 |> delete_change(:also_known_as)
617 |> unique_constraint(:email)
618 |> validate_format(:email, @email_regex)
619 |> validate_inclusion(:actor_type, ["Person", "Service"])
620 end
621
622 @spec update_as_admin(User.t(), map()) :: {:ok, User.t()} | {:error, Changeset.t()}
623 def update_as_admin(user, params) do
624 params = Map.put(params, "password_confirmation", params["password"])
625 changeset = update_as_admin_changeset(user, params)
626
627 if params["password"] do
628 reset_password(user, changeset, params)
629 else
630 User.update_and_set_cache(changeset)
631 end
632 end
633
634 def password_update_changeset(struct, params) do
635 struct
636 |> cast(params, [:password, :password_confirmation])
637 |> validate_required([:password, :password_confirmation])
638 |> validate_confirmation(:password)
639 |> put_password_hash()
640 |> put_change(:password_reset_pending, false)
641 end
642
643 @spec reset_password(User.t(), map()) :: {:ok, User.t()} | {:error, Changeset.t()}
644 def reset_password(%User{} = user, params) do
645 reset_password(user, user, params)
646 end
647
648 def reset_password(%User{id: user_id} = user, struct, params) do
649 multi =
650 Multi.new()
651 |> Multi.update(:user, password_update_changeset(struct, params))
652 |> Multi.delete_all(:tokens, OAuth.Token.Query.get_by_user(user_id))
653 |> Multi.delete_all(:auth, OAuth.Authorization.delete_by_user_query(user))
654
655 case Repo.transaction(multi) do
656 {:ok, %{user: user} = _} -> set_cache(user)
657 {:error, _, changeset, _} -> {:error, changeset}
658 end
659 end
660
661 def update_password_reset_pending(user, value) do
662 user
663 |> change()
664 |> put_change(:password_reset_pending, value)
665 |> update_and_set_cache()
666 end
667
668 def force_password_reset_async(user) do
669 BackgroundWorker.enqueue("force_password_reset", %{"user_id" => user.id})
670 end
671
672 @spec force_password_reset(User.t()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
673 def force_password_reset(user), do: update_password_reset_pending(user, true)
674
675 # Used to auto-register LDAP accounts which won't have a password hash stored locally
676 def register_changeset_ldap(struct, params = %{password: password})
677 when is_nil(password) do
678 params = Map.put_new(params, :accepts_chat_messages, true)
679
680 params =
681 if Map.has_key?(params, :email) do
682 Map.put_new(params, :email, params[:email])
683 else
684 params
685 end
686
687 struct
688 |> cast(params, [
689 :name,
690 :nickname,
691 :email,
692 :accepts_chat_messages
693 ])
694 |> validate_required([:name, :nickname])
695 |> unique_constraint(:nickname)
696 |> validate_exclusion(:nickname, Config.get([User, :restricted_nicknames]))
697 |> validate_format(:nickname, local_nickname_regex())
698 |> put_ap_id()
699 |> unique_constraint(:ap_id)
700 |> put_following_and_follower_and_featured_address()
701 end
702
703 def register_changeset(struct, params \\ %{}, opts \\ []) do
704 bio_limit = Config.get([:instance, :user_bio_length], 5000)
705 name_limit = Config.get([:instance, :user_name_length], 100)
706 reason_limit = Config.get([:instance, :registration_reason_length], 500)
707 params = Map.put_new(params, :accepts_chat_messages, true)
708
709 confirmed? =
710 if is_nil(opts[:confirmed]) do
711 !Config.get([:instance, :account_activation_required])
712 else
713 opts[:confirmed]
714 end
715
716 approved? =
717 if is_nil(opts[:approved]) do
718 !Config.get([:instance, :account_approval_required])
719 else
720 opts[:approved]
721 end
722
723 struct
724 |> confirmation_changeset(set_confirmation: confirmed?)
725 |> approval_changeset(set_approval: approved?)
726 |> cast(params, [
727 :bio,
728 :raw_bio,
729 :email,
730 :name,
731 :nickname,
732 :password,
733 :password_confirmation,
734 :emoji,
735 :accepts_chat_messages,
736 :registration_reason
737 ])
738 |> validate_required([:name, :nickname, :password, :password_confirmation])
739 |> validate_confirmation(:password)
740 |> unique_constraint(:email)
741 |> validate_format(:email, @email_regex)
742 |> validate_change(:email, fn :email, email ->
743 valid? =
744 Config.get([User, :email_blacklist])
745 |> Enum.all?(fn blacklisted_domain ->
746 !String.ends_with?(email, ["@" <> blacklisted_domain, "." <> blacklisted_domain])
747 end)
748
749 if valid?, do: [], else: [email: "Invalid email"]
750 end)
751 |> unique_constraint(:nickname)
752 |> validate_exclusion(:nickname, Config.get([User, :restricted_nicknames]))
753 |> validate_format(:nickname, local_nickname_regex())
754 |> validate_length(:bio, max: bio_limit)
755 |> validate_length(:name, min: 1, max: name_limit)
756 |> validate_length(:registration_reason, max: reason_limit)
757 |> maybe_validate_required_email(opts[:external])
758 |> put_password_hash
759 |> put_ap_id()
760 |> unique_constraint(:ap_id)
761 |> put_following_and_follower_and_featured_address()
762 end
763
764 def maybe_validate_required_email(changeset, true), do: changeset
765
766 def maybe_validate_required_email(changeset, _) do
767 if Config.get([:instance, :account_activation_required]) do
768 validate_required(changeset, [:email])
769 else
770 changeset
771 end
772 end
773
774 defp put_ap_id(changeset) do
775 ap_id = ap_id(%User{nickname: get_field(changeset, :nickname)})
776 put_change(changeset, :ap_id, ap_id)
777 end
778
779 defp put_following_and_follower_and_featured_address(changeset) do
780 user = %User{nickname: get_field(changeset, :nickname)}
781 followers = ap_followers(user)
782 following = ap_following(user)
783 featured = ap_featured_collection(user)
784
785 changeset
786 |> put_change(:follower_address, followers)
787 |> put_change(:following_address, following)
788 |> put_change(:featured_address, featured)
789 end
790
791 defp autofollow_users(user) do
792 candidates = Config.get([:instance, :autofollowed_nicknames])
793
794 autofollowed_users =
795 User.Query.build(%{nickname: candidates, local: true, is_active: true})
796 |> Repo.all()
797
798 follow_all(user, autofollowed_users)
799 end
800
801 defp autofollowing_users(user) do
802 candidates = Config.get([:instance, :autofollowing_nicknames])
803
804 User.Query.build(%{nickname: candidates, local: true, deactivated: false})
805 |> Repo.all()
806 |> Enum.each(&follow(&1, user, :follow_accept))
807
808 {:ok, :success}
809 end
810
811 @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
812 def register(%Ecto.Changeset{} = changeset) do
813 with {:ok, user} <- Repo.insert(changeset) do
814 post_register_action(user)
815 end
816 end
817
818 def post_register_action(%User{is_confirmed: false} = user) do
819 with {:ok, _} <- maybe_send_confirmation_email(user) do
820 {:ok, user}
821 end
822 end
823
824 def post_register_action(%User{is_approved: false} = user) do
825 with {:ok, _} <- send_user_approval_email(user),
826 {:ok, _} <- send_admin_approval_emails(user) do
827 {:ok, user}
828 end
829 end
830
831 def post_register_action(%User{is_approved: true, is_confirmed: true} = user) do
832 with {:ok, user} <- autofollow_users(user),
833 {:ok, _} <- autofollowing_users(user),
834 {:ok, user} <- set_cache(user),
835 {:ok, _} <- maybe_send_registration_email(user),
836 {:ok, _} <- maybe_send_welcome_email(user),
837 {:ok, _} <- maybe_send_welcome_message(user),
838 {:ok, _} <- maybe_send_welcome_chat_message(user) do
839 {:ok, user}
840 end
841 end
842
843 defp send_user_approval_email(user) do
844 user
845 |> Pleroma.Emails.UserEmail.approval_pending_email()
846 |> Pleroma.Emails.Mailer.deliver_async()
847
848 {:ok, :enqueued}
849 end
850
851 defp send_admin_approval_emails(user) do
852 all_superusers()
853 |> Enum.filter(fn user -> not is_nil(user.email) end)
854 |> Enum.each(fn superuser ->
855 superuser
856 |> Pleroma.Emails.AdminEmail.new_unapproved_registration(user)
857 |> Pleroma.Emails.Mailer.deliver_async()
858 end)
859
860 {:ok, :enqueued}
861 end
862
863 defp maybe_send_welcome_message(user) do
864 if User.WelcomeMessage.enabled?() do
865 User.WelcomeMessage.post_message(user)
866 {:ok, :enqueued}
867 else
868 {:ok, :noop}
869 end
870 end
871
872 defp maybe_send_welcome_chat_message(user) do
873 if User.WelcomeChatMessage.enabled?() do
874 User.WelcomeChatMessage.post_message(user)
875 {:ok, :enqueued}
876 else
877 {:ok, :noop}
878 end
879 end
880
881 defp maybe_send_welcome_email(%User{email: email} = user) when is_binary(email) do
882 if User.WelcomeEmail.enabled?() do
883 User.WelcomeEmail.send_email(user)
884 {:ok, :enqueued}
885 else
886 {:ok, :noop}
887 end
888 end
889
890 defp maybe_send_welcome_email(_), do: {:ok, :noop}
891
892 @spec maybe_send_confirmation_email(User.t()) :: {:ok, :enqueued | :noop}
893 def maybe_send_confirmation_email(%User{is_confirmed: false, email: email} = user)
894 when is_binary(email) do
895 if Config.get([:instance, :account_activation_required]) do
896 send_confirmation_email(user)
897 {:ok, :enqueued}
898 else
899 {:ok, :noop}
900 end
901 end
902
903 def maybe_send_confirmation_email(_), do: {:ok, :noop}
904
905 @spec send_confirmation_email(Uset.t()) :: User.t()
906 def send_confirmation_email(%User{} = user) do
907 user
908 |> Pleroma.Emails.UserEmail.account_confirmation_email()
909 |> Pleroma.Emails.Mailer.deliver_async()
910
911 user
912 end
913
914 @spec maybe_send_registration_email(User.t()) :: {:ok, :enqueued | :noop}
915 defp maybe_send_registration_email(%User{email: email} = user) when is_binary(email) do
916 with false <- User.WelcomeEmail.enabled?(),
917 false <- Config.get([:instance, :account_activation_required], false),
918 false <- Config.get([:instance, :account_approval_required], false) do
919 user
920 |> Pleroma.Emails.UserEmail.successful_registration_email()
921 |> Pleroma.Emails.Mailer.deliver_async()
922
923 {:ok, :enqueued}
924 else
925 _ ->
926 {:ok, :noop}
927 end
928 end
929
930 defp maybe_send_registration_email(_), do: {:ok, :noop}
931
932 def needs_update?(%User{local: true}), do: false
933
934 def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true
935
936 def needs_update?(%User{local: false} = user) do
937 NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
938 end
939
940 def needs_update?(_), do: true
941
942 @spec maybe_direct_follow(User.t(), User.t()) :: {:ok, User.t()} | {:error, String.t()}
943
944 # "Locked" (self-locked) users demand explicit authorization of follow requests
945 def maybe_direct_follow(%User{} = follower, %User{local: true, is_locked: true} = followed) do
946 follow(follower, followed, :follow_pending)
947 end
948
949 def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
950 follow(follower, followed)
951 end
952
953 def maybe_direct_follow(%User{} = follower, %User{} = followed) do
954 if not ap_enabled?(followed) do
955 follow(follower, followed)
956 else
957 {:ok, follower, followed}
958 end
959 end
960
961 @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
962 @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
963 def follow_all(follower, followeds) do
964 followeds
965 |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
966 |> Enum.each(&follow(follower, &1, :follow_accept))
967
968 set_cache(follower)
969 end
970
971 def follow(%User{} = follower, %User{} = followed, state \\ :follow_accept) do
972 deny_follow_blocked = Config.get([:user, :deny_follow_blocked])
973
974 cond do
975 not followed.is_active ->
976 {:error, "Could not follow user: #{followed.nickname} is deactivated."}
977
978 deny_follow_blocked and blocks?(followed, follower) ->
979 {:error, "Could not follow user: #{followed.nickname} blocked you."}
980
981 true ->
982 FollowingRelationship.follow(follower, followed, state)
983 end
984 end
985
986 def unfollow(%User{ap_id: ap_id}, %User{ap_id: ap_id}) do
987 {:error, "Not subscribed!"}
988 end
989
990 @spec unfollow(User.t(), User.t()) :: {:ok, User.t(), Activity.t()} | {:error, String.t()}
991 def unfollow(%User{} = follower, %User{} = followed) do
992 case do_unfollow(follower, followed) do
993 {:ok, follower, followed} ->
994 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
995
996 error ->
997 error
998 end
999 end
1000
1001 @spec do_unfollow(User.t(), User.t()) :: {:ok, User.t(), User.t()} | {:error, String.t()}
1002 defp do_unfollow(%User{} = follower, %User{} = followed) do
1003 case get_follow_state(follower, followed) do
1004 state when state in [:follow_pending, :follow_accept] ->
1005 FollowingRelationship.unfollow(follower, followed)
1006
1007 nil ->
1008 {:error, "Not subscribed!"}
1009 end
1010 end
1011
1012 @doc "Returns follow state as Pleroma.FollowingRelationship.State value"
1013 def get_follow_state(%User{} = follower, %User{} = following) do
1014 following_relationship = FollowingRelationship.get(follower, following)
1015 get_follow_state(follower, following, following_relationship)
1016 end
1017
1018 def get_follow_state(
1019 %User{} = follower,
1020 %User{} = following,
1021 following_relationship
1022 ) do
1023 case {following_relationship, following.local} do
1024 {nil, false} ->
1025 case Utils.fetch_latest_follow(follower, following) do
1026 %Activity{data: %{"state" => state}} when state in ["pending", "accept"] ->
1027 FollowingRelationship.state_to_enum(state)
1028
1029 _ ->
1030 nil
1031 end
1032
1033 {%{state: state}, _} ->
1034 state
1035
1036 {nil, _} ->
1037 nil
1038 end
1039 end
1040
1041 def locked?(%User{} = user) do
1042 user.is_locked || false
1043 end
1044
1045 def get_by_id(id) do
1046 Repo.get_by(User, id: id)
1047 end
1048
1049 def get_by_ap_id(ap_id) do
1050 Repo.get_by(User, ap_id: ap_id)
1051 end
1052
1053 def get_all_by_ap_id(ap_ids) do
1054 from(u in __MODULE__,
1055 where: u.ap_id in ^ap_ids
1056 )
1057 |> Repo.all()
1058 end
1059
1060 def get_all_by_ids(ids) do
1061 from(u in __MODULE__, where: u.id in ^ids)
1062 |> Repo.all()
1063 end
1064
1065 # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
1066 # of the ap_id and the domain and tries to get that user
1067 def get_by_guessed_nickname(ap_id) do
1068 domain = URI.parse(ap_id).host
1069 name = List.last(String.split(ap_id, "/"))
1070 nickname = "#{name}@#{domain}"
1071
1072 get_cached_by_nickname(nickname)
1073 end
1074
1075 def set_cache({:ok, user}), do: set_cache(user)
1076 def set_cache({:error, err}), do: {:error, err}
1077
1078 def set_cache(%User{} = user) do
1079 @cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
1080 @cachex.put(:user_cache, "nickname:#{user.nickname}", user)
1081 @cachex.put(:user_cache, "friends_ap_ids:#{user.nickname}", get_user_friends_ap_ids(user))
1082 {:ok, user}
1083 end
1084
1085 def update_and_set_cache(struct, params) do
1086 struct
1087 |> update_changeset(params)
1088 |> update_and_set_cache()
1089 end
1090
1091 def update_and_set_cache(changeset) do
1092 with {:ok, user} <- Repo.update(changeset, stale_error_field: :id) do
1093 Pleroma.Elasticsearch.maybe_put_into_elasticsearch(user)
1094 set_cache(user)
1095 end
1096 end
1097
1098 def get_user_friends_ap_ids(user) do
1099 from(u in User.get_friends_query(user), select: u.ap_id)
1100 |> Repo.all()
1101 end
1102
1103 @spec get_cached_user_friends_ap_ids(User.t()) :: [String.t()]
1104 def get_cached_user_friends_ap_ids(user) do
1105 @cachex.fetch!(:user_cache, "friends_ap_ids:#{user.ap_id}", fn _ ->
1106 get_user_friends_ap_ids(user)
1107 end)
1108 end
1109
1110 def invalidate_cache(user) do
1111 @cachex.del(:user_cache, "ap_id:#{user.ap_id}")
1112 @cachex.del(:user_cache, "nickname:#{user.nickname}")
1113 @cachex.del(:user_cache, "friends_ap_ids:#{user.ap_id}")
1114 @cachex.del(:user_cache, "blocked_users_ap_ids:#{user.ap_id}")
1115 @cachex.del(:user_cache, "muted_users_ap_ids:#{user.ap_id}")
1116 end
1117
1118 @spec get_cached_by_ap_id(String.t()) :: User.t() | nil
1119 def get_cached_by_ap_id(ap_id) do
1120 key = "ap_id:#{ap_id}"
1121
1122 with {:ok, nil} <- @cachex.get(:user_cache, key),
1123 user when not is_nil(user) <- get_by_ap_id(ap_id),
1124 {:ok, true} <- @cachex.put(:user_cache, key, user) do
1125 user
1126 else
1127 {:ok, user} -> user
1128 nil -> nil
1129 end
1130 end
1131
1132 def get_cached_by_id(id) do
1133 key = "id:#{id}"
1134
1135 ap_id =
1136 @cachex.fetch!(:user_cache, key, fn _ ->
1137 user = get_by_id(id)
1138
1139 if user do
1140 @cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
1141 {:commit, user.ap_id}
1142 else
1143 {:ignore, ""}
1144 end
1145 end)
1146
1147 get_cached_by_ap_id(ap_id)
1148 end
1149
1150 def get_cached_by_nickname(nickname) do
1151 key = "nickname:#{nickname}"
1152
1153 @cachex.fetch!(:user_cache, key, fn _ ->
1154 case get_or_fetch_by_nickname(nickname) do
1155 {:ok, user} -> {:commit, user}
1156 {:error, _error} -> {:ignore, nil}
1157 end
1158 end)
1159 end
1160
1161 def get_cached_by_nickname_or_id(nickname_or_id, opts \\ []) do
1162 restrict_to_local = Config.get([:instance, :limit_to_local_content])
1163
1164 cond do
1165 is_integer(nickname_or_id) or FlakeId.flake_id?(nickname_or_id) ->
1166 get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
1167
1168 restrict_to_local == false or not String.contains?(nickname_or_id, "@") ->
1169 get_cached_by_nickname(nickname_or_id)
1170
1171 restrict_to_local == :unauthenticated and match?(%User{}, opts[:for]) ->
1172 get_cached_by_nickname(nickname_or_id)
1173
1174 true ->
1175 nil
1176 end
1177 end
1178
1179 @spec get_by_nickname(String.t()) :: User.t() | nil
1180 def get_by_nickname(nickname) do
1181 Repo.get_by(User, nickname: nickname) ||
1182 if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
1183 Repo.get_by(User, nickname: local_nickname(nickname))
1184 end
1185 end
1186
1187 def get_by_email(email), do: Repo.get_by(User, email: email)
1188
1189 def get_by_nickname_or_email(nickname_or_email) do
1190 get_by_nickname(nickname_or_email) || get_by_email(nickname_or_email)
1191 end
1192
1193 def fetch_by_nickname(nickname), do: ActivityPub.make_user_from_nickname(nickname)
1194
1195 def get_or_fetch_by_nickname(nickname) do
1196 with %User{} = user <- get_by_nickname(nickname) do
1197 {:ok, user}
1198 else
1199 _e ->
1200 with [_nick, _domain] <- String.split(nickname, "@"),
1201 {:ok, user} <- fetch_by_nickname(nickname) do
1202 {:ok, user}
1203 else
1204 _e -> {:error, "not found " <> nickname}
1205 end
1206 end
1207 end
1208
1209 @spec get_followers_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
1210 def get_followers_query(%User{} = user, nil) do
1211 User.Query.build(%{followers: user, is_active: true})
1212 end
1213
1214 def get_followers_query(%User{} = user, page) do
1215 user
1216 |> get_followers_query(nil)
1217 |> User.Query.paginate(page, 20)
1218 end
1219
1220 @spec get_followers_query(User.t()) :: Ecto.Query.t()
1221 def get_followers_query(%User{} = user), do: get_followers_query(user, nil)
1222
1223 @spec get_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
1224 def get_followers(%User{} = user, page \\ nil) do
1225 user
1226 |> get_followers_query(page)
1227 |> Repo.all()
1228 end
1229
1230 @spec get_external_followers(User.t(), pos_integer() | nil) :: {:ok, list(User.t())}
1231 def get_external_followers(%User{} = user, page \\ nil) do
1232 user
1233 |> get_followers_query(page)
1234 |> User.Query.build(%{external: true})
1235 |> Repo.all()
1236 end
1237
1238 def get_followers_ids(%User{} = user, page \\ nil) do
1239 user
1240 |> get_followers_query(page)
1241 |> select([u], u.id)
1242 |> Repo.all()
1243 end
1244
1245 @spec get_friends_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
1246 def get_friends_query(%User{} = user, nil) do
1247 User.Query.build(%{friends: user, deactivated: false})
1248 end
1249
1250 def get_friends_query(%User{} = user, page) do
1251 user
1252 |> get_friends_query(nil)
1253 |> User.Query.paginate(page, 20)
1254 end
1255
1256 @spec get_friends_query(User.t()) :: Ecto.Query.t()
1257 def get_friends_query(%User{} = user), do: get_friends_query(user, nil)
1258
1259 def get_friends(%User{} = user, page \\ nil) do
1260 user
1261 |> get_friends_query(page)
1262 |> Repo.all()
1263 end
1264
1265 def get_friends_ap_ids(%User{} = user) do
1266 user
1267 |> get_friends_query(nil)
1268 |> select([u], u.ap_id)
1269 |> Repo.all()
1270 end
1271
1272 def get_friends_ids(%User{} = user, page \\ nil) do
1273 user
1274 |> get_friends_query(page)
1275 |> select([u], u.id)
1276 |> Repo.all()
1277 end
1278
1279 def increase_note_count(%User{} = user) do
1280 User
1281 |> where(id: ^user.id)
1282 |> update([u], inc: [note_count: 1])
1283 |> select([u], u)
1284 |> Repo.update_all([])
1285 |> case do
1286 {1, [user]} -> set_cache(user)
1287 _ -> {:error, user}
1288 end
1289 end
1290
1291 def decrease_note_count(%User{} = user) do
1292 User
1293 |> where(id: ^user.id)
1294 |> update([u],
1295 set: [
1296 note_count: fragment("greatest(0, note_count - 1)")
1297 ]
1298 )
1299 |> select([u], u)
1300 |> Repo.update_all([])
1301 |> case do
1302 {1, [user]} -> set_cache(user)
1303 _ -> {:error, user}
1304 end
1305 end
1306
1307 def update_note_count(%User{} = user, note_count \\ nil) do
1308 note_count =
1309 note_count ||
1310 from(
1311 a in Object,
1312 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
1313 select: count(a.id)
1314 )
1315 |> Repo.one()
1316
1317 user
1318 |> cast(%{note_count: note_count}, [:note_count])
1319 |> update_and_set_cache()
1320 end
1321
1322 @spec maybe_fetch_follow_information(User.t()) :: User.t()
1323 def maybe_fetch_follow_information(user) do
1324 with {:ok, user} <- fetch_follow_information(user) do
1325 user
1326 else
1327 e ->
1328 Logger.error("Follower/Following counter update for #{user.ap_id} failed.\n#{inspect(e)}")
1329
1330 user
1331 end
1332 end
1333
1334 def fetch_follow_information(user) do
1335 with {:ok, info} <- ActivityPub.fetch_follow_information_for_user(user) do
1336 user
1337 |> follow_information_changeset(info)
1338 |> update_and_set_cache()
1339 end
1340 end
1341
1342 defp follow_information_changeset(user, params) do
1343 user
1344 |> cast(params, [
1345 :hide_followers,
1346 :hide_follows,
1347 :follower_count,
1348 :following_count,
1349 :hide_followers_count,
1350 :hide_follows_count
1351 ])
1352 end
1353
1354 @spec update_follower_count(User.t()) :: {:ok, User.t()}
1355 def update_follower_count(%User{} = user) do
1356 if user.local or !Config.get([:instance, :external_user_synchronization]) do
1357 follower_count = FollowingRelationship.follower_count(user)
1358
1359 user
1360 |> follow_information_changeset(%{follower_count: follower_count})
1361 |> update_and_set_cache
1362 else
1363 {:ok, maybe_fetch_follow_information(user)}
1364 end
1365 end
1366
1367 @spec update_following_count(User.t()) :: {:ok, User.t()}
1368 def update_following_count(%User{local: false} = user) do
1369 if Config.get([:instance, :external_user_synchronization]) do
1370 {:ok, maybe_fetch_follow_information(user)}
1371 else
1372 {:ok, user}
1373 end
1374 end
1375
1376 def update_following_count(%User{local: true} = user) do
1377 following_count = FollowingRelationship.following_count(user)
1378
1379 user
1380 |> follow_information_changeset(%{following_count: following_count})
1381 |> update_and_set_cache()
1382 end
1383
1384 @spec get_users_from_set([String.t()], keyword()) :: [User.t()]
1385 def get_users_from_set(ap_ids, opts \\ []) do
1386 local_only = Keyword.get(opts, :local_only, true)
1387 criteria = %{ap_id: ap_ids, is_active: true}
1388 criteria = if local_only, do: Map.put(criteria, :local, true), else: criteria
1389
1390 User.Query.build(criteria)
1391 |> Repo.all()
1392 end
1393
1394 @spec get_recipients_from_activity(Activity.t()) :: [User.t()]
1395 def get_recipients_from_activity(%Activity{recipients: to, actor: actor}) do
1396 to = [actor | to]
1397
1398 query = User.Query.build(%{recipients_from_activity: to, local: true, is_active: true})
1399
1400 query
1401 |> Repo.all()
1402 end
1403
1404 @spec mute(User.t(), User.t(), map()) ::
1405 {:ok, list(UserRelationship.t())} | {:error, String.t()}
1406 def mute(%User{} = muter, %User{} = mutee, params \\ %{}) do
1407 notifications? = Map.get(params, :notifications, true)
1408 expires_in = Map.get(params, :expires_in, 0)
1409
1410 with {:ok, user_mute} <- UserRelationship.create_mute(muter, mutee),
1411 {:ok, user_notification_mute} <-
1412 (notifications? && UserRelationship.create_notification_mute(muter, mutee)) ||
1413 {:ok, nil} do
1414 if expires_in > 0 do
1415 Pleroma.Workers.MuteExpireWorker.enqueue(
1416 "unmute_user",
1417 %{"muter_id" => muter.id, "mutee_id" => mutee.id},
1418 schedule_in: expires_in
1419 )
1420 end
1421
1422 @cachex.del(:user_cache, "muted_users_ap_ids:#{muter.ap_id}")
1423
1424 {:ok, Enum.filter([user_mute, user_notification_mute], & &1)}
1425 end
1426 end
1427
1428 def unmute(%User{} = muter, %User{} = mutee) do
1429 with {:ok, user_mute} <- UserRelationship.delete_mute(muter, mutee),
1430 {:ok, user_notification_mute} <-
1431 UserRelationship.delete_notification_mute(muter, mutee) do
1432 @cachex.del(:user_cache, "muted_users_ap_ids:#{muter.ap_id}")
1433 {:ok, [user_mute, user_notification_mute]}
1434 end
1435 end
1436
1437 def unmute(muter_id, mutee_id) do
1438 with {:muter, %User{} = muter} <- {:muter, User.get_by_id(muter_id)},
1439 {:mutee, %User{} = mutee} <- {:mutee, User.get_by_id(mutee_id)} do
1440 unmute(muter, mutee)
1441 else
1442 {who, result} = error ->
1443 Logger.warn(
1444 "User.unmute/2 failed. #{who}: #{result}, muter_id: #{muter_id}, mutee_id: #{mutee_id}"
1445 )
1446
1447 {:error, error}
1448 end
1449 end
1450
1451 def subscribe(%User{} = subscriber, %User{} = target) do
1452 deny_follow_blocked = Config.get([:user, :deny_follow_blocked])
1453
1454 if blocks?(target, subscriber) and deny_follow_blocked do
1455 {:error, "Could not subscribe: #{target.nickname} is blocking you"}
1456 else
1457 # Note: the relationship is inverse: subscriber acts as relationship target
1458 UserRelationship.create_inverse_subscription(target, subscriber)
1459 end
1460 end
1461
1462 def subscribe(%User{} = subscriber, %{ap_id: ap_id}) do
1463 with %User{} = subscribee <- get_cached_by_ap_id(ap_id) do
1464 subscribe(subscriber, subscribee)
1465 end
1466 end
1467
1468 def unsubscribe(%User{} = unsubscriber, %User{} = target) do
1469 # Note: the relationship is inverse: subscriber acts as relationship target
1470 UserRelationship.delete_inverse_subscription(target, unsubscriber)
1471 end
1472
1473 def unsubscribe(%User{} = unsubscriber, %{ap_id: ap_id}) do
1474 with %User{} = user <- get_cached_by_ap_id(ap_id) do
1475 unsubscribe(unsubscriber, user)
1476 end
1477 end
1478
1479 def block(%User{} = blocker, %User{} = blocked) do
1480 # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
1481 blocker =
1482 if following?(blocker, blocked) do
1483 {:ok, blocker, _} = unfollow(blocker, blocked)
1484 blocker
1485 else
1486 blocker
1487 end
1488
1489 # clear any requested follows as well
1490 blocked =
1491 case CommonAPI.reject_follow_request(blocked, blocker) do
1492 {:ok, %User{} = updated_blocked} -> updated_blocked
1493 nil -> blocked
1494 end
1495
1496 unsubscribe(blocked, blocker)
1497
1498 unfollowing_blocked = Config.get([:activitypub, :unfollow_blocked], true)
1499 if unfollowing_blocked && following?(blocked, blocker), do: unfollow(blocked, blocker)
1500
1501 {:ok, blocker} = update_follower_count(blocker)
1502 {:ok, blocker, _} = Participation.mark_all_as_read(blocker, blocked)
1503 add_to_block(blocker, blocked)
1504 end
1505
1506 # helper to handle the block given only an actor's AP id
1507 def block(%User{} = blocker, %{ap_id: ap_id}) do
1508 block(blocker, get_cached_by_ap_id(ap_id))
1509 end
1510
1511 def unblock(%User{} = blocker, %User{} = blocked) do
1512 remove_from_block(blocker, blocked)
1513 end
1514
1515 # helper to handle the block given only an actor's AP id
1516 def unblock(%User{} = blocker, %{ap_id: ap_id}) do
1517 unblock(blocker, get_cached_by_ap_id(ap_id))
1518 end
1519
1520 def mutes?(nil, _), do: false
1521 def mutes?(%User{} = user, %User{} = target), do: mutes_user?(user, target)
1522
1523 def mutes_user?(%User{} = user, %User{} = target) do
1524 UserRelationship.mute_exists?(user, target)
1525 end
1526
1527 @spec muted_notifications?(User.t() | nil, User.t() | map()) :: boolean()
1528 def muted_notifications?(nil, _), do: false
1529
1530 def muted_notifications?(%User{} = user, %User{} = target),
1531 do: UserRelationship.notification_mute_exists?(user, target)
1532
1533 def blocks?(nil, _), do: false
1534
1535 def blocks?(%User{} = user, %User{} = target) do
1536 blocks_user?(user, target) ||
1537 (blocks_domain?(user, target) and not User.following?(user, target))
1538 end
1539
1540 def blocks_user?(%User{} = user, %User{} = target) do
1541 UserRelationship.block_exists?(user, target)
1542 end
1543
1544 def blocks_user?(_, _), do: false
1545
1546 def blocks_domain?(%User{} = user, %User{} = target) do
1547 domain_blocks = Pleroma.Web.ActivityPub.MRF.subdomains_regex(user.domain_blocks)
1548 %{host: host} = URI.parse(target.ap_id)
1549 Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, host)
1550 end
1551
1552 def blocks_domain?(_, _), do: false
1553
1554 def subscribed_to?(%User{} = user, %User{} = target) do
1555 # Note: the relationship is inverse: subscriber acts as relationship target
1556 UserRelationship.inverse_subscription_exists?(target, user)
1557 end
1558
1559 def subscribed_to?(%User{} = user, %{ap_id: ap_id}) do
1560 with %User{} = target <- get_cached_by_ap_id(ap_id) do
1561 subscribed_to?(user, target)
1562 end
1563 end
1564
1565 @doc """
1566 Returns map of outgoing (blocked, muted etc.) relationships' user AP IDs by relation type.
1567 E.g. `outgoing_relationships_ap_ids(user, [:block])` -> `%{block: ["https://some.site/users/userapid"]}`
1568 """
1569 @spec outgoing_relationships_ap_ids(User.t(), list(atom())) :: %{atom() => list(String.t())}
1570 def outgoing_relationships_ap_ids(_user, []), do: %{}
1571
1572 def outgoing_relationships_ap_ids(nil, _relationship_types), do: %{}
1573
1574 def outgoing_relationships_ap_ids(%User{} = user, relationship_types)
1575 when is_list(relationship_types) do
1576 db_result =
1577 user
1578 |> assoc(:outgoing_relationships)
1579 |> join(:inner, [user_rel], u in assoc(user_rel, :target))
1580 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1581 |> select([user_rel, u], [user_rel.relationship_type, fragment("array_agg(?)", u.ap_id)])
1582 |> group_by([user_rel, u], user_rel.relationship_type)
1583 |> Repo.all()
1584 |> Enum.into(%{}, fn [k, v] -> {k, v} end)
1585
1586 Enum.into(
1587 relationship_types,
1588 %{},
1589 fn rel_type -> {rel_type, db_result[rel_type] || []} end
1590 )
1591 end
1592
1593 def incoming_relationships_ungrouped_ap_ids(user, relationship_types, ap_ids \\ nil)
1594
1595 def incoming_relationships_ungrouped_ap_ids(_user, [], _ap_ids), do: []
1596
1597 def incoming_relationships_ungrouped_ap_ids(nil, _relationship_types, _ap_ids), do: []
1598
1599 def incoming_relationships_ungrouped_ap_ids(%User{} = user, relationship_types, ap_ids)
1600 when is_list(relationship_types) do
1601 user
1602 |> assoc(:incoming_relationships)
1603 |> join(:inner, [user_rel], u in assoc(user_rel, :source))
1604 |> where([user_rel, u], user_rel.relationship_type in ^relationship_types)
1605 |> maybe_filter_on_ap_id(ap_ids)
1606 |> select([user_rel, u], u.ap_id)
1607 |> distinct(true)
1608 |> Repo.all()
1609 end
1610
1611 defp maybe_filter_on_ap_id(query, ap_ids) when is_list(ap_ids) do
1612 where(query, [user_rel, u], u.ap_id in ^ap_ids)
1613 end
1614
1615 defp maybe_filter_on_ap_id(query, _ap_ids), do: query
1616
1617 def set_activation_async(user, status \\ true) do
1618 BackgroundWorker.enqueue("user_activation", %{"user_id" => user.id, "status" => status})
1619 end
1620
1621 @spec set_activation([User.t()], boolean()) :: {:ok, User.t()} | {:error, Changeset.t()}
1622 def set_activation(users, status) when is_list(users) do
1623 Repo.transaction(fn ->
1624 for user <- users, do: set_activation(user, status)
1625 end)
1626 end
1627
1628 @spec set_activation(User.t(), boolean()) :: {:ok, User.t()} | {:error, Changeset.t()}
1629 def set_activation(%User{} = user, status) do
1630 with {:ok, user} <- set_activation_status(user, status) do
1631 user
1632 |> get_followers()
1633 |> Enum.filter(& &1.local)
1634 |> Enum.each(&set_cache(update_following_count(&1)))
1635
1636 # Only update local user counts, remote will be update during the next pull.
1637 user
1638 |> get_friends()
1639 |> Enum.filter(& &1.local)
1640 |> Enum.each(&do_unfollow(user, &1))
1641
1642 {:ok, user}
1643 end
1644 end
1645
1646 def approve(users) when is_list(users) do
1647 Repo.transaction(fn ->
1648 Enum.map(users, fn user ->
1649 with {:ok, user} <- approve(user), do: user
1650 end)
1651 end)
1652 end
1653
1654 def approve(%User{is_approved: false} = user) do
1655 with chg <- change(user, is_approved: true),
1656 {:ok, user} <- update_and_set_cache(chg) do
1657 post_register_action(user)
1658 {:ok, user}
1659 end
1660 end
1661
1662 def approve(%User{} = user), do: {:ok, user}
1663
1664 def confirm(users) when is_list(users) do
1665 Repo.transaction(fn ->
1666 Enum.map(users, fn user ->
1667 with {:ok, user} <- confirm(user), do: user
1668 end)
1669 end)
1670 end
1671
1672 def confirm(%User{is_confirmed: false} = user) do
1673 with chg <- confirmation_changeset(user, set_confirmation: true),
1674 {:ok, user} <- update_and_set_cache(chg) do
1675 post_register_action(user)
1676 {:ok, user}
1677 end
1678 end
1679
1680 def confirm(%User{} = user), do: {:ok, user}
1681
1682 def set_suggestion(users, is_suggested) when is_list(users) do
1683 Repo.transaction(fn ->
1684 Enum.map(users, fn user ->
1685 with {:ok, user} <- set_suggestion(user, is_suggested), do: user
1686 end)
1687 end)
1688 end
1689
1690 def set_suggestion(%User{is_suggested: is_suggested} = user, is_suggested), do: {:ok, user}
1691
1692 def set_suggestion(%User{} = user, is_suggested) when is_boolean(is_suggested) do
1693 user
1694 |> change(is_suggested: is_suggested)
1695 |> update_and_set_cache()
1696 end
1697
1698 def update_notification_settings(%User{} = user, settings) do
1699 user
1700 |> cast(%{notification_settings: settings}, [])
1701 |> cast_embed(:notification_settings)
1702 |> validate_required([:notification_settings])
1703 |> update_and_set_cache()
1704 end
1705
1706 @spec purge_user_changeset(User.t()) :: Changeset.t()
1707 def purge_user_changeset(user) do
1708 # "Right to be forgotten"
1709 # https://gdpr.eu/right-to-be-forgotten/
1710 change(user, %{
1711 bio: "",
1712 raw_bio: nil,
1713 email: nil,
1714 name: nil,
1715 password_hash: nil,
1716 avatar: %{},
1717 tags: [],
1718 last_refreshed_at: nil,
1719 last_digest_emailed_at: nil,
1720 banner: %{},
1721 background: %{},
1722 note_count: 0,
1723 follower_count: 0,
1724 following_count: 0,
1725 is_locked: false,
1726 password_reset_pending: false,
1727 registration_reason: nil,
1728 confirmation_token: nil,
1729 domain_blocks: [],
1730 is_active: false,
1731 ap_enabled: false,
1732 is_moderator: false,
1733 is_admin: false,
1734 mascot: nil,
1735 emoji: %{},
1736 pleroma_settings_store: %{},
1737 fields: [],
1738 raw_fields: [],
1739 is_discoverable: false,
1740 also_known_as: []
1741 # id: preserved
1742 # ap_id: preserved
1743 # nickname: preserved
1744 })
1745 end
1746
1747 # Purge doesn't delete the user from the database.
1748 # It just nulls all its fields and deactivates it.
1749 # See `User.purge_user_changeset/1` above.
1750 defp purge(%User{} = user) do
1751 user
1752 |> purge_user_changeset()
1753 |> update_and_set_cache()
1754 end
1755
1756 def delete(users) when is_list(users) do
1757 for user <- users, do: delete(user)
1758 end
1759
1760 def delete(%User{} = user) do
1761 # Purge the user immediately
1762 purge(user)
1763 BackgroundWorker.enqueue("delete_user", %{"user_id" => user.id})
1764 end
1765
1766 # *Actually* delete the user from the DB
1767 defp delete_from_db(%User{} = user) do
1768 invalidate_cache(user)
1769 Repo.delete(user)
1770 end
1771
1772 # If the user never finalized their account, it's safe to delete them.
1773 defp maybe_delete_from_db(%User{local: true, is_confirmed: false} = user),
1774 do: delete_from_db(user)
1775
1776 defp maybe_delete_from_db(%User{local: true, is_approved: false} = user),
1777 do: delete_from_db(user)
1778
1779 defp maybe_delete_from_db(user), do: {:ok, user}
1780
1781 def perform(:force_password_reset, user), do: force_password_reset(user)
1782
1783 @spec perform(atom(), User.t()) :: {:ok, User.t()}
1784 def perform(:delete, %User{} = user) do
1785 # Purge the user again, in case perform/2 is called directly
1786 purge(user)
1787
1788 # Remove all relationships
1789 user
1790 |> get_followers()
1791 |> Enum.each(fn follower ->
1792 ActivityPub.unfollow(follower, user)
1793 unfollow(follower, user)
1794 end)
1795
1796 user
1797 |> get_friends()
1798 |> Enum.each(fn followed ->
1799 ActivityPub.unfollow(user, followed)
1800 unfollow(user, followed)
1801 end)
1802
1803 delete_user_activities(user)
1804 delete_notifications_from_user_activities(user)
1805 delete_outgoing_pending_follow_requests(user)
1806
1807 maybe_delete_from_db(user)
1808 end
1809
1810 def perform(:set_activation_async, user, status), do: set_activation(user, status)
1811
1812 @spec external_users_query() :: Ecto.Query.t()
1813 def external_users_query do
1814 User.Query.build(%{
1815 external: true,
1816 active: true,
1817 order_by: :id
1818 })
1819 end
1820
1821 @spec external_users(keyword()) :: [User.t()]
1822 def external_users(opts \\ []) do
1823 query =
1824 external_users_query()
1825 |> select([u], struct(u, [:id, :ap_id]))
1826
1827 query =
1828 if opts[:max_id],
1829 do: where(query, [u], u.id > ^opts[:max_id]),
1830 else: query
1831
1832 query =
1833 if opts[:limit],
1834 do: limit(query, ^opts[:limit]),
1835 else: query
1836
1837 Repo.all(query)
1838 end
1839
1840 def delete_notifications_from_user_activities(%User{ap_id: ap_id}) do
1841 Notification
1842 |> join(:inner, [n], activity in assoc(n, :activity))
1843 |> where([n, a], fragment("? = ?", a.actor, ^ap_id))
1844 |> Repo.delete_all()
1845 end
1846
1847 def delete_user_activities(%User{ap_id: ap_id} = user) do
1848 ap_id
1849 |> Activity.Queries.by_actor()
1850 |> Repo.chunk_stream(50, :batches)
1851 |> Stream.each(fn activities ->
1852 Enum.each(activities, fn activity -> delete_activity(activity, user) end)
1853 end)
1854 |> Stream.run()
1855 end
1856
1857 defp delete_activity(%{data: %{"type" => "Create", "object" => object}} = activity, user) do
1858 with {_, %Object{}} <- {:find_object, Object.get_by_ap_id(object)},
1859 {:ok, delete_data, _} <- Builder.delete(user, object) do
1860 Pipeline.common_pipeline(delete_data, local: user.local)
1861 else
1862 {:find_object, nil} ->
1863 # We have the create activity, but not the object, it was probably pruned.
1864 # Insert a tombstone and try again
1865 with {:ok, tombstone_data, _} <- Builder.tombstone(user.ap_id, object),
1866 {:ok, _tombstone} <- Object.create(tombstone_data) do
1867 delete_activity(activity, user)
1868 end
1869
1870 e ->
1871 Logger.error("Could not delete #{object} created by #{activity.data["ap_id"]}")
1872 Logger.error("Error: #{inspect(e)}")
1873 end
1874 end
1875
1876 defp delete_activity(%{data: %{"type" => type}} = activity, user)
1877 when type in ["Like", "Announce"] do
1878 {:ok, undo, _} = Builder.undo(user, activity)
1879 Pipeline.common_pipeline(undo, local: user.local)
1880 end
1881
1882 defp delete_activity(_activity, _user), do: "Doing nothing"
1883
1884 defp delete_outgoing_pending_follow_requests(user) do
1885 user
1886 |> FollowingRelationship.outgoing_pending_follow_requests_query()
1887 |> Repo.delete_all()
1888 end
1889
1890 def html_filter_policy(%User{no_rich_text: true}) do
1891 Pleroma.HTML.Scrubber.TwitterText
1892 end
1893
1894 def html_filter_policy(_), do: Config.get([:markup, :scrub_policy])
1895
1896 def fetch_by_ap_id(ap_id), do: ActivityPub.make_user_from_ap_id(ap_id)
1897
1898 def get_or_fetch_by_ap_id(ap_id) do
1899 cached_user = get_cached_by_ap_id(ap_id)
1900
1901 maybe_fetched_user = needs_update?(cached_user) && fetch_by_ap_id(ap_id)
1902
1903 case {cached_user, maybe_fetched_user} do
1904 {_, {:ok, %User{} = user}} ->
1905 {:ok, user}
1906
1907 {%User{} = user, _} ->
1908 {:ok, user}
1909
1910 _ ->
1911 {:error, :not_found}
1912 end
1913 end
1914
1915 @doc """
1916 Creates an internal service actor by URI if missing.
1917 Optionally takes nickname for addressing.
1918 """
1919 @spec get_or_create_service_actor_by_ap_id(String.t(), String.t()) :: User.t() | nil
1920 def get_or_create_service_actor_by_ap_id(uri, nickname) do
1921 {_, user} =
1922 case get_cached_by_ap_id(uri) do
1923 nil ->
1924 with {:error, %{errors: errors}} <- create_service_actor(uri, nickname) do
1925 Logger.error("Cannot create service actor: #{uri}/.\n#{inspect(errors)}")
1926 {:error, nil}
1927 end
1928
1929 %User{invisible: false} = user ->
1930 set_invisible(user)
1931
1932 user ->
1933 {:ok, user}
1934 end
1935
1936 user
1937 end
1938
1939 @spec set_invisible(User.t()) :: {:ok, User.t()}
1940 defp set_invisible(user) do
1941 user
1942 |> change(%{invisible: true})
1943 |> update_and_set_cache()
1944 end
1945
1946 @spec create_service_actor(String.t(), String.t()) ::
1947 {:ok, User.t()} | {:error, Ecto.Changeset.t()}
1948 defp create_service_actor(uri, nickname) do
1949 %User{
1950 invisible: true,
1951 local: true,
1952 ap_id: uri,
1953 nickname: nickname,
1954 follower_address: uri <> "/followers"
1955 }
1956 |> change
1957 |> unique_constraint(:nickname)
1958 |> Repo.insert()
1959 |> set_cache()
1960 end
1961
1962 def public_key(%{public_key: public_key_pem}) when is_binary(public_key_pem) do
1963 key =
1964 public_key_pem
1965 |> :public_key.pem_decode()
1966 |> hd()
1967 |> :public_key.pem_entry_decode()
1968
1969 {:ok, key}
1970 end
1971
1972 def public_key(_), do: {:error, "key not found"}
1973
1974 def get_public_key_for_ap_id(ap_id) do
1975 with {:ok, %User{} = user} <- get_or_fetch_by_ap_id(ap_id),
1976 {:ok, public_key} <- public_key(user) do
1977 {:ok, public_key}
1978 else
1979 _ -> :error
1980 end
1981 end
1982
1983 def ap_enabled?(%User{local: true}), do: true
1984 def ap_enabled?(%User{ap_enabled: ap_enabled}), do: ap_enabled
1985 def ap_enabled?(_), do: false
1986
1987 @doc "Gets or fetch a user by uri or nickname."
1988 @spec get_or_fetch(String.t()) :: {:ok, User.t()} | {:error, String.t()}
1989 def get_or_fetch("http" <> _host = uri), do: get_or_fetch_by_ap_id(uri)
1990 def get_or_fetch(nickname), do: get_or_fetch_by_nickname(nickname)
1991
1992 # wait a period of time and return newest version of the User structs
1993 # this is because we have synchronous follow APIs and need to simulate them
1994 # with an async handshake
1995 def wait_and_refresh(_, %User{local: true} = a, %User{local: true} = b) do
1996 with %User{} = a <- get_cached_by_id(a.id),
1997 %User{} = b <- get_cached_by_id(b.id) do
1998 {:ok, a, b}
1999 else
2000 nil -> :error
2001 end
2002 end
2003
2004 def wait_and_refresh(timeout, %User{} = a, %User{} = b) do
2005 with :ok <- :timer.sleep(timeout),
2006 %User{} = a <- get_cached_by_id(a.id),
2007 %User{} = b <- get_cached_by_id(b.id) do
2008 {:ok, a, b}
2009 else
2010 nil -> :error
2011 end
2012 end
2013
2014 def parse_bio(bio) when is_binary(bio) and bio != "" do
2015 bio
2016 |> CommonUtils.format_input("text/plain", mentions_format: :full)
2017 |> elem(0)
2018 end
2019
2020 def parse_bio(_), do: ""
2021
2022 def parse_bio(bio, user) when is_binary(bio) and bio != "" do
2023 # TODO: get profile URLs other than user.ap_id
2024 profile_urls = [user.ap_id]
2025
2026 bio
2027 |> CommonUtils.format_input("text/plain",
2028 mentions_format: :full,
2029 rel: &RelMe.maybe_put_rel_me(&1, profile_urls)
2030 )
2031 |> elem(0)
2032 end
2033
2034 def parse_bio(_, _), do: ""
2035
2036 def tag(user_identifiers, tags) when is_list(user_identifiers) do
2037 Repo.transaction(fn ->
2038 for user_identifier <- user_identifiers, do: tag(user_identifier, tags)
2039 end)
2040 end
2041
2042 def tag(nickname, tags) when is_binary(nickname),
2043 do: tag(get_by_nickname(nickname), tags)
2044
2045 def tag(%User{} = user, tags),
2046 do: update_tags(user, Enum.uniq((user.tags || []) ++ normalize_tags(tags)))
2047
2048 def untag(user_identifiers, tags) when is_list(user_identifiers) do
2049 Repo.transaction(fn ->
2050 for user_identifier <- user_identifiers, do: untag(user_identifier, tags)
2051 end)
2052 end
2053
2054 def untag(nickname, tags) when is_binary(nickname),
2055 do: untag(get_by_nickname(nickname), tags)
2056
2057 def untag(%User{} = user, tags),
2058 do: update_tags(user, (user.tags || []) -- normalize_tags(tags))
2059
2060 defp update_tags(%User{} = user, new_tags) do
2061 {:ok, updated_user} =
2062 user
2063 |> change(%{tags: new_tags})
2064 |> update_and_set_cache()
2065
2066 updated_user
2067 end
2068
2069 defp normalize_tags(tags) do
2070 [tags]
2071 |> List.flatten()
2072 |> Enum.map(&String.downcase/1)
2073 end
2074
2075 defp local_nickname_regex do
2076 if Config.get([:instance, :extended_nickname_format]) do
2077 @extended_local_nickname_regex
2078 else
2079 @strict_local_nickname_regex
2080 end
2081 end
2082
2083 def local_nickname(nickname_or_mention) do
2084 nickname_or_mention
2085 |> full_nickname()
2086 |> String.split("@")
2087 |> hd()
2088 end
2089
2090 def full_nickname(%User{} = user) do
2091 if String.contains?(user.nickname, "@") do
2092 user.nickname
2093 else
2094 %{host: host} = URI.parse(user.ap_id)
2095 user.nickname <> "@" <> host
2096 end
2097 end
2098
2099 def full_nickname(nickname_or_mention),
2100 do: String.trim_leading(nickname_or_mention, "@")
2101
2102 def error_user(ap_id) do
2103 %User{
2104 name: ap_id,
2105 ap_id: ap_id,
2106 nickname: "erroruser@example.com",
2107 inserted_at: NaiveDateTime.utc_now()
2108 }
2109 end
2110
2111 @spec all_superusers() :: [User.t()]
2112 def all_superusers do
2113 User.Query.build(%{super_users: true, local: true, is_active: true})
2114 |> Repo.all()
2115 end
2116
2117 def muting_reblogs?(%User{} = user, %User{} = target) do
2118 UserRelationship.reblog_mute_exists?(user, target)
2119 end
2120
2121 def showing_reblogs?(%User{} = user, %User{} = target) do
2122 not muting_reblogs?(user, target)
2123 end
2124
2125 @doc """
2126 The function returns a query to get users with no activity for given interval of days.
2127 Inactive users are those who didn't read any notification, or had any activity where
2128 the user is the activity's actor, during `inactivity_threshold` days.
2129 Deactivated users will not appear in this list.
2130
2131 ## Examples
2132
2133 iex> Pleroma.User.list_inactive_users()
2134 %Ecto.Query{}
2135 """
2136 @spec list_inactive_users_query(integer()) :: Ecto.Query.t()
2137 def list_inactive_users_query(inactivity_threshold \\ 7) do
2138 negative_inactivity_threshold = -inactivity_threshold
2139 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
2140 # Subqueries are not supported in `where` clauses, join gets too complicated.
2141 has_read_notifications =
2142 from(n in Pleroma.Notification,
2143 where: n.seen == true,
2144 group_by: n.id,
2145 having: max(n.updated_at) > datetime_add(^now, ^negative_inactivity_threshold, "day"),
2146 select: n.user_id
2147 )
2148 |> Pleroma.Repo.all()
2149
2150 from(u in Pleroma.User,
2151 left_join: a in Pleroma.Activity,
2152 on: u.ap_id == a.actor,
2153 where: not is_nil(u.nickname),
2154 where: u.is_active == ^true,
2155 where: u.id not in ^has_read_notifications,
2156 group_by: u.id,
2157 having:
2158 max(a.inserted_at) < datetime_add(^now, ^negative_inactivity_threshold, "day") or
2159 is_nil(max(a.inserted_at))
2160 )
2161 end
2162
2163 @doc """
2164 Enable or disable email notifications for user
2165
2166 ## Examples
2167
2168 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => false}}, "digest", true)
2169 Pleroma.User{email_notifications: %{"digest" => true}}
2170
2171 iex> Pleroma.User.switch_email_notifications(Pleroma.User{email_notifications: %{"digest" => true}}, "digest", false)
2172 Pleroma.User{email_notifications: %{"digest" => false}}
2173 """
2174 @spec switch_email_notifications(t(), String.t(), boolean()) ::
2175 {:ok, t()} | {:error, Ecto.Changeset.t()}
2176 def switch_email_notifications(user, type, status) do
2177 User.update_email_notifications(user, %{type => status})
2178 end
2179
2180 @doc """
2181 Set `last_digest_emailed_at` value for the user to current time
2182 """
2183 @spec touch_last_digest_emailed_at(t()) :: t()
2184 def touch_last_digest_emailed_at(user) do
2185 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
2186
2187 {:ok, updated_user} =
2188 user
2189 |> change(%{last_digest_emailed_at: now})
2190 |> update_and_set_cache()
2191
2192 updated_user
2193 end
2194
2195 @spec set_confirmation(User.t(), boolean()) :: {:ok, User.t()} | {:error, Changeset.t()}
2196 def set_confirmation(%User{} = user, bool) do
2197 user
2198 |> confirmation_changeset(set_confirmation: bool)
2199 |> update_and_set_cache()
2200 end
2201
2202 def get_mascot(%{mascot: %{} = mascot}) when not is_nil(mascot) do
2203 mascot
2204 end
2205
2206 def get_mascot(%{mascot: mascot}) when is_nil(mascot) do
2207 # use instance-default
2208 config = Config.get([:assets, :mascots])
2209 default_mascot = Config.get([:assets, :default_mascot])
2210 mascot = Keyword.get(config, default_mascot)
2211
2212 %{
2213 "id" => "default-mascot",
2214 "url" => mascot[:url],
2215 "preview_url" => mascot[:url],
2216 "pleroma" => %{
2217 "mime_type" => mascot[:mime_type]
2218 }
2219 }
2220 end
2221
2222 def ensure_keys_present(%{keys: keys} = user) when not is_nil(keys), do: {:ok, user}
2223
2224 def ensure_keys_present(%User{} = user) do
2225 with {:ok, pem} <- Keys.generate_rsa_pem() do
2226 user
2227 |> cast(%{keys: pem}, [:keys])
2228 |> validate_required([:keys])
2229 |> update_and_set_cache()
2230 end
2231 end
2232
2233 def get_ap_ids_by_nicknames(nicknames) do
2234 from(u in User,
2235 where: u.nickname in ^nicknames,
2236 select: u.ap_id
2237 )
2238 |> Repo.all()
2239 end
2240
2241 defp put_password_hash(
2242 %Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset
2243 ) do
2244 change(changeset, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))
2245 end
2246
2247 defp put_password_hash(changeset), do: changeset
2248
2249 def is_internal_user?(%User{nickname: nil}), do: true
2250 def is_internal_user?(%User{local: true, nickname: "internal." <> _}), do: true
2251 def is_internal_user?(_), do: false
2252
2253 # A hack because user delete activities have a fake id for whatever reason
2254 # TODO: Get rid of this
2255 def get_delivered_users_by_object_id("pleroma:fake_object_id"), do: []
2256
2257 def get_delivered_users_by_object_id(object_id) do
2258 from(u in User,
2259 inner_join: delivery in assoc(u, :deliveries),
2260 where: delivery.object_id == ^object_id
2261 )
2262 |> Repo.all()
2263 end
2264
2265 def change_email(user, email) do
2266 user
2267 |> cast(%{email: email}, [:email])
2268 |> maybe_validate_required_email(false)
2269 |> unique_constraint(:email)
2270 |> validate_format(:email, @email_regex)
2271 |> update_and_set_cache()
2272 end
2273
2274 # Internal function; public one is `deactivate/2`
2275 defp set_activation_status(user, status) do
2276 user
2277 |> cast(%{is_active: status}, [:is_active])
2278 |> update_and_set_cache()
2279 end
2280
2281 def update_banner(user, banner) do
2282 user
2283 |> cast(%{banner: banner}, [:banner])
2284 |> update_and_set_cache()
2285 end
2286
2287 def update_background(user, background) do
2288 user
2289 |> cast(%{background: background}, [:background])
2290 |> update_and_set_cache()
2291 end
2292
2293 def validate_fields(changeset, remote? \\ false) do
2294 limit_name = if remote?, do: :max_remote_account_fields, else: :max_account_fields
2295 limit = Config.get([:instance, limit_name], 0)
2296
2297 changeset
2298 |> validate_length(:fields, max: limit)
2299 |> validate_change(:fields, fn :fields, fields ->
2300 if Enum.all?(fields, &valid_field?/1) do
2301 []
2302 else
2303 [fields: "invalid"]
2304 end
2305 end)
2306 end
2307
2308 defp valid_field?(%{"name" => name, "value" => value}) do
2309 name_limit = Config.get([:instance, :account_field_name_length], 255)
2310 value_limit = Config.get([:instance, :account_field_value_length], 255)
2311
2312 is_binary(name) && is_binary(value) && String.length(name) <= name_limit &&
2313 String.length(value) <= value_limit
2314 end
2315
2316 defp valid_field?(_), do: false
2317
2318 defp truncate_field(%{"name" => name, "value" => value}) do
2319 {name, _chopped} =
2320 String.split_at(name, Config.get([:instance, :account_field_name_length], 255))
2321
2322 {value, _chopped} =
2323 String.split_at(value, Config.get([:instance, :account_field_value_length], 255))
2324
2325 %{"name" => name, "value" => value}
2326 end
2327
2328 def admin_api_update(user, params) do
2329 user
2330 |> cast(params, [
2331 :is_moderator,
2332 :is_admin,
2333 :show_role
2334 ])
2335 |> update_and_set_cache()
2336 end
2337
2338 @doc "Signs user out of all applications"
2339 def global_sign_out(user) do
2340 OAuth.Authorization.delete_user_authorizations(user)
2341 OAuth.Token.delete_user_tokens(user)
2342 end
2343
2344 def mascot_update(user, url) do
2345 user
2346 |> cast(%{mascot: url}, [:mascot])
2347 |> validate_required([:mascot])
2348 |> update_and_set_cache()
2349 end
2350
2351 @spec confirmation_changeset(User.t(), keyword()) :: Changeset.t()
2352 def confirmation_changeset(user, set_confirmation: confirmed?) do
2353 params =
2354 if confirmed? do
2355 %{
2356 is_confirmed: true,
2357 confirmation_token: nil
2358 }
2359 else
2360 %{
2361 is_confirmed: false,
2362 confirmation_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64()
2363 }
2364 end
2365
2366 cast(user, params, [:is_confirmed, :confirmation_token])
2367 end
2368
2369 @spec approval_changeset(User.t(), keyword()) :: Changeset.t()
2370 def approval_changeset(user, set_approval: approved?) do
2371 cast(user, %{is_approved: approved?}, [:is_approved])
2372 end
2373
2374 @spec add_pinned_object_id(User.t(), String.t()) :: {:ok, User.t()} | {:error, term()}
2375 def add_pinned_object_id(%User{} = user, object_id) do
2376 if !user.pinned_objects[object_id] do
2377 params = %{pinned_objects: Map.put(user.pinned_objects, object_id, NaiveDateTime.utc_now())}
2378
2379 user
2380 |> cast(params, [:pinned_objects])
2381 |> validate_change(:pinned_objects, fn :pinned_objects, pinned_objects ->
2382 max_pinned_statuses = Config.get([:instance, :max_pinned_statuses], 0)
2383
2384 if Enum.count(pinned_objects) <= max_pinned_statuses do
2385 []
2386 else
2387 [pinned_objects: "You have already pinned the maximum number of statuses"]
2388 end
2389 end)
2390 else
2391 change(user)
2392 end
2393 |> update_and_set_cache()
2394 end
2395
2396 @spec remove_pinned_object_id(User.t(), String.t()) :: {:ok, t()} | {:error, term()}
2397 def remove_pinned_object_id(%User{} = user, object_id) do
2398 user
2399 |> cast(
2400 %{pinned_objects: Map.delete(user.pinned_objects, object_id)},
2401 [:pinned_objects]
2402 )
2403 |> update_and_set_cache()
2404 end
2405
2406 def update_email_notifications(user, settings) do
2407 email_notifications =
2408 user.email_notifications
2409 |> Map.merge(settings)
2410 |> Map.take(["digest"])
2411
2412 params = %{email_notifications: email_notifications}
2413 fields = [:email_notifications]
2414
2415 user
2416 |> cast(params, fields)
2417 |> validate_required(fields)
2418 |> update_and_set_cache()
2419 end
2420
2421 defp set_domain_blocks(user, domain_blocks) do
2422 params = %{domain_blocks: domain_blocks}
2423
2424 user
2425 |> cast(params, [:domain_blocks])
2426 |> validate_required([:domain_blocks])
2427 |> update_and_set_cache()
2428 end
2429
2430 def block_domain(user, domain_blocked) do
2431 set_domain_blocks(user, Enum.uniq([domain_blocked | user.domain_blocks]))
2432 end
2433
2434 def unblock_domain(user, domain_blocked) do
2435 set_domain_blocks(user, List.delete(user.domain_blocks, domain_blocked))
2436 end
2437
2438 @spec add_to_block(User.t(), User.t()) ::
2439 {:ok, UserRelationship.t()} | {:error, Ecto.Changeset.t()}
2440 defp add_to_block(%User{} = user, %User{} = blocked) do
2441 with {:ok, relationship} <- UserRelationship.create_block(user, blocked) do
2442 @cachex.del(:user_cache, "blocked_users_ap_ids:#{user.ap_id}")
2443 {:ok, relationship}
2444 end
2445 end
2446
2447 @spec add_to_block(User.t(), User.t()) ::
2448 {:ok, UserRelationship.t()} | {:ok, nil} | {:error, Ecto.Changeset.t()}
2449 defp remove_from_block(%User{} = user, %User{} = blocked) do
2450 with {:ok, relationship} <- UserRelationship.delete_block(user, blocked) do
2451 @cachex.del(:user_cache, "blocked_users_ap_ids:#{user.ap_id}")
2452 {:ok, relationship}
2453 end
2454 end
2455
2456 def set_invisible(user, invisible) do
2457 params = %{invisible: invisible}
2458
2459 user
2460 |> cast(params, [:invisible])
2461 |> validate_required([:invisible])
2462 |> update_and_set_cache()
2463 end
2464
2465 def sanitize_html(%User{} = user) do
2466 sanitize_html(user, nil)
2467 end
2468
2469 # User data that mastodon isn't filtering (treated as plaintext):
2470 # - field name
2471 # - display name
2472 def sanitize_html(%User{} = user, filter) do
2473 fields =
2474 Enum.map(user.fields, fn %{"name" => name, "value" => value} ->
2475 %{
2476 "name" => name,
2477 "value" => HTML.filter_tags(value, Pleroma.HTML.Scrubber.LinksOnly)
2478 }
2479 end)
2480
2481 user
2482 |> Map.put(:bio, HTML.filter_tags(user.bio, filter))
2483 |> Map.put(:fields, fields)
2484 end
2485
2486 def get_host(%User{ap_id: ap_id} = _user) do
2487 URI.parse(ap_id).host
2488 end
2489
2490 def update_last_active_at(%__MODULE__{local: true} = user) do
2491 user
2492 |> cast(%{last_active_at: NaiveDateTime.utc_now()}, [:last_active_at])
2493 |> update_and_set_cache()
2494 end
2495
2496 def active_user_count(days \\ 30) do
2497 active_after = Timex.shift(NaiveDateTime.utc_now(), days: -days)
2498
2499 __MODULE__
2500 |> where([u], u.last_active_at >= ^active_after)
2501 |> where([u], u.local == true)
2502 |> Repo.aggregate(:count)
2503 end
2504
2505 def update_last_status_at(user) do
2506 User
2507 |> where(id: ^user.id)
2508 |> update([u], set: [last_status_at: fragment("NOW()")])
2509 |> select([u], u)
2510 |> Repo.update_all([])
2511 |> case do
2512 {1, [user]} -> set_cache(user)
2513 _ -> {:error, user}
2514 end
2515 end
2516 end