Resolve merge conflicts
[akkoma] / lib / pleroma / web / media_proxy / media_proxy.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MediaProxy do
6 alias Pleroma.Config
7 alias Pleroma.Web
8
9 @base64_opts [padding: false]
10
11 def url(url) when is_nil(url) or url == "", do: nil
12 def url("/" <> _ = url), do: url
13
14 def url(url) do
15 if disabled?() or local?(url) or whitelisted?(url) do
16 url
17 else
18 encode_url(url)
19 end
20 end
21
22 defp disabled?, do: !Config.get([:media_proxy, :enabled], false)
23
24 defp local?(url), do: String.starts_with?(url, Pleroma.Web.base_url())
25
26 defp whitelisted?(url) do
27 %{host: domain} = URI.parse(url)
28
29 Enum.any?(Config.get([:media_proxy, :whitelist]), fn pattern ->
30 String.equivalent?(domain, pattern)
31 end)
32 end
33
34 def encode_url(url) do
35 base64 = Base.url_encode64(url, @base64_opts)
36
37 sig64 =
38 base64
39 |> signed_url
40 |> Base.url_encode64(@base64_opts)
41
42 build_url(sig64, base64, filename(url))
43 end
44
45 def decode_url(sig, url) do
46 with {:ok, sig} <- Base.url_decode64(sig, @base64_opts),
47 signature when signature == sig <- signed_url(url) do
48 {:ok, Base.url_decode64!(url, @base64_opts)}
49 else
50 _ -> {:error, :invalid_signature}
51 end
52 end
53
54 defp signed_url(url) do
55 :crypto.hmac(:sha, Config.get([Web.Endpoint, :secret_key_base]), url)
56 end
57
58 def filename(url_or_path) do
59 if path = URI.parse(url_or_path).path, do: Path.basename(path)
60 end
61
62 def build_url(sig_base64, url_base64, filename \\ nil) do
63 [
64 Pleroma.Config.get([:media_proxy, :base_url], Web.base_url()),
65 "proxy",
66 sig_base64,
67 url_base64,
68 filename
69 ]
70 |> Enum.filter(& &1)
71 |> Path.join()
72 end
73 end