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