1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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]
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.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: [])
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_by_params(map()) :: ConfigDB.t() | nil
45 def get_by_params(params), do: Repo.get_by(ConfigDB, params)
47 @spec changeset(ConfigDB.t(), map()) :: Changeset.t()
48 def changeset(config, params \\ %{}) do
50 |> cast(params, [:key, :group, :value])
51 |> validate_required([:key, :group, :value])
52 |> unique_constraint(:key, name: :config_group_key_index)
55 defp create(params) do
61 defp update(%ConfigDB{} = config, %{value: value}) do
63 |> changeset(%{value: value})
67 @spec get_db_keys(keyword(), any()) :: [String.t()]
68 def get_db_keys(value, key) do
70 if Keyword.keyword?(value) do
76 Enum.map(keys, &to_json_types(&1))
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)
83 intersect_keys = old_value |> to_mapset() |> MapSet.intersection(new_keys) |> MapSet.to_list()
85 merged_value = ConfigDB.merge(old_value, new_value)
89 {g, k, subkey} when g == group and k == key ->
90 if subkey in intersect_keys, do: subkey, else: []
96 |> Enum.reduce(merged_value, &Keyword.put(&2, &1, new_value[&1]))
99 defp to_mapset(keyword) do
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
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)
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)
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])
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})
142 {reason, false, config} when reason in [:partial_update, :can_be_merged] ->
143 update(config, params)
150 defp can_be_partially_updated?(%ConfigDB{} = config), do: not only_full_update?(config)
152 defp only_full_update?(%ConfigDB{group: group, key: key}) do
154 {:pleroma, :ecto_repos},
157 {:cors_plug, [:max_age, :methods, :expose, :headers]},
158 {:auto_linker, :opts},
159 {:swarm, :node_blacklist},
163 Enum.any?(full_key_update, fn
165 group == s_group and ((is_list(s_key) and key in s_key) or key == s_key)
169 @spec delete(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
170 def delete(params) do
171 search_opts = Map.delete(params, :subkeys)
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})
180 {:partial_remove, config, []} ->
188 dgettext("errors", "Config with params %{params} not found", params: inspect(params))
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)
199 def to_json_types(%Regex{} = entity), do: inspect(entity)
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)
205 def to_json_types({:args, args}) when is_list(args) do
208 arg when is_tuple(arg) -> inspect(arg)
209 arg -> to_json_types(arg)
212 %{"tuple" => [":args", arguments]}
215 def to_json_types({:proxy_url, {type, :localhost, port}}) do
216 %{"tuple" => [":proxy_url", %{"tuple" => [to_json_types(type), "localhost", port]}]}
219 def to_json_types({:proxy_url, {type, host, port}}) when is_tuple(host) do
222 |> :inet_parse.ntoa()
228 %{"tuple" => [to_json_types(type), ip, port]}
233 def to_json_types({:proxy_url, {type, host, port}}) do
237 %{"tuple" => [to_json_types(type), to_string(host), port]}
242 def to_json_types({:partial_chain, entity}),
243 do: %{"tuple" => [":partial_chain", inspect(entity)]}
245 def to_json_types(entity) when is_tuple(entity) do
254 def to_json_types(entity) when is_binary(entity), do: entity
256 def to_json_types(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
260 def to_json_types(entity) when entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
264 def to_json_types(entity) when is_atom(entity), do: inspect(entity)
266 @spec to_elixir_types(boolean() | String.t() | map() | list()) :: term()
267 def to_elixir_types(%{"tuple" => [":args", args]}) when is_list(args) do
269 Enum.map(args, fn arg ->
270 if String.contains?(arg, ["{", "}"]) do
271 {elem, []} = Code.eval_string(arg)
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}}
285 def to_elixir_types(%{"tuple" => [":partial_chain", entity]}) do
286 {partial_chain, []} =
288 |> String.replace(~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
289 |> Code.eval_string()
291 {:partial_chain, partial_chain}
294 def to_elixir_types(%{"tuple" => entity}) do
295 Enum.reduce(entity, {}, &Tuple.append(&2, to_elixir_types(&1)))
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)
302 def to_elixir_types(entity) when is_list(entity) do
303 Enum.map(entity, &to_elixir_types/1)
306 def to_elixir_types(entity) when is_binary(entity) do
309 |> string_to_elixir_types()
312 def to_elixir_types(entity), do: entity
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
318 ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
320 delimiters = ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
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
330 def string_to_elixir_types(":" <> atom), do: String.to_atom(atom)
332 def string_to_elixir_types(value) do
333 if is_module_name?(value) do
334 String.to_existing_atom("Elixir." <> value)
340 defp parse_host("localhost"), do: :localhost
342 defp parse_host(host) do
343 charlist = to_charlist(host)
345 case :inet.parse_address(charlist) do
354 defp find_valid_delimiter([], _string, _) do
355 raise(ArgumentError, message: "valid delimiter for Regex expression not found")
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)
363 {:ok, {leading, closing}}
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)
371 {:ok, {delimiter, delimiter}}
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"]