1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MastodonAPI.MediaController do
6 use Pleroma.Web, :controller
10 alias Pleroma.Web.ActivityPub.ActivityPub
11 alias Pleroma.Web.Plugs.OAuthScopesPlug
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)
17 plug(OAuthScopesPlug, %{scopes: ["read:media"]} when action == :show)
18 plug(OAuthScopesPlug, %{scopes: ["write:media"]} when action != :show)
20 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.MediaOperation
22 @doc "POST /api/v1/media"
23 def create(%{assigns: %{user: user}, body_params: %{file: file} = data} = conn, _) do
27 actor: User.ap_id(user),
28 description: Map.get(data, :description)
30 attachment_data = Map.put(object.data, "id", object.id)
32 render(conn, "attachment.json", %{attachment: attachment_data})
36 def create(_conn, _data), do: {:error, :bad_request}
38 @doc "POST /api/v2/media"
39 def create2(%{assigns: %{user: user}, body_params: %{file: file} = data} = conn, _) do
43 actor: User.ap_id(user),
44 description: Map.get(data, :description)
46 attachment_data = Map.put(object.data, "id", object.id)
50 |> render("attachment.json", %{attachment: attachment_data})
54 def create2(_conn, _data), do: {:error, :bad_request}
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)
63 render(conn, "attachment.json", %{attachment: attachment_data})
67 def update(conn, data), do: show(conn, data)
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)
75 render(conn, "attachment.json", %{attachment: attachment_data})
79 def show(_conn, _data), do: {:error, :bad_request}