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.Web.AdminAPI.Config do
8 import Pleroma.Web.Gettext
12 @type t :: %__MODULE__{}
16 field(:group, :string)
17 field(:value, :binary)
22 @spec get_by_params(map()) :: Config.t() | nil
23 def get_by_params(params), do: Repo.get_by(Config, params)
25 @spec changeset(Config.t(), map()) :: Changeset.t()
26 def changeset(config, params \\ %{}) do
27 params = Map.put(params, :value, transform(params[:value]))
30 |> cast(params, [:key, :group, :value])
31 |> validate_required([:key, :group, :value])
32 |> unique_constraint(:key, name: :config_group_key_index)
35 @spec create(map()) :: {:ok, Config.t()} | {:error, Changeset.t()}
42 @spec update(Config.t(), map()) :: {:ok, Config} | {:error, Changeset.t()}
43 def update(%Config{} = config, %{value: value}) do
45 |> changeset(%{value: value})
50 {:pleroma, :ecto_repos},
53 {:cors_plug, [:max_age, :methods, :expose, :headers]},
54 {:auto_linker, :opts},
55 {:swarm, :node_blacklist}
58 defp only_full_update?(%Config{} = config) do
59 config_group = Config.from_string(config.group)
60 config_key = Config.from_string(config.key)
62 Enum.any?(@full_key_update, fn
63 {group, key} when is_list(key) ->
64 config_group == group and config_key in key
67 config_group == group and config_key == key
71 defp can_be_partially_updated?(%Config{} = config), do: not only_full_update?(config)
73 @spec update_or_create(map()) :: {:ok, Config.t()} | {:error, Changeset.t()}
74 def update_or_create(params) do
75 search_opts = Map.take(params, [:group, :key])
77 with %Config{} = config <- Config.get_by_params(search_opts),
78 {:partial_update, true, config} <-
79 {:partial_update, can_be_partially_updated?(config), config},
80 old_value <- from_binary(config.value),
81 transformed_value <- do_transform(params[:value]),
82 {:can_be_merged, true, config} <- {:can_be_merged, is_list(transformed_value), config},
83 new_value <- Keyword.merge(old_value, transformed_value) do
84 Config.update(config, %{value: new_value, transformed?: true})
86 {reason, false, config} when reason in [:partial_update, :can_be_merged] ->
87 Config.update(config, params)
94 @spec delete(map()) :: {:ok, Config.t()} | {:error, Changeset.t()} | {:ok, nil}
96 search_opts = Map.delete(params, :subkeys)
98 with %Config{} = config <- Config.get_by_params(search_opts),
99 {config, sub_keys} when is_list(sub_keys) <- {config, params[:subkeys]},
100 old_value <- from_binary(config.value),
101 keys <- Enum.map(sub_keys, &do_transform_string(&1)),
102 new_value <- Keyword.drop(old_value, keys) do
103 Config.update(config, %{value: new_value})
111 dgettext("errors", "Config with params %{params} not found", params: inspect(params))
117 @spec from_binary(binary()) :: term()
118 def from_binary(binary), do: :erlang.binary_to_term(binary)
120 @spec from_binary_with_convert(binary()) :: any()
121 def from_binary_with_convert(binary) do
127 @spec from_string(String.t()) :: atom() | no_return()
128 def from_string(":" <> entity), do: String.to_existing_atom(entity)
130 def from_string(entity) when is_binary(entity) do
131 if is_module_name?(entity) do
132 String.to_existing_atom("Elixir.#{entity}")
138 defp do_convert(entity) when is_list(entity) do
139 for v <- entity, into: [], do: do_convert(v)
142 defp do_convert(%Regex{} = entity), do: inspect(entity)
144 defp do_convert(entity) when is_map(entity) do
145 for {k, v} <- entity, into: %{}, do: {do_convert(k), do_convert(v)}
148 defp do_convert({:dispatch, [entity]}), do: %{"tuple" => [":dispatch", [inspect(entity)]]}
149 # TODO: will become useless after removing hackney
150 defp do_convert({:partial_chain, entity}), do: %{"tuple" => [":partial_chain", inspect(entity)]}
152 defp do_convert(entity) when is_tuple(entity),
153 do: %{"tuple" => do_convert(Tuple.to_list(entity))}
155 defp do_convert(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity),
158 defp do_convert(entity) when is_atom(entity), do: inspect(entity)
160 defp do_convert(entity) when is_binary(entity), do: entity
162 @spec transform(any()) :: binary() | no_return()
163 def transform(entity) when is_binary(entity) or is_map(entity) or is_list(entity) do
169 def transform(entity), do: to_binary(entity)
171 @spec to_binary(any()) :: binary()
172 def to_binary(entity), do: :erlang.term_to_binary(entity)
174 defp do_transform(%Regex{} = entity), do: entity
176 defp do_transform(%{"tuple" => [":dispatch", [entity]]}) do
177 {dispatch_settings, []} = do_eval(entity)
178 {:dispatch, [dispatch_settings]}
181 # TODO: will become useless after removing hackney
182 defp do_transform(%{"tuple" => [":partial_chain", entity]}) do
183 {partial_chain, []} = do_eval(entity)
184 {:partial_chain, partial_chain}
187 defp do_transform(%{"tuple" => entity}) do
188 Enum.reduce(entity, {}, fn val, acc -> Tuple.append(acc, do_transform(val)) end)
191 defp do_transform(entity) when is_map(entity) do
192 for {k, v} <- entity, into: %{}, do: {do_transform(k), do_transform(v)}
195 defp do_transform(entity) when is_list(entity) do
196 for v <- entity, into: [], do: do_transform(v)
199 defp do_transform(entity) when is_binary(entity) do
202 |> do_transform_string()
205 defp do_transform(entity), do: entity
207 @delimiters ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
209 defp find_valid_delimiter([], _string, _),
210 do: raise(ArgumentError, message: "valid delimiter for Regex expression not found")
212 defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
213 when is_tuple(delimiter) do
214 if String.contains?(pattern, closing) do
215 find_valid_delimiter(others, pattern, regex_delimiter)
217 {:ok, {leading, closing}}
221 defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
222 if String.contains?(pattern, delimiter) do
223 find_valid_delimiter(others, pattern, regex_delimiter)
225 {:ok, {delimiter, delimiter}}
229 @regex_parts ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
231 defp do_transform_string("~r" <> _pattern = regex) do
232 with %{"modifier" => modifier, "pattern" => pattern, "delimiter" => regex_delimiter} <-
233 Regex.named_captures(@regex_parts, regex),
234 {:ok, {leading, closing}} <- find_valid_delimiter(@delimiters, pattern, regex_delimiter),
235 {result, _} <- Code.eval_string("~r#{leading}#{pattern}#{closing}#{modifier}") do
240 defp do_transform_string(":" <> atom), do: String.to_atom(atom)
242 defp do_transform_string(value) do
243 if is_module_name?(value) do
244 String.to_existing_atom("Elixir." <> value)
250 @spec is_module_name?(String.t()) :: boolean()
251 def is_module_name?(string) do
252 Regex.match?(~r/^(Pleroma|Phoenix|Tesla)\./, string) or string in ["Oban", "Ueberauth"]
255 defp do_eval(entity) do
256 cleaned_string = String.replace(entity, ~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
257 Code.eval_string(cleaned_string)