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