1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.ConfigDB do
9 import Ecto.Query, only: [select: 3, from: 2]
10 import Pleroma.Web.Gettext
15 @type t :: %__MODULE__{}
18 {:pleroma, :assets, :mascots},
19 {:pleroma, :emoji, :groups},
20 {:pleroma, :workers, :retries},
21 {:pleroma, :mrf_subchain, :match_actor},
22 {:pleroma, :mrf_keyword, :replace}
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: [])
34 @spec get_all_as_keyword() :: keyword()
35 def get_all_as_keyword do
37 |> select([c], {c.group, c.key, c.value})
39 |> Enum.reduce([], fn {group, key, value}, acc ->
40 Keyword.update(acc, group, [{key, value}], &Keyword.merge(&1, [{key, value}]))
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()
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})
54 @spec get_by_params(map()) :: ConfigDB.t() | nil
55 def get_by_params(%{group: _, key: _} = params), do: Repo.get_by(ConfigDB, params)
57 @spec changeset(ConfigDB.t(), map()) :: Changeset.t()
58 def changeset(config, params \\ %{}) do
60 |> cast(params, [:key, :group, :value])
61 |> validate_required([:key, :group, :value])
62 |> unique_constraint(:key, name: :config_group_key_index)
65 defp create(params) do
71 defp update(%ConfigDB{} = config, %{value: value}) do
73 |> changeset(%{value: value})
77 @spec get_db_keys(keyword(), any()) :: [String.t()]
78 def get_db_keys(value, key) do
80 if Keyword.keyword?(value) do
86 Enum.map(keys, &to_json_types(&1))
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)
93 intersect_keys = old_value |> to_mapset() |> MapSet.intersection(new_keys) |> MapSet.to_list()
95 merged_value = ConfigDB.merge(old_value, new_value)
99 {g, k, subkey} when g == group and k == key ->
100 if subkey in intersect_keys, do: subkey, else: []
106 |> Enum.reduce(merged_value, &Keyword.put(&2, &1, new_value[&1]))
109 defp to_mapset(keyword) do
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
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)
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)
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])
146 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
147 {_, true, config} <- {:partial_update, can_be_partially_updated?(config), 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})
153 {reason, false, config} when reason in [:partial_update, :can_be_merged] ->
154 update(config, params)
161 defp can_be_partially_updated?(%ConfigDB{} = config), do: not only_full_update?(config)
163 defp only_full_update?(%ConfigDB{group: group, key: key}) do
165 {:pleroma, :ecto_repos},
167 {:cors_plug, [:max_age, :methods, :expose, :headers]},
168 {:swarm, :node_blacklist},
172 Enum.any?(full_key_update, fn
174 group == s_group and ((is_list(s_key) and key in s_key) or key == s_key)
178 @spec delete(ConfigDB.t() | map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
179 def delete(%ConfigDB{} = config), do: Repo.delete(config)
181 def delete(params) do
182 search_opts = Map.delete(params, :subkeys)
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})
191 {:partial_remove, config, []} ->
199 dgettext("errors", "Config with params %{params} not found", params: inspect(params))
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)
210 def to_json_types(%Regex{} = entity), do: inspect(entity)
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)
216 def to_json_types({:args, args}) when is_list(args) do
219 arg when is_tuple(arg) -> inspect(arg)
220 arg -> to_json_types(arg)
223 %{"tuple" => [":args", arguments]}
226 def to_json_types({:proxy_url, {type, :localhost, port}}) do
227 %{"tuple" => [":proxy_url", %{"tuple" => [to_json_types(type), "localhost", port]}]}
230 def to_json_types({:proxy_url, {type, host, port}}) when is_tuple(host) do
233 |> :inet_parse.ntoa()
239 %{"tuple" => [to_json_types(type), ip, port]}
244 def to_json_types({:proxy_url, {type, host, port}}) do
248 %{"tuple" => [to_json_types(type), to_string(host), port]}
253 def to_json_types({:partial_chain, entity}),
254 do: %{"tuple" => [":partial_chain", inspect(entity)]}
256 def to_json_types(entity) when is_tuple(entity) do
265 def to_json_types(entity) when is_binary(entity), do: entity
267 def to_json_types(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
271 def to_json_types(entity) when entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
275 def to_json_types(entity) when is_atom(entity), do: inspect(entity)
277 @spec to_elixir_types(boolean() | String.t() | map() | list()) :: term()
278 def to_elixir_types(%{"tuple" => [":args", args]}) when is_list(args) do
280 Enum.map(args, fn arg ->
281 if String.contains?(arg, ["{", "}"]) do
282 {elem, []} = Code.eval_string(arg)
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}}
296 def to_elixir_types(%{"tuple" => [":partial_chain", entity]}) do
297 {partial_chain, []} =
299 |> String.replace(~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
300 |> Code.eval_string()
302 {:partial_chain, partial_chain}
305 def to_elixir_types(%{"tuple" => entity}) do
306 Enum.reduce(entity, {}, &Tuple.append(&2, to_elixir_types(&1)))
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)
313 def to_elixir_types(entity) when is_list(entity) do
314 Enum.map(entity, &to_elixir_types/1)
317 def to_elixir_types(entity) when is_binary(entity) do
320 |> string_to_elixir_types()
323 def to_elixir_types(entity), do: entity
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
329 ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
331 delimiters = ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
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
341 def string_to_elixir_types(":" <> atom), do: String.to_atom(atom)
343 def string_to_elixir_types(value) do
344 if module_name?(value) do
345 String.to_existing_atom("Elixir." <> value)
351 defp parse_host("localhost"), do: :localhost
353 defp parse_host(host) do
354 charlist = to_charlist(host)
356 case :inet.parse_address(charlist) do
365 defp find_valid_delimiter([], _string, _) do
366 raise(ArgumentError, message: "valid delimiter for Regex expression not found")
369 defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
370 when is_tuple(delimiter) do
371 if String.contains?(pattern, closing) do
372 find_valid_delimiter(others, pattern, regex_delimiter)
374 {:ok, {leading, closing}}
378 defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
379 if String.contains?(pattern, delimiter) do
380 find_valid_delimiter(others, pattern, regex_delimiter)
382 {:ok, {delimiter, delimiter}}
386 @spec module_name?(String.t()) :: boolean()
387 def module_name?(string) do
388 Regex.match?(~r/^(Pleroma|Phoenix|Tesla|Ueberauth|Swoosh)\./, string) or
389 string in ["Oban", "Ueberauth", "ExSyslogger", "ConcurrentLimiter"]