aboutsummaryrefslogtreecommitdiff
path: root/lib/pleroma/web/admin_api/controllers/announcement_controller.ex
blob: 6ad5fc12ca00d25f68ba3ba224bc43ed591fd5c0 (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-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.AdminAPI.AnnouncementController do
  use Pleroma.Web, :controller

  alias Pleroma.Announcement
  alias Pleroma.Web.ControllerHelper
  alias Pleroma.Web.Plugs.OAuthScopesPlug

  plug(Pleroma.Web.ApiSpec.CastAndValidate)
  plug(OAuthScopesPlug, %{scopes: ["admin:write"]} when action in [:create, :delete, :change])
  plug(OAuthScopesPlug, %{scopes: ["admin:read"]} when action in [:index, :show])
  action_fallback(Pleroma.Web.AdminAPI.FallbackController)

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

  defp default_limit, do: 20

  def index(conn, params) do
    limit = Map.get(params, :limit, default_limit())
    offset = Map.get(params, :offset, 0)

    announcements = Announcement.list_paginated(%{limit: limit, offset: offset})

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

  def show(conn, %{id: id} = _params) do
    announcement = Announcement.get_by_id(id)

    if is_nil(announcement) do
      {:error, :not_found}
    else
      render(conn, "show.json", announcement: announcement)
    end
  end

  def create(%{body_params: params} = conn, _params) do
    with {:ok, announcement} <- Announcement.add(change_params(params)) do
      render(conn, "show.json", announcement: announcement)
    else
      _ ->
        {:error, 400}
    end
  end

  def change_params(orig_params) do
    data =
      %{}
      |> Pleroma.Maps.put_if_present("content", orig_params, &Map.fetch(&1, :content))
      |> Pleroma.Maps.put_if_present("all_day", orig_params, &Map.fetch(&1, :all_day))

    orig_params
    |> Map.merge(%{data: data})
  end

  def change(%{body_params: params} = conn, %{id: id} = _params) do
    with announcement <- Announcement.get_by_id(id),
         {:exists, true} <- {:exists, not is_nil(announcement)},
         {:ok, announcement} <- Announcement.update(announcement, change_params(params)) do
      render(conn, "show.json", announcement: announcement)
    else
      {:exists, false} ->
        {:error, :not_found}

      _ ->
        {:error, 400}
    end
  end

  def delete(conn, %{id: id} = _params) do
    case Announcement.delete_by_id(id) do
      :ok ->
        conn
        |> ControllerHelper.json_response(:ok, %{})

      _ ->
        {:error, :not_found}
    end
  end
end