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