Merge commit '07fed0fda2473fc4e1e3b01e863217391fd2902f'; commit 'e3173a279dad89dfce6e...
[akkoma] / lib / pleroma / web / mastodon_api / controllers / media_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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.User
10 alias Pleroma.Web.ActivityPub.ActivityPub
11 alias Pleroma.Web.Plugs.OAuthScopesPlug
12
13 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
14 plug(Majic.Plug, [pool: Pleroma.MajicPool] when action in [:create, :create2])
15 plug(Pleroma.Web.ApiSpec.CastAndValidate)
16
17 plug(OAuthScopesPlug, %{scopes: ["read:media"]} when action == :show)
18 plug(OAuthScopesPlug, %{scopes: ["write:media"]} when action != :show)
19
20 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.MediaOperation
21
22 @doc "POST /api/v1/media"
23 def create(%{assigns: %{user: user}, body_params: %{file: file} = data} = conn, _) do
24 with {:ok, object} <-
25 ActivityPub.upload(
26 file,
27 actor: User.ap_id(user),
28 description: Map.get(data, :description)
29 ) do
30 attachment_data = Map.put(object.data, "id", object.id)
31
32 render(conn, "attachment.json", %{attachment: attachment_data})
33 end
34 end
35
36 def create(_conn, _data), do: {:error, :bad_request}
37
38 @doc "POST /api/v2/media"
39 def create2(%{assigns: %{user: user}, body_params: %{file: file} = data} = conn, _) do
40 with {:ok, object} <-
41 ActivityPub.upload(
42 file,
43 actor: User.ap_id(user),
44 description: Map.get(data, :description)
45 ) do
46 attachment_data = Map.put(object.data, "id", object.id)
47
48 conn
49 |> put_status(202)
50 |> render("attachment.json", %{attachment: attachment_data})
51 end
52 end
53
54 def create2(_conn, _data), do: {:error, :bad_request}
55
56 @doc "PUT /api/v1/media/:id"
57 def update(%{assigns: %{user: user}, body_params: %{description: description}} = conn, %{id: id}) do
58 with %Object{} = object <- Object.get_by_id(id),
59 :ok <- Object.authorize_access(object, user),
60 {:ok, %Object{data: data}} <- Object.update_data(object, %{"name" => description}) do
61 attachment_data = Map.put(data, "id", object.id)
62
63 render(conn, "attachment.json", %{attachment: attachment_data})
64 end
65 end
66
67 def update(conn, data), do: show(conn, data)
68
69 @doc "GET /api/v1/media/:id"
70 def show(%{assigns: %{user: user}} = conn, %{id: id}) do
71 with %Object{data: data, id: object_id} = object <- Object.get_by_id(id),
72 :ok <- Object.authorize_access(object, user) do
73 attachment_data = Map.put(data, "id", object_id)
74
75 render(conn, "attachment.json", %{attachment: attachment_data})
76 end
77 end
78
79 def show(_conn, _data), do: {:error, :bad_request}
80 end