1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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 = String.replace(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 proxy_remote = Keyword.get(config, :proxy_remote, false),
51 {:ok, get_method} <- uploader.get_file(file),
52 false <- media_is_banned(conn, get_method) do
53 get_media(conn, get_method, proxy_remote, opts)
57 |> send_resp(:internal_server_error, dgettext("errors", "Failed"))
62 def call(conn, _opts), do: conn
64 defp media_is_banned(%{request_path: path} = _conn, {:static_dir, _}) do
65 MediaProxy.in_banned_urls(Pleroma.Web.base_url() <> path)
68 defp media_is_banned(_, {:url, url}), do: MediaProxy.in_banned_urls(url)
70 defp media_is_banned(_, _), do: false
72 defp get_media(conn, {:static_dir, directory}, _, opts) do
74 Map.get(opts, :static_plug_opts)
75 |> Map.put(:at, [@path])
76 |> Map.put(:from, directory)
78 conn = Plug.Static.call(conn, static_opts)
84 |> send_resp(:not_found, dgettext("errors", "Not found"))
89 defp get_media(conn, {:url, url}, true, _) do
91 |> Pleroma.ReverseProxy.call(url, Pleroma.Config.get([Pleroma.Upload, :proxy_opts], []))
94 defp get_media(conn, {:url, url}, _, _) do
96 |> Phoenix.Controller.redirect(external: url)
100 defp get_media(conn, unknown, _, _) do
101 Logger.error("#{__MODULE__}: Unknown get startegy: #{inspect(unknown)}")
104 |> send_resp(:internal_server_error, dgettext("errors", "Internal Error"))