30c0d2bf17c467d6f561a3bc46873ae039cd08e0
[akkoma] / lib / mix / tasks / pleroma / database.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Mix.Tasks.Pleroma.Database do
6 alias Pleroma.Conversation
7 alias Pleroma.Maintenance
8 alias Pleroma.Object
9 alias Pleroma.Repo
10 alias Pleroma.User
11
12 require Logger
13 require Pleroma.Constants
14
15 import Ecto.Query
16 import Mix.Pleroma
17
18 use Mix.Task
19
20 @shortdoc "A collection of database related tasks"
21 @moduledoc File.read!("docs/administration/CLI_tasks/database.md")
22
23 # Rolls back a specific migration (leaving subsequent migrations applied)
24 # Based on https://stackoverflow.com/a/53825840
25 def run(["rollback", version]) do
26 start_pleroma()
27
28 version = String.to_integer(version)
29 re = ~r/^#{version}_.*\.exs/
30 path = Application.app_dir(:pleroma, Path.join(["priv", "repo", "migrations"]))
31
32 result =
33 with {:find, "" <> file} <- {:find, Enum.find(File.ls!(path), &String.match?(&1, re))},
34 {:compile, [{mod, _} | _]} <- {:compile, Code.compile_file(Path.join(path, file))},
35 {:rollback, :ok} <- {:rollback, Ecto.Migrator.down(Repo, version, mod)} do
36 {:ok, "Reversed migration: #{file}"}
37 else
38 {:find, _} -> {:error, "No migration found with version prefix: #{version}"}
39 {:compile, e} -> {:error, "Problem compiling migration module: #{inspect(e)}"}
40 {:rollback, e} -> {:error, "Problem reversing migration: #{inspect(e)}"}
41 e -> {:error, "Something unexpected happened: #{inspect(e)}"}
42 end
43
44 IO.inspect(result)
45 end
46
47 def run(["remove_embedded_objects" | args]) do
48 {options, [], []} =
49 OptionParser.parse(
50 args,
51 strict: [
52 vacuum: :boolean
53 ]
54 )
55
56 start_pleroma()
57 Logger.info("Removing embedded objects")
58
59 Repo.query!(
60 "update activities set data = safe_jsonb_set(data, '{object}'::text[], data->'object'->'id') where data->'object'->>'id' is not null;",
61 [],
62 timeout: :infinity
63 )
64
65 if Keyword.get(options, :vacuum) do
66 Maintenance.vacuum("full")
67 end
68 end
69
70 def run(["bump_all_conversations"]) do
71 start_pleroma()
72 Conversation.bump_for_all_activities()
73 end
74
75 def run(["update_users_following_followers_counts"]) do
76 start_pleroma()
77
78 Repo.transaction(
79 fn ->
80 from(u in User, select: u)
81 |> Repo.stream()
82 |> Stream.each(&User.update_follower_count/1)
83 |> Stream.run()
84 end,
85 timeout: :infinity
86 )
87 end
88
89 def run(["prune_objects" | args]) do
90 {options, [], []} =
91 OptionParser.parse(
92 args,
93 strict: [
94 vacuum: :boolean
95 ]
96 )
97
98 start_pleroma()
99
100 deadline = Pleroma.Config.get([:instance, :remote_post_retention_days])
101
102 Logger.info("Pruning objects older than #{deadline} days")
103
104 time_deadline =
105 NaiveDateTime.utc_now()
106 |> NaiveDateTime.add(-(deadline * 86_400))
107
108 from(o in Object,
109 where:
110 fragment(
111 "?->'to' \\? ? OR ?->'cc' \\? ?",
112 o.data,
113 ^Pleroma.Constants.as_public(),
114 o.data,
115 ^Pleroma.Constants.as_public()
116 ),
117 where: o.inserted_at < ^time_deadline,
118 where:
119 fragment("split_part(?->>'actor', '/', 3) != ?", o.data, ^Pleroma.Web.Endpoint.host())
120 )
121 |> Repo.delete_all(timeout: :infinity)
122
123 if Keyword.get(options, :vacuum) do
124 Maintenance.vacuum("full")
125 end
126 end
127
128 def run(["fix_likes_collections"]) do
129 start_pleroma()
130
131 from(object in Object,
132 where: fragment("(?)->>'likes' is not null", object.data),
133 select: %{id: object.id, likes: fragment("(?)->>'likes'", object.data)}
134 )
135 |> Pleroma.Repo.chunk_stream(100, :batches)
136 |> Stream.each(fn objects ->
137 ids =
138 objects
139 |> Enum.filter(fn object -> object.likes |> Jason.decode!() |> is_map() end)
140 |> Enum.map(& &1.id)
141
142 Object
143 |> where([object], object.id in ^ids)
144 |> update([object],
145 set: [
146 data:
147 fragment(
148 "safe_jsonb_set(?, '{likes}', '[]'::jsonb, true)",
149 object.data
150 )
151 ]
152 )
153 |> Repo.update_all([], timeout: :infinity)
154 end)
155 |> Stream.run()
156 end
157
158 def run(["vacuum", args]) do
159 start_pleroma()
160
161 Maintenance.vacuum(args)
162 end
163
164 def run(["ensure_expiration"]) do
165 start_pleroma()
166 days = Pleroma.Config.get([:mrf_activity_expiration, :days], 365)
167
168 Pleroma.Activity
169 |> join(:inner, [a], o in Object,
170 on:
171 fragment(
172 "(?->>'id') = COALESCE((?)->'object'->> 'id', (?)->>'object')",
173 o.data,
174 a.data,
175 a.data
176 )
177 )
178 |> where(local: true)
179 |> where([a], fragment("(? ->> 'type'::text) = 'Create'", a.data))
180 |> where([_a, o], fragment("?->>'type' = 'Note'", o.data))
181 |> Pleroma.Repo.chunk_stream(100, :batches)
182 |> Stream.each(fn activities ->
183 Enum.each(activities, fn activity ->
184 expires_at =
185 activity.inserted_at
186 |> DateTime.from_naive!("Etc/UTC")
187 |> Timex.shift(days: days)
188
189 Pleroma.Workers.PurgeExpiredActivity.enqueue(%{
190 activity_id: activity.id,
191 expires_at: expires_at
192 })
193 end)
194 end)
195 |> Stream.run()
196 end
197 end