giant massive dep upgrade and dialyxir-found error emporium (#371)
[akkoma] / lib / pleroma / activity / html.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Activity.HTML do
6 alias Pleroma.HTML
7 alias Pleroma.Object
8
9 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
10
11 # We store a list of cache keys related to an activity in a
12 # separate cache, scrubber_management_cache. It has the same
13 # size as scrubber_cache (see application.ex). Every time we add
14 # a cache to scrubber_cache, we update scrubber_management_cache.
15 #
16 # The most recent write of a certain key in the management cache
17 # is the same as the most recent write of any record related to that
18 # key in the main cache.
19 # Assuming LRW ( https://hexdocs.pm/cachex/Cachex.Policy.LRW.html ),
20 # this means when the management cache is evicted by cachex, all
21 # related records in the main cache will also have been evicted.
22
23 defp get_cache_keys_for(activity_id) do
24 with {:ok, list} when is_list(list) <- @cachex.get(:scrubber_management_cache, activity_id) do
25 list
26 else
27 _ -> []
28 end
29 end
30
31 defp add_cache_key_for(activity_id, additional_key) do
32 current = get_cache_keys_for(activity_id)
33
34 unless additional_key in current do
35 @cachex.put(:scrubber_management_cache, activity_id, [additional_key | current])
36 end
37 end
38
39 def invalidate_cache_for(activity_id) do
40 keys = get_cache_keys_for(activity_id)
41
42 for key <- keys do
43 @cachex.del(:scrubber_cache, key)
44 end
45
46 @cachex.del(:scrubber_management_cache, activity_id)
47 end
48
49 def get_cached_scrubbed_html_for_activity(
50 content,
51 scrubbers,
52 activity,
53 key \\ "",
54 callback \\ fn x -> x end
55 ) do
56 key = "#{key}#{generate_scrubber_signature(scrubbers)}|#{activity.id}"
57
58 @cachex.fetch!(:scrubber_cache, key, fn _key ->
59 object = Object.normalize(activity, fetch: false)
60
61 add_cache_key_for(activity.id, key)
62 HTML.ensure_scrubbed_html(content, scrubbers, object.data["fake"] || false, callback)
63 end)
64 end
65
66 def get_cached_stripped_html_for_activity(content, activity, key) do
67 get_cached_scrubbed_html_for_activity(
68 content,
69 FastSanitize.Sanitizer.StripTags,
70 activity,
71 key,
72 &HtmlEntities.decode/1
73 )
74 end
75
76 defp generate_scrubber_signature(scrubber) when is_atom(scrubber) do
77 generate_scrubber_signature([scrubber])
78 end
79
80 defp generate_scrubber_signature(scrubbers) do
81 Enum.reduce(scrubbers, "", fn scrubber, signature ->
82 "#{signature}#{to_string(scrubber)}"
83 end)
84 end
85 end