Merge develop to bump elixir version in the CI so I don't get failing formatting
[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 conn =
28 case fetch_query_params(conn) do
29 %{query_params: %{"name" => name}} = conn ->
30 name = String.replace(name, "\"", "\\\"")
31
32 conn
33 |> put_resp_header("content-disposition", "filename=\"#{name}\"")
34
35 conn ->
36 conn
37 end
38
39 config = Pleroma.Config.get([Pleroma.Upload])
40
41 with uploader <- Keyword.fetch!(config, :uploader),
42 proxy_remote = Keyword.get(config, :proxy_remote, false),
43 {:ok, get_method} <- uploader.get_file(file) do
44 get_media(conn, get_method, proxy_remote, opts)
45 else
46 _ ->
47 conn
48 |> send_resp(500, "Failed")
49 |> halt()
50 end
51 end
52
53 def call(conn, _opts), do: conn
54
55 defp get_media(conn, {:static_dir, directory}, _, opts) do
56 static_opts =
57 Map.get(opts, :static_plug_opts)
58 |> Map.put(:at, [@path])
59 |> Map.put(:from, directory)
60
61 conn = Plug.Static.call(conn, static_opts)
62
63 if conn.halted do
64 conn
65 else
66 conn
67 |> send_resp(404, "Not found")
68 |> halt()
69 end
70 end
71
72 defp get_media(conn, {:url, url}, true, _) do
73 conn
74 |> Pleroma.ReverseProxy.call(url, Pleroma.Config.get([Pleroma.Upload, :proxy_opts], []))
75 end
76
77 defp get_media(conn, {:url, url}, _, _) do
78 conn
79 |> Phoenix.Controller.redirect(external: url)
80 |> halt()
81 end
82
83 defp get_media(conn, unknown, _, _) do
84 Logger.error("#{__MODULE__}: Unknown get startegy: #{inspect(unknown)}")
85
86 conn
87 |> send_resp(500, "Internal Error")
88 |> halt()
89 end
90 end