user.ex 36.5 KB
Newer Older
1
# Pleroma: A lightweight social networking server
2
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 4
# SPDX-License-Identifier: AGPL-3.0-only

lain's avatar
lain committed
5 6
defmodule Pleroma.User do
  use Ecto.Schema
7

Haelwenn's avatar
Haelwenn committed
8 9 10
  import Ecto.Changeset
  import Ecto.Query

11 12
  alias Comeonin.Pbkdf2
  alias Pleroma.Activity
13
  alias Pleroma.Keys
14 15
  alias Pleroma.Notification
  alias Pleroma.Object
16
  alias Pleroma.Registration
Haelwenn's avatar
Haelwenn committed
17
  alias Pleroma.Repo
Sergey Suprunenko's avatar
Sergey Suprunenko committed
18
  alias Pleroma.RepoStreamer
Haelwenn's avatar
Haelwenn committed
19 20
  alias Pleroma.User
  alias Pleroma.Web
21 22
  alias Pleroma.Web.ActivityPub.ActivityPub
  alias Pleroma.Web.ActivityPub.Utils
Maxim Filippov's avatar
Maxim Filippov committed
23
  alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils
Haelwenn's avatar
Haelwenn committed
24
  alias Pleroma.Web.OAuth
25
  alias Pleroma.Web.OStatus
26
  alias Pleroma.Web.RelMe
27
  alias Pleroma.Web.Websub
lain's avatar
lain committed
28

29 30
  require Logger

Maksim's avatar
Maksim committed
31 32
  @type t :: %__MODULE__{}

href's avatar
href committed
33 34
  @primary_key {:id, Pleroma.FlakeId, autogenerate: true}

35
  # credo:disable-for-next-line Credo.Check.Readability.MaxLineLength
href's avatar
href committed
36 37 38
  @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])?)*$/

  @strict_local_nickname_regex ~r/^[a-zA-Z\d]+$/
href's avatar
href committed
39
  @extended_local_nickname_regex ~r/^[a-zA-Z\d_-]+$/
href's avatar
href committed
40

lain's avatar
lain committed
41
  schema "users" do
lain's avatar
lain committed
42 43 44 45 46 47 48 49 50 51 52 53
    field(:bio, :string)
    field(:email, :string)
    field(:name, :string)
    field(:nickname, :string)
    field(:password_hash, :string)
    field(:password, :string, virtual: true)
    field(:password_confirmation, :string, virtual: true)
    field(:following, {:array, :string}, default: [])
    field(:ap_id, :string)
    field(:avatar, :map)
    field(:local, :boolean, default: true)
    field(:follower_address, :string)
54
    field(:search_rank, :float, virtual: true)
55
    field(:search_type, :integer, virtual: true)
56
    field(:tags, {:array, :string}, default: [])
rinpatch's avatar
rinpatch committed
57
    field(:last_refreshed_at, :naive_datetime_usec)
lain's avatar
lain committed
58
    has_many(:notifications, Notification)
59
    has_many(:registrations, Registration)
60
    embeds_one(:info, User.Info)
lain's avatar
lain committed
61 62 63

    timestamps()
  end
lain's avatar
lain committed
64

65 66
  def auth_active?(%User{info: %User.Info{confirmation_pending: true}}),
    do: !Pleroma.Config.get([:instance, :account_activation_required])
67

68
  def auth_active?(%User{}), do: true
69

70 71 72 73 74
  def visible_for?(user, for_user \\ nil)

  def visible_for?(%User{id: user_id}, %User{id: for_id}) when user_id == for_id, do: true

  def visible_for?(%User{} = user, for_user) do
75
    auth_active?(user) || superuser?(for_user)
76 77
  end

78 79
  def visible_for?(_, _), do: false

80 81
  def superuser?(%User{local: true, info: %User.Info{is_admin: true}}), do: true
  def superuser?(%User{local: true, info: %User.Info{is_moderator: true}}), do: true
82
  def superuser?(_), do: false
83

84
  def avatar_url(user, options \\ []) do
lain's avatar
lain committed
85 86
    case user.avatar do
      %{"url" => [%{"href" => href} | _]} -> href
87
      _ -> !options[:no_default] && "#{Web.base_url()}/images/avi.png"
lain's avatar
lain committed
88 89 90
    end
  end

91
  def banner_url(user, options \\ []) do
lain's avatar
lain committed
92
    case user.info.banner do
lain's avatar
lain committed
93
      %{"url" => [%{"href" => href} | _]} -> href
94
      _ -> !options[:no_default] && "#{Web.base_url()}/images/banner.png"
lain's avatar
lain committed
95 96 97
    end
  end

lain's avatar
lain committed
98
  def profile_url(%User{info: %{source_data: %{"url" => url}}}), do: url
99 100 101
  def profile_url(%User{ap_id: ap_id}), do: ap_id
  def profile_url(_), do: nil

lain's avatar
lain committed
102
  def ap_id(%User{nickname: nickname}) do
lain's avatar
lain committed
103
    "#{Web.base_url()}/users/#{nickname}"
lain's avatar
lain committed
104 105
  end

106 107
  def ap_followers(%User{follower_address: fa}) when is_binary(fa), do: fa
  def ap_followers(%User{} = user), do: "#{ap_id(user)}/followers"
lain's avatar
lain committed
108

lain's avatar
lain committed
109 110
  def user_info(%User{} = user) do
    %{
111
      following_count: following_count(user),
lain's avatar
lain committed
112 113 114
      note_count: user.info.note_count,
      follower_count: user.info.follower_count,
      locked: user.info.locked,
Ivan Tashkinov's avatar
Ivan Tashkinov committed
115
      confirmation_pending: user.info.confirmation_pending,
lain's avatar
lain committed
116
      default_scope: user.info.default_scope
lain's avatar
lain committed
117 118 119
    }
  end

120
  def restrict_deactivated(query) do
121
    from(u in query,
122
      where: not fragment("? \\? 'deactivated' AND ?->'deactivated' @> 'true'", u.info, u.info)
123 124 125 126 127
    )
  end

  def following_count(%User{following: []}), do: 0

128 129 130
  def following_count(%User{} = user) do
    user
    |> get_friends_query()
131 132 133
    |> Repo.aggregate(:count, :id)
  end

lain's avatar
lain committed
134
  def remote_user_creation(params) do
lain's avatar
lain committed
135 136 137
    params =
      params
      |> Map.put(:info, params[:info] || %{})
lain's avatar
lain committed
138 139 140

    info_cng = User.Info.remote_user_creation(%User.Info{}, params[:info])

lain's avatar
lain committed
141
    changes =
lain's avatar
lain committed
142
      %User{}
lain's avatar
lain committed
143
      |> cast(params, [:bio, :name, :ap_id, :nickname, :avatar])
144
      |> validate_required([:name, :ap_id])
lain's avatar
lain committed
145 146 147 148 149
      |> unique_constraint(:nickname)
      |> validate_format(:nickname, @email_regex)
      |> validate_length(:bio, max: 5000)
      |> validate_length(:name, max: 100)
      |> put_change(:local, false)
lain's avatar
lain committed
150
      |> put_embed(:info, info_cng)
lain's avatar
lain committed
151

152
    if changes.valid? do
lain's avatar
lain committed
153
      case info_cng.changes[:source_data] do
lain's avatar
lain committed
154 155 156
        %{"followers" => followers} ->
          changes
          |> put_change(:follower_address, followers)
lain's avatar
lain committed
157

lain's avatar
lain committed
158 159
        _ ->
          followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
lain's avatar
lain committed
160

lain's avatar
lain committed
161 162 163
          changes
          |> put_change(:follower_address, followers)
      end
164 165 166
    else
      changes
    end
lain's avatar
lain committed
167 168
  end

lain's avatar
lain committed
169
  def update_changeset(struct, params \\ %{}) do
Thog's avatar
Thog committed
170
    struct
171
    |> cast(params, [:bio, :name, :avatar, :following])
lain's avatar
lain committed
172
    |> unique_constraint(:nickname)
href's avatar
href committed
173
    |> validate_format(:nickname, local_nickname_regex())
lain's avatar
lain committed
174
    |> validate_length(:bio, max: 5000)
lain's avatar
lain committed
175 176 177
    |> validate_length(:name, min: 1, max: 100)
  end

lain's avatar
lain committed
178
  def upgrade_changeset(struct, params \\ %{}) do
179 180 181 182
    params =
      params
      |> Map.put(:last_refreshed_at, NaiveDateTime.utc_now())

lain's avatar
lain committed
183 184 185 186
    info_cng =
      struct.info
      |> User.Info.user_upgrade(params[:info])

lain's avatar
lain committed
187
    struct
lain's avatar
lain committed
188
    |> cast(params, [:bio, :name, :follower_address, :avatar, :last_refreshed_at])
lain's avatar
lain committed
189
    |> unique_constraint(:nickname)
href's avatar
href committed
190
    |> validate_format(:nickname, local_nickname_regex())
lain's avatar
lain committed
191 192
    |> validate_length(:bio, max: 5000)
    |> validate_length(:name, max: 100)
lain's avatar
lain committed
193
    |> put_embed(:info, info_cng)
lain's avatar
lain committed
194 195
  end

Roger Braun's avatar
Roger Braun committed
196
  def password_update_changeset(struct, params) do
lain's avatar
lain committed
197 198 199 200 201
    changeset =
      struct
      |> cast(params, [:password, :password_confirmation])
      |> validate_required([:password, :password_confirmation])
      |> validate_confirmation(:password)
Roger Braun's avatar
Roger Braun committed
202

203 204 205
    OAuth.Token.delete_user_tokens(struct)
    OAuth.Authorization.delete_user_authorizations(struct)

Roger Braun's avatar
Roger Braun committed
206 207
    if changeset.valid? do
      hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
lain's avatar
lain committed
208

Roger Braun's avatar
Roger Braun committed
209 210 211 212 213 214 215 216
      changeset
      |> put_change(:password_hash, hashed)
    else
      changeset
    end
  end

  def reset_password(user, data) do
lain's avatar
lain committed
217
    update_and_set_cache(password_update_changeset(user, data))
Roger Braun's avatar
Roger Braun committed
218 219
  end

220
  def register_changeset(struct, params \\ %{}, opts \\ []) do
221 222 223
    need_confirmation? =
      if is_nil(opts[:need_confirmation]) do
        Pleroma.Config.get([:instance, :account_activation_required])
224
      else
225
        opts[:need_confirmation]
226 227
      end

228 229
    info_change =
      User.Info.confirmation_changeset(%User.Info{}, need_confirmation: need_confirmation?)
Ivan Tashkinov's avatar
Ivan Tashkinov committed
230

lain's avatar
lain committed
231 232 233
    changeset =
      struct
      |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
234
      |> validate_required([:name, :nickname, :password, :password_confirmation])
lain's avatar
lain committed
235 236 237
      |> validate_confirmation(:password)
      |> unique_constraint(:email)
      |> unique_constraint(:nickname)
238
      |> validate_exclusion(:nickname, Pleroma.Config.get([User, :restricted_nicknames]))
href's avatar
href committed
239
      |> validate_format(:nickname, local_nickname_regex())
lain's avatar
lain committed
240 241 242
      |> validate_format(:email, @email_regex)
      |> validate_length(:bio, max: 1000)
      |> validate_length(:name, min: 1, max: 100)
Ivan Tashkinov's avatar
Ivan Tashkinov committed
243
      |> put_change(:info, info_change)
lain's avatar
lain committed
244

245 246 247 248 249 250 251
    changeset =
      if opts[:external] do
        changeset
      else
        validate_required(changeset, [:email])
      end

lain's avatar
lain committed
252
    if changeset.valid? do
253
      hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
lain's avatar
lain committed
254 255
      ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
      followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
lain's avatar
lain committed
256

lain's avatar
lain committed
257 258 259
      changeset
      |> put_change(:password_hash, hashed)
      |> put_change(:ap_id, ap_id)
rinpatch's avatar
rinpatch committed
260
      |> unique_constraint(:ap_id)
lain's avatar
lain committed
261
      |> put_change(:following, [followers])
262
      |> put_change(:follower_address, followers)
lain's avatar
lain committed
263 264 265 266 267
    else
      changeset
    end
  end

268 269 270 271
  defp autofollow_users(user) do
    candidates = Pleroma.Config.get([:instance, :autofollowed_nicknames])

    autofollowed_users =
272
      User.Query.build(%{nickname: candidates, local: true, deactivated: false})
273 274
      |> Repo.all()

lain's avatar
lain committed
275
    follow_all(user, autofollowed_users)
276 277
  end

278 279
  @doc "Inserts provided changeset, performs post-registration actions (confirmation email sending etc.)"
  def register(%Ecto.Changeset{} = changeset) do
Ivan Tashkinov's avatar
Ivan Tashkinov committed
280
    with {:ok, user} <- Repo.insert(changeset),
lain's avatar
lain committed
281
         {:ok, user} <- autofollow_users(user),
minibikini's avatar
minibikini committed
282
         {:ok, user} <- set_cache(user),
283
         {:ok, _} <- User.WelcomeMessage.post_welcome_message_to_user(user),
lain's avatar
lain committed
284
         {:ok, _} <- try_send_confirmation_email(user) do
285 286 287 288
      {:ok, user}
    end
  end

289
  def try_send_confirmation_email(%User{} = user) do
290 291
    if user.info.confirmation_pending &&
         Pleroma.Config.get([:instance, :account_activation_required]) do
292
      user
293 294
      |> Pleroma.Emails.UserEmail.account_confirmation_email()
      |> Pleroma.Emails.Mailer.deliver_async()
295 296

      {:ok, :enqueued}
297 298 299 300 301
    else
      {:ok, :noop}
    end
  end

302 303 304 305 306
  def needs_update?(%User{local: true}), do: false

  def needs_update?(%User{local: false, last_refreshed_at: nil}), do: true

  def needs_update?(%User{local: false} = user) do
307
    NaiveDateTime.diff(NaiveDateTime.utc_now(), user.last_refreshed_at) >= 86_400
308 309 310 311
  end

  def needs_update?(_), do: true

lain's avatar
lain committed
312
  def maybe_direct_follow(%User{} = follower, %User{local: true, info: %{locked: true}}) do
313 314 315 316 317 318 319 320
    {:ok, follower}
  end

  def maybe_direct_follow(%User{} = follower, %User{local: true} = followed) do
    follow(follower, followed)
  end

  def maybe_direct_follow(%User{} = follower, %User{} = followed) do
Maksim's avatar
Maksim committed
321
    if not User.ap_enabled?(followed) do
322
      follow(follower, followed)
323 324 325 326 327
    else
      {:ok, follower}
    end
  end

328
  @doc "A mass follow for local users. Respects blocks in both directions but does not create activities."
lain's avatar
lain committed
329 330
  @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
  def follow_all(follower, followeds) do
lain's avatar
lain committed
331 332
    followed_addresses =
      followeds
333
      |> Enum.reject(fn followed -> blocks?(follower, followed) || blocks?(followed, follower) end)
lain's avatar
lain committed
334
      |> Enum.map(fn %{follower_address: fa} -> fa end)
lain's avatar
lain committed
335

lain's avatar
lain committed
336 337 338
    q =
      from(u in User,
        where: u.id == ^follower.id,
339 340 341 342 343 344 345 346 347
        update: [
          set: [
            following:
              fragment(
                "array(select distinct unnest (array_cat(?, ?)))",
                u.following,
                ^followed_addresses
              )
          ]
rinpatch's avatar
rinpatch committed
348 349
        ],
        select: u
lain's avatar
lain committed
350 351
      )

rinpatch's avatar
rinpatch committed
352
    {1, [follower]} = Repo.update_all(q, [])
lain's avatar
lain committed
353 354 355 356 357

    Enum.each(followeds, fn followed ->
      update_follower_count(followed)
    end)

lain's avatar
lain committed
358
    set_cache(follower)
lain's avatar
lain committed
359 360
  end

lain's avatar
lain committed
361
  def follow(%User{} = follower, %User{info: info} = followed) do
minibikini's avatar
minibikini committed
362
    deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
363
    ap_followers = followed.follower_address
364

365
    cond do
366
      info.deactivated ->
lain's avatar
lain committed
367
        {:error, "Could not follow user: You are deactivated."}
lain's avatar
lain committed
368

369
      deny_follow_blocked and blocks?(followed, follower) ->
370
        {:error, "Could not follow user: #{followed.nickname} blocked you."}
lain's avatar
lain committed
371

372 373 374 375 376
      true ->
        if !followed.local && follower.local && !ap_enabled?(followed) do
          Websub.subscribe(follower, followed)
        end

377 378 379
        q =
          from(u in User,
            where: u.id == ^follower.id,
rinpatch's avatar
rinpatch committed
380 381
            update: [push: [following: ^ap_followers]],
            select: u
382
          )
383

rinpatch's avatar
rinpatch committed
384
        {1, [follower]} = Repo.update_all(q, [])
385

386 387
        {:ok, _} = update_follower_count(followed)

388
        set_cache(follower)
389
    end
lain's avatar
lain committed
390
  end
lain's avatar
lain committed
391 392

  def unfollow(%User{} = follower, %User{} = followed) do
393
    ap_followers = followed.follower_address
lain's avatar
lain committed
394

395
    if following?(follower, followed) and follower.ap_id != followed.ap_id do
396 397 398
      q =
        from(u in User,
          where: u.id == ^follower.id,
rinpatch's avatar
rinpatch committed
399 400
          update: [pull: [following: ^ap_followers]],
          select: u
401
        )
lain's avatar
lain committed
402

rinpatch's avatar
rinpatch committed
403
      {1, [follower]} = Repo.update_all(q, [])
404 405 406

      {:ok, followed} = update_follower_count(followed)

407 408
      set_cache(follower)

409
      {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
410
    else
411
      {:error, "Not subscribed!"}
412
    end
lain's avatar
lain committed
413
  end
414

Maksim's avatar
Maksim committed
415
  @spec following?(User.t(), User.t()) :: boolean
416
  def following?(%User{} = follower, %User{} = followed) do
417
    Enum.member?(follower.following, followed.follower_address)
418
  end
lain's avatar
lain committed
419

420
  def locked?(%User{} = user) do
421
    user.info.locked || false
422 423
  end

424 425 426 427
  def get_by_id(id) do
    Repo.get_by(User, id: id)
  end

lain's avatar
lain committed
428 429 430 431
  def get_by_ap_id(ap_id) do
    Repo.get_by(User, ap_id: ap_id)
  end

432 433
  # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
  # of the ap_id and the domain and tries to get that user
434 435 436 437 438
  def get_by_guessed_nickname(ap_id) do
    domain = URI.parse(ap_id).host
    name = List.last(String.split(ap_id, "/"))
    nickname = "#{name}@#{domain}"

minibikini's avatar
minibikini committed
439
    get_cached_by_nickname(nickname)
440 441
  end

minibikini's avatar
minibikini committed
442 443 444 445
  def set_cache({:ok, user}), do: set_cache(user)
  def set_cache({:error, err}), do: {:error, err}

  def set_cache(%User{} = user) do
446 447 448 449 450 451
    Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
    Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
    Cachex.put(:user_cache, "user_info:#{user.id}", user_info(user))
    {:ok, user}
  end

lain's avatar
lain committed
452 453
  def update_and_set_cache(changeset) do
    with {:ok, user} <- Repo.update(changeset) do
454
      set_cache(user)
lain's avatar
lain committed
455 456 457 458 459
    else
      e -> e
    end
  end

lain's avatar
lain committed
460 461 462
  def invalidate_cache(user) do
    Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
    Cachex.del(:user_cache, "nickname:#{user.nickname}")
463
    Cachex.del(:user_cache, "user_info:#{user.id}")
lain's avatar
lain committed
464 465
  end

lain's avatar
lain committed
466
  def get_cached_by_ap_id(ap_id) do
467
    key = "ap_id:#{ap_id}"
Thog's avatar
Thog committed
468
    Cachex.fetch!(:user_cache, key, fn _ -> get_by_ap_id(ap_id) end)
lain's avatar
lain committed
469 470
  end

471 472
  def get_cached_by_id(id) do
    key = "id:#{id}"
473 474 475 476

    ap_id =
      Cachex.fetch!(:user_cache, key, fn _ ->
        user = get_by_id(id)
477 478 479 480 481 482 483

        if user do
          Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
          {:commit, user.ap_id}
        else
          {:ignore, ""}
        end
484 485 486
      end)

    get_cached_by_ap_id(ap_id)
487 488
  end

lain's avatar
lain committed
489
  def get_cached_by_nickname(nickname) do
490
    key = "nickname:#{nickname}"
0x1C3B00DA's avatar
Run  
0x1C3B00DA committed
491

492 493 494 495 496
    Cachex.fetch!(:user_cache, key, fn ->
      user_result = get_or_fetch_by_nickname(nickname)

      case user_result do
        {:ok, user} -> {:commit, user}
Alexander Strizhakov's avatar
Alexander Strizhakov committed
497
        {:error, _error} -> {:ignore, nil}
498 499
      end
    end)
lain's avatar
lain committed
500
  end
lain's avatar
lain committed
501

502
  def get_cached_by_nickname_or_id(nickname_or_id) do
503
    get_cached_by_id(nickname_or_id) || get_cached_by_nickname(nickname_or_id)
504 505
  end

lain's avatar
lain committed
506
  def get_by_nickname(nickname) do
507
    Repo.get_by(User, nickname: nickname) ||
508
      if Regex.match?(~r(@#{Pleroma.Web.Endpoint.host()})i, nickname) do
509
        Repo.get_by(User, nickname: local_nickname(nickname))
510
      end
511 512
  end

513 514
  def get_by_email(email), do: Repo.get_by(User, email: email)

515
  def get_by_nickname_or_email(nickname_or_email) do
516
    get_by_nickname(nickname_or_email) || get_by_email(nickname_or_email)
517 518
  end

lain's avatar
lain committed
519 520
  def get_cached_user_info(user) do
    key = "user_info:#{user.id}"
Thog's avatar
Thog committed
521
    Cachex.fetch!(:user_cache, key, fn _ -> user_info(user) end)
lain's avatar
lain committed
522
  end
lain's avatar
lain committed
523

lain's avatar
lain committed
524 525 526 527 528 529 530 531 532
  def fetch_by_nickname(nickname) do
    ap_try = ActivityPub.make_user_from_nickname(nickname)

    case ap_try do
      {:ok, user} -> {:ok, user}
      _ -> OStatus.make_user(nickname)
    end
  end

lain's avatar
lain committed
533
  def get_or_fetch_by_nickname(nickname) do
lain's avatar
lain committed
534
    with %User{} = user <- get_by_nickname(nickname) do
535
      {:ok, user}
lain's avatar
lain committed
536 537 538 539
    else
      _e ->
        with [_nick, _domain] <- String.split(nickname, "@"),
             {:ok, user} <- fetch_by_nickname(nickname) do
540
          if Pleroma.Config.get([:fetch_initial_posts, :enabled]) do
541
            fetch_initial_posts(user)
542 543
          end

544
          {:ok, user}
lain's avatar
lain committed
545
        else
Alexander Strizhakov's avatar
Alexander Strizhakov committed
546
          _e -> {:error, "not found " <> nickname}
lain's avatar
lain committed
547
        end
lain's avatar
lain committed
548
    end
lain's avatar
lain committed
549
  end
lain's avatar
lain committed
550

551
  @doc "Fetch some posts when the user has just been federated with"
552 553
  def fetch_initial_posts(user),
    do: PleromaJobQueue.enqueue(:background, __MODULE__, [:fetch_initial_posts, user])
554

Alexander Strizhakov's avatar
Alexander Strizhakov committed
555 556
  @spec get_followers_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
  def get_followers_query(%User{} = user, nil) do
557
    User.Query.build(%{followers: user, deactivated: false})
558 559
  end

560
  def get_followers_query(user, page) do
Maxim Filippov's avatar
Maxim Filippov committed
561
    from(u in get_followers_query(user, nil))
Alexander Strizhakov's avatar
Alexander Strizhakov committed
562
    |> User.Query.paginate(page, 20)
563 564
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
565
  @spec get_followers_query(User.t()) :: Ecto.Query.t()
566 567 568 569
  def get_followers_query(user), do: get_followers_query(user, nil)

  def get_followers(user, page \\ nil) do
    q = get_followers_query(user, page)
lain's avatar
lain committed
570 571 572 573

    {:ok, Repo.all(q)}
  end

574 575 576 577 578 579
  def get_followers_ids(user, page \\ nil) do
    q = get_followers_query(user, page)

    Repo.all(from(u in q, select: u.id))
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
580 581
  @spec get_friends_query(User.t(), pos_integer() | nil) :: Ecto.Query.t()
  def get_friends_query(%User{} = user, nil) do
582
    User.Query.build(%{friends: user, deactivated: false})
583 584
  end

585
  def get_friends_query(user, page) do
Maxim Filippov's avatar
Maxim Filippov committed
586
    from(u in get_friends_query(user, nil))
Alexander Strizhakov's avatar
Alexander Strizhakov committed
587
    |> User.Query.paginate(page, 20)
588 589
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
590
  @spec get_friends_query(User.t()) :: Ecto.Query.t()
591 592 593 594
  def get_friends_query(user), do: get_friends_query(user, nil)

  def get_friends(user, page \\ nil) do
    q = get_friends_query(user, page)
lain's avatar
lain committed
595 596 597

    {:ok, Repo.all(q)}
  end
598

599 600 601 602 603 604
  def get_friends_ids(user, page \\ nil) do
    q = get_friends_query(user, page)

    Repo.all(from(u in q, select: u.id))
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
605
  @spec get_follow_requests(User.t()) :: {:ok, [User.t()]}
606 607
  def get_follow_requests(%User{} = user) do
    users =
Alexander Strizhakov's avatar
Alexander Strizhakov committed
608
      Activity.follow_requests_for_actor(user)
rinpatch's avatar
rinpatch committed
609
      |> join(:inner, [a], u in User, on: a.actor == u.ap_id)
610 611 612 613
      |> where([a, u], not fragment("? @> ?", u.following, ^[user.follower_address]))
      |> group_by([a, u], u.id)
      |> select([a, u], u)
      |> Repo.all()
614 615 616 617

    {:ok, users}
  end

618
  def increase_note_count(%User{} = user) do
619 620 621 622 623 624 625 626 627 628 629 630
    User
    |> where(id: ^user.id)
    |> update([u],
      set: [
        info:
          fragment(
            "jsonb_set(?, '{note_count}', ((?->>'note_count')::int + 1)::varchar::jsonb, true)",
            u.info,
            u.info
          )
      ]
    )
rinpatch's avatar
rinpatch committed
631 632
    |> select([u], u)
    |> Repo.update_all([])
633 634 635 636
    |> case do
      {1, [user]} -> set_cache(user)
      _ -> {:error, user}
    end
637 638
  end

639
  def decrease_note_count(%User{} = user) do
640 641 642 643 644 645 646 647 648 649 650 651
    User
    |> where(id: ^user.id)
    |> update([u],
      set: [
        info:
          fragment(
            "jsonb_set(?, '{note_count}', (greatest(0, (?->>'note_count')::int - 1))::varchar::jsonb, true)",
            u.info,
            u.info
          )
      ]
    )
rinpatch's avatar
rinpatch committed
652 653
    |> select([u], u)
    |> Repo.update_all([])
654 655 656 657
    |> case do
      {1, [user]} -> set_cache(user)
      _ -> {:error, user}
    end
658 659
  end

660
  def update_note_count(%User{} = user) do
lain's avatar
lain committed
661 662 663 664 665 666
    note_count_query =
      from(
        a in Object,
        where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
        select: count(a.id)
      )
667 668 669

    note_count = Repo.one(note_count_query)

lain's avatar
lain committed
670
    info_cng = User.Info.set_note_count(user.info, note_count)
671

672 673 674 675
    user
    |> change()
    |> put_embed(:info, info_cng)
    |> update_and_set_cache()
676 677 678
  end

  def update_follower_count(%User{} = user) do
lain's avatar
lain committed
679
    follower_count_query =
680
      User.Query.build(%{followers: user, deactivated: false})
681
      |> select([u], %{count: count(u.id)})
682

683 684 685 686 687 688 689 690 691 692 693 694 695
    User
    |> where(id: ^user.id)
    |> join(:inner, [u], s in subquery(follower_count_query))
    |> update([u, s],
      set: [
        info:
          fragment(
            "jsonb_set(?, '{follower_count}', ?::varchar::jsonb, true)",
            u.info,
            s.count
          )
      ]
    )
rinpatch's avatar
rinpatch committed
696 697
    |> select([u], u)
    |> Repo.update_all([])
698 699 700 701
    |> case do
      {1, [user]} -> set_cache(user)
      _ -> {:error, user}
    end
702
  end
703

704 705 706 707 708 709 710 711 712 713 714 715
  def remove_duplicated_following(%User{following: following} = user) do
    uniq_following = Enum.uniq(following)

    if length(following) == length(uniq_following) do
      {:ok, user}
    else
      user
      |> update_changeset(%{following: uniq_following})
      |> update_and_set_cache()
    end
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
716
  @spec get_users_from_set([String.t()], boolean()) :: [User.t()]
717
  def get_users_from_set(ap_ids, local_only \\ true) do
718
    criteria = %{ap_id: ap_ids, deactivated: false}
Alexander Strizhakov's avatar
Alexander Strizhakov committed
719 720 721
    criteria = if local_only, do: Map.put(criteria, :local, true), else: criteria

    User.Query.build(criteria)
722 723 724
    |> Repo.all()
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
725
  @spec get_recipients_from_activity(Activity.t()) :: [User.t()]
726
  def get_recipients_from_activity(%Activity{recipients: to}) do
727
    User.Query.build(%{recipients_from_activity: to, local: true, deactivated: false})
Alexander Strizhakov's avatar
Alexander Strizhakov committed
728
    |> Repo.all()
729 730
  end

731
  def mute(muter, %User{ap_id: ap_id}) do
732 733 734 735 736 737 738
    info_cng =
      muter.info
      |> User.Info.add_to_mutes(ap_id)

    cng =
      change(muter)
      |> put_embed(:info, info_cng)
739

740
    update_and_set_cache(cng)
741 742
  end

743 744 745 746
  def unmute(muter, %{ap_id: ap_id}) do
    info_cng =
      muter.info
      |> User.Info.remove_from_mutes(ap_id)
747

748 749 750 751 752
    cng =
      change(muter)
      |> put_embed(:info, info_cng)

    update_and_set_cache(cng)
753 754
  end

755
  def subscribe(subscriber, %{ap_id: ap_id}) do
756
    deny_follow_blocked = Pleroma.Config.get([:user, :deny_follow_blocked])
757

758
    with %User{} = subscribed <- get_cached_by_ap_id(ap_id) do
759 760 761 762 763 764 765 766 767 768 769 770 771
      blocked = blocks?(subscribed, subscriber) and deny_follow_blocked

      if blocked do
        {:error, "Could not subscribe: #{subscribed.nickname} is blocking you"}
      else
        info_cng =
          subscribed.info
          |> User.Info.add_to_subscribers(subscriber.ap_id)

        change(subscribed)
        |> put_embed(:info, info_cng)
        |> update_and_set_cache()
      end
772
    end
773 774 775
  end

  def unsubscribe(unsubscriber, %{ap_id: ap_id}) do
776
    with %User{} = user <- get_cached_by_ap_id(ap_id) do
777 778 779
      info_cng =
        user.info
        |> User.Info.remove_from_subscribers(unsubscriber.ap_id)
780

781 782 783 784
      change(user)
      |> put_embed(:info, info_cng)
      |> update_and_set_cache()
    end
785 786
  end

787 788 789 790 791 792 793 794 795 796
  def block(blocker, %User{ap_id: ap_id} = blocked) do
    # sever any follow relationships to prevent leaks per activitypub (Pleroma issue #213)
    blocker =
      if following?(blocker, blocked) do
        {:ok, blocker, _} = unfollow(blocker, blocked)
        blocker
      else
        blocker
      end

797 798 799 800 801 802 803 804
    blocker =
      if subscribed_to?(blocked, blocker) do
        {:ok, blocker} = unsubscribe(blocked, blocker)
        blocker
      else
        blocker
      end

805 806 807 808
    if following?(blocked, blocker) do
      unfollow(blocked, blocker)
    end

809 810
    {:ok, blocker} = update_follower_count(blocker)

lain's avatar
lain committed
811 812 813
    info_cng =
      blocker.info
      |> User.Info.add_to_block(ap_id)
lain's avatar
lain committed
814

lain's avatar
lain committed
815 816 817 818 819
    cng =
      change(blocker)
      |> put_embed(:info, info_cng)

    update_and_set_cache(cng)
lain's avatar
lain committed
820 821
  end

822 823
  # helper to handle the block given only an actor's AP id
  def block(blocker, %{ap_id: ap_id}) do
minibikini's avatar
minibikini committed
824
    block(blocker, get_cached_by_ap_id(ap_id))
825 826
  end

lain's avatar
lain committed
827 828 829 830
  def unblock(blocker, %{ap_id: ap_id}) do
    info_cng =
      blocker.info
      |> User.Info.remove_from_block(ap_id)
lain's avatar
lain committed
831

lain's avatar
lain committed
832 833 834 835 836
    cng =
      change(blocker)
      |> put_embed(:info, info_cng)

    update_and_set_cache(cng)
lain's avatar
lain committed
837 838
  end

839
  def mutes?(nil, _), do: false
840
  def mutes?(user, %{ap_id: ap_id}), do: Enum.member?(user.info.mutes, ap_id)
841

lain's avatar
lain committed
842
  def blocks?(user, %{ap_id: ap_id}) do
lain's avatar
lain committed
843 844
    blocks = user.info.blocks
    domain_blocks = user.info.domain_blocks
eal's avatar
eal committed
845
    %{host: host} = URI.parse(ap_id)
eal's avatar
eal committed
846 847 848 849 850

    Enum.member?(blocks, ap_id) ||
      Enum.any?(domain_blocks, fn domain ->
        host == domain
      end)
eal's avatar
eal committed
851 852
  end

Sadposter's avatar
Sadposter committed
853
  def subscribed_to?(user, %{ap_id: ap_id}) do
minibikini's avatar
minibikini committed
854
    with %User{} = target <- get_cached_by_ap_id(ap_id) do
855 856
      Enum.member?(target.info.subscribers, user.ap_id)
    end
Sadposter's avatar
Sadposter committed
857 858
  end

Alexander Strizhakov's avatar
Alexander Strizhakov committed
859 860
  @spec muted_users(User.t()) :: [User.t()]
  def muted_users(user) do
861
    User.Query.build(%{ap_id: user.info.mutes, deactivated: false})
Alexander Strizhakov's avatar
Alexander Strizhakov committed
862 863
    |> Repo.all()
  end
864

Alexander Strizhakov's avatar
Alexander Strizhakov committed
865 866
  @spec blocked_users(User.t()) :: [User.t()]
  def blocked_users(user) do
867
    User.Query.build(%{ap_id: user.info.blocks, deactivated: false})
Alexander Strizhakov's avatar
Alexander Strizhakov committed
868 869
    |> Repo.all()
  end
870

Alexander Strizhakov's avatar
Alexander Strizhakov committed
871 872
  @spec subscribers(User.t()) :: [User.t()]
  def subscribers(user) do
873
    User.Query.build(%{ap_id: user.info.subscribers, deactivated: false})
Alexander Strizhakov's avatar
Alexander Strizhakov committed
874 875
    |> Repo.all()
  end
Sadposter's avatar
Sadposter committed
876

eal's avatar
eal committed
877
  def block_domain(user, domain) do
lain's avatar
lain committed
878 879 880
    info_cng =
      user.info
      |> User.Info.add_to_domain_block(domain)
eal's avatar
eal committed
881

lain's avatar
lain committed
882 883 884
    cng =
      change(user)
      |> put_embed(:info, info_cng)
lain's avatar
lain committed
885 886

    update_and_set_cache(cng)
eal's avatar
eal committed
887 888 889
  end

  def unblock_domain(user, domain) do
lain's avatar
lain committed
890 891 892
    info_cng =
      user.info
      |> User.Info.remove_from_domain_block(domain)
eal's avatar
eal committed
893

lain's avatar
lain committed
894 895 896
    cng =
      change(user)
      |> put_embed(:info, info_cng)
lain's avatar
lain committed
897 898

    update_and_set_cache(cng)
lain's avatar
lain committed
899 900
  end

901
  def deactivate_async(user, status \\ true) do
902
    PleromaJobQueue.enqueue(:background, __MODULE__, [:deactivate_async, user, status])
903 904
  end

scarlett's avatar
scarlett committed
905
  def deactivate(%User{} = user, status \\ true) do
lain's avatar
lain committed
906
    info_cng = User.Info.set_activation_status(user.info, status)
lain's avatar
lain committed
907

minibikini's avatar
minibikini committed
908 909 910
    with {:ok, friends} <- User.get_friends(user),
         {:ok, followers} <- User.get_followers(user),
         {:ok, user} <-
minibikini's avatar
minibikini committed
911 912 913
           user
           |> change()
           |> put_embed(:info, info_cng)
minibikini's avatar
minibikini committed
914 915
           |> update_and_set_cache() do
      Enum.each(followers, &invalidate_cache(&1))
916
      Enum.each(friends, &update_follower_count(&1))
minibikini's avatar
minibikini committed
917

918 919
      {:ok, user}
    end
lain's avatar
lain committed
920
  end
lain's avatar
lain committed
921

922 923 924 925 926 927 928 929
  def update_notification_settings(%User{} = user, settings \\ %{}) do
    info_changeset = User.Info.update_notification_settings(user.info, settings)

    change(user)
    |> put_embed(:info, info_changeset)
    |> update_and_set_cache()
  end

930 931 932 933 934 935
  @spec delete(User.t()) :: :ok
  def delete(%User{} = user),
    do: PleromaJobQueue.enqueue(:background, __MODULE__, [:delete, user])

  @spec perform(atom(), User.t()) :: {:ok, User.t()}
  def perform(:delete, %User{} = user) do
lain's avatar
lain committed
936
    # Remove all relationships
lain's avatar
lain committed
937 938
    {:ok, followers} = User.get_followers(user)

Sergey Suprunenko's avatar
Sergey Suprunenko committed
939 940 941 942
    Enum.each(followers, fn follower ->
      ActivityPub.unfollow(follower, user)
      User.unfollow(follower, user)
    end)
lain's avatar
lain committed
943 944

    {:ok, friends} = User.get_friends(user)
lain's avatar
lain committed
945

Sergey Suprunenko's avatar
Sergey Suprunenko committed
946 947 948 949
    Enum.each(friends, fn followed ->
      ActivityPub.unfollow(user, followed)
      User.unfollow(user, followed)
    end)
lain's avatar
lain committed
950

951
    delete_user_activities(user)
Sergey Suprunenko's avatar
Sergey Suprunenko committed
952 953

    {:ok, _user} = Repo.delete(user)
954
  end
lain's avatar
lain committed
955

956 957 958 959 960 961 962 963 964 965 966 967 968
  @spec perform(atom(), User.t()) :: {:ok, User.t()}
  def perform(:fetch_initial_posts, %User{} = user) do
    pages = Pleroma.Config.get!([:fetch_initial_posts, :pages])

    Enum.each(
      # Insert all the posts in reverse order, so they're in the right order on the timeline
      Enum.reverse(Utils.fetch_ordered_collection(user.info.source_data["outbox"], pages)),
      &Pleroma.Web.Federator.incoming_ap_doc/1
    )

    {:ok, user}
  end

969 970
  def perform(:deactivate_async, user, status), do: deactivate(user, status)

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
  def perform(:blocks_import, %User{} = blocker, blocked_identifiers)
      when is_list(blocked_identifiers) do
    Enum.map(
      blocked_identifiers,
      fn blocked_identifier ->
        with {:ok, %User{} = blocked} <- get_or_fetch(blocked_identifier),
             {:ok, blocker} <- block(blocker, blocked),
             {:ok, _} <- ActivityPub.block(blocker, blocked) do
          blocked
        else
          err ->
            Logger.debug("blocks_import failed for #{blocked_identifier} with: #{inspect(err)}")
            err
        end
      end
    )
  end

  @spec perform(atom(), User.t(), list()) :: list() | {:error, any()}
  def perform(:follow_import, %User{} = follower, followed_identifiers)
      when is_list(followed_identifiers) do
    Enum.map(
      followed_identifiers,
      fn followed_identifier ->
        with {:ok, %User{} = followed} <- get_or_fetch(followed_identifier),
             {:ok, follower} <- maybe_direct_follow(follower, followed),
             {:ok, _} <- ActivityPub.follow(follower, followed) do
          followed
        else
          err ->
            Logger.debug("follow_import failed for #{followed_identifier} with: #{inspect(err)}")
            err
        end
      end
    )
  end

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
  def blocks_import(%User{} = blocker, blocked_identifiers) when is_list(blocked_identifiers),
    do:
      PleromaJobQueue.enqueue(:background, __MODULE__, [
        :blocks_import,
        blocker,
        blocked_identifiers
      ])

  def follow_import(%User{} = follower, followed_identifiers) when is_list(followed_identifiers),
    do:
      PleromaJobQueue.enqueue(:b