summaryrefslogtreecommitdiff
path: root/lib/pleroma/web/pleroma_api/controllers/mascot_controller.ex
blob: df6c50ca5d139f110c72e64d35c0f80e72cb7a3b (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
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

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

  alias Pleroma.Plugs.OAuthScopesPlug
  alias Pleroma.User
  alias Pleroma.Web.ActivityPub.ActivityPub

  plug(Pleroma.Web.ApiSpec.CastAndValidate)
  plug(OAuthScopesPlug, %{scopes: ["read:accounts"]} when action == :show)
  plug(OAuthScopesPlug, %{scopes: ["write:accounts"]} when action != :show)

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

  @doc "GET /api/v1/pleroma/mascot"
  def show(%{assigns: %{user: user}} = conn, _params) do
    json(conn, User.get_mascot(user))
  end

  @doc "PUT /api/v1/pleroma/mascot"
  def update(%{assigns: %{user: user}, body_params: %{file: file}} = conn, _) do
    with {:ok, object} <- ActivityPub.upload(file, actor: User.ap_id(user)),
         # Reject if not an image
         %{type: "image"} = attachment <- render_attachment(object) do
      {:ok, _user} = User.mascot_update(user, attachment)

      json(conn, attachment)
    else
      %{type: _} -> render_error(conn, :unsupported_media_type, "mascots can only be images")
    end
  end

  defp render_attachment(object) do
    attachment_data = Map.put(object.data, "id", object.id)
    Pleroma.Web.MastodonAPI.StatusView.render("attachment.json", %{attachment: attachment_data})
  end
end