1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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: Pleroma.FlakeId)
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, account_id) do
88 user = User.get_cached_by_id(account_id)
94 l.user_id == ^owner.id and
97 ^user.follower_address,
105 def rename(%Pleroma.List{} = list, title) do
107 |> title_changeset(%{title: title})
111 def create(title, %User{} = creator) do
112 list = %Pleroma.List{user_id: creator.id, title: title}
114 Repo.transaction(fn ->
115 list = Repo.insert!(list)
118 |> change(ap_id: "#{creator.ap_id}/lists/#{list.id}")
123 def follow(%Pleroma.List{following: following} = list, %User{} = followed) do
124 update_follows(list, %{following: Enum.uniq([followed.follower_address | following])})
127 def unfollow(%Pleroma.List{following: following} = list, %User{} = unfollowed) do
128 update_follows(list, %{following: List.delete(following, unfollowed.follower_address)})
131 def delete(%Pleroma.List{} = list) do
135 def update_follows(%Pleroma.List{} = list, attrs) do
137 |> follow_changeset(attrs)
141 def memberships(%User{follower_address: follower_address}) do
143 |> where([l], ^follower_address in l.following)
144 |> select([l], l.ap_id)
148 def memberships(_), do: []
150 def member?(%Pleroma.List{following: following}, %User{follower_address: follower_address}) do
151 Enum.member?(following, follower_address)
154 def member?(_, _), do: false