Merge branch 'develop' into fix/cache-control-headers
[akkoma] / lib / pleroma / plugs / uploaded_media.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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 require Logger
12
13 @behaviour Plug
14 # no slashes
15 @path "media"
16
17 @default_cache_control_header "public, max-age=1209600"
18
19 def init(_opts) do
20 static_plug_opts =
21 []
22 |> Keyword.put(:from, "__unconfigured_media_plug")
23 |> Keyword.put(:at, "/__unconfigured_media_plug")
24 |> Plug.Static.init()
25
26 %{static_plug_opts: static_plug_opts}
27 end
28
29 def call(%{request_path: <<"/", @path, "/", file::binary>>} = conn, opts) do
30 conn =
31 case fetch_query_params(conn) do
32 %{query_params: %{"name" => name}} = conn ->
33 name = String.replace(name, "\"", "\\\"")
34
35 conn
36 |> put_resp_header("content-disposition", "filename=\"#{name}\"")
37
38 conn ->
39 conn
40 end
41
42 config = Pleroma.Config.get(Pleroma.Upload)
43
44 with uploader <- Keyword.fetch!(config, :uploader),
45 proxy_remote = Keyword.get(config, :proxy_remote, false),
46 {:ok, get_method} <- uploader.get_file(file) do
47 get_media(conn, get_method, proxy_remote, opts)
48 else
49 _ ->
50 conn
51 |> send_resp(:internal_server_error, dgettext("errors", "Failed"))
52 |> halt()
53 end
54 end
55
56 def call(conn, _opts), do: conn
57
58 defp get_media(conn, {:static_dir, directory}, _, opts) do
59 static_opts =
60 Map.get(opts, :static_plug_opts)
61 |> Map.put(:at, [@path])
62 |> Map.put(:from, directory)
63 |> Map.put(:cache_control_for_etags, @default_cache_control_header)
64 |> Map.put(:headers, %{
65 "cache-control" => @default_cache_control_header
66 })
67
68 conn = Plug.Static.call(conn, static_opts)
69
70 if conn.halted do
71 conn
72 else
73 conn
74 |> send_resp(:not_found, dgettext("errors", "Not found"))
75 |> halt()
76 end
77 end
78
79 defp get_media(conn, {:url, url}, true, _) do
80 conn
81 |> Pleroma.ReverseProxy.call(url, Pleroma.Config.get([Pleroma.Upload, :proxy_opts], []))
82 end
83
84 defp get_media(conn, {:url, url}, _, _) do
85 conn
86 |> Phoenix.Controller.redirect(external: url)
87 |> halt()
88 end
89
90 defp get_media(conn, unknown, _, _) do
91 Logger.error("#{__MODULE__}: Unknown get startegy: #{inspect(unknown)}")
92
93 conn
94 |> send_resp(:internal_server_error, dgettext("errors", "Internal Error"))
95 |> halt()
96 end
97 end