summaryrefslogtreecommitdiff
path: root/lib/pleroma/web/mastodon_api/controllers/filter_controller.ex
blob: abbf0ce02e9c0f50085f682ecca6e4e19f231e79 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.MastodonAPI.FilterController do
  use Pleroma.Web, :controller

  alias Pleroma.Filter
  alias Pleroma.Plugs.OAuthScopesPlug

  @oauth_read_actions [:show, :index]

  plug(Pleroma.Web.ApiSpec.CastAndValidate)
  plug(OAuthScopesPlug, %{scopes: ["read:filters"]} when action in @oauth_read_actions)

  plug(
    OAuthScopesPlug,
    %{scopes: ["write:filters"]} when action not in @oauth_read_actions
  )

  defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.FilterOperation

  @doc "GET /api/v1/filters"
  def index(%{assigns: %{user: user}} = conn, _) do
    filters = Filter.get_filters(user)

    render(conn, "index.json", filters: filters)
  end

  @doc "POST /api/v1/filters"
  def create(%{assigns: %{user: user}, body_params: params} = conn, _) do
    query = %Filter{
      user_id: user.id,
      phrase: params.phrase,
      context: params.context,
      hide: params.irreversible,
      whole_word: params.whole_word
      # TODO: support `expires_in` parameter (as in Mastodon API)
    }

    {:ok, response} = Filter.create(query)

    render(conn, "show.json", filter: response)
  end

  @doc "GET /api/v1/filters/:id"
  def show(%{assigns: %{user: user}} = conn, %{id: filter_id}) do
    filter = Filter.get(filter_id, user)

    render(conn, "show.json", filter: filter)
  end

  @doc "PUT /api/v1/filters/:id"
  def update(
        %{assigns: %{user: user}, body_params: params} = conn,
        %{id: filter_id}
      ) do
    params =
      params
      |> Map.delete(:irreversible)
      |> Map.put(:hide, params[:irreversible])
      |> Enum.reject(fn {_key, value} -> is_nil(value) end)
      |> Map.new()

    # TODO: support `expires_in` parameter (as in Mastodon API)

    with %Filter{} = filter <- Filter.get(filter_id, user),
         {:ok, %Filter{} = filter} <- Filter.update(filter, params) do
      render(conn, "show.json", filter: filter)
    end
  end

  @doc "DELETE /api/v1/filters/:id"
  def delete(%{assigns: %{user: user}} = conn, %{id: filter_id}) do
    query = %Filter{
      user_id: user.id,
      filter_id: filter_id
    }

    {:ok, _} = Filter.delete(query)
    json(conn, %{})
  end
end