change `Repo.get(User, id)` => `User.get_by_id(id)`
[akkoma] / lib / pleroma / list.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 defmodule Pleroma.List do
6 use Ecto.Schema
7
8 import Ecto.Query
9 import Ecto.Changeset
10
11 alias Pleroma.Activity
12 alias Pleroma.Repo
13 alias Pleroma.User
14
15 schema "lists" do
16 belongs_to(:user, User, type: Pleroma.FlakeId)
17 field(:title, :string)
18 field(:following, {:array, :string}, default: [])
19
20 timestamps()
21 end
22
23 def title_changeset(list, attrs \\ %{}) do
24 list
25 |> cast(attrs, [:title])
26 |> validate_required([:title])
27 end
28
29 def follow_changeset(list, attrs \\ %{}) do
30 list
31 |> cast(attrs, [:following])
32 |> validate_required([:following])
33 end
34
35 def for_user(user, _opts) do
36 query =
37 from(
38 l in Pleroma.List,
39 where: l.user_id == ^user.id,
40 order_by: [desc: l.id],
41 limit: 50
42 )
43
44 Repo.all(query)
45 end
46
47 def get(id, %{id: user_id} = _user) do
48 query =
49 from(
50 l in Pleroma.List,
51 where: l.id == ^id,
52 where: l.user_id == ^user_id
53 )
54
55 Repo.one(query)
56 end
57
58 def get_following(%Pleroma.List{following: following} = _list) do
59 q =
60 from(
61 u in User,
62 where: u.follower_address in ^following
63 )
64
65 {:ok, Repo.all(q)}
66 end
67
68 # Get lists the activity should be streamed to.
69 def get_lists_from_activity(%Activity{actor: ap_id}) do
70 actor = User.get_cached_by_ap_id(ap_id)
71
72 query =
73 from(
74 l in Pleroma.List,
75 where: fragment("? && ?", l.following, ^[actor.follower_address])
76 )
77
78 Repo.all(query)
79 end
80
81 # Get lists to which the account belongs.
82 def get_lists_account_belongs(%User{} = owner, account_id) do
83 user = User.get_by_id(account_id)
84
85 query =
86 from(
87 l in Pleroma.List,
88 where:
89 l.user_id == ^owner.id and
90 fragment(
91 "? = ANY(?)",
92 ^user.follower_address,
93 l.following
94 )
95 )
96
97 Repo.all(query)
98 end
99
100 def rename(%Pleroma.List{} = list, title) do
101 list
102 |> title_changeset(%{title: title})
103 |> Repo.update()
104 end
105
106 def create(title, %User{} = creator) do
107 list = %Pleroma.List{user_id: creator.id, title: title}
108 Repo.insert(list)
109 end
110
111 def follow(%Pleroma.List{following: following} = list, %User{} = followed) do
112 update_follows(list, %{following: Enum.uniq([followed.follower_address | following])})
113 end
114
115 def unfollow(%Pleroma.List{following: following} = list, %User{} = unfollowed) do
116 update_follows(list, %{following: List.delete(following, unfollowed.follower_address)})
117 end
118
119 def delete(%Pleroma.List{} = list) do
120 Repo.delete(list)
121 end
122
123 def update_follows(%Pleroma.List{} = list, attrs) do
124 list
125 |> follow_changeset(attrs)
126 |> Repo.update()
127 end
128 end