Rename Activity.Search to Search.DatabaseSearch
[akkoma] / lib / pleroma / config_db.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.ConfigDB do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9 import Ecto.Query, only: [select: 3, from: 2]
10 import Pleroma.Web.Gettext
11
12 alias __MODULE__
13 alias Pleroma.Repo
14
15 @type t :: %__MODULE__{}
16
17 @full_subkey_update [
18 {:pleroma, :assets, :mascots},
19 {:pleroma, :emoji, :groups},
20 {:pleroma, :workers, :retries},
21 {:pleroma, :mrf_subchain, :match_actor},
22 {:pleroma, :mrf_keyword, :replace}
23 ]
24
25 schema "config" do
26 field(:key, Pleroma.EctoType.Config.Atom)
27 field(:group, Pleroma.EctoType.Config.Atom)
28 field(:value, Pleroma.EctoType.Config.BinaryValue)
29 field(:db, {:array, :string}, virtual: true, default: [])
30
31 timestamps()
32 end
33
34 @spec get_all_as_keyword() :: keyword()
35 def get_all_as_keyword do
36 ConfigDB
37 |> select([c], {c.group, c.key, c.value})
38 |> Repo.all()
39 |> Enum.reduce([], fn {group, key, value}, acc ->
40 Keyword.update(acc, group, [{key, value}], &Keyword.merge(&1, [{key, value}]))
41 end)
42 end
43
44 @spec get_all_by_group(atom() | String.t()) :: [t()]
45 def get_all_by_group(group) do
46 from(c in ConfigDB, where: c.group == ^group) |> Repo.all()
47 end
48
49 @spec get_by_group_and_key(atom() | String.t(), atom() | String.t()) :: t() | nil
50 def get_by_group_and_key(group, key) do
51 get_by_params(%{group: group, key: key})
52 end
53
54 @spec get_by_params(map()) :: ConfigDB.t() | nil
55 def get_by_params(%{group: _, key: _} = params), do: Repo.get_by(ConfigDB, params)
56
57 @spec changeset(ConfigDB.t(), map()) :: Changeset.t()
58 def changeset(config, params \\ %{}) do
59 config
60 |> cast(params, [:key, :group, :value])
61 |> validate_required([:key, :group, :value])
62 |> unique_constraint(:key, name: :config_group_key_index)
63 end
64
65 defp create(params) do
66 %ConfigDB{}
67 |> changeset(params)
68 |> Repo.insert()
69 end
70
71 defp update(%ConfigDB{} = config, %{value: value}) do
72 config
73 |> changeset(%{value: value})
74 |> Repo.update()
75 end
76
77 @spec get_db_keys(keyword(), any()) :: [String.t()]
78 def get_db_keys(value, key) do
79 keys =
80 if Keyword.keyword?(value) do
81 Keyword.keys(value)
82 else
83 [key]
84 end
85
86 Enum.map(keys, &to_json_types(&1))
87 end
88
89 @spec merge_group(atom(), atom(), keyword(), keyword()) :: keyword()
90 def merge_group(group, key, old_value, new_value) do
91 new_keys = to_mapset(new_value)
92
93 intersect_keys = old_value |> to_mapset() |> MapSet.intersection(new_keys) |> MapSet.to_list()
94
95 merged_value = ConfigDB.merge(old_value, new_value)
96
97 @full_subkey_update
98 |> Enum.map(fn
99 {g, k, subkey} when g == group and k == key ->
100 if subkey in intersect_keys, do: subkey, else: []
101
102 _ ->
103 []
104 end)
105 |> List.flatten()
106 |> Enum.reduce(merged_value, &Keyword.put(&2, &1, new_value[&1]))
107 end
108
109 defp to_mapset(keyword) do
110 keyword
111 |> Keyword.keys()
112 |> MapSet.new()
113 end
114
115 @spec sub_key_full_update?(atom(), atom(), [Keyword.key()]) :: boolean()
116 def sub_key_full_update?(group, key, subkeys) do
117 Enum.any?(@full_subkey_update, fn {g, k, subkey} ->
118 g == group and k == key and subkey in subkeys
119 end)
120 end
121
122 @spec merge(keyword(), keyword()) :: keyword()
123 def merge(config1, config2) when is_list(config1) and is_list(config2) do
124 Keyword.merge(config1, config2, fn _, app1, app2 ->
125 if Keyword.keyword?(app1) and Keyword.keyword?(app2) do
126 Keyword.merge(app1, app2, &deep_merge/3)
127 else
128 app2
129 end
130 end)
131 end
132
133 defp deep_merge(_key, value1, value2) do
134 if Keyword.keyword?(value1) and Keyword.keyword?(value2) do
135 Keyword.merge(value1, value2, &deep_merge/3)
136 else
137 value2
138 end
139 end
140
141 @spec update_or_create(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
142 def update_or_create(params) do
143 params = Map.put(params, :value, to_elixir_types(params[:value]))
144 search_opts = Map.take(params, [:group, :key])
145
146 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
147 {_, true, config} <- {:partial_update, can_be_partially_updated?(config), config},
148 {_, true, config} <-
149 {:can_be_merged, is_list(params[:value]) and is_list(config.value), config} do
150 new_value = merge_group(config.group, config.key, config.value, params[:value])
151 update(config, %{value: new_value})
152 else
153 {reason, false, config} when reason in [:partial_update, :can_be_merged] ->
154 update(config, params)
155
156 nil ->
157 create(params)
158 end
159 end
160
161 defp can_be_partially_updated?(%ConfigDB{} = config), do: not only_full_update?(config)
162
163 defp only_full_update?(%ConfigDB{group: group, key: key}) do
164 full_key_update = [
165 {:pleroma, :ecto_repos},
166 {:quack, :meta},
167 {:mime, :types},
168 {:cors_plug, [:max_age, :methods, :expose, :headers]},
169 {:swarm, :node_blacklist},
170 {:logger, :backends}
171 ]
172
173 Enum.any?(full_key_update, fn
174 {s_group, s_key} ->
175 group == s_group and ((is_list(s_key) and key in s_key) or key == s_key)
176 end)
177 end
178
179 @spec delete(ConfigDB.t() | map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
180 def delete(%ConfigDB{} = config), do: Repo.delete(config)
181
182 def delete(params) do
183 search_opts = Map.delete(params, :subkeys)
184
185 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
186 {config, sub_keys} when is_list(sub_keys) <- {config, params[:subkeys]},
187 keys <- Enum.map(sub_keys, &string_to_elixir_types(&1)),
188 {_, config, new_value} when new_value != [] <-
189 {:partial_remove, config, Keyword.drop(config.value, keys)} do
190 update(config, %{value: new_value})
191 else
192 {:partial_remove, config, []} ->
193 Repo.delete(config)
194
195 {config, nil} ->
196 Repo.delete(config)
197
198 nil ->
199 err =
200 dgettext("errors", "Config with params %{params} not found", params: inspect(params))
201
202 {:error, err}
203 end
204 end
205
206 @spec to_json_types(term()) :: map() | list() | boolean() | String.t()
207 def to_json_types(entity) when is_list(entity) do
208 Enum.map(entity, &to_json_types/1)
209 end
210
211 def to_json_types(%Regex{} = entity), do: inspect(entity)
212
213 def to_json_types(entity) when is_map(entity) do
214 Map.new(entity, fn {k, v} -> {to_json_types(k), to_json_types(v)} end)
215 end
216
217 def to_json_types({:args, args}) when is_list(args) do
218 arguments =
219 Enum.map(args, fn
220 arg when is_tuple(arg) -> inspect(arg)
221 arg -> to_json_types(arg)
222 end)
223
224 %{"tuple" => [":args", arguments]}
225 end
226
227 def to_json_types({:proxy_url, {type, :localhost, port}}) do
228 %{"tuple" => [":proxy_url", %{"tuple" => [to_json_types(type), "localhost", port]}]}
229 end
230
231 def to_json_types({:proxy_url, {type, host, port}}) when is_tuple(host) do
232 ip =
233 host
234 |> :inet_parse.ntoa()
235 |> to_string()
236
237 %{
238 "tuple" => [
239 ":proxy_url",
240 %{"tuple" => [to_json_types(type), ip, port]}
241 ]
242 }
243 end
244
245 def to_json_types({:proxy_url, {type, host, port}}) do
246 %{
247 "tuple" => [
248 ":proxy_url",
249 %{"tuple" => [to_json_types(type), to_string(host), port]}
250 ]
251 }
252 end
253
254 def to_json_types({:partial_chain, entity}),
255 do: %{"tuple" => [":partial_chain", inspect(entity)]}
256
257 def to_json_types(entity) when is_tuple(entity) do
258 value =
259 entity
260 |> Tuple.to_list()
261 |> to_json_types()
262
263 %{"tuple" => value}
264 end
265
266 def to_json_types(entity) when is_binary(entity), do: entity
267
268 def to_json_types(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
269 entity
270 end
271
272 def to_json_types(entity) when entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
273 ":#{entity}"
274 end
275
276 def to_json_types(entity) when is_atom(entity), do: inspect(entity)
277
278 @spec to_elixir_types(boolean() | String.t() | map() | list()) :: term()
279 def to_elixir_types(%{"tuple" => [":args", args]}) when is_list(args) do
280 arguments =
281 Enum.map(args, fn arg ->
282 if String.contains?(arg, ["{", "}"]) do
283 {elem, []} = Code.eval_string(arg)
284 elem
285 else
286 to_elixir_types(arg)
287 end
288 end)
289
290 {:args, arguments}
291 end
292
293 def to_elixir_types(%{"tuple" => [":proxy_url", %{"tuple" => [type, host, port]}]}) do
294 {:proxy_url, {string_to_elixir_types(type), parse_host(host), port}}
295 end
296
297 def to_elixir_types(%{"tuple" => [":partial_chain", entity]}) do
298 {partial_chain, []} =
299 entity
300 |> String.replace(~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
301 |> Code.eval_string()
302
303 {:partial_chain, partial_chain}
304 end
305
306 def to_elixir_types(%{"tuple" => entity}) do
307 Enum.reduce(entity, {}, &Tuple.append(&2, to_elixir_types(&1)))
308 end
309
310 def to_elixir_types(entity) when is_map(entity) do
311 Map.new(entity, fn {k, v} -> {to_elixir_types(k), to_elixir_types(v)} end)
312 end
313
314 def to_elixir_types(entity) when is_list(entity) do
315 Enum.map(entity, &to_elixir_types/1)
316 end
317
318 def to_elixir_types(entity) when is_binary(entity) do
319 entity
320 |> String.trim()
321 |> string_to_elixir_types()
322 end
323
324 def to_elixir_types(entity), do: entity
325
326 @spec string_to_elixir_types(String.t()) ::
327 atom() | Regex.t() | module() | String.t() | no_return()
328 def string_to_elixir_types("~r" <> _pattern = regex) do
329 pattern =
330 ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
331
332 delimiters = ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
333
334 with %{"modifier" => modifier, "pattern" => pattern, "delimiter" => regex_delimiter} <-
335 Regex.named_captures(pattern, regex),
336 {:ok, {leading, closing}} <- find_valid_delimiter(delimiters, pattern, regex_delimiter),
337 {result, _} <- Code.eval_string("~r#{leading}#{pattern}#{closing}#{modifier}") do
338 result
339 end
340 end
341
342 def string_to_elixir_types(":" <> atom), do: String.to_atom(atom)
343
344 def string_to_elixir_types(value) do
345 if module_name?(value) do
346 String.to_existing_atom("Elixir." <> value)
347 else
348 value
349 end
350 end
351
352 defp parse_host("localhost"), do: :localhost
353
354 defp parse_host(host) do
355 charlist = to_charlist(host)
356
357 case :inet.parse_address(charlist) do
358 {:error, :einval} ->
359 charlist
360
361 {:ok, ip} ->
362 ip
363 end
364 end
365
366 defp find_valid_delimiter([], _string, _) do
367 raise(ArgumentError, message: "valid delimiter for Regex expression not found")
368 end
369
370 defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
371 when is_tuple(delimiter) do
372 if String.contains?(pattern, closing) do
373 find_valid_delimiter(others, pattern, regex_delimiter)
374 else
375 {:ok, {leading, closing}}
376 end
377 end
378
379 defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
380 if String.contains?(pattern, delimiter) do
381 find_valid_delimiter(others, pattern, regex_delimiter)
382 else
383 {:ok, {delimiter, delimiter}}
384 end
385 end
386
387 @spec module_name?(String.t()) :: boolean()
388 def module_name?(string) do
389 Regex.match?(~r/^(Pleroma|Phoenix|Tesla|Quack|Ueberauth|Swoosh)\./, string) or
390 string in ["Oban", "Ueberauth", "ExSyslogger", "ConcurrentLimiter"]
391 end
392 end