Fix response
[akkoma] / lib / pleroma / plugs / uploaded_media.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Plugs.UploadedMedia do
6 @moduledoc """
7 """
8
9 import Plug.Conn
10 import Pleroma.Web.Gettext
11 import Pleroma.Web.TranslationHelpers
12 require Logger
13
14 @behaviour Plug
15 # no slashes
16 @path "media"
17
18 def init(_opts) do
19 static_plug_opts =
20 []
21 |> Keyword.put(:from, "__unconfigured_media_plug")
22 |> Keyword.put(:at, "/__unconfigured_media_plug")
23 |> Plug.Static.init()
24
25 %{static_plug_opts: static_plug_opts}
26 end
27
28 def call(%{request_path: <<"/", @path, "/", file::binary>>} = conn, opts) do
29 conn =
30 case fetch_query_params(conn) do
31 %{query_params: %{"name" => name}} = conn ->
32 name = String.replace(name, "\"", "\\\"")
33
34 conn
35 |> put_resp_header("content-disposition", "filename=\"#{name}\"")
36
37 conn ->
38 conn
39 end
40
41 config = Pleroma.Config.get(Pleroma.Upload)
42
43 with uploader <- Keyword.fetch!(config, :uploader),
44 proxy_remote = Keyword.get(config, :proxy_remote, false),
45 {:ok, get_method} <- uploader.get_file(file) do
46 get_media(conn, get_method, proxy_remote, opts)
47 else
48 _ ->
49 conn
50 |> send_resp(:internal_server_error, dgettext("errors", "Failed"))
51 |> halt()
52 end
53 end
54
55 def call(conn, _opts), do: conn
56
57 defp get_media(conn, {:static_dir, directory}, _, opts) do
58 static_opts =
59 Map.get(opts, :static_plug_opts)
60 |> Map.put(:at, [@path])
61 |> Map.put(:from, directory)
62
63 conn = Plug.Static.call(conn, static_opts)
64
65 if conn.halted do
66 conn
67 else
68 conn
69 |> send_resp(:not_found, dgettext("errors", "Not found"))
70 |> halt()
71 end
72 end
73
74 defp get_media(conn, {:url, url}, true, _) do
75 conn
76 |> Pleroma.ReverseProxy.call(url, Pleroma.Config.get([Pleroma.Upload, :proxy_opts], []))
77 end
78
79 defp get_media(conn, {:url, url}, _, _) do
80 conn
81 |> Phoenix.Controller.redirect(external: url)
82 |> halt()
83 end
84
85 defp get_media(conn, unknown, _, _) do
86 Logger.error("#{__MODULE__}: Unknown get startegy: #{inspect(unknown)}")
87
88 conn
89 |> send_resp(:internal_server_error, dgettext("errors", "Internal Error"))
90 |> halt()
91 end
92 end