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