revert ae54c06bb4bd2389d6eb1502b842c6b632e12e40
[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 {:mime, :types},
167 {:cors_plug, [:max_age, :methods, :expose, :headers]},
168 {:swarm, :node_blacklist},
169 {:logger, :backends}
170 ]
171
172 Enum.any?(full_key_update, fn
173 {s_group, s_key} ->
174 group == s_group and ((is_list(s_key) and key in s_key) or key == s_key)
175 end)
176 end
177
178 @spec delete(ConfigDB.t() | map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
179 def delete(%ConfigDB{} = config), do: Repo.delete(config)
180
181 def delete(params) do
182 search_opts = Map.delete(params, :subkeys)
183
184 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
185 {config, sub_keys} when is_list(sub_keys) <- {config, params[:subkeys]},
186 keys <- Enum.map(sub_keys, &string_to_elixir_types(&1)),
187 {_, config, new_value} when new_value != [] <-
188 {:partial_remove, config, Keyword.drop(config.value, keys)} do
189 update(config, %{value: new_value})
190 else
191 {:partial_remove, config, []} ->
192 Repo.delete(config)
193
194 {config, nil} ->
195 Repo.delete(config)
196
197 nil ->
198 err =
199 dgettext("errors", "Config with params %{params} not found", params: inspect(params))
200
201 {:error, err}
202 end
203 end
204
205 @spec to_json_types(term()) :: map() | list() | boolean() | String.t()
206 def to_json_types(entity) when is_list(entity) do
207 Enum.map(entity, &to_json_types/1)
208 end
209
210 def to_json_types(%Regex{} = entity), do: inspect(entity)
211
212 def to_json_types(entity) when is_map(entity) do
213 Map.new(entity, fn {k, v} -> {to_json_types(k), to_json_types(v)} end)
214 end
215
216 def to_json_types({:args, args}) when is_list(args) do
217 arguments =
218 Enum.map(args, fn
219 arg when is_tuple(arg) -> inspect(arg)
220 arg -> to_json_types(arg)
221 end)
222
223 %{"tuple" => [":args", arguments]}
224 end
225
226 def to_json_types({:proxy_url, {type, :localhost, port}}) do
227 %{"tuple" => [":proxy_url", %{"tuple" => [to_json_types(type), "localhost", port]}]}
228 end
229
230 def to_json_types({:proxy_url, {type, host, port}}) when is_tuple(host) do
231 ip =
232 host
233 |> :inet_parse.ntoa()
234 |> to_string()
235
236 %{
237 "tuple" => [
238 ":proxy_url",
239 %{"tuple" => [to_json_types(type), ip, port]}
240 ]
241 }
242 end
243
244 def to_json_types({:proxy_url, {type, host, port}}) do
245 %{
246 "tuple" => [
247 ":proxy_url",
248 %{"tuple" => [to_json_types(type), to_string(host), port]}
249 ]
250 }
251 end
252
253 def to_json_types({:partial_chain, entity}),
254 do: %{"tuple" => [":partial_chain", inspect(entity)]}
255
256 def to_json_types(entity) when is_tuple(entity) do
257 value =
258 entity
259 |> Tuple.to_list()
260 |> to_json_types()
261
262 %{"tuple" => value}
263 end
264
265 def to_json_types(entity) when is_binary(entity), do: entity
266
267 def to_json_types(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
268 entity
269 end
270
271 def to_json_types(entity) when entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
272 ":#{entity}"
273 end
274
275 def to_json_types(entity) when is_atom(entity), do: inspect(entity)
276
277 @spec to_elixir_types(boolean() | String.t() | map() | list()) :: term()
278 def to_elixir_types(%{"tuple" => [":args", args]}) when is_list(args) do
279 arguments =
280 Enum.map(args, fn arg ->
281 if String.contains?(arg, ["{", "}"]) do
282 {elem, []} = Code.eval_string(arg)
283 elem
284 else
285 to_elixir_types(arg)
286 end
287 end)
288
289 {:args, arguments}
290 end
291
292 def to_elixir_types(%{"tuple" => [":proxy_url", %{"tuple" => [type, host, port]}]}) do
293 {:proxy_url, {string_to_elixir_types(type), parse_host(host), port}}
294 end
295
296 def to_elixir_types(%{"tuple" => [":partial_chain", entity]}) do
297 {partial_chain, []} =
298 entity
299 |> String.replace(~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
300 |> Code.eval_string()
301
302 {:partial_chain, partial_chain}
303 end
304
305 def to_elixir_types(%{"tuple" => entity}) do
306 Enum.reduce(entity, {}, &Tuple.append(&2, to_elixir_types(&1)))
307 end
308
309 def to_elixir_types(entity) when is_map(entity) do
310 Map.new(entity, fn {k, v} -> {to_elixir_types(k), to_elixir_types(v)} end)
311 end
312
313 def to_elixir_types(entity) when is_list(entity) do
314 Enum.map(entity, &to_elixir_types/1)
315 end
316
317 def to_elixir_types(entity) when is_binary(entity) do
318 entity
319 |> String.trim()
320 |> string_to_elixir_types()
321 end
322
323 def to_elixir_types(entity), do: entity
324
325 @spec string_to_elixir_types(String.t()) ::
326 atom() | Regex.t() | module() | String.t() | no_return()
327 def string_to_elixir_types("~r" <> _pattern = regex) do
328 pattern =
329 ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
330
331 delimiters = ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
332
333 with %{"modifier" => modifier, "pattern" => pattern, "delimiter" => regex_delimiter} <-
334 Regex.named_captures(pattern, regex),
335 {:ok, {leading, closing}} <- find_valid_delimiter(delimiters, pattern, regex_delimiter),
336 {result, _} <- Code.eval_string("~r#{leading}#{pattern}#{closing}#{modifier}") do
337 result
338 end
339 end
340
341 def string_to_elixir_types(":" <> atom), do: String.to_atom(atom)
342
343 def string_to_elixir_types(value) do
344 if module_name?(value) do
345 try do
346 String.to_existing_atom("Elixir." <> value)
347 rescue
348 ArgumentError -> :invalid_atom
349 end
350 else
351 value
352 end
353 end
354
355 defp parse_host("localhost"), do: :localhost
356
357 defp parse_host(host) do
358 charlist = to_charlist(host)
359
360 case :inet.parse_address(charlist) do
361 {:error, :einval} ->
362 charlist
363
364 {:ok, ip} ->
365 ip
366 end
367 end
368
369 defp find_valid_delimiter([], _string, _) do
370 raise(ArgumentError, message: "valid delimiter for Regex expression not found")
371 end
372
373 defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
374 when is_tuple(delimiter) do
375 if String.contains?(pattern, closing) do
376 find_valid_delimiter(others, pattern, regex_delimiter)
377 else
378 {:ok, {leading, closing}}
379 end
380 end
381
382 defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
383 if String.contains?(pattern, delimiter) do
384 find_valid_delimiter(others, pattern, regex_delimiter)
385 else
386 {:ok, {delimiter, delimiter}}
387 end
388 end
389
390 @spec module_name?(String.t()) :: boolean()
391 def module_name?(string) do
392 Regex.match?(~r/^(Pleroma|Phoenix|Tesla|Quack|Ueberauth|Swoosh)\./, string) or
393 string in ["Oban", "Ueberauth", "ExSyslogger", "ConcurrentLimiter"]
394 end
395 end