Merge branch 'refactor/locked_user_field' into 'develop'
[akkoma] / lib / pleroma / web / pleroma_api / controllers / mascot_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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(Pleroma.Web.ApiSpec.CastAndValidate)
13 plug(OAuthScopesPlug, %{scopes: ["read:accounts"]} when action == :show)
14 plug(OAuthScopesPlug, %{scopes: ["write:accounts"]} when action != :show)
15
16 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.PleromaMascotOperation
17
18 @doc "GET /api/v1/pleroma/mascot"
19 def show(%{assigns: %{user: user}} = conn, _params) do
20 json(conn, User.get_mascot(user))
21 end
22
23 @doc "PUT /api/v1/pleroma/mascot"
24 def update(%{assigns: %{user: user}, body_params: %{file: file}} = conn, _) do
25 with {:ok, object} <- ActivityPub.upload(file, actor: User.ap_id(user)),
26 # Reject if not an image
27 %{type: "image"} = attachment <- render_attachment(object) do
28 {:ok, _user} = User.mascot_update(user, attachment)
29
30 json(conn, attachment)
31 else
32 %{type: _} -> render_error(conn, :unsupported_media_type, "mascots can only be images")
33 end
34 end
35
36 defp render_attachment(object) do
37 attachment_data = Map.put(object.data, "id", object.id)
38 Pleroma.Web.MastodonAPI.StatusView.render("attachment.json", %{attachment: attachment_data})
39 end
40 end