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