Merge branch 'develop' into command-available-check
[akkoma] / priv / repo / migrations / 20200724133313_move_welcome_settings.exs
1 defmodule Pleroma.Repo.Migrations.MoveWelcomeSettings do
2 use Ecto.Migration
3
4 alias Pleroma.ConfigDB
5
6 @old_keys [:welcome_user_nickname, :welcome_message]
7
8 def up do
9 with {:ok, config, {keep_values, move_values}} <- get_old_values() do
10 insert_welcome_settings(move_values)
11 update_instance_config(config, keep_values)
12 end
13 end
14
15 def down do
16 with {:ok, welcome_config, revert_values} <- get_revert_values() do
17 revert_instance_config(revert_values)
18 Pleroma.Repo.delete(welcome_config)
19 end
20 end
21
22 defp insert_welcome_settings([_ | _] = values) do
23 unless String.trim(values[:welcome_message]) == "" do
24 config_values = [
25 direct_message: %{
26 enabled: true,
27 sender_nickname: values[:welcome_user_nickname],
28 message: values[:welcome_message]
29 },
30 email: %{
31 enabled: false,
32 sender: nil,
33 subject: "Welcome to <%= instance_name %>",
34 html: "Welcome to <%= instance_name %>",
35 text: "Welcome to <%= instance_name %>"
36 }
37 ]
38
39 {:ok, _} =
40 %ConfigDB{}
41 |> ConfigDB.changeset(%{group: :pleroma, key: :welcome, value: config_values})
42 |> Pleroma.Repo.insert()
43 end
44
45 :ok
46 end
47
48 defp insert_welcome_settings(_), do: :noop
49
50 defp revert_instance_config(%{} = revert_values) do
51 values = [
52 welcome_user_nickname: revert_values[:sender_nickname],
53 welcome_message: revert_values[:message]
54 ]
55
56 ConfigDB.update_or_create(%{group: :pleroma, key: :instance, value: values})
57 end
58
59 defp revert_instance_config(_), do: :noop
60
61 defp update_instance_config(config, values) do
62 {:ok, _} =
63 config
64 |> ConfigDB.changeset(%{value: values})
65 |> Pleroma.Repo.update()
66
67 :ok
68 end
69
70 defp get_revert_values do
71 config = ConfigDB.get_by_params(%{group: :pleroma, key: :welcome})
72
73 cond do
74 is_nil(config) -> {:noop, nil, nil}
75 true -> {:ok, config, config.value[:direct_message]}
76 end
77 end
78
79 defp get_old_values do
80 config = ConfigDB.get_by_params(%{group: :pleroma, key: :instance})
81
82 cond do
83 is_nil(config) ->
84 {:noop, config, {}}
85
86 is_binary(config.value[:welcome_message]) ->
87 {:ok, config,
88 {Keyword.drop(config.value, @old_keys), Keyword.take(config.value, @old_keys)}}
89
90 true ->
91 {:ok, config, {Keyword.drop(config.value, @old_keys), []}}
92 end
93 end
94 end