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