Fix OpenAPI spec
[akkoma] / lib / pleroma / web / mastodon_api / controllers / media_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.MastodonAPI.MediaController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.Object
9 alias Pleroma.Plugs.OAuthScopesPlug
10 alias Pleroma.User
11 alias Pleroma.Web.ActivityPub.ActivityPub
12
13 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
14 plug(Pleroma.Web.ApiSpec.CastAndValidate)
15 plug(:put_view, Pleroma.Web.MastodonAPI.StatusView)
16
17 plug(OAuthScopesPlug, %{scopes: ["write:media"]})
18
19 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.MediaOperation
20
21 @doc "POST /api/v1/media"
22 def create(%{assigns: %{user: user}, body_params: %{file: file} = data} = conn, _) do
23 with {:ok, object} <-
24 ActivityPub.upload(
25 file,
26 actor: User.ap_id(user),
27 description: Map.get(data, :description)
28 ) do
29 attachment_data = Map.put(object.data, "id", object.id)
30
31 render(conn, "attachment.json", %{attachment: attachment_data})
32 end
33 end
34
35 def create(_conn, _data), do: {:error, :bad_request}
36
37 @doc "POST /api/v2/media"
38 def create2(%{assigns: %{user: user}, body_params: %{file: file} = data} = conn, _) do
39 with {:ok, object} <-
40 ActivityPub.upload(
41 file,
42 actor: User.ap_id(user),
43 description: Map.get(data, :description)
44 ) do
45 attachment_data = Map.put(object.data, "id", object.id)
46
47 conn
48 |> put_status(202)
49 |> render("attachment.json", %{attachment: attachment_data})
50 end
51 end
52
53 def create2(_conn, _data), do: {:error, :bad_request}
54
55 @doc "PUT /api/v1/media/:id"
56 def update(%{assigns: %{user: user}, body_params: %{description: description}} = conn, %{
57 id: id
58 })
59 when is_binary(description) do
60 with %Object{} = object <- Object.get_by_id(id),
61 true <- Object.authorize_mutation(object, user),
62 {:ok, %Object{data: data}} <- Object.update_data(object, %{"name" => description}) do
63 attachment_data = Map.put(data, "id", object.id)
64
65 render(conn, "attachment.json", %{attachment: attachment_data})
66 end
67 end
68
69 def update(_conn, _data), do: {:error, :bad_request}
70
71 @doc "GET /api/v1/media/:id"
72 def show(conn, %{id: id}) do
73 with %Object{data: data, id: object_id} <- Object.get_by_id(id) do
74 attachment_data = Map.put(data, "id", object_id)
75
76 render(conn, "attachment.json", %{attachment: attachment_data})
77 end
78 end
79
80 def get_media(_conn, _data), do: {:error, :bad_request}
81 end