41cf56fdd60925a696df1fec4dedde2e4ed68650
[akkoma] / lib / pleroma / spc_fixes / spc_fixes.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 alias Pleroma.Repo
6 alias Pleroma.User
7 alias Pleroma.Activity
8 import Ecto.Query
9
10 defmodule Pleroma.SpcFixes do
11 def upgrade_users do
12 query =
13 from(u in User,
14 where: fragment("? like ?", u.ap_id, "https://shitposter.club/user/%")
15 )
16
17 {:ok, file} = File.read("lib/pleroma/spc_fixes/users_conversion.txt")
18
19 # Mapping of old ap_id to new ap_id and vice reversa
20 mapping =
21 file
22 |> String.trim()
23 |> String.split("\n")
24 |> Enum.map(fn line ->
25 line
26 |> String.split("\t")
27 end)
28 |> Enum.reduce(%{}, fn [_id, old_ap_id, new_ap_id], acc ->
29 acc
30 |> Map.put(String.trim(old_ap_id), String.trim(new_ap_id))
31 |> Map.put(String.trim(new_ap_id), String.trim(old_ap_id))
32 end)
33
34 # First, refetch all the old users.
35 _old_users =
36 query
37 |> Repo.all()
38 |> Enum.each(fn user ->
39 with ap_id when is_binary(ap_id) <- mapping[user.ap_id] do
40 # This fetches and updates the user.
41 User.get_or_fetch_by_ap_id(ap_id)
42 end
43 end)
44
45 # Now, fix follow relationships.
46 query =
47 from(u in User,
48 where: fragment("? like ?", u.ap_id, "https://shitposter.club/users/%")
49 )
50
51 query
52 |> Repo.all()
53 |> Enum.each(fn user ->
54 old_follower_address = User.ap_followers(user)
55
56 # Fix users
57 query =
58 from(u in User,
59 where: ^old_follower_address in u.following,
60 update: [
61 push: [following: ^user.follower_address]
62 ]
63 )
64
65 Repo.update_all(query, [])
66
67 # Fix activities
68 query =
69 from(a in Activity,
70 where: fragment("?->>'actor' = ?", a.data, ^mapping[user.ap_id]),
71 update: [
72 set: [
73 data:
74 fragment(
75 "jsonb_set(jsonb_set(?, '{actor}', ?), '{to}', (?->'to')::jsonb || ?)",
76 a.data,
77 ^user.ap_id,
78 a.data,
79 ^[user.follower_address]
80 ),
81 actor: ^user.ap_id
82 ],
83 push: [
84 recipients: ^user.follower_address
85 ]
86 ]
87 )
88
89 Repo.update_all(query, [])
90 end)
91 end
92 end