7e1e841267c628a70e47bfd9a09e61ff0755b297
[akkoma] / lib / pleroma / plugs / uploaded_media.ex
1 defmodule Pleroma.Plugs.UploadedMedia do
2 @moduledoc """
3 """
4
5 import Plug.Conn
6 require Logger
7
8 @behaviour Plug
9 # no slashes
10 @path "media"
11
12 def init(_opts) do
13 static_plug_opts =
14 []
15 |> Keyword.put(:from, "__unconfigured_media_plug")
16 |> Keyword.put(:at, "/__unconfigured_media_plug")
17 |> Plug.Static.init()
18
19 %{static_plug_opts: static_plug_opts}
20 end
21
22 def call(conn = %{request_path: <<"/", @path, "/", file::binary>>}, opts) do
23 config = Pleroma.Config.get([Pleroma.Upload])
24
25 with uploader <- Keyword.fetch!(config, :uploader),
26 proxy_remote = Keyword.get(config, :proxy_remote, false),
27 {:ok, get_method} <- uploader.get_file(file) do
28 get_media(conn, get_method, proxy_remote, opts)
29 else
30 _ ->
31 conn
32 |> send_resp(500, "Failed")
33 |> halt()
34 end
35 end
36
37 def call(conn, _opts), do: conn
38
39 defp get_media(conn, {:static_dir, directory}, _, opts) do
40 static_opts =
41 Map.get(opts, :static_plug_opts)
42 |> Map.put(:at, [@path])
43 |> Map.put(:from, directory)
44
45 conn = Plug.Static.call(conn, static_opts)
46
47 if conn.halted do
48 conn
49 else
50 conn
51 |> send_resp(404, "Not found")
52 |> halt()
53 end
54 end
55
56 defp get_media(conn, {:url, url}, true, _) do
57 conn
58 |> Pleroma.ReverseProxy.call(url, Pleroma.Config.get([Pleroma.Upload, :proxy_opts], []))
59 end
60
61 defp get_media(conn, {:url, url}, _, _) do
62 conn
63 |> Phoenix.Controller.redirect(external: url)
64 |> halt()
65 end
66
67 defp get_media(conn, unknown, _, _) do
68 Logger.error("#{__MODULE__}: Unknown get startegy: #{inspect(unknown)}")
69
70 conn
71 |> send_resp(500, "Internal Error")
72 |> halt()
73 end
74 end