1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Plugs.UploadedMedia do
10 import Pleroma.Web.Gettext
13 alias Pleroma.Web.MediaProxy
19 @default_cache_control_header "public, max-age=1209600"
24 headers: %{"cache-control" => @default_cache_control_header},
25 cache_control_for_etags: @default_cache_control_header
27 |> Keyword.put(:from, "__unconfigured_media_plug")
28 |> Keyword.put(:at, "/__unconfigured_media_plug")
31 %{static_plug_opts: static_plug_opts}
34 def call(%{request_path: <<"/", @path, "/", file::binary>>} = conn, opts) do
36 case fetch_query_params(conn) do
37 %{query_params: %{"name" => name}} = conn ->
38 name = escape_header_value(name)
40 put_resp_header(conn, "content-disposition", "filename=\"#{name}\"")
45 |> merge_resp_headers([{"content-security-policy", "sandbox"}])
47 config = Pleroma.Config.get(Pleroma.Upload)
49 with uploader <- Keyword.fetch!(config, :uploader),
50 {:ok, get_method} <- uploader.get_file(file),
51 false <- media_is_banned(conn, get_method) do
52 get_media(conn, get_method, opts)
56 |> send_resp(:internal_server_error, dgettext("errors", "Failed"))
61 def call(conn, _opts), do: conn
63 defp media_is_banned(%{request_path: path} = _conn, {:static_dir, _}) do
64 MediaProxy.in_banned_urls(Pleroma.Upload.base_url() <> path)
67 defp media_is_banned(_, {:url, url}), do: MediaProxy.in_banned_urls(url)
69 defp media_is_banned(_, _), do: false
71 defp get_media(conn, {:static_dir, directory}, opts) do
73 Map.get(opts, :static_plug_opts)
74 |> Map.put(:at, [@path])
75 |> Map.put(:from, directory)
77 conn = Plug.Static.call(conn, static_opts)
83 |> send_resp(:not_found, dgettext("errors", "Not found"))
88 defp get_media(conn, {:url, url}, _) do
90 |> Phoenix.Controller.redirect(external: url)
94 defp get_media(conn, unknown, _) do
95 Logger.error("#{__MODULE__}: Unknown get startegy: #{inspect(unknown)}")
98 |> send_resp(:internal_server_error, dgettext("errors", "Internal Error"))
102 defp escape_header_value(value) do
104 |> String.replace("\"", "\\\"")
105 |> String.replace("\\r", "")
106 |> String.replace("\\n", "")