1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Activity.HTML do
9 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
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.
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.
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
31 def add_cache_key_for(activity_id, additional_key) do
32 current = get_cache_keys_for(activity_id)
34 unless additional_key in current do
35 @cachex.put(:scrubber_management_cache, activity_id, [additional_key | current])
39 def invalidate_cache_for(activity_id) do
40 keys = get_cache_keys_for(activity_id)
41 Enum.map(keys, &@cachex.del(:scrubber_cache, &1))
42 @cachex.del(:scrubber_management_cache, activity_id)
45 def get_cached_scrubbed_html_for_activity(
50 callback \\ fn x -> x end
52 key = "#{key}#{generate_scrubber_signature(scrubbers)}|#{activity.id}"
54 @cachex.fetch!(:scrubber_cache, key, fn _key ->
55 object = Object.normalize(activity, fetch: false)
57 add_cache_key_for(activity.id, key)
58 HTML.ensure_scrubbed_html(content, scrubbers, object.data["fake"] || false, callback)
62 def get_cached_stripped_html_for_activity(content, activity, key) do
63 get_cached_scrubbed_html_for_activity(
65 FastSanitize.Sanitizer.StripTags,
68 &HtmlEntities.decode/1
72 defp generate_scrubber_signature(scrubber) when is_atom(scrubber) do
73 generate_scrubber_signature([scrubber])
76 defp generate_scrubber_signature(scrubbers) do
77 Enum.reduce(scrubbers, "", fn scrubber, signature ->
78 "#{signature}#{to_string(scrubber)}"