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
15 @ap_id_regex ~r/^\/users\/(?<nickname>\w+)\/lists\/(?<list_id>\d+)/
18 belongs_to(:user, User, type: Pleroma.FlakeId)
19 field(:title, :string)
20 field(:following, {:array, :string}, default: [])
25 def title_changeset(list, attrs \\ %{}) do
27 |> cast(attrs, [:title])
28 |> validate_required([:title])
31 def follow_changeset(list, attrs \\ %{}) do
33 |> cast(attrs, [:following])
34 |> validate_required([:following])
37 def ap_id(%User{nickname: nickname}, list_id) do
38 Pleroma.Web.Endpoint.url() <> "/users/#{nickname}/lists/#{list_id}"
41 def ap_id({nickname, list_id}), do: ap_id(%User{nickname: nickname}, list_id)
43 def for_user(user, _opts) do
47 where: l.user_id == ^user.id,
48 order_by: [desc: l.id],
55 def get(id, %{id: user_id} = _user) do
60 where: l.user_id == ^user_id
66 def get_by_ap_id(ap_id) do
67 host = Pleroma.Web.Endpoint.host()
69 with %{host: ^host, path: path} <- URI.parse(ap_id),
70 %{"list_id" => list_id, "nickname" => nickname} <-
71 Regex.named_captures(@ap_id_regex, path),
72 %User{} = user <- User.get_cached_by_nickname(nickname) do
79 def get_following(%Pleroma.List{following: following} = _list) do
83 where: u.follower_address in ^following
89 # Get lists the activity should be streamed to.
90 def get_lists_from_activity(%Activity{actor: ap_id}) do
91 actor = User.get_cached_by_ap_id(ap_id)
96 where: fragment("? && ?", l.following, ^[actor.follower_address])
102 # Get lists to which the account belongs.
103 def get_lists_account_belongs(%User{} = owner, account_id) do
104 user = User.get_cached_by_id(account_id)
110 l.user_id == ^owner.id and
113 ^user.follower_address,
121 def rename(%Pleroma.List{} = list, title) do
123 |> title_changeset(%{title: title})
127 def create(title, %User{} = creator) do
128 list = %Pleroma.List{user_id: creator.id, title: title}
132 def follow(%Pleroma.List{following: following} = list, %User{} = followed) do
133 update_follows(list, %{following: Enum.uniq([followed.follower_address | following])})
136 def unfollow(%Pleroma.List{following: following} = list, %User{} = unfollowed) do
137 update_follows(list, %{following: List.delete(following, unfollowed.follower_address)})
140 def delete(%Pleroma.List{} = list) do
144 def update_follows(%Pleroma.List{} = list, attrs) do
146 |> follow_changeset(attrs)
150 def memberships(%User{follower_address: follower_address}) do
152 |> where([l], ^follower_address in l.following)
153 |> join(:inner, [l], u in User, on: l.user_id == u.id)
154 |> select([l, u], {u.nickname, l.id})
156 |> Enum.map(&ap_id/1)
159 def memberships(_), do: []