1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.ConfigDB do
10 import Pleroma.Web.Gettext
15 @type t :: %__MODULE__{}
18 {:pleroma, :ecto_repos},
21 {:cors_plug, [:max_age, :methods, :expose, :headers]},
22 {:auto_linker, :opts},
23 {:swarm, :node_blacklist},
28 {:pleroma, :assets, :mascots},
29 {:pleroma, :emoji, :groups},
30 {:pleroma, :workers, :retries},
31 {:pleroma, :mrf_subchain, :match_actor},
32 {:pleroma, :mrf_keyword, :replace}
35 @regex ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
37 @delimiters ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
41 field(:group, :string)
42 field(:value, :binary)
43 field(:db, {:array, :string}, virtual: true, default: [])
48 @spec get_all_as_keyword() :: keyword()
49 def get_all_as_keyword do
51 |> select([c], {c.group, c.key, c.value})
53 |> Enum.reduce([], fn {group, key, value}, acc ->
54 group = ConfigDB.from_string(group)
55 key = ConfigDB.from_string(key)
56 value = from_binary(value)
58 Keyword.update(acc, group, [{key, value}], &Keyword.merge(&1, [{key, value}]))
62 @spec get_by_params(map()) :: ConfigDB.t() | nil
63 def get_by_params(params), do: Repo.get_by(ConfigDB, params)
65 @spec changeset(ConfigDB.t(), map()) :: Changeset.t()
66 def changeset(config, params \\ %{}) do
67 params = Map.put(params, :value, transform(params[:value]))
70 |> cast(params, [:key, :group, :value])
71 |> validate_required([:key, :group, :value])
72 |> unique_constraint(:key, name: :config_group_key_index)
75 @spec create(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
82 @spec update(ConfigDB.t(), map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
83 def update(%ConfigDB{} = config, %{value: value}) do
85 |> changeset(%{value: value})
89 @spec get_db_keys(ConfigDB.t()) :: [String.t()]
90 def get_db_keys(%ConfigDB{} = config) do
92 |> ConfigDB.from_binary()
93 |> get_db_keys(config.key)
96 @spec get_db_keys(keyword(), any()) :: [String.t()]
97 def get_db_keys(value, key) do
98 if Keyword.keyword?(value) do
99 value |> Keyword.keys() |> Enum.map(&convert(&1))
105 @spec merge_group(atom(), atom(), keyword(), keyword()) :: keyword()
106 def merge_group(group, key, old_value, new_value) do
107 new_keys = to_map_set(new_value)
110 old_value |> to_map_set() |> MapSet.intersection(new_keys) |> MapSet.to_list()
112 merged_value = ConfigDB.merge(old_value, new_value)
116 {g, k, subkey} when g == group and k == key ->
117 if subkey in intersect_keys, do: subkey, else: []
123 |> Enum.reduce(merged_value, fn subkey, acc ->
124 Keyword.put(acc, subkey, new_value[subkey])
128 defp to_map_set(keyword) do
134 @spec sub_key_full_update?(atom(), atom(), [Keyword.key()]) :: boolean()
135 def sub_key_full_update?(group, key, subkeys) do
136 Enum.any?(@full_subkey_update, fn {g, k, subkey} ->
137 g == group and k == key and subkey in subkeys
141 @spec merge(keyword(), keyword()) :: keyword()
142 def merge(config1, config2) when is_list(config1) and is_list(config2) do
143 Keyword.merge(config1, config2, fn _, app1, app2 ->
144 if Keyword.keyword?(app1) and Keyword.keyword?(app2) do
145 Keyword.merge(app1, app2, &deep_merge/3)
152 defp deep_merge(_key, value1, value2) do
153 if Keyword.keyword?(value1) and Keyword.keyword?(value2) do
154 Keyword.merge(value1, value2, &deep_merge/3)
160 @spec update_or_create(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
161 def update_or_create(params) do
162 search_opts = Map.take(params, [:group, :key])
164 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
165 {:partial_update, true, config} <-
166 {:partial_update, can_be_partially_updated?(config), config},
167 old_value <- from_binary(config.value),
168 transformed_value <- do_transform(params[:value]),
169 {:can_be_merged, true, config} <- {:can_be_merged, is_list(transformed_value), config},
172 ConfigDB.from_string(config.group),
173 ConfigDB.from_string(config.key),
177 ConfigDB.update(config, %{value: new_value})
179 {reason, false, config} when reason in [:partial_update, :can_be_merged] ->
180 ConfigDB.update(config, params)
183 ConfigDB.create(params)
187 defp can_be_partially_updated?(%ConfigDB{} = config), do: not only_full_update?(config)
189 defp only_full_update?(%ConfigDB{} = config) do
190 config_group = ConfigDB.from_string(config.group)
191 config_key = ConfigDB.from_string(config.key)
193 Enum.any?(@full_key_update, fn
194 {group, key} when is_list(key) ->
195 config_group == group and config_key in key
198 config_group == group and config_key == key
202 @spec delete(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
203 def delete(params) do
204 search_opts = Map.delete(params, :subkeys)
206 with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
207 {config, sub_keys} when is_list(sub_keys) <- {config, params[:subkeys]},
208 old_value <- from_binary(config.value),
209 keys <- Enum.map(sub_keys, &do_transform_string(&1)),
210 {:partial_remove, config, new_value} when new_value != [] <-
211 {:partial_remove, config, Keyword.drop(old_value, keys)} do
212 ConfigDB.update(config, %{value: new_value})
214 {:partial_remove, config, []} ->
222 dgettext("errors", "Config with params %{params} not found", params: inspect(params))
228 @spec from_binary(binary()) :: term()
229 def from_binary(binary), do: :erlang.binary_to_term(binary)
231 @spec from_binary_with_convert(binary()) :: any()
232 def from_binary_with_convert(binary) do
238 @spec from_string(String.t()) :: atom() | no_return()
239 def from_string(string), do: do_transform_string(string)
241 @spec convert(any()) :: any()
242 def convert(entity), do: do_convert(entity)
244 defp do_convert(entity) when is_list(entity) do
245 for v <- entity, into: [], do: do_convert(v)
248 defp do_convert(%Regex{} = entity), do: inspect(entity)
250 defp do_convert(entity) when is_map(entity) do
251 for {k, v} <- entity, into: %{}, do: {do_convert(k), do_convert(v)}
254 defp do_convert({:proxy_url, {type, :localhost, port}}) do
255 %{"tuple" => [":proxy_url", %{"tuple" => [do_convert(type), "localhost", port]}]}
258 defp do_convert({:proxy_url, {type, host, port}}) when is_tuple(host) do
261 |> :inet_parse.ntoa()
267 %{"tuple" => [do_convert(type), ip, port]}
272 defp do_convert({:proxy_url, {type, host, port}}) do
276 %{"tuple" => [do_convert(type), to_string(host), port]}
281 defp do_convert(entity) when is_tuple(entity) do
290 defp do_convert(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
294 defp do_convert(entity)
295 when is_atom(entity) and entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
299 defp do_convert(entity) when is_atom(entity), do: inspect(entity)
301 defp do_convert(entity) when is_binary(entity), do: entity
303 @spec transform(any()) :: binary() | no_return()
304 def transform(entity) when is_binary(entity) or is_map(entity) or is_list(entity) do
310 def transform(entity), do: to_binary(entity)
312 @spec transform_with_out_binary(any()) :: any()
313 def transform_with_out_binary(entity), do: do_transform(entity)
315 @spec to_binary(any()) :: binary()
316 def to_binary(entity), do: :erlang.term_to_binary(entity)
318 defp do_transform(%Regex{} = entity), do: entity
320 defp do_transform(%{"tuple" => [":proxy_url", %{"tuple" => [type, host, port]}]}) do
321 {:proxy_url, {do_transform_string(type), parse_host(host), port}}
324 defp do_transform(%{"tuple" => entity}) do
325 Enum.reduce(entity, {}, fn val, acc -> Tuple.append(acc, do_transform(val)) end)
328 defp do_transform(entity) when is_map(entity) do
329 for {k, v} <- entity, into: %{}, do: {do_transform(k), do_transform(v)}
332 defp do_transform(entity) when is_list(entity) do
333 for v <- entity, into: [], do: do_transform(v)
336 defp do_transform(entity) when is_binary(entity) do
339 |> do_transform_string()
342 defp do_transform(entity), do: entity
344 defp parse_host("localhost"), do: :localhost
346 defp parse_host(host) do
347 charlist = to_charlist(host)
349 case :inet.parse_address(charlist) do
358 defp find_valid_delimiter([], _string, _) do
359 raise(ArgumentError, message: "valid delimiter for Regex expression not found")
362 defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
363 when is_tuple(delimiter) do
364 if String.contains?(pattern, closing) do
365 find_valid_delimiter(others, pattern, regex_delimiter)
367 {:ok, {leading, closing}}
371 defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
372 if String.contains?(pattern, delimiter) do
373 find_valid_delimiter(others, pattern, regex_delimiter)
375 {:ok, {delimiter, delimiter}}
379 defp do_transform_string("~r" <> _pattern = regex) do
380 with %{"modifier" => modifier, "pattern" => pattern, "delimiter" => regex_delimiter} <-
381 Regex.named_captures(@regex, regex),
382 {:ok, {leading, closing}} <- find_valid_delimiter(@delimiters, pattern, regex_delimiter),
383 {result, _} <- Code.eval_string("~r#{leading}#{pattern}#{closing}#{modifier}") do
388 defp do_transform_string(":" <> atom), do: String.to_atom(atom)
390 defp do_transform_string(value) do
391 if is_module_name?(value) do
392 String.to_existing_atom("Elixir." <> value)
398 @spec is_module_name?(String.t()) :: boolean()
399 def is_module_name?(string) do
400 Regex.match?(~r/^(Pleroma|Phoenix|Tesla|Quack|Ueberauth|Swoosh)\./, string) or
401 string in ["Oban", "Ueberauth", "ExSyslogger"]