Exclude reblogs from `GET /api/pleroma/admin/statuses` by default
[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.Upload
8 alias Pleroma.Web
9
10 @base64_opts [padding: false]
11
12 def url(url) when is_nil(url) or url == "", do: nil
13 def url("/" <> _ = url), do: url
14
15 def url(url) do
16 if disabled?() or local?(url) or whitelisted?(url) do
17 url
18 else
19 encode_url(url)
20 end
21 end
22
23 defp disabled?, do: !Config.get([:media_proxy, :enabled], false)
24
25 defp local?(url), do: String.starts_with?(url, Pleroma.Web.base_url())
26
27 defp whitelisted?(url) do
28 %{host: domain} = URI.parse(url)
29
30 mediaproxy_whitelist = Config.get([:media_proxy, :whitelist])
31
32 upload_base_url_domain =
33 if !is_nil(Config.get([Upload, :base_url])) do
34 [URI.parse(Config.get([Upload, :base_url])).host]
35 else
36 []
37 end
38
39 whitelist = mediaproxy_whitelist ++ upload_base_url_domain
40
41 Enum.any?(whitelist, fn pattern ->
42 String.equivalent?(domain, pattern)
43 end)
44 end
45
46 def encode_url(url) do
47 base64 = Base.url_encode64(url, @base64_opts)
48
49 sig64 =
50 base64
51 |> signed_url
52 |> Base.url_encode64(@base64_opts)
53
54 build_url(sig64, base64, filename(url))
55 end
56
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)}
61 else
62 _ -> {:error, :invalid_signature}
63 end
64 end
65
66 defp signed_url(url) do
67 :crypto.hmac(:sha, Config.get([Web.Endpoint, :secret_key_base]), url)
68 end
69
70 def filename(url_or_path) do
71 if path = URI.parse(url_or_path).path, do: Path.basename(path)
72 end
73
74 def build_url(sig_base64, url_base64, filename \\ nil) do
75 [
76 Pleroma.Config.get([:media_proxy, :base_url], Web.base_url()),
77 "proxy",
78 sig_base64,
79 url_base64,
80 filename
81 ]
82 |> Enum.filter(& &1)
83 |> Path.join()
84 end
85 end