66e9d84812e7488e93b00d8677c496facf764624
[anni] / lib / pleroma / web / pleroma_api / controllers / mascot_controller.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.Web.PleromaAPI.MascotController do
6   use Pleroma.Web, :controller
7
8   alias Pleroma.User
9   alias Pleroma.Web.ActivityPub.ActivityPub
10   alias Pleroma.Web.Plugs.OAuthScopesPlug
11
12   plug(Majic.Plug, [pool: Pleroma.MajicPool] when action in [:update])
13   plug(Pleroma.Web.ApiSpec.CastAndValidate)
14   plug(OAuthScopesPlug, %{scopes: ["read:accounts"]} when action == :show)
15   plug(OAuthScopesPlug, %{scopes: ["write:accounts"]} when action != :show)
16
17   defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.PleromaMascotOperation
18
19   @doc "GET /api/v1/pleroma/mascot"
20   def show(%{assigns: %{user: user}} = conn, _params) do
21     json(conn, User.get_mascot(user))
22   end
23
24   @doc "PUT /api/v1/pleroma/mascot"
25   def update(%{assigns: %{user: user}, body_params: %{file: file}} = conn, _) do
26     with {:content_type, "image" <> _} <- {:content_type, file.content_type},
27          {:ok, object} <- ActivityPub.upload(file, actor: User.ap_id(user)) do
28       attachment = render_attachment(object)
29       {:ok, _user} = User.mascot_update(user, attachment)
30
31       json(conn, attachment)
32     else
33       {:content_type, _} ->
34         render_error(conn, :unsupported_media_type, "mascots can only be images")
35     end
36   end
37
38   defp render_attachment(object) do
39     attachment_data = Map.put(object.data, "id", object.id)
40     Pleroma.Web.MastodonAPI.StatusView.render("attachment.json", %{attachment: attachment_data})
41   end
42 end