summaryrefslogtreecommitdiff
path: root/lib/pleroma/web/pleroma_api/controllers/user_import_controller.ex
blob: 6d9a11fb6757f558ab1fb789739f5bb6bf05f3b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Pleroma: A lightweight social networking server
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.PleromaAPI.UserImportController do
  use Pleroma.Web, :controller

  require Logger

  alias Pleroma.User
  alias Pleroma.Web.ApiSpec
  alias Pleroma.Web.Plugs.OAuthScopesPlug

  plug(OAuthScopesPlug, %{scopes: ["follow", "write:follows"]} when action == :follow)
  plug(OAuthScopesPlug, %{scopes: ["follow", "write:blocks"]} when action == :blocks)
  plug(OAuthScopesPlug, %{scopes: ["follow", "write:mutes"]} when action == :mutes)

  plug(OpenApiSpex.Plug.CastAndValidate)
  defdelegate open_api_operation(action), to: ApiSpec.UserImportOperation

  def follow(%{body_params: %{list: %Plug.Upload{path: path}}} = conn, _) do
    follow(%Plug.Conn{conn | body_params: %{list: File.read!(path)}}, %{})
  end

  def follow(%{assigns: %{user: follower}, body_params: %{list: list}} = conn, _) do
    identifiers =
      list
      |> String.split("\n")
      |> Enum.map(&(&1 |> String.split(",") |> List.first()))
      |> List.delete("Account address")
      |> Enum.map(&(&1 |> String.trim() |> String.trim_leading("@")))
      |> Enum.reject(&(&1 == ""))

    User.Import.follow_import(follower, identifiers)
    json(conn, "job started")
  end

  def blocks(%{body_params: %{list: %Plug.Upload{path: path}}} = conn, _) do
    blocks(%Plug.Conn{conn | body_params: %{list: File.read!(path)}}, %{})
  end

  def blocks(%{assigns: %{user: blocker}, body_params: %{list: list}} = conn, _) do
    User.Import.blocks_import(blocker, prepare_user_identifiers(list))
    json(conn, "job started")
  end

  def mutes(%{body_params: %{list: %Plug.Upload{path: path}}} = conn, _) do
    mutes(%Plug.Conn{conn | body_params: %{list: File.read!(path)}}, %{})
  end

  def mutes(%{assigns: %{user: user}, body_params: %{list: list}} = conn, _) do
    User.Import.mutes_import(user, prepare_user_identifiers(list))
    json(conn, "job started")
  end

  defp prepare_user_identifiers(list) do
    list
    |> String.split()
    |> Enum.map(&String.trim_leading(&1, "@"))
  end
end