1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MediaProxy do
10 @base64_opts [padding: false]
12 def url(url) when is_nil(url) or url == "", do: nil
13 def url("/" <> _ = url), do: url
16 if disabled?() or local?(url) or whitelisted?(url) do
23 defp disabled?, do: !Config.get([:media_proxy, :enabled], false)
25 defp local?(url), do: String.starts_with?(url, Pleroma.Web.base_url())
27 defp whitelisted?(url) do
28 %{host: domain} = URI.parse(url)
30 mediaproxy_whitelist = Config.get([:media_proxy, :whitelist])
32 upload_base_url_domain =
33 if !is_nil(Config.get([Upload, :base_url])) do
34 [URI.parse(Config.get([Upload, :base_url])).host]
39 whitelist = mediaproxy_whitelist ++ upload_base_url_domain
41 Enum.any?(whitelist, fn pattern ->
42 String.equivalent?(domain, pattern)
46 def encode_url(url) do
47 base64 = Base.url_encode64(url, @base64_opts)
52 |> Base.url_encode64(@base64_opts)
54 build_url(sig64, base64, filename(url))
57 def decode_url(sig, url) do
58 with {:ok, sig} <- Base.url_decode64(sig, @base64_opts),
59 signature when signature == sig <- signed_url(url) do
60 {:ok, Base.url_decode64!(url, @base64_opts)}
62 _ -> {:error, :invalid_signature}
66 defp signed_url(url) do
67 :crypto.hmac(:sha, Config.get([Web.Endpoint, :secret_key_base]), url)
70 def filename(url_or_path) do
71 if path = URI.parse(url_or_path).path, do: Path.basename(path)
74 def build_url(sig_base64, url_base64, filename \\ nil) do
76 Pleroma.Config.get([:media_proxy, :base_url], Web.base_url()),