aboutsummaryrefslogtreecommitdiff
path: root/lib/pleroma/config/transfer_task.ex
blob: cf880aa22939efeacd7182a52d2c74d13889d862 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
defmodule Pleroma.Config.TransferTask do
  use Task
  alias Pleroma.Web.AdminAPI.Config

  def start_link do
    load_and_update_env()
    if Pleroma.Config.get(:env) == :test, do: Ecto.Adapters.SQL.Sandbox.checkin(Pleroma.Repo)
    :ignore
  end

  def load_and_update_env do
    if Pleroma.Config.get([:instance, :dynamic_configuration]) and
         Ecto.Adapters.SQL.table_exists?(Pleroma.Repo, "config") do
      for_restart =
        Pleroma.Repo.all(Config)
        |> Enum.map(&update_env(&1))

      # We need to restart applications for loaded settings take effect
      for_restart
      |> Enum.reject(&(&1 in [:pleroma, :ok]))
      |> Enum.each(fn app ->
        Application.stop(app)
        :ok = Application.start(app)
      end)
    end
  end

  defp update_env(setting) do
    try do
      key =
        if String.starts_with?(setting.key, "Pleroma.") do
          "Elixir." <> setting.key
        else
          setting.key
        end

      group = String.to_existing_atom(setting.group)

      Application.put_env(
        group,
        String.to_existing_atom(key),
        Config.from_binary(setting.value)
      )

      group
    rescue
      e ->
        require Logger

        Logger.warn(
          "updating env causes error, key: #{inspect(setting.key)}, error: #{inspect(e)}"
        )
    end
  end
end