total rebase
[anni] / lib / pleroma / user / import.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.User.Import do
6   use Ecto.Schema
7
8   alias Pleroma.User
9   alias Pleroma.Web.CommonAPI
10   alias Pleroma.Workers.BackgroundWorker
11
12   require Logger
13
14   @spec perform(atom(), User.t(), list()) :: :ok | list() | {:error, any()}
15   def perform(:mutes_import, %User{} = user, [_ | _] = identifiers) do
16     Enum.map(
17       identifiers,
18       fn identifier ->
19         with {:ok, %User{} = muted_user} <- User.get_or_fetch(identifier),
20              {:ok, _} <- User.mute(user, muted_user) do
21           muted_user
22         else
23           error -> handle_error(:mutes_import, identifier, error)
24         end
25       end
26     )
27   end
28
29   def perform(:blocks_import, %User{} = blocker, [_ | _] = identifiers) do
30     Enum.map(
31       identifiers,
32       fn identifier ->
33         with {:ok, %User{} = blocked} <- User.get_or_fetch(identifier),
34              {:ok, _block} <- CommonAPI.block(blocker, blocked) do
35           blocked
36         else
37           error -> handle_error(:blocks_import, identifier, error)
38         end
39       end
40     )
41   end
42
43   def perform(:follow_import, %User{} = follower, [_ | _] = identifiers) do
44     Enum.map(
45       identifiers,
46       fn identifier ->
47         with {:ok, %User{} = followed} <- User.get_or_fetch(identifier),
48              {:ok, follower, followed} <- User.maybe_direct_follow(follower, followed),
49              {:ok, _, _, _} <- CommonAPI.follow(follower, followed) do
50           followed
51         else
52           error -> handle_error(:follow_import, identifier, error)
53         end
54       end
55     )
56   end
57
58   def perform(_, _, _), do: :ok
59
60   defp handle_error(op, user_id, error) do
61     Logger.debug("#{op} failed for #{user_id} with: #{inspect(error)}")
62     error
63   end
64
65   def blocks_import(%User{} = blocker, [_ | _] = identifiers) do
66     BackgroundWorker.enqueue(
67       "blocks_import",
68       %{"user_id" => blocker.id, "identifiers" => identifiers}
69     )
70   end
71
72   def follow_import(%User{} = follower, [_ | _] = identifiers) do
73     BackgroundWorker.enqueue(
74       "follow_import",
75       %{"user_id" => follower.id, "identifiers" => identifiers}
76     )
77   end
78
79   def mutes_import(%User{} = user, [_ | _] = identifiers) do
80     BackgroundWorker.enqueue(
81       "mutes_import",
82       %{"user_id" => user.id, "identifiers" => identifiers}
83     )
84   end
85 end