d44bd34784b24b2c2bbd9d727c4464fb6d7fac9d
[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(["transfer_hashtags"]) do
136 import Ecto.Query
137
138 start_pleroma()
139
140 Logger.info("Starting transferring object embedded hashtags to `hashtags` table...")
141
142 from(
143 object in Object,
144 left_join: hashtag in assoc(object, :hashtags),
145 where: is_nil(hashtag.id),
146 where: fragment("(?)->>'tag' != '[]'", object.data),
147 select: %{
148 id: object.id,
149 tag: fragment("(?)->>'tag'", object.data)
150 }
151 )
152 |> Pleroma.Repo.chunk_stream(100, :batches)
153 |> Stream.each(fn objects ->
154 Logger.info("Processing #{length(objects)} objects...")
155
156 Enum.map(
157 objects,
158 fn object ->
159 hashtags =
160 object.tag
161 |> Jason.decode!()
162 |> Enum.filter(&is_bitstring(&1))
163
164 Repo.transaction(fn ->
165 with {:ok, hashtag_records} <- Hashtag.get_or_create_by_names(hashtags) do
166 for hashtag_record <- hashtag_records do
167 with {:ok, _} <-
168 Ecto.Adapters.SQL.query(
169 Repo,
170 "insert into hashtags_objects(hashtag_id, object_id) values " <>
171 "(#{hashtag_record.id}, #{object.id});"
172 ) do
173 :noop
174 else
175 {:error, e} ->
176 error =
177 "ERROR: could not link object #{object.id} and hashtag " <>
178 "#{hashtag_record.id}: #{inspect(e)}"
179
180 Logger.error(error)
181 Repo.rollback(error)
182 end
183 end
184 else
185 e ->
186 error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
187 Logger.error(error)
188 Repo.rollback(error)
189 end
190 end)
191 end
192 )
193 end)
194 |> Stream.run()
195
196 Logger.info("Done transferring hashtags. Please check logs to ensure no errors.")
197 end
198
199 def run(["vacuum", args]) do
200 start_pleroma()
201
202 Maintenance.vacuum(args)
203 end
204
205 def run(["ensure_expiration"]) do
206 start_pleroma()
207 days = Pleroma.Config.get([:mrf_activity_expiration, :days], 365)
208
209 Pleroma.Activity
210 |> join(:inner, [a], o in Object,
211 on:
212 fragment(
213 "(?->>'id') = COALESCE((?)->'object'->> 'id', (?)->>'object')",
214 o.data,
215 a.data,
216 a.data
217 )
218 )
219 |> where(local: true)
220 |> where([a], fragment("(? ->> 'type'::text) = 'Create'", a.data))
221 |> where([_a, o], fragment("?->>'type' = 'Note'", o.data))
222 |> Pleroma.Repo.chunk_stream(100, :batches)
223 |> Stream.each(fn activities ->
224 Enum.each(activities, fn activity ->
225 expires_at =
226 activity.inserted_at
227 |> DateTime.from_naive!("Etc/UTC")
228 |> Timex.shift(days: days)
229
230 Pleroma.Workers.PurgeExpiredActivity.enqueue(%{
231 activity_id: activity.id,
232 expires_at: expires_at
233 })
234 end)
235 end)
236 |> Stream.run()
237 end
238 end