saving to DB only added by user settings
[akkoma] / lib / pleroma / config / transfer_task.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Config.TransferTask do
6 use Task
7
8 alias Pleroma.ConfigDB
9 alias Pleroma.Repo
10
11 require Logger
12
13 def start_link(_) do
14 load_and_update_env()
15 if Pleroma.Config.get(:env) == :test, do: Ecto.Adapters.SQL.Sandbox.checkin(Repo)
16 :ignore
17 end
18
19 def load_and_update_env do
20 with true <- Pleroma.Config.get(:configurable_from_database),
21 true <- Ecto.Adapters.SQL.table_exists?(Repo, "config"),
22 started_applications <- Application.started_applications() do
23 # We need to restart applications for loaded settings take effect
24 ConfigDB
25 |> Repo.all()
26 |> Enum.map(&update_env(&1))
27 |> Enum.uniq()
28 # TODO: some problem with prometheus after restart!
29 |> Enum.reject(&(&1 in [:pleroma, nil, :prometheus]))
30 |> Enum.each(&restart(started_applications, &1))
31 end
32 end
33
34 defp update_env(setting) do
35 try do
36 key = ConfigDB.from_string(setting.key)
37 group = ConfigDB.from_string(setting.group)
38 value = ConfigDB.from_binary(setting.value)
39
40 if group != :phoenix and key != :serve_endpoints do
41 default = Pleroma.Config.Holder.config(group, key)
42
43 merged_value =
44 if can_be_merged?(default, value) do
45 DeepMerge.deep_merge(default, value)
46 else
47 value
48 end
49
50 :ok = Application.put_env(group, key, merged_value)
51 group
52 end
53 rescue
54 e ->
55 Logger.warn(
56 "updating env causes error, key: #{inspect(setting.key)}, error: #{inspect(e)}"
57 )
58
59 nil
60 end
61 end
62
63 defp restart(started_applications, app) do
64 with {^app, _, _} <- List.keyfind(started_applications, app, 0),
65 :ok <- Application.stop(app) do
66 :ok = Application.start(app)
67 else
68 nil -> Logger.warn("#{app} is not started.")
69 error -> Logger.warn(inspect(error))
70 end
71 end
72
73 defp can_be_merged?(val1, val2) when is_map(val1) and is_map(val2), do: true
74
75 defp can_be_merged?(val1, val2) when is_list(val1) and is_list(val2) do
76 Keyword.keyword?(val1) and Keyword.keyword?(val2)
77 end
78
79 defp can_be_merged?(_val1, _val2), do: false
80 end