[#3213] Hashtag-filtering functions in ActivityPub. Mix task for migrating hashtags...
[akkoma] / lib / pleroma / web / admin_api / controllers / media_proxy_cache_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.AdminAPI.MediaProxyCacheController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.Web.ApiSpec.Admin, as: Spec
9 alias Pleroma.Web.MediaProxy
10 alias Pleroma.Web.Plugs.OAuthScopesPlug
11
12 plug(Pleroma.Web.ApiSpec.CastAndValidate)
13
14 plug(
15 OAuthScopesPlug,
16 %{scopes: ["read:media_proxy_caches"], admin: true} when action in [:index]
17 )
18
19 plug(
20 OAuthScopesPlug,
21 %{scopes: ["write:media_proxy_caches"], admin: true} when action in [:purge, :delete]
22 )
23
24 action_fallback(Pleroma.Web.AdminAPI.FallbackController)
25
26 defdelegate open_api_operation(action), to: Spec.MediaProxyCacheOperation
27
28 def index(%{assigns: %{user: _}} = conn, params) do
29 entries = fetch_entries(params)
30 urls = paginate_entries(entries, params.page, params.page_size)
31
32 render(conn, "index.json",
33 urls: urls,
34 page_size: params.page_size,
35 count: length(entries)
36 )
37 end
38
39 defp fetch_entries(params) do
40 MediaProxy.cache_table()
41 |> Cachex.stream!(Cachex.Query.create(true, :key))
42 |> filter_entries(params[:query])
43 end
44
45 defp filter_entries(stream, query) when is_binary(query) do
46 regex = ~r/#{query}/i
47
48 stream
49 |> Enum.filter(fn url -> String.match?(url, regex) end)
50 |> Enum.to_list()
51 end
52
53 defp filter_entries(stream, _), do: Enum.to_list(stream)
54
55 defp paginate_entries(entries, page, page_size) do
56 offset = page_size * (page - 1)
57 Enum.slice(entries, offset, page_size)
58 end
59
60 def delete(%{assigns: %{user: _}, body_params: %{urls: urls}} = conn, _) do
61 MediaProxy.remove_from_banned_urls(urls)
62 json(conn, %{})
63 end
64
65 def purge(%{assigns: %{user: _}, body_params: %{urls: urls, ban: ban}} = conn, _) do
66 MediaProxy.Invalidation.purge(urls)
67
68 if ban do
69 MediaProxy.put_in_banned_urls(urls)
70 end
71
72 json(conn, %{})
73 end
74 end