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