Put rich media processing in a Task
[akkoma] / lib / pleroma / web / rich_media / parser.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.Web.RichMedia.Parser do
6 require Logger
7
8 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
9
10 defp parsers do
11 Pleroma.Config.get([:rich_media, :parsers])
12 end
13
14 def parse(nil), do: {:error, "No URL provided"}
15
16 if Pleroma.Config.get(:env) == :test do
17 @spec parse(String.t()) :: {:ok, map()} | {:error, any()}
18 def parse(url), do: parse_with_timeout(url)
19 else
20 @spec parse(String.t()) :: {:ok, map()} | {:error, any()}
21 def parse(url) do
22 with {:ok, data} <- get_cached_or_parse(url),
23 {:ok, _} <- set_ttl_based_on_image(data, url) do
24 {:ok, data}
25 end
26 end
27
28 defp get_cached_or_parse(url) do
29 case @cachex.fetch(:rich_media_cache, url, fn ->
30 case parse_with_timeout(url) do
31 {:ok, _} = res ->
32 {:commit, res}
33
34 {:error, reason} = e ->
35 # Unfortunately we have to log errors here, instead of doing that
36 # along with ttl setting at the bottom. Otherwise we can get log spam
37 # if more than one process was waiting for the rich media card
38 # while it was generated. Ideally we would set ttl here as well,
39 # so we don't override it number_of_waiters_on_generation
40 # times, but one, obviously, can't set ttl for not-yet-created entry
41 # and Cachex doesn't support returning ttl from the fetch callback.
42 log_error(url, reason)
43 {:commit, e}
44 end
45 end) do
46 {action, res} when action in [:commit, :ok] ->
47 case res do
48 {:ok, _data} = res ->
49 res
50
51 {:error, reason} = e ->
52 if action == :commit, do: set_error_ttl(url, reason)
53 e
54 end
55
56 {:error, e} ->
57 {:error, {:cachex_error, e}}
58 end
59 end
60
61 defp set_error_ttl(_url, :body_too_large), do: :ok
62 defp set_error_ttl(_url, {:content_type, _}), do: :ok
63
64 # The TTL is not set for the errors above, since they are unlikely to change
65 # with time
66
67 defp set_error_ttl(url, _reason) do
68 ttl = Pleroma.Config.get([:rich_media, :failure_backoff], 60_000)
69 @cachex.expire(:rich_media_cache, url, ttl)
70 :ok
71 end
72
73 defp log_error(url, {:invalid_metadata, data}) do
74 Logger.debug(fn -> "Incomplete or invalid metadata for #{url}: #{inspect(data)}" end)
75 end
76
77 defp log_error(url, reason) do
78 Logger.warn(fn -> "Rich media error for #{url}: #{inspect(reason)}" end)
79 end
80 end
81
82 @doc """
83 Set the rich media cache based on the expiration time of image.
84
85 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
86
87 ## Example
88
89 defmodule MyModule do
90 @behaviour Pleroma.Web.RichMedia.Parser.TTL
91 def ttl(data, url) do
92 image_url = Map.get(data, :image)
93 # do some parsing in the url and get the ttl of the image
94 # and return ttl is unix time
95 parse_ttl_from_url(image_url)
96 end
97 end
98
99 Define the module in the config
100
101 config :pleroma, :rich_media,
102 ttl_setters: [MyModule]
103 """
104 @spec set_ttl_based_on_image(map(), String.t()) ::
105 {:ok, Integer.t() | :noop} | {:error, :no_key}
106 def set_ttl_based_on_image(data, url) do
107 case get_ttl_from_image(data, url) do
108 {:ok, ttl} when is_number(ttl) ->
109 ttl = ttl * 1000
110
111 case @cachex.expire_at(:rich_media_cache, url, ttl) do
112 {:ok, true} -> {:ok, ttl}
113 {:ok, false} -> {:error, :no_key}
114 end
115
116 _ ->
117 {:ok, :noop}
118 end
119 end
120
121 defp get_ttl_from_image(data, url) do
122 [:rich_media, :ttl_setters]
123 |> Pleroma.Config.get()
124 |> Enum.reduce({:ok, nil}, fn
125 module, {:ok, _ttl} ->
126 module.ttl(data, url)
127
128 _, error ->
129 error
130 end)
131 end
132
133 def parse_url(url) do
134 with {:ok, %Tesla.Env{body: html}} <- Pleroma.Web.RichMedia.Helpers.rich_media_get(url),
135 {:ok, html} <- Floki.parse_document(html) do
136 html
137 |> maybe_parse()
138 |> Map.put("url", url)
139 |> clean_parsed_data()
140 |> check_parsed_data()
141 end
142 end
143
144 def parse_with_timeout(url) do
145 try do
146 task =
147 Task.Supervisor.async_nolink(Pleroma.TaskSupervisor, fn ->
148 parse_url(url)
149 end)
150
151 Task.await(task, 5000)
152 catch
153 :exit, {:timeout, _} ->
154 Logger.warn("Timeout while fetching rich media for #{url}")
155 {:error, :timeout}
156 end
157 end
158
159 defp maybe_parse(html) do
160 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
161 case parser.parse(html, acc) do
162 data when data != %{} -> {:halt, data}
163 _ -> {:cont, acc}
164 end
165 end)
166 end
167
168 defp check_parsed_data(%{"title" => title} = data)
169 when is_binary(title) and title != "" do
170 {:ok, data}
171 end
172
173 defp check_parsed_data(data) do
174 {:error, {:invalid_metadata, data}}
175 end
176
177 defp clean_parsed_data(data) do
178 data
179 |> Enum.reject(fn {key, val} ->
180 not match?({:ok, _}, Jason.encode(%{key => val}))
181 end)
182 |> Map.new()
183 end
184 end