move to 2.5.5
[anni] / priv / repo / migrations / 20200428221338_insert_skeletons_for_deleted_users.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Repo.Migrations.InsertSkeletonsForDeletedUsers do
6   use Ecto.Migration
7
8   alias Pleroma.User
9   alias Pleroma.Repo
10
11   import Ecto.Query
12
13   def change do
14     Application.ensure_all_started(:flake_id)
15
16     local_ap_id =
17       User.Query.build(%{local: true})
18       |> select([u], u.ap_id)
19       |> limit(1)
20       |> Repo.one()
21
22     unless local_ap_id == nil do
23       # Hack to get instance base url because getting it from Phoenix
24       # would require starting the whole application
25       instance_uri =
26         local_ap_id
27         |> URI.parse()
28         |> Map.put(:query, nil)
29         |> Map.put(:path, nil)
30         |> URI.to_string()
31
32       {:ok, %{rows: ap_ids}} =
33         Ecto.Adapters.SQL.query(
34           Repo,
35           "select distinct unnest(nonexistent_locals.recipients) from activities, lateral (select array_agg(recipient) as recipients from unnest(activities.recipients) as recipient where recipient similar to '#{instance_uri}/users/[A-Za-z0-9]*' and not(recipient in (select ap_id from users))) nonexistent_locals;",
36           [],
37           timeout: :infinity
38         )
39
40       ap_ids
41       |> Enum.each(fn [ap_id] ->
42         Ecto.Changeset.change(%User{}, deactivated: true, ap_id: ap_id)
43         |> Repo.insert()
44       end)
45     end
46   end
47 end