controller.ex 1.21 KB
Newer Older
href's avatar
href committed
1
2
defmodule Pleroma.Web.MediaProxy.MediaProxyController do
  use Pleroma.Web, :controller
href's avatar
href committed
3
  alias Pleroma.{Web.MediaProxy, ReverseProxy}
href's avatar
href committed
4

href's avatar
href committed
5
6
  @default_proxy_opts [max_body_length: 25 * 1_048_576]

href's avatar
href committed
7
  def remote(conn, params = %{"sig" => sig64, "url" => url64}) do
href's avatar
href committed
8
    with config <- Pleroma.Config.get([:media_proxy], []),
href's avatar
href committed
9
10
         true <- Keyword.get(config, :enabled, false),
         {:ok, url} <- MediaProxy.decode_url(sig64, url64),
11
         filename <- Path.basename(URI.parse(url).path),
href's avatar
href committed
12
         :ok <- filename_matches(Map.has_key?(params, "filename"), conn.request_path, url) do
href's avatar
href committed
13
      ReverseProxy.call(conn, url, Keyword.get(config, :proxy_opts, @default_proxy_opts))
14
    else
lain's avatar
lain committed
15
      false ->
href's avatar
href committed
16
        send_resp(conn, 404, Plug.Conn.Status.reason_phrase(404))
lain's avatar
lain committed
17
18

      {:error, :invalid_signature} ->
href's avatar
href committed
19
        send_resp(conn, 403, Plug.Conn.Status.reason_phrase(403))
lain's avatar
lain committed
20

href's avatar
href committed
21
22
      {:wrong_filename, filename} ->
        redirect(conn, external: MediaProxy.build_url(sig64, url64, filename))
href's avatar
href committed
23
24
25
    end
  end

href's avatar
href committed
26
27
  def filename_matches(has_filename, path, url) do
    filename = MediaProxy.filename(url)
lain's avatar
lain committed
28

href's avatar
href committed
29
30
31
    cond do
      has_filename && filename && Path.basename(path) != filename -> {:wrong_filename, filename}
      true -> :ok
href's avatar
href committed
32
33
    end
  end
href's avatar
href committed
34
end