e9686fc1ba5ebd06cf24e4699d75df60a4d28b20
[akkoma] / lib / mix / tasks / pleroma / database.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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.Hashtag
8 alias Pleroma.Maintenance
9 alias Pleroma.Object
10 alias Pleroma.Repo
11 alias Pleroma.User
12
13 require Logger
14 require Pleroma.Constants
15
16 import Ecto.Query
17 import Mix.Pleroma
18
19 use Mix.Task
20
21 @shortdoc "A collection of database related tasks"
22 @moduledoc File.read!("docs/administration/CLI_tasks/database.md")
23
24 def run(["remove_embedded_objects" | args]) do
25 {options, [], []} =
26 OptionParser.parse(
27 args,
28 strict: [
29 vacuum: :boolean
30 ]
31 )
32
33 start_pleroma()
34 Logger.info("Removing embedded objects")
35
36 Repo.query!(
37 "update activities set data = safe_jsonb_set(data, '{object}'::text[], data->'object'->'id') where data->'object'->>'id' is not null;",
38 [],
39 timeout: :infinity
40 )
41
42 if Keyword.get(options, :vacuum) do
43 Maintenance.vacuum("full")
44 end
45 end
46
47 def run(["bump_all_conversations"]) do
48 start_pleroma()
49 Conversation.bump_for_all_activities()
50 end
51
52 def run(["update_users_following_followers_counts"]) do
53 start_pleroma()
54
55 Repo.transaction(
56 fn ->
57 from(u in User, select: u)
58 |> Repo.stream()
59 |> Stream.each(&User.update_follower_count/1)
60 |> Stream.run()
61 end,
62 timeout: :infinity
63 )
64 end
65
66 def run(["prune_objects" | args]) do
67 {options, [], []} =
68 OptionParser.parse(
69 args,
70 strict: [
71 vacuum: :boolean
72 ]
73 )
74
75 start_pleroma()
76
77 deadline = Pleroma.Config.get([:instance, :remote_post_retention_days])
78
79 Logger.info("Pruning objects older than #{deadline} days")
80
81 time_deadline =
82 NaiveDateTime.utc_now()
83 |> NaiveDateTime.add(-(deadline * 86_400))
84
85 from(o in Object,
86 where:
87 fragment(
88 "?->'to' \\? ? OR ?->'cc' \\? ?",
89 o.data,
90 ^Pleroma.Constants.as_public(),
91 o.data,
92 ^Pleroma.Constants.as_public()
93 ),
94 where: o.inserted_at < ^time_deadline,
95 where:
96 fragment("split_part(?->>'actor', '/', 3) != ?", o.data, ^Pleroma.Web.Endpoint.host())
97 )
98 |> Repo.delete_all(timeout: :infinity)
99
100 if Keyword.get(options, :vacuum) do
101 Maintenance.vacuum("full")
102 end
103 end
104
105 def run(["fix_likes_collections"]) do
106 start_pleroma()
107
108 from(object in Object,
109 where: fragment("(?)->>'likes' is not null", object.data),
110 select: %{id: object.id, likes: fragment("(?)->>'likes'", object.data)}
111 )
112 |> Pleroma.Repo.chunk_stream(100, :batches)
113 |> Stream.each(fn objects ->
114 ids =
115 objects
116 |> Enum.filter(fn object -> object.likes |> Jason.decode!() |> is_map() end)
117 |> Enum.map(& &1.id)
118
119 Object
120 |> where([object], object.id in ^ids)
121 |> update([object],
122 set: [
123 data:
124 fragment(
125 "safe_jsonb_set(?, '{likes}', '[]'::jsonb, true)",
126 object.data
127 )
128 ]
129 )
130 |> Repo.update_all([], timeout: :infinity)
131 end)
132 |> Stream.run()
133 end
134
135 def run(["vacuum", args]) do
136 start_pleroma()
137
138 Maintenance.vacuum(args)
139 end
140
141 def run(["ensure_expiration"]) do
142 start_pleroma()
143 days = Pleroma.Config.get([:mrf_activity_expiration, :days], 365)
144
145 Pleroma.Activity
146 |> join(:inner, [a], o in Object,
147 on:
148 fragment(
149 "(?->>'id') = COALESCE((?)->'object'->> 'id', (?)->>'object')",
150 o.data,
151 a.data,
152 a.data
153 )
154 )
155 |> where(local: true)
156 |> where([a], fragment("(? ->> 'type'::text) = 'Create'", a.data))
157 |> where([_a, o], fragment("?->>'type' = 'Note'", o.data))
158 |> Pleroma.Repo.chunk_stream(100, :batches)
159 |> Stream.each(fn activities ->
160 Enum.each(activities, fn activity ->
161 expires_at =
162 activity.inserted_at
163 |> DateTime.from_naive!("Etc/UTC")
164 |> Timex.shift(days: days)
165
166 Pleroma.Workers.PurgeExpiredActivity.enqueue(%{
167 activity_id: activity.id,
168 expires_at: expires_at
169 })
170 end)
171 end)
172 |> Stream.run()
173 end
174
175 def run(["transfer_hashtags"]) do
176 import Ecto.Query
177
178 start_pleroma()
179
180 Logger.info("Starting transferring object embedded hashtags to `hashtags` table...")
181
182 # Note: most objects have Mention-type AS2 tags and no hashtags (but we can't filter them out)
183 from(
184 object in Object,
185 left_join: hashtag in assoc(object, :hashtags),
186 where: is_nil(hashtag.id),
187 where:
188 fragment("(?)->'tag' IS NOT NULL AND (?)->'tag' != '[]'::jsonb", object.data, object.data),
189 select: %{
190 id: object.id,
191 tag: fragment("(?)->'tag'", object.data)
192 }
193 )
194 |> Repo.chunk_stream(100, :one, timeout: :infinity)
195 |> Stream.each(&transfer_object_hashtags(&1))
196 |> Stream.run()
197
198 Logger.info("Done transferring hashtags. Please check logs to ensure no errors.")
199 end
200
201 defp transfer_object_hashtags(object) do
202 hashtags = Object.object_data_hashtags(%{"tag" => object.tag})
203
204 Repo.transaction(fn ->
205 with {:ok, hashtag_records} <- Hashtag.get_or_create_by_names(hashtags) do
206 for hashtag_record <- hashtag_records do
207 with {:ok, _} <-
208 Repo.query(
209 "insert into hashtags_objects(hashtag_id, object_id) values ($1, $2);",
210 [hashtag_record.id, object.id]
211 ) do
212 nil
213 else
214 {:error, e} ->
215 error =
216 "ERROR: could not link object #{object.id} and hashtag " <>
217 "#{hashtag_record.id}: #{inspect(e)}"
218
219 Logger.error(error)
220 Repo.rollback(object.id)
221 end
222 end
223
224 object.id
225 else
226 e ->
227 error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
228 Logger.error(error)
229 Repo.rollback(object.id)
230 end
231 end)
232 end
233 end