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