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