Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into feature/expire...
[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.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 plug(:put_view, Pleroma.Web.MastodonAPI.StatusView)
17
18 plug(OAuthScopesPlug, %{scopes: ["read:media"]} when action == :show)
19 plug(OAuthScopesPlug, %{scopes: ["write:media"]} when action != :show)
20
21 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.MediaOperation
22
23 @doc "POST /api/v1/media"
24 def create(%{assigns: %{user: user}, body_params: %{file: file} = data} = conn, _) do
25 with {:ok, object} <-
26 ActivityPub.upload(
27 file,
28 actor: User.ap_id(user),
29 description: Map.get(data, :description)
30 ) do
31 attachment_data = Map.put(object.data, "id", object.id)
32
33 render(conn, "attachment.json", %{attachment: attachment_data})
34 end
35 end
36
37 def create(_conn, _data), do: {:error, :bad_request}
38
39 @doc "POST /api/v2/media"
40 def create2(%{assigns: %{user: user}, body_params: %{file: file} = data} = conn, _) do
41 with {:ok, object} <-
42 ActivityPub.upload(
43 file,
44 actor: User.ap_id(user),
45 description: Map.get(data, :description)
46 ) do
47 attachment_data = Map.put(object.data, "id", object.id)
48
49 conn
50 |> put_status(202)
51 |> render("attachment.json", %{attachment: attachment_data})
52 end
53 end
54
55 def create2(_conn, _data), do: {:error, :bad_request}
56
57 @doc "PUT /api/v1/media/:id"
58 def update(%{assigns: %{user: user}, body_params: %{description: description}} = conn, %{id: id}) do
59 with %Object{} = object <- Object.get_by_id(id),
60 :ok <- Object.authorize_access(object, user),
61 {:ok, %Object{data: data}} <- Object.update_data(object, %{"name" => description}) do
62 attachment_data = Map.put(data, "id", object.id)
63
64 render(conn, "attachment.json", %{attachment: attachment_data})
65 end
66 end
67
68 def update(conn, data), do: show(conn, data)
69
70 @doc "GET /api/v1/media/:id"
71 def show(%{assigns: %{user: user}} = conn, %{id: id}) do
72 with %Object{data: data, id: object_id} = object <- Object.get_by_id(id),
73 :ok <- Object.authorize_access(object, user) 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 show(_conn, _data), do: {:error, :bad_request}
81 end