1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.List do
11 alias Pleroma.Activity
16 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
17 field(:title, :string)
18 field(:following, {:array, :string}, default: [])
19 field(:ap_id, :string)
24 def title_changeset(list, attrs \\ %{}) do
26 |> cast(attrs, [:title])
27 |> validate_required([:title])
30 def follow_changeset(list, attrs \\ %{}) do
32 |> cast(attrs, [:following])
33 |> validate_required([:following])
36 def for_user(user, _opts) do
40 where: l.user_id == ^user.id,
41 order_by: [desc: l.id],
48 def get(id, %{id: user_id} = _user) do
53 where: l.user_id == ^user_id
59 def get_by_ap_id(ap_id) do
60 Repo.get_by(__MODULE__, ap_id: ap_id)
63 def get_following(%Pleroma.List{following: following} = _list) do
67 where: u.follower_address in ^following
73 # Get lists the activity should be streamed to.
74 def get_lists_from_activity(%Activity{actor: ap_id}) do
75 actor = User.get_cached_by_ap_id(ap_id)
80 where: fragment("? && ?", l.following, ^[actor.follower_address])
86 # Get lists to which the account belongs.
87 def get_lists_account_belongs(%User{} = owner, user) do
89 |> where([l], l.user_id == ^owner.id)
90 |> where([l], fragment("? = ANY(?)", ^user.follower_address, l.following))
94 def rename(%Pleroma.List{} = list, title) do
96 |> title_changeset(%{title: title})
100 def create(title, %User{} = creator) do
101 changeset = title_changeset(%Pleroma.List{user_id: creator.id}, %{title: title})
103 if changeset.valid? do
104 Repo.transaction(fn ->
105 list = Repo.insert!(changeset)
108 |> change(ap_id: "#{creator.ap_id}/lists/#{list.id}")
116 def follow(%Pleroma.List{following: following} = list, %User{} = followed) do
117 update_follows(list, %{following: Enum.uniq([followed.follower_address | following])})
120 def unfollow(%Pleroma.List{following: following} = list, %User{} = unfollowed) do
121 update_follows(list, %{following: List.delete(following, unfollowed.follower_address)})
124 def delete(%Pleroma.List{} = list) do
128 def update_follows(%Pleroma.List{} = list, attrs) do
130 |> follow_changeset(attrs)
134 def memberships(%User{follower_address: follower_address}) do
136 |> where([l], ^follower_address in l.following)
137 |> select([l], l.ap_id)
141 def memberships(_), do: []
143 def member?(%Pleroma.List{following: following}, %User{follower_address: follower_address}) do
144 Enum.member?(following, follower_address)
147 def member?(_, _), do: false